Bypassing Endpoint Security for $20 or Less Philip A. Polstra, Sr. @ppolstra Roadmap • 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 Why this talk? • 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 $1 8-30 can easily construct device to allow any mass storage device to impersonate authorized device "0 1> 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,1 2, 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 1 2 B 4 3 Type B Pin Name Cable color Description 1 VBUS +5 V 2 D- White Data - 3 D+ Green Data + 4 GND Black Ground 4 3 2 1 Type A 5 4321 Mini-A ^ " | f_ 4 _ 3 _ 2 _ 1 ." j Micro-A 543 21 Mini-B 54321 . Micro-B 1 Automatic configuration No settable jumpers Enumeration Standard device classes with corresponding drivers - HID - Printer - Audio - Mass Storage 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 J 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 sf ? * Control Endpoints • Primary mechanism for most devices to communicate with host • Every device must have at least one in and out control endpoint EPO • 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 • 1 st 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 succefi^ 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, or more data packets, and an ACK handshake packet (if successf^ if Descriptors • They describe things (duh!) • Have a standard format - 1 st byte is the length in bytes (so you known when you're done; - 2 nd 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. /'W$/k - String: Describe something in Unicode text Device Descriptor Offset Field 1 2 4 5 6 7 8 10 12 14 15 16 17 bLength 1 bDescriptorType 1 bcdUSB 2 bDeviceClass 1 bDeviceSubClass 1 bDeviceProtocol 1 bMaxPacketSize 1 idVendor 2 idProduct 2 bcdDevice 2 iManufacturer 1 iProduct 1 iSerialNumber 1 bNumConfigurations 1 Number Constant BCD Class SubClass Protocol Number ID ID BCD Index Index Index Integer Description 1 8 bytes Device Descriptor (0x01) 0x200 Class Code Subclass Code Protocol Code Maxi Packet Size EP0 Vendor ID Product ID Device Release Number Index of Manu Descriptor Index of Prod Descriptor Index of SN Descriptor Num Configurations Configuration Descriptor (header) Offset Field Size Value Description bLength 1 Number Size in Bytes 1 bDescriptorType 1 Constant 0x02 2 wTotal Length 2 Number Total data returned 4 bNum Interfaces 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 . bo Self Powered b5 Remote Wakeup b4..0 Reserved 0. 8 b Max Power 1 mA Max Power in mA/2 Interface Descriptor Offset Field Size Value Description bLength Number 9 Bytes 1 bDescriptorType ] Constant 0x04 2 blnterfaceNumber 1 Number Number of Interface 3 bAlternateSetting 1 Number Alternative setting 4 bNumEndpoints Number Number of Endpoints used 5 blnterfaceClass Class Class Code 6 blnterfaceSubClass SubClass Subclass Code 7 blnterfaceProtocol Protocol Protocol Code 8 i I interface Index Index of String Descriptor Endpoint Descriptor Offset Field Size Value Description 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 D/ uirecuon u = uut, \ = in 3 bmAttributes 1 Bitmap b0..1 Transfer Type 10 = Bulk b2..7 are reserved. I 4 wMaxPacketSize 2 Number Maximum Packet Size 6 blnterval 1 Number Interval for polling endpoint data String Descriptors Offset Field Size Value Description bLength 1 Number Size of Descriptor in Bytes 1 bDescriptorType 1 Constant String Descriptor (0x03) 2 bString n Unicode Unicode Encoded String Note: String is a special case that lists available languages. Most common is 0x0409 - U.S. English Now that we have learned a little about general devices, without further delay... BULK-ONLY MASS STORAGE DEVICES USB Flash Drives • Hardware • Software • Filesystems • Talk to a flash drive Hardware (continued) Typically utilize NAND flash memory Memory degrades after 1 0,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 51 2, 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 - Atypical 512 byte sector needs 16 bytes for error correction f ? * Software • Usually implemented in firmware within specialized controller chips • Must: - Detect communication directed at drive 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 bCBWFIags; // 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[1 6]; // the actual command block (>= 6 bytes) } USB_MSI_CBW; J^ijL* 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 Defectl_istFormat:3; //000 = 32-bit LBAs unsigned char VendorSpecific; //vendor specific code unsigned short Interleave; //OxOOOO = use vendor default unsigned char Control; y } CB_FORMAT_UNIT; WA Command Block (continued) • Read (10) Example: typedef struct _CB_READ1 { unsigned char OperationCode; //must be 0x28 unsigned char RelativeAddress:1 ; // normally 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=0x1 2, //required MODE_SELECT6=0x15, MODE_SELECT1 0=0x55, MODE_SENSE6=0x1A, MODE_SENSE10=0x5A, READ6=0x08, //required READ1 0=0x28, //required READ12=0xA8, READ_CAPACITY1 0=0x25, //required READ_FORMAT_CAPACITIES=0x23, REPORT_LUNS=0xA0, //required REQUEST_SENSE=0x03, //required SEND_DIAGNOSTIC=0x1 D, //required START_STOP_UNIT=0x1 B, SYNCHRONIZE_CACHE1 0=0x35, TEST_UNIT_READ=OxOO, //required VERIFY10=0x2F, WRITE6=0x0A, //required WRITE10=0x2A, WRITE12=0xAA , j M f 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; Now that we know how bulk-only mass storage devices work... HOW DO I BYPASS ENDPOINT SECURITY? uUfi 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 Enough background. Let the fun begin... MICROCONTROLLERS ARE FUN (AND CHEAP) 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 p H 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 (continue VINCULUM BINDING USB TECHNOLOGIES Chip Choice (continued) I I - fc¥terfac=e SP I Mjste - 5PI Slaue 1 3PI SlweO General Purpose Debugger l/F Os-cill jtorV PLL Flash Pregrammer Debugge DMA □ DMA 1 DMA 2 DMA 3 USB 1 DP - l_3= DV • USB Hus-ti' Device Transce^er D USB H(Kt' Device : :. m i ti i . II - m USB2DP - UEB2DM- USB Heist.' Device Tcanscewer 1 USB Host' Device Canlmller Internal Clacks and Timers 256K Bytes E-FLASH C&4K jc 32} Embedded 1SK Bytes DdU Ran (4K. X 32} 3- b 1 d--s Chip Choice (continued) ■ » Ui «*« Vf^li IvMi* Fin ten UvrIL Uw-fc' Fitfarf) The Tabbed Toolbar r he Watchlist Window LH It? lit 2a±.lnl_U..vamm - iJUT_njC«_m_CTl : ^rivt^idetl imit. - jit'. _ j :rt . j ■ jr'. >»!♦ #.!•* ■• -i:-. Jcct.JSTtl ndr - TO9_:DCII._IIU?_SZT_BUA_BiTS: ■:i ii' than. >iut: _nA| a The Memory Window J i.iocti on - ns IDCTL BUI xr_ns> 1ITI: l,M.U»Ht * •MT_17W - WTF > l7 :«E] IMUtT,hUUt UA)| 'fits 't I - Vfsli<LJIU! 4 t .kef la.pixw - MT Him 111 III 114 JH. vt—HL i rfWjf ^p'Ah'i Jh ' ii I - ' ■ I I llf Mi's IHU"'"** I (wqi^rbvlvi ■ ■ i^- ^^^^ ■ nM| UMf-fM* Messages Window T he Breakpoints window i m Chip Choice (continued) H-rmfackaoe .~WWP«Uae 44-Pni>«k w Piri Number 31 Obsignation IOBUS12 Current Signal UARTTXD Default Signal UAftTTXD Direction Output lemplale Options R4St«e Defaults Code Generation Optnns Include PotKs^e lyp* Dec!*- sttm Qutpt* File Path: C:^W*1^ Wr«orrttocleri«in\VWCl- f&owsT GerAate cad* fat 32-f» Paotage Generate Code for Wsn Pa*** Gwwate Cod* for H-Rn Pacfesge | Generate Code j Key Non-conllguraWe pin Default pin configuration User rjustomfeed oin selection airemiy t*p*$mi pti Package A - Small & only 4 Pins to Solder* Package B - Slightly Larger-No Soldering* 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): • ACKCBW • Fake Data phase (if any) • Return CSW to PC - Some commands return success because Windows is unhappy with failures , * ^ A Main Loop usbSlaveBoms_readCbw(cbw, slaveBomsCtx) switch (cbw->cb.formated. command) { case BOMSJNQUIRY: 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) ; } } fimer "hread • 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 ITS DEMO TIME! Food for thought • Speed up process by searching registry for previously mounted <9 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 (4 th ed.) by Jan Axelson • USB Mass Storage: Designing and Programming Devices and Embedded Hosts by Jan Axelson • http://www.usb.org • h tt p ://w w w. ftdichip.com for more on VNC2 • http://seaqate.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=CIVGzGOW-DM • Schematics and source code are available - Git hub usb-impersonator - Email ppolstra@qmail.com - Twitter @ppolstra V Questions?